#!/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__ */ ((x3) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x3, {
  get: (a2, b2) => (typeof require !== "undefined" ? require : a2)[b2]
}) : x3)(function(x3) {
  if (typeof require !== "undefined") return require.apply(this, arguments);
  throw Error('Dynamic require of "' + x3 + '" is not supported');
});
var __glob = (map2) => (path125) => {
  var fn = map2[path125];
  if (fn) return fn();
  throw new Error("Module not found in bundle: " + path125);
};
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);
  }
});

// packages/core/node_modules/undici/lib/core/symbols.js
var require_symbols = __commonJS({
  "packages/core/node_modules/undici/lib/core/symbols.js"(exports2, module2) {
    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"),
      kInterceptors: Symbol("dispatch interceptors"),
      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")
    };
  }
});

// packages/core/node_modules/undici/lib/core/errors.js
var require_errors = __commonJS({
  "packages/core/node_modules/undici/lib/core/errors.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var kUndiciError = Symbol.for("undici.error.UND_ERR");
    var UndiciError = class extends Error {
      static {
        __name(this, "UndiciError");
      }
      constructor(message) {
        super(message);
        this.name = "UndiciError";
        this.code = "UND_ERR";
      }
      static [Symbol.hasInstance](instance) {
        return instance && instance[kUndiciError] === true;
      }
      [kUndiciError] = true;
    };
    var kConnectTimeoutError = Symbol.for("undici.error.UND_ERR_CONNECT_TIMEOUT");
    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";
      }
      static [Symbol.hasInstance](instance) {
        return instance && instance[kConnectTimeoutError] === true;
      }
      [kConnectTimeoutError] = true;
    };
    var kHeadersTimeoutError = Symbol.for("undici.error.UND_ERR_HEADERS_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";
      }
      static [Symbol.hasInstance](instance) {
        return instance && instance[kHeadersTimeoutError] === true;
      }
      [kHeadersTimeoutError] = true;
    };
    var kHeadersOverflowError = Symbol.for("undici.error.UND_ERR_HEADERS_OVERFLOW");
    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";
      }
      static [Symbol.hasInstance](instance) {
        return instance && instance[kHeadersOverflowError] === true;
      }
      [kHeadersOverflowError] = true;
    };
    var kBodyTimeoutError = Symbol.for("undici.error.UND_ERR_BODY_TIMEOUT");
    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";
      }
      static [Symbol.hasInstance](instance) {
        return instance && instance[kBodyTimeoutError] === true;
      }
      [kBodyTimeoutError] = true;
    };
    var kResponseStatusCodeError = Symbol.for("undici.error.UND_ERR_RESPONSE_STATUS_CODE");
    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;
      }
      static [Symbol.hasInstance](instance) {
        return instance && instance[kResponseStatusCodeError] === true;
      }
      [kResponseStatusCodeError] = true;
    };
    var kInvalidArgumentError = Symbol.for("undici.error.UND_ERR_INVALID_ARG");
    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";
      }
      static [Symbol.hasInstance](instance) {
        return instance && instance[kInvalidArgumentError] === true;
      }
      [kInvalidArgumentError] = true;
    };
    var kInvalidReturnValueError = Symbol.for("undici.error.UND_ERR_INVALID_RETURN_VALUE");
    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";
      }
      static [Symbol.hasInstance](instance) {
        return instance && instance[kInvalidReturnValueError] === true;
      }
      [kInvalidReturnValueError] = true;
    };
    var kAbortError = Symbol.for("undici.error.UND_ERR_ABORT");
    var AbortError4 = class extends UndiciError {
      static {
        __name(this, "AbortError");
      }
      constructor(message) {
        super(message);
        this.name = "AbortError";
        this.message = message || "The operation was aborted";
        this.code = "UND_ERR_ABORT";
      }
      static [Symbol.hasInstance](instance) {
        return instance && instance[kAbortError] === true;
      }
      [kAbortError] = true;
    };
    var kRequestAbortedError = Symbol.for("undici.error.UND_ERR_ABORTED");
    var RequestAbortedError = class extends AbortError4 {
      static {
        __name(this, "RequestAbortedError");
      }
      constructor(message) {
        super(message);
        this.name = "AbortError";
        this.message = message || "Request aborted";
        this.code = "UND_ERR_ABORTED";
      }
      static [Symbol.hasInstance](instance) {
        return instance && instance[kRequestAbortedError] === true;
      }
      [kRequestAbortedError] = true;
    };
    var kInformationalError = Symbol.for("undici.error.UND_ERR_INFO");
    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";
      }
      static [Symbol.hasInstance](instance) {
        return instance && instance[kInformationalError] === true;
      }
      [kInformationalError] = true;
    };
    var kRequestContentLengthMismatchError = Symbol.for("undici.error.UND_ERR_REQ_CONTENT_LENGTH_MISMATCH");
    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";
      }
      static [Symbol.hasInstance](instance) {
        return instance && instance[kRequestContentLengthMismatchError] === true;
      }
      [kRequestContentLengthMismatchError] = true;
    };
    var kResponseContentLengthMismatchError = Symbol.for("undici.error.UND_ERR_RES_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";
      }
      static [Symbol.hasInstance](instance) {
        return instance && instance[kResponseContentLengthMismatchError] === true;
      }
      [kResponseContentLengthMismatchError] = true;
    };
    var kClientDestroyedError = Symbol.for("undici.error.UND_ERR_DESTROYED");
    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";
      }
      static [Symbol.hasInstance](instance) {
        return instance && instance[kClientDestroyedError] === true;
      }
      [kClientDestroyedError] = true;
    };
    var kClientClosedError = Symbol.for("undici.error.UND_ERR_CLOSED");
    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";
      }
      static [Symbol.hasInstance](instance) {
        return instance && instance[kClientClosedError] === true;
      }
      [kClientClosedError] = true;
    };
    var kSocketError = Symbol.for("undici.error.UND_ERR_SOCKET");
    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;
      }
      static [Symbol.hasInstance](instance) {
        return instance && instance[kSocketError] === true;
      }
      [kSocketError] = true;
    };
    var kNotSupportedError = Symbol.for("undici.error.UND_ERR_NOT_SUPPORTED");
    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";
      }
      static [Symbol.hasInstance](instance) {
        return instance && instance[kNotSupportedError] === true;
      }
      [kNotSupportedError] = true;
    };
    var kBalancedPoolMissingUpstreamError = Symbol.for("undici.error.UND_ERR_BPL_MISSING_UPSTREAM");
    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";
      }
      static [Symbol.hasInstance](instance) {
        return instance && instance[kBalancedPoolMissingUpstreamError] === true;
      }
      [kBalancedPoolMissingUpstreamError] = true;
    };
    var kHTTPParserError = Symbol.for("undici.error.UND_ERR_HTTP_PARSER");
    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;
      }
      static [Symbol.hasInstance](instance) {
        return instance && instance[kHTTPParserError] === true;
      }
      [kHTTPParserError] = true;
    };
    var kResponseExceededMaxSizeError = Symbol.for("undici.error.UND_ERR_RES_EXCEEDED_MAX_SIZE");
    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";
      }
      static [Symbol.hasInstance](instance) {
        return instance && instance[kResponseExceededMaxSizeError] === true;
      }
      [kResponseExceededMaxSizeError] = true;
    };
    var kRequestRetryError = Symbol.for("undici.error.UND_ERR_REQ_RETRY");
    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;
      }
      static [Symbol.hasInstance](instance) {
        return instance && instance[kRequestRetryError] === true;
      }
      [kRequestRetryError] = true;
    };
    var kResponseError = Symbol.for("undici.error.UND_ERR_RESPONSE");
    var ResponseError = class extends UndiciError {
      static {
        __name(this, "ResponseError");
      }
      constructor(message, code2, { headers, data }) {
        super(message);
        this.name = "ResponseError";
        this.message = message || "Response error";
        this.code = "UND_ERR_RESPONSE";
        this.statusCode = code2;
        this.data = data;
        this.headers = headers;
      }
      static [Symbol.hasInstance](instance) {
        return instance && instance[kResponseError] === true;
      }
      [kResponseError] = true;
    };
    var kSecureProxyConnectionError = Symbol.for("undici.error.UND_ERR_PRX_TLS");
    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;
      }
      static [Symbol.hasInstance](instance) {
        return instance && instance[kSecureProxyConnectionError] === true;
      }
      [kSecureProxyConnectionError] = true;
    };
    module2.exports = {
      AbortError: AbortError4,
      HTTPParserError,
      UndiciError,
      HeadersTimeoutError,
      HeadersOverflowError,
      BodyTimeoutError,
      RequestContentLengthMismatchError,
      ConnectTimeoutError,
      ResponseStatusCodeError,
      InvalidArgumentError,
      InvalidReturnValueError,
      RequestAbortedError,
      ClientDestroyedError,
      ClientClosedError,
      InformationalError,
      SocketError,
      NotSupportedError,
      ResponseContentLengthMismatchError,
      BalancedPoolMissingUpstreamError,
      ResponseExceededMaxSizeError,
      RequestRetryError,
      ResponseError,
      SecureProxyConnectionError
    };
  }
});

// packages/core/node_modules/undici/lib/core/constants.js
var require_constants = __commonJS({
  "packages/core/node_modules/undici/lib/core/constants.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var headerNameLowerCasedRecord = {};
    var wellknownHeaderNames = [
      "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"
    ];
    for (let i3 = 0; i3 < wellknownHeaderNames.length; ++i3) {
      const key = wellknownHeaderNames[i3];
      const lowerCasedKey = key.toLowerCase();
      headerNameLowerCasedRecord[key] = headerNameLowerCasedRecord[lowerCasedKey] = lowerCasedKey;
    }
    Object.setPrototypeOf(headerNameLowerCasedRecord, null);
    module2.exports = {
      wellknownHeaderNames,
      headerNameLowerCasedRecord
    };
  }
});

// packages/core/node_modules/undici/lib/core/tree.js
var require_tree = __commonJS({
  "packages/core/node_modules/undici/lib/core/tree.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var {
      wellknownHeaderNames,
      headerNameLowerCasedRecord
    } = require_constants();
    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
       */
      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
       * @return {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
       * */
      insert(key, value) {
        if (this.node === null) {
          this.node = new TstNode(key, value, 0);
        } else {
          this.node.add(key, value);
        }
      }
      /**
       * @param {Uint8Array} key
       * @return {any}
       */
      lookup(key) {
        return this.node?.search(key)?.value ?? null;
      }
    };
    var tree = new TernarySearchTree();
    for (let i3 = 0; i3 < wellknownHeaderNames.length; ++i3) {
      const key = headerNameLowerCasedRecord[wellknownHeaderNames[i3]];
      tree.insert(key, key);
    }
    module2.exports = {
      TernarySearchTree,
      tree
    };
  }
});

// packages/core/node_modules/undici/lib/core/util.js
var require_util = __commonJS({
  "packages/core/node_modules/undici/lib/core/util.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var assert4 = __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 { Blob: Blob6 } = __require("node:buffer");
    var nodeUtil = __require("node:util");
    var { stringify: stringify4 } = __require("node:querystring");
    var { EventEmitter: EE3 } = __require("node:events");
    var { InvalidArgumentError } = require_errors();
    var { headerNameLowerCasedRecord } = require_constants();
    var { tree } = require_tree();
    var [nodeMajor, nodeMinor] = process.versions.node.split(".").map((v2) => Number(v2));
    var BodyAsyncIterable = class {
      static {
        __name(this, "BodyAsyncIterable");
      }
      constructor(body) {
        this[kBody] = body;
        this[kBodyUsed] = false;
      }
      async *[Symbol.asyncIterator]() {
        assert4(!this[kBodyUsed], "disturbed");
        this[kBodyUsed] = true;
        yield* this[kBody];
      }
    };
    function wrapRequestBody(body) {
      if (isStream2(body)) {
        if (bodyLength(body) === 0) {
          body.on("data", function() {
            assert4(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 nop() {
    }
    __name(nop, "nop");
    function isStream2(obj) {
      return obj && typeof obj === "object" && typeof obj.pipe === "function" && typeof obj.on === "function";
    }
    __name(isStream2, "isStream");
    function isBlobLike3(object3) {
      if (object3 === null) {
        return false;
      } else if (object3 instanceof Blob6) {
        return true;
      } else if (typeof object3 !== "object") {
        return false;
      } else {
        const sTag = object3[Symbol.toStringTag];
        return (sTag === "Blob" || sTag === "File") && ("stream" in object3 && typeof object3.stream === "function" || "arrayBuffer" in object3 && typeof object3.arrayBuffer === "function");
      }
    }
    __name(isBlobLike3, "isBlobLike");
    function buildURL(url2, queryParams) {
      if (url2.includes("?") || url2.includes("#")) {
        throw new Error('Query params cannot be passed when url already contains "?" or "#".');
      }
      const stringified = stringify4(queryParams);
      if (stringified) {
        url2 += "?" + stringified;
      }
      return url2;
    }
    __name(buildURL, "buildURL");
    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 path125 = url2.path != null ? url2.path : `${url2.pathname || ""}${url2.search || ""}`;
        if (origin[origin.length - 1] === "/") {
          origin = origin.slice(0, origin.length - 1);
        }
        if (path125 && path125[0] !== "/") {
          path125 = `/${path125}`;
        }
        return new URL(`${origin}${path125}`);
      }
      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("]");
        assert4(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;
      }
      assert4(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 (isBlobLike3(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 m3 = val.toString().match(KEEPALIVE_TIMEOUT_EXPR);
      return m3 ? parseInt(m3[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 i3 = 0; i3 < headers.length; i3 += 2) {
        const key = headerNameToString(headers[i3]);
        let val = obj[key];
        if (val) {
          if (typeof val === "string") {
            val = [val];
            obj[key] = val;
          }
          val.push(headers[i3 + 1].toString("utf8"));
        } else {
          const headersValue = headers[i3 + 1];
          if (typeof headersValue === "string") {
            obj[key] = headersValue;
          } else {
            obj[key] = Array.isArray(headersValue) ? headersValue.map((x3) => x3.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 len = headers.length;
      const ret = new Array(len);
      let hasContentLength = false;
      let contentDispositionIdx = -1;
      let key;
      let val;
      let kLen = 0;
      for (let n3 = 0; n3 < headers.length; n3 += 2) {
        key = headers[n3];
        val = headers[n3 + 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 = n3 + 1;
        }
        ret[n3] = key;
        ret[n3 + 1] = val;
      }
      if (hasContentLength && contentDispositionIdx !== -1) {
        ret[contentDispositionIdx] = Buffer.from(ret[contentDispositionIdx]).toString("latin1");
      }
      return ret;
    }
    __name(parseRawHeaders, "parseRawHeaders");
    function isBuffer(buffer) {
      return buffer instanceof Uint8Array || Buffer.isBuffer(buffer);
    }
    __name(isBuffer, "isBuffer");
    function validateHandler(handler, method, upgrade) {
      if (!handler || typeof handler !== "object") {
        throw new InvalidArgumentError("handler must be an object");
      }
      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(validateHandler, "validateHandler");
    function isDisturbed(body) {
      return !!(body && (stream2.isDisturbed(body) || body[kBodyUsed]));
    }
    __name(isDisturbed, "isDisturbed");
    function isErrored(body) {
      return !!(body && stream2.isErrored(body));
    }
    __name(isErrored, "isErrored");
    function isReadable2(body) {
      return !!(body && stream2.isReadable(body));
    }
    __name(isReadable2, "isReadable");
    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]();
          },
          async pull(controller) {
            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));
              }
            }
            return controller.desiredSize > 0;
          },
          async cancel(reason) {
            await iterator.return();
          },
          type: "bytes"
        }
      );
    }
    __name(ReadableStreamFrom2, "ReadableStreamFrom");
    function isFormDataLike(object3) {
      return object3 && typeof object3 === "object" && typeof object3.append === "function" && typeof object3.delete === "function" && typeof object3.get === "function" && typeof object3.getAll === "function" && typeof object3.has === "function" && typeof object3.set === "function" && object3[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.addListener("abort", listener);
      return () => signal.removeListener("abort", listener);
    }
    __name(addAbortListener, "addAbortListener");
    var hasToWellFormed = typeof String.prototype.toWellFormed === "function";
    var hasIsWellFormed = typeof String.prototype.isWellFormed === "function";
    function toUSVString(val) {
      return hasToWellFormed ? `${val}`.toWellFormed() : nodeUtil.toUSVString(val);
    }
    __name(toUSVString, "toUSVString");
    function isUSVString(val) {
      return hasIsWellFormed ? `${val}`.isWellFormed() : toUSVString(val) === `${val}`;
    }
    __name(isUSVString, "isUSVString");
    function isTokenCharCode(c4) {
      switch (c4) {
        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 c4 >= 33 && c4 <= 126;
      }
    }
    __name(isTokenCharCode, "isTokenCharCode");
    function isValidHTTPToken(characters) {
      if (characters.length === 0) {
        return false;
      }
      for (let i3 = 0; i3 < characters.length; ++i3) {
        if (!isTokenCharCode(characters.charCodeAt(i3))) {
          return false;
        }
      }
      return true;
    }
    __name(isValidHTTPToken, "isValidHTTPToken");
    var headerCharRegex = /[^\t\x20-\x7e\x80-\xff]/;
    function isValidHeaderValue(characters) {
      return !headerCharRegex.test(characters);
    }
    __name(isValidHeaderValue, "isValidHeaderValue");
    function parseRangeHeader(range) {
      if (range == null || range === "") return { start: 0, end: null, size: null };
      const m3 = range ? range.match(/^bytes (\d+)-(\d+)\/(\d+)?$/) : null;
      return m3 ? {
        start: parseInt(m3[1]),
        end: m3[2] ? parseInt(m3[2]) : null,
        size: m3[3] ? parseInt(m3[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) {
      for (const [name3, listener] of obj[kListeners] ?? []) {
        obj.removeListener(name3, listener);
      }
      obj[kListeners] = null;
    }
    __name(removeAllListeners, "removeAllListeners");
    function errorRequest(client, request4, err) {
      try {
        request4.onError(err);
        assert4(request4.aborted);
      } catch (err2) {
        client.emit("error", err2);
      }
    }
    __name(errorRequest, "errorRequest");
    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,
      nop,
      isDisturbed,
      isErrored,
      isReadable: isReadable2,
      toUSVString,
      isUSVString,
      isBlobLike: isBlobLike3,
      parseOrigin,
      parseURL,
      getServerName,
      isStream: isStream2,
      isIterable,
      isAsyncIterable: isAsyncIterable2,
      isDestroyed,
      headerNameToString,
      bufferToLowerCasedHeaderName,
      addListener,
      removeAllListeners,
      errorRequest,
      parseRawHeaders,
      parseHeaders,
      parseKeepAliveTimeout,
      destroy,
      bodyLength,
      deepClone,
      ReadableStreamFrom: ReadableStreamFrom2,
      isBuffer,
      validateHandler,
      getSocketInfo,
      isFormDataLike,
      buildURL,
      addAbortListener,
      isValidHTTPToken,
      isValidHeaderValue,
      isTokenCharCode,
      parseRangeHeader,
      normalizedMethodRecordsBase,
      normalizedMethodRecords,
      isValidPort,
      isHttpOrHttpsPrefixed,
      nodeMajor,
      nodeMinor,
      safeHTTPMethods: ["GET", "HEAD", "OPTIONS", "TRACE"],
      wrapRequestBody
    };
  }
});

// packages/core/node_modules/undici/lib/core/diagnostics.js
var require_diagnostics = __commonJS({
  "packages/core/node_modules/undici/lib/core/diagnostics.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var diagnosticsChannel = __require("node:diagnostics_channel");
    var util3 = __require("node:util");
    var undiciDebugLog = util3.debuglog("undici");
    var fetchDebuglog = util3.debuglog("fetch");
    var websocketDebuglog = util3.debuglog("websocket");
    var isClientSet = false;
    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"),
      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")
    };
    if (undiciDebugLog.enabled || fetchDebuglog.enabled) {
      const debuglog = fetchDebuglog.enabled ? fetchDebuglog : undiciDebugLog;
      diagnosticsChannel.channel("undici:client:beforeConnect").subscribe((evt) => {
        const {
          connectParams: { version: version2, protocol, port, host }
        } = evt;
        debuglog(
          "connecting to %s using %s%s",
          `${host}${port ? `:${port}` : ""}`,
          protocol,
          version2
        );
      });
      diagnosticsChannel.channel("undici:client:connected").subscribe((evt) => {
        const {
          connectParams: { version: version2, protocol, port, host }
        } = evt;
        debuglog(
          "connected to %s using %s%s",
          `${host}${port ? `:${port}` : ""}`,
          protocol,
          version2
        );
      });
      diagnosticsChannel.channel("undici:client:connectError").subscribe((evt) => {
        const {
          connectParams: { version: version2, protocol, port, host },
          error: error2
        } = evt;
        debuglog(
          "connection to %s using %s%s errored - %s",
          `${host}${port ? `:${port}` : ""}`,
          protocol,
          version2,
          error2.message
        );
      });
      diagnosticsChannel.channel("undici:client:sendHeaders").subscribe((evt) => {
        const {
          request: { method, path: path125, origin }
        } = evt;
        debuglog("sending request to %s %s/%s", method, origin, path125);
      });
      diagnosticsChannel.channel("undici:request:headers").subscribe((evt) => {
        const {
          request: { method, path: path125, origin },
          response: { statusCode }
        } = evt;
        debuglog(
          "received response to %s %s/%s - HTTP %d",
          method,
          origin,
          path125,
          statusCode
        );
      });
      diagnosticsChannel.channel("undici:request:trailers").subscribe((evt) => {
        const {
          request: { method, path: path125, origin }
        } = evt;
        debuglog("trailers received from %s %s/%s", method, origin, path125);
      });
      diagnosticsChannel.channel("undici:request:error").subscribe((evt) => {
        const {
          request: { method, path: path125, origin },
          error: error2
        } = evt;
        debuglog(
          "request to %s %s/%s errored - %s",
          method,
          origin,
          path125,
          error2.message
        );
      });
      isClientSet = true;
    }
    if (websocketDebuglog.enabled) {
      if (!isClientSet) {
        const debuglog = undiciDebugLog.enabled ? undiciDebugLog : websocketDebuglog;
        diagnosticsChannel.channel("undici:client:beforeConnect").subscribe((evt) => {
          const {
            connectParams: { version: version2, protocol, port, host }
          } = evt;
          debuglog(
            "connecting to %s%s using %s%s",
            host,
            port ? `:${port}` : "",
            protocol,
            version2
          );
        });
        diagnosticsChannel.channel("undici:client:connected").subscribe((evt) => {
          const {
            connectParams: { version: version2, protocol, port, host }
          } = evt;
          debuglog(
            "connected to %s%s using %s%s",
            host,
            port ? `:${port}` : "",
            protocol,
            version2
          );
        });
        diagnosticsChannel.channel("undici:client:connectError").subscribe((evt) => {
          const {
            connectParams: { version: version2, protocol, port, host },
            error: error2
          } = evt;
          debuglog(
            "connection to %s%s using %s%s errored - %s",
            host,
            port ? `:${port}` : "",
            protocol,
            version2,
            error2.message
          );
        });
        diagnosticsChannel.channel("undici:client:sendHeaders").subscribe((evt) => {
          const {
            request: { method, path: path125, origin }
          } = evt;
          debuglog("sending request to %s %s/%s", method, origin, path125);
        });
      }
      diagnosticsChannel.channel("undici:websocket:open").subscribe((evt) => {
        const {
          address: { address, port }
        } = evt;
        websocketDebuglog("connection opened %s%s", address, port ? `:${port}` : "");
      });
      diagnosticsChannel.channel("undici:websocket:close").subscribe((evt) => {
        const { websocket, code: code2, reason } = evt;
        websocketDebuglog(
          "closed connection to %s - %s %s",
          websocket.url,
          code2,
          reason
        );
      });
      diagnosticsChannel.channel("undici:websocket:socket_error").subscribe((err) => {
        websocketDebuglog("connection errored - %s", err.message);
      });
      diagnosticsChannel.channel("undici:websocket:ping").subscribe((evt) => {
        websocketDebuglog("ping received");
      });
      diagnosticsChannel.channel("undici:websocket:pong").subscribe((evt) => {
        websocketDebuglog("pong received");
      });
    }
    module2.exports = {
      channels
    };
  }
});

// packages/core/node_modules/undici/lib/core/request.js
var require_request = __commonJS({
  "packages/core/node_modules/undici/lib/core/request.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var {
      InvalidArgumentError,
      NotSupportedError
    } = require_errors();
    var assert4 = __require("node:assert");
    var {
      isValidHTTPToken,
      isValidHeaderValue,
      isStream: isStream2,
      destroy,
      isBuffer,
      isFormDataLike,
      isIterable,
      isBlobLike: isBlobLike3,
      buildURL,
      validateHandler,
      getServerName,
      normalizedMethodRecords
    } = require_util();
    var { channels } = require_diagnostics();
    var { headerNameLowerCasedRecord } = require_constants();
    var invalidPathRegex = /[^\u0021-\u00ff]/;
    var kHandler = Symbol("handler");
    var Request6 = class {
      static {
        __name(this, "Request");
      }
      constructor(origin, {
        path: path125,
        method,
        body,
        headers,
        query,
        idempotent,
        blocking,
        upgrade,
        headersTimeout,
        bodyTimeout,
        reset,
        throwOnError,
        expectContinue,
        servername
      }, handler) {
        if (typeof path125 !== "string") {
          throw new InvalidArgumentError("path must be a string");
        } else if (path125[0] !== "/" && !(path125.startsWith("http://") || path125.startsWith("https://")) && method !== "CONNECT") {
          throw new InvalidArgumentError("path must be an absolute URL or start with a slash");
        } else if (invalidPathRegex.test(path125)) {
          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");
        }
        this.headersTimeout = headersTimeout;
        this.bodyTimeout = bodyTimeout;
        this.throwOnError = throwOnError === true;
        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) || isBlobLike3(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 ? buildURL(path125, query) : path125;
        this.origin = origin;
        this.idempotent = idempotent == null ? method === "HEAD" || method === "GET" : idempotent;
        this.blocking = blocking == null ? false : blocking;
        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 i3 = 0; i3 < headers.length; i3 += 2) {
            processHeader(this, headers[i3], headers[i3 + 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 i3 = 0; i3 < keys.length; ++i3) {
              processHeader(this, keys[i3], headers[keys[i3]]);
            }
          }
        } else if (headers != null) {
          throw new InvalidArgumentError("headers must be an object or an array");
        }
        validateHandler(handler, method, upgrade);
        this.servername = servername || getServerName(this.host);
        this[kHandler] = handler;
        if (channels.create.hasSubscribers) {
          channels.create.publish({ request: this });
        }
      }
      onBodySent(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) {
        assert4(!this.aborted);
        assert4(!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) {
        assert4(!this.aborted);
        assert4(!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) {
        assert4(!this.aborted);
        assert4(!this.completed);
        try {
          return this[kHandler].onData(chunk);
        } catch (err) {
          this.abort(err);
          return false;
        }
      }
      onUpgrade(statusCode, headers, socket) {
        assert4(!this.aborted);
        assert4(!this.completed);
        return this[kHandler].onUpgrade(statusCode, headers, socket);
      }
      onComplete(trailers) {
        this.onFinally();
        assert4(!this.aborted);
        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(error2) {
        this.onFinally();
        if (channels.error.hasSubscribers) {
          channels.error.publish({ request: this, error: error2 });
        }
        if (this.aborted) {
          return;
        }
        this.aborted = true;
        return this[kHandler].onError(error2);
      }
      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 i3 = 0; i3 < val.length; i3++) {
          if (typeof val[i3] === "string") {
            if (!isValidHeaderValue(val[i3])) {
              throw new InvalidArgumentError(`invalid ${key} header`);
            }
            arr.push(val[i3]);
          } else if (val[i3] === null) {
            arr.push("");
          } else if (typeof val[i3] === "object") {
            throw new InvalidArgumentError(`invalid ${key} header`);
          } else {
            arr.push(`${val[i3]}`);
          }
        }
        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 = Request6;
  }
});

// packages/core/node_modules/undici/lib/dispatcher/dispatcher.js
var require_dispatcher = __commonJS({
  "packages/core/node_modules/undici/lib/dispatcher/dispatcher.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var EventEmitter11 = __require("node:events");
    var Dispatcher = class extends EventEmitter11 {
      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);
          if (dispatch == null || typeof dispatch !== "function" || dispatch.length !== 2) {
            throw new TypeError("invalid interceptor");
          }
        }
        return new ComposedDispatcher(this, dispatch);
      }
    };
    var ComposedDispatcher = class extends Dispatcher {
      static {
        __name(this, "ComposedDispatcher");
      }
      #dispatcher = null;
      #dispatch = null;
      constructor(dispatcher, dispatch) {
        super();
        this.#dispatcher = dispatcher;
        this.#dispatch = dispatch;
      }
      dispatch(...args) {
        this.#dispatch(...args);
      }
      close(...args) {
        return this.#dispatcher.close(...args);
      }
      destroy(...args) {
        return this.#dispatcher.destroy(...args);
      }
    };
    module2.exports = Dispatcher;
  }
});

// packages/core/node_modules/undici/lib/dispatcher/dispatcher-base.js
var require_dispatcher_base = __commonJS({
  "packages/core/node_modules/undici/lib/dispatcher/dispatcher-base.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var Dispatcher = require_dispatcher();
    var {
      ClientDestroyedError,
      ClientClosedError,
      InvalidArgumentError
    } = require_errors();
    var { kDestroy, kClose, kClosed, kDestroyed, kDispatch, kInterceptors } = require_symbols();
    var kOnDestroyed = Symbol("onDestroyed");
    var kOnClosed = Symbol("onClosed");
    var kInterceptedDispatch = Symbol("Intercepted Dispatch");
    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];
      }
      get interceptors() {
        return this[kInterceptors];
      }
      set interceptors(newInterceptors) {
        if (newInterceptors) {
          for (let i3 = newInterceptors.length - 1; i3 >= 0; i3--) {
            const interceptor = this[kInterceptors][i3];
            if (typeof interceptor !== "function") {
              throw new InvalidArgumentError("interceptor must be an function");
            }
          }
        }
        this[kInterceptors] = newInterceptors;
      }
      close(callback) {
        if (callback === void 0) {
          return new Promise((resolve30, reject) => {
            this.close((err, data) => {
              return err ? reject(err) : resolve30(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 i3 = 0; i3 < callbacks.length; i3++) {
            callbacks[i3](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((resolve30, reject) => {
            this.destroy(err, (err2, data) => {
              return err2 ? (
                /* istanbul ignore next: should never error */
                reject(err2)
              ) : resolve30(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 i3 = 0; i3 < callbacks.length; i3++) {
            callbacks[i3](null, null);
          }
        }, "onDestroyed");
        this[kDestroy](err).then(() => {
          queueMicrotask(onDestroyed);
        });
      }
      [kInterceptedDispatch](opts, handler) {
        if (!this[kInterceptors] || this[kInterceptors].length === 0) {
          this[kInterceptedDispatch] = this[kDispatch];
          return this[kDispatch](opts, handler);
        }
        let dispatch = this[kDispatch].bind(this);
        for (let i3 = this[kInterceptors].length - 1; i3 >= 0; i3--) {
          dispatch = this[kInterceptors][i3](dispatch);
        }
        this[kInterceptedDispatch] = dispatch;
        return dispatch(opts, handler);
      }
      dispatch(opts, handler) {
        if (!handler || typeof handler !== "object") {
          throw new InvalidArgumentError("handler must be an object");
        }
        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[kInterceptedDispatch](opts, handler);
        } catch (err) {
          if (typeof handler.onError !== "function") {
            throw new InvalidArgumentError("invalid onError method");
          }
          handler.onError(err);
          return false;
        }
      }
    };
    module2.exports = DispatcherBase;
  }
});

// packages/core/node_modules/undici/lib/util/timers.js
var require_timers = __commonJS({
  "packages/core/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) {
        fastNowTimeout.refresh();
      } else {
        clearTimeout(fastNowTimeout);
        fastNowTimeout = setTimeout(onTick, TICK_MS);
        if (fastNowTimeout.unref) {
          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
    };
  }
});

// packages/core/node_modules/undici/lib/core/connect.js
var require_connect = __commonJS({
  "packages/core/node_modules/undici/lib/core/connect.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var net2 = __require("node:net");
    var assert4 = __require("node:assert");
    var util3 = require_util();
    var { InvalidArgumentError, ConnectTimeoutError } = require_errors();
    var timers = require_timers();
    function noop8() {
    }
    __name(noop8, "noop");
    var tls;
    var SessionCache;
    if (globalThis.FinalizationRegistry && !(process.env.NODE_V8_COVERAGE || process.env.UNDICI_NO_FG)) {
      SessionCache = class WeakSessionCache {
        static {
          __name(this, "WeakSessionCache");
        }
        constructor(maxCachedSessions) {
          this._maxCachedSessions = maxCachedSessions;
          this._sessionCache = /* @__PURE__ */ new Map();
          this._sessionRegistry = new globalThis.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);
        }
      };
    } else {
      SessionCache = class SimpleSessionCache {
        static {
          __name(this, "SimpleSessionCache");
        }
        constructor(maxCachedSessions) {
          this._maxCachedSessions = maxCachedSessions;
          this._sessionCache = /* @__PURE__ */ new Map();
        }
        get(sessionKey) {
          return this._sessionCache.get(sessionKey);
        }
        set(sessionKey, session) {
          if (this._maxCachedSessions === 0) {
            return;
          }
          if (this._sessionCache.size >= this._maxCachedSessions) {
            const { value: oldestKey } = this._sessionCache.keys().next();
            this._sessionCache.delete(oldestKey);
          }
          this._sessionCache.set(sessionKey, session);
        }
      };
    }
    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: hostname4, host, protocol, port, servername, localAddress, httpSocket }, callback) {
        let socket;
        if (protocol === "https:") {
          if (!tls) {
            tls = __require("node:tls");
          }
          servername = servername || options2.servername || util3.getServerName(host) || null;
          const sessionKey = servername || hostname4;
          assert4(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,
            // TODO(HTTP/2): Add support for h2c
            ALPNProtocols: allowH2 ? ["http/1.1", "h2"] : ["http/1.1"],
            socket: httpSocket,
            // upgrade socket connection
            port,
            host: hostname4
          });
          socket.on("session", function(session2) {
            sessionCache.set(sessionKey, session2);
          });
        } else {
          assert4(!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: hostname4
          });
        }
        if (options2.keepAlive == null || options2.keepAlive) {
          const keepAliveInitialDelay = options2.keepAliveInitialDelay === void 0 ? 6e4 : options2.keepAliveInitialDelay;
          socket.setKeepAlive(true, keepAliveInitialDelay);
        }
        const clearConnectTimeout = setupConnectTimeout(new WeakRef(socket), { timeout: timeout2, hostname: hostname4, 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");
    var setupConnectTimeout = process.platform === "win32" ? (socketWeakRef, opts) => {
      if (!opts.timeout) {
        return noop8;
      }
      let s1 = null;
      let s22 = null;
      const fastTimer = timers.setFastTimeout(() => {
        s1 = setImmediate(() => {
          s22 = setImmediate(() => onConnectTimeout(socketWeakRef.deref(), opts));
        });
      }, opts.timeout);
      return () => {
        timers.clearFastTimeout(fastTimer);
        clearImmediate(s1);
        clearImmediate(s22);
      };
    } : (socketWeakRef, opts) => {
      if (!opts.timeout) {
        return noop8;
      }
      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)`;
      util3.destroy(socket, new ConnectTimeoutError(message));
    }
    __name(onConnectTimeout, "onConnectTimeout");
    module2.exports = buildConnector;
  }
});

// packages/core/node_modules/undici/lib/llhttp/utils.js
var require_utils = __commonJS({
  "packages/core/node_modules/undici/lib/llhttp/utils.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.enumToMap = void 0;
    function enumToMap(obj) {
      const res = {};
      Object.keys(obj).forEach((key) => {
        const value = obj[key];
        if (typeof value === "number") {
          res[key] = value;
        }
      });
      return res;
    }
    __name(enumToMap, "enumToMap");
    exports2.enumToMap = enumToMap;
  }
});

// packages/core/node_modules/undici/lib/llhttp/constants.js
var require_constants2 = __commonJS({
  "packages/core/node_modules/undici/lib/llhttp/constants.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.SPECIAL_HEADERS = exports2.HEADER_STATE = exports2.MINOR = exports2.MAJOR = exports2.CONNECTION_TOKEN_CHARS = exports2.HEADER_CHARS = exports2.TOKEN = exports2.STRICT_TOKEN = exports2.HEX = exports2.URL_CHAR = exports2.STRICT_URL_CHAR = exports2.USERINFO_CHARS = exports2.MARK = exports2.ALPHANUM = exports2.NUM = exports2.HEX_MAP = exports2.NUM_MAP = exports2.ALPHA = exports2.FINISH = exports2.H_METHOD_MAP = exports2.METHOD_MAP = exports2.METHODS_RTSP = exports2.METHODS_ICE = exports2.METHODS_HTTP = exports2.METHODS = exports2.LENIENT_FLAGS = exports2.FLAGS = exports2.TYPE = exports2.ERROR = void 0;
    var utils_1 = require_utils();
    var ERROR2;
    (function(ERROR3) {
      ERROR3[ERROR3["OK"] = 0] = "OK";
      ERROR3[ERROR3["INTERNAL"] = 1] = "INTERNAL";
      ERROR3[ERROR3["STRICT"] = 2] = "STRICT";
      ERROR3[ERROR3["LF_EXPECTED"] = 3] = "LF_EXPECTED";
      ERROR3[ERROR3["UNEXPECTED_CONTENT_LENGTH"] = 4] = "UNEXPECTED_CONTENT_LENGTH";
      ERROR3[ERROR3["CLOSED_CONNECTION"] = 5] = "CLOSED_CONNECTION";
      ERROR3[ERROR3["INVALID_METHOD"] = 6] = "INVALID_METHOD";
      ERROR3[ERROR3["INVALID_URL"] = 7] = "INVALID_URL";
      ERROR3[ERROR3["INVALID_CONSTANT"] = 8] = "INVALID_CONSTANT";
      ERROR3[ERROR3["INVALID_VERSION"] = 9] = "INVALID_VERSION";
      ERROR3[ERROR3["INVALID_HEADER_TOKEN"] = 10] = "INVALID_HEADER_TOKEN";
      ERROR3[ERROR3["INVALID_CONTENT_LENGTH"] = 11] = "INVALID_CONTENT_LENGTH";
      ERROR3[ERROR3["INVALID_CHUNK_SIZE"] = 12] = "INVALID_CHUNK_SIZE";
      ERROR3[ERROR3["INVALID_STATUS"] = 13] = "INVALID_STATUS";
      ERROR3[ERROR3["INVALID_EOF_STATE"] = 14] = "INVALID_EOF_STATE";
      ERROR3[ERROR3["INVALID_TRANSFER_ENCODING"] = 15] = "INVALID_TRANSFER_ENCODING";
      ERROR3[ERROR3["CB_MESSAGE_BEGIN"] = 16] = "CB_MESSAGE_BEGIN";
      ERROR3[ERROR3["CB_HEADERS_COMPLETE"] = 17] = "CB_HEADERS_COMPLETE";
      ERROR3[ERROR3["CB_MESSAGE_COMPLETE"] = 18] = "CB_MESSAGE_COMPLETE";
      ERROR3[ERROR3["CB_CHUNK_HEADER"] = 19] = "CB_CHUNK_HEADER";
      ERROR3[ERROR3["CB_CHUNK_COMPLETE"] = 20] = "CB_CHUNK_COMPLETE";
      ERROR3[ERROR3["PAUSED"] = 21] = "PAUSED";
      ERROR3[ERROR3["PAUSED_UPGRADE"] = 22] = "PAUSED_UPGRADE";
      ERROR3[ERROR3["PAUSED_H2_UPGRADE"] = 23] = "PAUSED_H2_UPGRADE";
      ERROR3[ERROR3["USER"] = 24] = "USER";
    })(ERROR2 = exports2.ERROR || (exports2.ERROR = {}));
    var TYPE2;
    (function(TYPE3) {
      TYPE3[TYPE3["BOTH"] = 0] = "BOTH";
      TYPE3[TYPE3["REQUEST"] = 1] = "REQUEST";
      TYPE3[TYPE3["RESPONSE"] = 2] = "RESPONSE";
    })(TYPE2 = exports2.TYPE || (exports2.TYPE = {}));
    var FLAGS;
    (function(FLAGS2) {
      FLAGS2[FLAGS2["CONNECTION_KEEP_ALIVE"] = 1] = "CONNECTION_KEEP_ALIVE";
      FLAGS2[FLAGS2["CONNECTION_CLOSE"] = 2] = "CONNECTION_CLOSE";
      FLAGS2[FLAGS2["CONNECTION_UPGRADE"] = 4] = "CONNECTION_UPGRADE";
      FLAGS2[FLAGS2["CHUNKED"] = 8] = "CHUNKED";
      FLAGS2[FLAGS2["UPGRADE"] = 16] = "UPGRADE";
      FLAGS2[FLAGS2["CONTENT_LENGTH"] = 32] = "CONTENT_LENGTH";
      FLAGS2[FLAGS2["SKIPBODY"] = 64] = "SKIPBODY";
      FLAGS2[FLAGS2["TRAILING"] = 128] = "TRAILING";
      FLAGS2[FLAGS2["TRANSFER_ENCODING"] = 512] = "TRANSFER_ENCODING";
    })(FLAGS = exports2.FLAGS || (exports2.FLAGS = {}));
    var LENIENT_FLAGS;
    (function(LENIENT_FLAGS2) {
      LENIENT_FLAGS2[LENIENT_FLAGS2["HEADERS"] = 1] = "HEADERS";
      LENIENT_FLAGS2[LENIENT_FLAGS2["CHUNKED_LENGTH"] = 2] = "CHUNKED_LENGTH";
      LENIENT_FLAGS2[LENIENT_FLAGS2["KEEP_ALIVE"] = 4] = "KEEP_ALIVE";
    })(LENIENT_FLAGS = exports2.LENIENT_FLAGS || (exports2.LENIENT_FLAGS = {}));
    var METHODS;
    (function(METHODS2) {
      METHODS2[METHODS2["DELETE"] = 0] = "DELETE";
      METHODS2[METHODS2["GET"] = 1] = "GET";
      METHODS2[METHODS2["HEAD"] = 2] = "HEAD";
      METHODS2[METHODS2["POST"] = 3] = "POST";
      METHODS2[METHODS2["PUT"] = 4] = "PUT";
      METHODS2[METHODS2["CONNECT"] = 5] = "CONNECT";
      METHODS2[METHODS2["OPTIONS"] = 6] = "OPTIONS";
      METHODS2[METHODS2["TRACE"] = 7] = "TRACE";
      METHODS2[METHODS2["COPY"] = 8] = "COPY";
      METHODS2[METHODS2["LOCK"] = 9] = "LOCK";
      METHODS2[METHODS2["MKCOL"] = 10] = "MKCOL";
      METHODS2[METHODS2["MOVE"] = 11] = "MOVE";
      METHODS2[METHODS2["PROPFIND"] = 12] = "PROPFIND";
      METHODS2[METHODS2["PROPPATCH"] = 13] = "PROPPATCH";
      METHODS2[METHODS2["SEARCH"] = 14] = "SEARCH";
      METHODS2[METHODS2["UNLOCK"] = 15] = "UNLOCK";
      METHODS2[METHODS2["BIND"] = 16] = "BIND";
      METHODS2[METHODS2["REBIND"] = 17] = "REBIND";
      METHODS2[METHODS2["UNBIND"] = 18] = "UNBIND";
      METHODS2[METHODS2["ACL"] = 19] = "ACL";
      METHODS2[METHODS2["REPORT"] = 20] = "REPORT";
      METHODS2[METHODS2["MKACTIVITY"] = 21] = "MKACTIVITY";
      METHODS2[METHODS2["CHECKOUT"] = 22] = "CHECKOUT";
      METHODS2[METHODS2["MERGE"] = 23] = "MERGE";
      METHODS2[METHODS2["M-SEARCH"] = 24] = "M-SEARCH";
      METHODS2[METHODS2["NOTIFY"] = 25] = "NOTIFY";
      METHODS2[METHODS2["SUBSCRIBE"] = 26] = "SUBSCRIBE";
      METHODS2[METHODS2["UNSUBSCRIBE"] = 27] = "UNSUBSCRIBE";
      METHODS2[METHODS2["PATCH"] = 28] = "PATCH";
      METHODS2[METHODS2["PURGE"] = 29] = "PURGE";
      METHODS2[METHODS2["MKCALENDAR"] = 30] = "MKCALENDAR";
      METHODS2[METHODS2["LINK"] = 31] = "LINK";
      METHODS2[METHODS2["UNLINK"] = 32] = "UNLINK";
      METHODS2[METHODS2["SOURCE"] = 33] = "SOURCE";
      METHODS2[METHODS2["PRI"] = 34] = "PRI";
      METHODS2[METHODS2["DESCRIBE"] = 35] = "DESCRIBE";
      METHODS2[METHODS2["ANNOUNCE"] = 36] = "ANNOUNCE";
      METHODS2[METHODS2["SETUP"] = 37] = "SETUP";
      METHODS2[METHODS2["PLAY"] = 38] = "PLAY";
      METHODS2[METHODS2["PAUSE"] = 39] = "PAUSE";
      METHODS2[METHODS2["TEARDOWN"] = 40] = "TEARDOWN";
      METHODS2[METHODS2["GET_PARAMETER"] = 41] = "GET_PARAMETER";
      METHODS2[METHODS2["SET_PARAMETER"] = 42] = "SET_PARAMETER";
      METHODS2[METHODS2["REDIRECT"] = 43] = "REDIRECT";
      METHODS2[METHODS2["RECORD"] = 44] = "RECORD";
      METHODS2[METHODS2["FLUSH"] = 45] = "FLUSH";
    })(METHODS = exports2.METHODS || (exports2.METHODS = {}));
    exports2.METHODS_HTTP = [
      METHODS.DELETE,
      METHODS.GET,
      METHODS.HEAD,
      METHODS.POST,
      METHODS.PUT,
      METHODS.CONNECT,
      METHODS.OPTIONS,
      METHODS.TRACE,
      METHODS.COPY,
      METHODS.LOCK,
      METHODS.MKCOL,
      METHODS.MOVE,
      METHODS.PROPFIND,
      METHODS.PROPPATCH,
      METHODS.SEARCH,
      METHODS.UNLOCK,
      METHODS.BIND,
      METHODS.REBIND,
      METHODS.UNBIND,
      METHODS.ACL,
      METHODS.REPORT,
      METHODS.MKACTIVITY,
      METHODS.CHECKOUT,
      METHODS.MERGE,
      METHODS["M-SEARCH"],
      METHODS.NOTIFY,
      METHODS.SUBSCRIBE,
      METHODS.UNSUBSCRIBE,
      METHODS.PATCH,
      METHODS.PURGE,
      METHODS.MKCALENDAR,
      METHODS.LINK,
      METHODS.UNLINK,
      METHODS.PRI,
      // TODO(indutny): should we allow it with HTTP?
      METHODS.SOURCE
    ];
    exports2.METHODS_ICE = [
      METHODS.SOURCE
    ];
    exports2.METHODS_RTSP = [
      METHODS.OPTIONS,
      METHODS.DESCRIBE,
      METHODS.ANNOUNCE,
      METHODS.SETUP,
      METHODS.PLAY,
      METHODS.PAUSE,
      METHODS.TEARDOWN,
      METHODS.GET_PARAMETER,
      METHODS.SET_PARAMETER,
      METHODS.REDIRECT,
      METHODS.RECORD,
      METHODS.FLUSH,
      // For AirPlay
      METHODS.GET,
      METHODS.POST
    ];
    exports2.METHOD_MAP = utils_1.enumToMap(METHODS);
    exports2.H_METHOD_MAP = {};
    Object.keys(exports2.METHOD_MAP).forEach((key) => {
      if (/^H/.test(key)) {
        exports2.H_METHOD_MAP[key] = exports2.METHOD_MAP[key];
      }
    });
    var FINISH;
    (function(FINISH2) {
      FINISH2[FINISH2["SAFE"] = 0] = "SAFE";
      FINISH2[FINISH2["SAFE_WITH_CB"] = 1] = "SAFE_WITH_CB";
      FINISH2[FINISH2["UNSAFE"] = 2] = "UNSAFE";
    })(FINISH = exports2.FINISH || (exports2.FINISH = {}));
    exports2.ALPHA = [];
    for (let i3 = "A".charCodeAt(0); i3 <= "Z".charCodeAt(0); i3++) {
      exports2.ALPHA.push(String.fromCharCode(i3));
      exports2.ALPHA.push(String.fromCharCode(i3 + 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.STRICT_URL_CHAR = [
      "!",
      '"',
      "$",
      "%",
      "&",
      "'",
      "(",
      ")",
      "*",
      "+",
      ",",
      "-",
      ".",
      "/",
      ":",
      ";",
      "<",
      "=",
      ">",
      "@",
      "[",
      "\\",
      "]",
      "^",
      "_",
      "`",
      "{",
      "|",
      "}",
      "~"
    ].concat(exports2.ALPHANUM);
    exports2.URL_CHAR = exports2.STRICT_URL_CHAR.concat(["	", "\f"]);
    for (let i3 = 128; i3 <= 255; i3++) {
      exports2.URL_CHAR.push(i3);
    }
    exports2.HEX = exports2.NUM.concat(["a", "b", "c", "d", "e", "f", "A", "B", "C", "D", "E", "F"]);
    exports2.STRICT_TOKEN = [
      "!",
      "#",
      "$",
      "%",
      "&",
      "'",
      "*",
      "+",
      "-",
      ".",
      "^",
      "_",
      "`",
      "|",
      "~"
    ].concat(exports2.ALPHANUM);
    exports2.TOKEN = exports2.STRICT_TOKEN.concat([" "]);
    exports2.HEADER_CHARS = ["	"];
    for (let i3 = 32; i3 <= 255; i3++) {
      if (i3 !== 127) {
        exports2.HEADER_CHARS.push(i3);
      }
    }
    exports2.CONNECTION_TOKEN_CHARS = exports2.HEADER_CHARS.filter((c4) => c4 !== 44);
    exports2.MAJOR = exports2.NUM_MAP;
    exports2.MINOR = exports2.MAJOR;
    var HEADER_STATE;
    (function(HEADER_STATE2) {
      HEADER_STATE2[HEADER_STATE2["GENERAL"] = 0] = "GENERAL";
      HEADER_STATE2[HEADER_STATE2["CONNECTION"] = 1] = "CONNECTION";
      HEADER_STATE2[HEADER_STATE2["CONTENT_LENGTH"] = 2] = "CONTENT_LENGTH";
      HEADER_STATE2[HEADER_STATE2["TRANSFER_ENCODING"] = 3] = "TRANSFER_ENCODING";
      HEADER_STATE2[HEADER_STATE2["UPGRADE"] = 4] = "UPGRADE";
      HEADER_STATE2[HEADER_STATE2["CONNECTION_KEEP_ALIVE"] = 5] = "CONNECTION_KEEP_ALIVE";
      HEADER_STATE2[HEADER_STATE2["CONNECTION_CLOSE"] = 6] = "CONNECTION_CLOSE";
      HEADER_STATE2[HEADER_STATE2["CONNECTION_UPGRADE"] = 7] = "CONNECTION_UPGRADE";
      HEADER_STATE2[HEADER_STATE2["TRANSFER_ENCODING_CHUNKED"] = 8] = "TRANSFER_ENCODING_CHUNKED";
    })(HEADER_STATE = exports2.HEADER_STATE || (exports2.HEADER_STATE = {}));
    exports2.SPECIAL_HEADERS = {
      "connection": HEADER_STATE.CONNECTION,
      "content-length": HEADER_STATE.CONTENT_LENGTH,
      "proxy-connection": HEADER_STATE.CONNECTION,
      "transfer-encoding": HEADER_STATE.TRANSFER_ENCODING,
      "upgrade": HEADER_STATE.UPGRADE
    };
  }
});

// packages/core/node_modules/undici/lib/llhttp/llhttp-wasm.js
var require_llhttp_wasm = __commonJS({
  "packages/core/node_modules/undici/lib/llhttp/llhttp-wasm.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var { Buffer: Buffer9 } = __require("node:buffer");
    module2.exports = Buffer9.from(" ", "base64");
  }
});

// packages/core/node_modules/undici/lib/llhttp/llhttp_simd-wasm.js
var require_llhttp_simd_wasm = __commonJS({
  "packages/core/node_modules/undici/lib/llhttp/llhttp_simd-wasm.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var { Buffer: Buffer9 } = __require("node:buffer");
    module2.exports = Buffer9.from(" ", "base64");
  }
});

// packages/core/node_modules/undici/lib/web/fetch/constants.js
var require_constants3 = __commonJS({
  "packages/core/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 redirectStatus3 = (
      /** @type {const} */
      [301, 302, 303, 307, 308]
    );
    var redirectStatusSet = new Set(redirectStatus3);
    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 referrerPolicy = (
      /** @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 referrerPolicySet = new Set(referrerPolicy);
    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: redirectStatus3,
      corsSafeListedMethods,
      nullBodyStatus,
      safeMethods,
      badPorts,
      requestDuplex,
      subresourceSet,
      badPortsSet,
      redirectStatusSet,
      corsSafeListedMethodsSet,
      safeMethodsSet,
      forbiddenMethodsSet,
      referrerPolicySet
    };
  }
});

// packages/core/node_modules/undici/lib/web/fetch/global.js
var require_global = __commonJS({
  "packages/core/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
    };
  }
});

// packages/core/node_modules/undici/lib/web/fetch/data-url.js
var require_data_url = __commonJS({
  "packages/core/node_modules/undici/lib/web/fetch/data-url.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var assert4 = __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) {
      assert4(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 j2 = 0;
      for (let i3 = 0; i3 < length; ++i3) {
        const byte = input[i3];
        if (byte !== 37) {
          output[j2++] = byte;
        } else if (byte === 37 && !(isHexCharByte(input[i3 + 1]) && isHexCharByte(input[i3 + 2]))) {
          output[j2++] = 37;
        } else {
          output[j2++] = hexByteToNumber(input[i3 + 1]) << 4 | hexByteToNumber(input[i3 + 2]);
          i3 += 2;
        }
      }
      return length === j2 ? output : output.subarray(0, j2);
    }
    __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) {
      const positionStart = position.position;
      let value = "";
      assert4(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 {
          assert4(quoteOrBackslash === '"');
          break;
        }
      }
      if (extractValue) {
        return value;
      }
      return input.slice(positionStart, position.position);
    }
    __name(collectAnHTTPQuotedString, "collectAnHTTPQuotedString");
    function serializeAMimeType(mimeType) {
      assert4(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 i3 = 0;
      let addition = (2 << 15) - 1;
      while (i3 < length) {
        if (i3 + addition > length) {
          addition = length - i3;
        }
        result += String.fromCharCode.apply(null, input.subarray(i3, i3 += 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
    };
  }
});

// packages/core/node_modules/undici/lib/web/fetch/webidl.js
var require_webidl = __commonJS({
  "packages/core/node_modules/undici/lib/web/fetch/webidl.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var { types: types7, inspect: inspect3 } = __require("node:util");
    var { markAsUncloneable } = __require("node:worker_threads");
    var { toUSVString } = require_util();
    var webidl = {};
    webidl.converters = {};
    webidl.util = {};
    webidl.errors = {};
    webidl.errors.exception = function(message) {
      return new TypeError(`${message.header}: ${message.message}`);
    };
    webidl.errors.conversionFailed = function(context2) {
      const plural = context2.types.length === 1 ? "" : " one of";
      const message = `${context2.argument} could not be converted to${plural}: ${context2.types.join(", ")}.`;
      return webidl.errors.exception({
        header: context2.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(V3, I3, opts) {
      if (opts?.strict !== false) {
        if (!(V3 instanceof I3)) {
          const err = new TypeError("Illegal invocation");
          err.code = "ERR_INVALID_THIS";
          throw err;
        }
      } else {
        if (V3?.[Symbol.toStringTag] !== I3.prototype[Symbol.toStringTag]) {
          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.Type = function(V3) {
      switch (typeof V3) {
        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 (V3 === null) {
            return "Null";
          }
          return "Object";
        }
      }
    };
    webidl.util.markAsUncloneable = markAsUncloneable || (() => {
    });
    webidl.util.ConvertToInt = function(V3, 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 x3 = Number(V3);
      if (x3 === 0) {
        x3 = 0;
      }
      if (opts?.enforceRange === true) {
        if (Number.isNaN(x3) || x3 === Number.POSITIVE_INFINITY || x3 === Number.NEGATIVE_INFINITY) {
          throw webidl.errors.exception({
            header: "Integer conversion",
            message: `Could not convert ${webidl.util.Stringify(V3)} to an integer.`
          });
        }
        x3 = webidl.util.IntegerPart(x3);
        if (x3 < lowerBound || x3 > upperBound) {
          throw webidl.errors.exception({
            header: "Integer conversion",
            message: `Value must be between ${lowerBound}-${upperBound}, got ${x3}.`
          });
        }
        return x3;
      }
      if (!Number.isNaN(x3) && opts?.clamp === true) {
        x3 = Math.min(Math.max(x3, lowerBound), upperBound);
        if (Math.floor(x3) % 2 === 0) {
          x3 = Math.floor(x3);
        } else {
          x3 = Math.ceil(x3);
        }
        return x3;
      }
      if (Number.isNaN(x3) || x3 === 0 && Object.is(0, x3) || x3 === Number.POSITIVE_INFINITY || x3 === Number.NEGATIVE_INFINITY) {
        return 0;
      }
      x3 = webidl.util.IntegerPart(x3);
      x3 = x3 % Math.pow(2, bitLength);
      if (signedness === "signed" && x3 >= Math.pow(2, bitLength) - 1) {
        return x3 - Math.pow(2, bitLength);
      }
      return x3;
    };
    webidl.util.IntegerPart = function(n3) {
      const r5 = Math.floor(Math.abs(n3));
      if (n3 < 0) {
        return -1 * r5;
      }
      return r5;
    };
    webidl.util.Stringify = function(V3) {
      const type = webidl.util.Type(V3);
      switch (type) {
        case "Symbol":
          return `Symbol(${V3.description})`;
        case "Object":
          return inspect3(V3);
        case "String":
          return `"${V3}"`;
        default:
          return `${V3}`;
      }
    };
    webidl.sequenceConverter = function(converter) {
      return (V3, prefix, argument, Iterable) => {
        if (webidl.util.Type(V3) !== "Object") {
          throw webidl.errors.exception({
            header: prefix,
            message: `${argument} (${webidl.util.Stringify(V3)}) is not iterable.`
          });
        }
        const method = typeof Iterable === "function" ? Iterable() : V3?.[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 (O2, prefix, argument) => {
        if (webidl.util.Type(O2) !== "Object") {
          throw webidl.errors.exception({
            header: prefix,
            message: `${argument} ("${webidl.util.Type(O2)}") is not an Object.`
          });
        }
        const result = {};
        if (!types7.isProxy(O2)) {
          const keys2 = [...Object.getOwnPropertyNames(O2), ...Object.getOwnPropertySymbols(O2)];
          for (const key of keys2) {
            const typedKey = keyConverter(key, prefix, argument);
            const typedValue = valueConverter(O2[key], prefix, argument);
            result[typedKey] = typedValue;
          }
          return result;
        }
        const keys = Reflect.ownKeys(O2);
        for (const key of keys) {
          const desc2 = Reflect.getOwnPropertyDescriptor(O2, key);
          if (desc2?.enumerable) {
            const typedKey = keyConverter(key, prefix, argument);
            const typedValue = valueConverter(O2[key], prefix, argument);
            result[typedKey] = typedValue;
          }
        }
        return result;
      };
    };
    webidl.interfaceConverter = function(i3) {
      return (V3, prefix, argument, opts) => {
        if (opts?.strict !== false && !(V3 instanceof i3)) {
          throw webidl.errors.exception({
            header: prefix,
            message: `Expected ${argument} ("${webidl.util.Stringify(V3)}") to be an instance of ${i3.name}.`
          });
        }
        return V3;
      };
    };
    webidl.dictionaryConverter = function(converters) {
      return (dictionary, prefix, argument) => {
        const type = webidl.util.Type(dictionary);
        const dict = {};
        if (type === "Null" || type === "Undefined") {
          return dict;
        } else if (type !== "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: required2, converter } = options2;
          if (required2 === true) {
            if (!Object.hasOwn(dictionary, key)) {
              throw webidl.errors.exception({
                header: prefix,
                message: `Missing required key "${key}".`
              });
            }
          }
          let value = dictionary[key];
          const hasDefault = Object.hasOwn(options2, "defaultValue");
          if (hasDefault && value !== null) {
            value ??= defaultValue();
          }
          if (required2 || 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 (V3, prefix, argument) => {
        if (V3 === null) {
          return V3;
        }
        return converter(V3, prefix, argument);
      };
    };
    webidl.converters.DOMString = function(V3, prefix, argument, opts) {
      if (V3 === null && opts?.legacyNullToEmptyString) {
        return "";
      }
      if (typeof V3 === "symbol") {
        throw webidl.errors.exception({
          header: prefix,
          message: `${argument} is a symbol, which cannot be converted to a DOMString.`
        });
      }
      return String(V3);
    };
    webidl.converters.ByteString = function(V3, prefix, argument) {
      const x3 = webidl.converters.DOMString(V3, prefix, argument);
      for (let index = 0; index < x3.length; index++) {
        if (x3.charCodeAt(index) > 255) {
          throw new TypeError(
            `Cannot convert argument to a ByteString because the character at index ${index} has a value of ${x3.charCodeAt(index)} which is greater than 255.`
          );
        }
      }
      return x3;
    };
    webidl.converters.USVString = toUSVString;
    webidl.converters.boolean = function(V3) {
      const x3 = Boolean(V3);
      return x3;
    };
    webidl.converters.any = function(V3) {
      return V3;
    };
    webidl.converters["long long"] = function(V3, prefix, argument) {
      const x3 = webidl.util.ConvertToInt(V3, 64, "signed", void 0, prefix, argument);
      return x3;
    };
    webidl.converters["unsigned long long"] = function(V3, prefix, argument) {
      const x3 = webidl.util.ConvertToInt(V3, 64, "unsigned", void 0, prefix, argument);
      return x3;
    };
    webidl.converters["unsigned long"] = function(V3, prefix, argument) {
      const x3 = webidl.util.ConvertToInt(V3, 32, "unsigned", void 0, prefix, argument);
      return x3;
    };
    webidl.converters["unsigned short"] = function(V3, prefix, argument, opts) {
      const x3 = webidl.util.ConvertToInt(V3, 16, "unsigned", opts, prefix, argument);
      return x3;
    };
    webidl.converters.ArrayBuffer = function(V3, prefix, argument, opts) {
      if (webidl.util.Type(V3) !== "Object" || !types7.isAnyArrayBuffer(V3)) {
        throw webidl.errors.conversionFailed({
          prefix,
          argument: `${argument} ("${webidl.util.Stringify(V3)}")`,
          types: ["ArrayBuffer"]
        });
      }
      if (opts?.allowShared === false && types7.isSharedArrayBuffer(V3)) {
        throw webidl.errors.exception({
          header: "ArrayBuffer",
          message: "SharedArrayBuffer is not allowed."
        });
      }
      if (V3.resizable || V3.growable) {
        throw webidl.errors.exception({
          header: "ArrayBuffer",
          message: "Received a resizable ArrayBuffer."
        });
      }
      return V3;
    };
    webidl.converters.TypedArray = function(V3, T2, prefix, name3, opts) {
      if (webidl.util.Type(V3) !== "Object" || !types7.isTypedArray(V3) || V3.constructor.name !== T2.name) {
        throw webidl.errors.conversionFailed({
          prefix,
          argument: `${name3} ("${webidl.util.Stringify(V3)}")`,
          types: [T2.name]
        });
      }
      if (opts?.allowShared === false && types7.isSharedArrayBuffer(V3.buffer)) {
        throw webidl.errors.exception({
          header: "ArrayBuffer",
          message: "SharedArrayBuffer is not allowed."
        });
      }
      if (V3.buffer.resizable || V3.buffer.growable) {
        throw webidl.errors.exception({
          header: "ArrayBuffer",
          message: "Received a resizable ArrayBuffer."
        });
      }
      return V3;
    };
    webidl.converters.DataView = function(V3, prefix, name3, opts) {
      if (webidl.util.Type(V3) !== "Object" || !types7.isDataView(V3)) {
        throw webidl.errors.exception({
          header: prefix,
          message: `${name3} is not a DataView.`
        });
      }
      if (opts?.allowShared === false && types7.isSharedArrayBuffer(V3.buffer)) {
        throw webidl.errors.exception({
          header: "ArrayBuffer",
          message: "SharedArrayBuffer is not allowed."
        });
      }
      if (V3.buffer.resizable || V3.buffer.growable) {
        throw webidl.errors.exception({
          header: "ArrayBuffer",
          message: "Received a resizable ArrayBuffer."
        });
      }
      return V3;
    };
    webidl.converters.BufferSource = function(V3, prefix, name3, opts) {
      if (types7.isAnyArrayBuffer(V3)) {
        return webidl.converters.ArrayBuffer(V3, prefix, name3, { ...opts, allowShared: false });
      }
      if (types7.isTypedArray(V3)) {
        return webidl.converters.TypedArray(V3, V3.constructor, prefix, name3, { ...opts, allowShared: false });
      }
      if (types7.isDataView(V3)) {
        return webidl.converters.DataView(V3, prefix, name3, { ...opts, allowShared: false });
      }
      throw webidl.errors.conversionFailed({
        prefix,
        argument: `${name3} ("${webidl.util.Stringify(V3)}")`,
        types: ["BufferSource"]
      });
    };
    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
    );
    module2.exports = {
      webidl
    };
  }
});

// packages/core/node_modules/undici/lib/web/fetch/util.js
var require_util2 = __commonJS({
  "packages/core/node_modules/undici/lib/web/fetch/util.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var { Transform: Transform2 } = __require("node:stream");
    var zlib4 = __require("node:zlib");
    var { redirectStatusSet, referrerPolicySet: referrerPolicyTokens, badPortsSet } = require_constants3();
    var { getGlobalOrigin } = require_global();
    var { collectASequenceOfCodePoints, collectAnHTTPQuotedString, removeChars, parseMIMEType } = require_data_url();
    var { performance: performance2 } = __require("node:perf_hooks");
    var { isBlobLike: isBlobLike3, ReadableStreamFrom: ReadableStreamFrom2, isValidHTTPToken, normalizedMethodRecordsBase } = require_util();
    var assert4 = __require("node:assert");
    var { isUint8Array } = __require("node:util/types");
    var { webidl } = require_webidl();
    var supportedHashes = [];
    var crypto14;
    try {
      crypto14 = __require("node:crypto");
      const possibleRelevantHashes = ["sha256", "sha384", "sha512"];
      supportedHashes = crypto14.getHashes().filter((hash) => possibleRelevantHashes.includes(hash));
    } catch {
    }
    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 i3 = 0; i3 < url2.length; ++i3) {
        const code2 = url2.charCodeAt(i3);
        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(object3) {
      return object3 instanceof Error || (object3?.constructor?.name === "Error" || object3?.constructor?.name === "DOMException");
    }
    __name(isErrorLike, "isErrorLike");
    function isValidReasonPhrase(statusText) {
      for (let i3 = 0; i3 < statusText.length; ++i3) {
        const c4 = statusText.charCodeAt(i3);
        if (!(c4 === 9 || // HTAB
        c4 >= 32 && c4 <= 126 || // SP / VCHAR
        c4 >= 128 && c4 <= 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 setRequestReferrerPolicyOnRedirect(request4, actualResponse) {
      const { headersList } = actualResponse;
      const policyHeader = (headersList.get("referrer-policy", true) ?? "").split(",");
      let policy = "";
      if (policyHeader.length > 0) {
        for (let i3 = policyHeader.length; i3 !== 0; i3--) {
          const token2 = policyHeader[i3 - 1].trim();
          if (referrerPolicyTokens.has(token2)) {
            policy = token2;
            break;
          }
        }
      }
      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 determineRequestsReferrer3(request4) {
      const policy = request4.referrerPolicy;
      assert4(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 (request4.referrer instanceof URL) {
        referrerSource = request4.referrer;
      }
      let referrerURL = stripURLForReferrer(referrerSource);
      const referrerOrigin = stripURLForReferrer(referrerSource, true);
      if (referrerURL.toString().length > 4096) {
        referrerURL = referrerOrigin;
      }
      const areSameOrigin = sameOrigin(request4, referrerURL);
      const isNonPotentiallyTrustWorthy = isURLPotentiallyTrustworthy(referrerURL) && !isURLPotentiallyTrustworthy(request4.url);
      switch (policy) {
        case "origin":
          return referrerOrigin != null ? referrerOrigin : stripURLForReferrer(referrerSource, true);
        case "unsafe-url":
          return referrerURL;
        case "same-origin":
          return areSameOrigin ? referrerOrigin : "no-referrer";
        case "origin-when-cross-origin":
          return areSameOrigin ? referrerURL : 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 "strict-origin":
        // eslint-disable-line
        /**
           * 1. If referrerURL is a potentially trustworthy URL and
           * request’s current URL is not a potentially trustworthy URL,
           * then return no referrer.
           * 2. Return referrerOrigin
          */
        case "no-referrer-when-downgrade":
        // eslint-disable-line
        /**
         * 1. If referrerURL is a potentially trustworthy URL and
         * request’s current URL is not a potentially trustworthy URL,
         * then return no referrer.
         * 2. Return referrerOrigin
        */
        default:
          return isNonPotentiallyTrustWorthy ? "no-referrer" : referrerOrigin;
      }
    }
    __name(determineRequestsReferrer3, "determineRequestsReferrer");
    function stripURLForReferrer(url2, originOnly) {
      assert4(url2 instanceof URL);
      url2 = new URL(url2);
      if (url2.protocol === "file:" || url2.protocol === "about:" || url2.protocol === "blank:") {
        return "no-referrer";
      }
      url2.username = "";
      url2.password = "";
      url2.hash = "";
      if (originOnly) {
        url2.pathname = "";
        url2.search = "";
      }
      return url2;
    }
    __name(stripURLForReferrer, "stripURLForReferrer");
    function isURLPotentiallyTrustworthy(url2) {
      if (!(url2 instanceof URL)) {
        return false;
      }
      if (url2.href === "about:blank" || url2.href === "about:srcdoc") {
        return true;
      }
      if (url2.protocol === "data:") return true;
      if (url2.protocol === "file:") return true;
      return isOriginPotentiallyTrustworthy3(url2.origin);
      function isOriginPotentiallyTrustworthy3(origin) {
        if (origin == null || origin === "null") return false;
        const originAsURL = new URL(origin);
        if (originAsURL.protocol === "https:" || originAsURL.protocol === "wss:") {
          return true;
        }
        if (/^127(?:\.[0-9]+){0,2}\.[0-9]+$|^\[(?:0*:)*?:?0*1\]$/.test(originAsURL.hostname) || (originAsURL.hostname === "localhost" || originAsURL.hostname.includes("localhost.")) || originAsURL.hostname.endsWith(".localhost")) {
          return true;
        }
        return false;
      }
      __name(isOriginPotentiallyTrustworthy3, "isOriginPotentiallyTrustworthy");
    }
    __name(isURLPotentiallyTrustworthy, "isURLPotentiallyTrustworthy");
    function bytesMatch(bytes, metadataList) {
      if (crypto14 === void 0) {
        return true;
      }
      const parsedMetadata = parseMetadata(metadataList);
      if (parsedMetadata === "no metadata") {
        return true;
      }
      if (parsedMetadata.length === 0) {
        return true;
      }
      const strongest = getStrongestMetadata(parsedMetadata);
      const metadata = filterMetadataListByAlgorithm(parsedMetadata, strongest);
      for (const item of metadata) {
        const algorithm = item.algo;
        const expectedValue = item.hash;
        let actualValue = crypto14.createHash(algorithm).update(bytes).digest("base64");
        if (actualValue[actualValue.length - 1] === "=") {
          if (actualValue[actualValue.length - 2] === "=") {
            actualValue = actualValue.slice(0, -2);
          } else {
            actualValue = actualValue.slice(0, -1);
          }
        }
        if (compareBase64Mixed(actualValue, expectedValue)) {
          return true;
        }
      }
      return false;
    }
    __name(bytesMatch, "bytesMatch");
    var parseHashWithOptions = /(?<algo>sha256|sha384|sha512)-((?<hash>[A-Za-z0-9+/]+|[A-Za-z0-9_-]+)={0,2}(?:\s|$)( +[!-~]*)?)?/i;
    function parseMetadata(metadata) {
      const result = [];
      let empty = true;
      for (const token2 of metadata.split(" ")) {
        empty = false;
        const parsedToken = parseHashWithOptions.exec(token2);
        if (parsedToken === null || parsedToken.groups === void 0 || parsedToken.groups.algo === void 0) {
          continue;
        }
        const algorithm = parsedToken.groups.algo.toLowerCase();
        if (supportedHashes.includes(algorithm)) {
          result.push(parsedToken.groups);
        }
      }
      if (empty === true) {
        return "no metadata";
      }
      return result;
    }
    __name(parseMetadata, "parseMetadata");
    function getStrongestMetadata(metadataList) {
      let algorithm = metadataList[0].algo;
      if (algorithm[3] === "5") {
        return algorithm;
      }
      for (let i3 = 1; i3 < metadataList.length; ++i3) {
        const metadata = metadataList[i3];
        if (metadata.algo[3] === "5") {
          algorithm = "sha512";
          break;
        } else if (algorithm[3] === "3") {
          continue;
        } else if (metadata.algo[3] === "3") {
          algorithm = "sha384";
        }
      }
      return algorithm;
    }
    __name(getStrongestMetadata, "getStrongestMetadata");
    function filterMetadataListByAlgorithm(metadataList, algorithm) {
      if (metadataList.length === 1) {
        return metadataList;
      }
      let pos2 = 0;
      for (let i3 = 0; i3 < metadataList.length; ++i3) {
        if (metadataList[i3].algo === algorithm) {
          metadataList[pos2++] = metadataList[i3];
        }
      }
      metadataList.length = pos2;
      return metadataList;
    }
    __name(filterMetadataListByAlgorithm, "filterMetadataListByAlgorithm");
    function compareBase64Mixed(actualValue, expectedValue) {
      if (actualValue.length !== expectedValue.length) {
        return false;
      }
      for (let i3 = 0; i3 < actualValue.length; ++i3) {
        if (actualValue[i3] !== expectedValue[i3]) {
          if (actualValue[i3] === "+" && expectedValue[i3] === "-" || actualValue[i3] === "/" && expectedValue[i3] === "_") {
            continue;
          }
          return false;
        }
      }
      return true;
    }
    __name(compareBase64Mixed, "compareBase64Mixed");
    function tryUpgradeRequestToAPotentiallyTrustworthyURL(request4) {
    }
    __name(tryUpgradeRequestToAPotentiallyTrustworthyURL, "tryUpgradeRequestToAPotentiallyTrustworthyURL");
    function sameOrigin(A4, B2) {
      if (A4.origin === B2.origin && A4.origin === "null") {
        return true;
      }
      if (A4.protocol === B2.protocol && A4.hostname === B2.hostname && A4.port === B2.port) {
        return true;
      }
      return false;
    }
    __name(sameOrigin, "sameOrigin");
    function createDeferredPromise() {
      let res;
      let rej;
      const promise = new Promise((resolve30, reject) => {
        res = resolve30;
        rej = reject;
      });
      return { promise, resolve: res, reject: rej };
    }
    __name(createDeferredPromise, "createDeferredPromise");
    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");
      }
      assert4(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, kind2) {
          this.#target = target;
          this.#kind = kind2;
          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 = this.#target[kInternalIterator];
          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, kind2) {
        return new FastIterableIterator(target, kind2);
      };
    }
    __name(createIterator, "createIterator");
    function iteratorMixin(name3, object3, 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, object3);
            return makeIterator(this, "key");
          }, "keys")
        },
        values: {
          writable: true,
          enumerable: true,
          configurable: true,
          value: /* @__PURE__ */ __name(function values() {
            webidl.brandCheck(this, object3);
            return makeIterator(this, "value");
          }, "values")
        },
        entries: {
          writable: true,
          enumerable: true,
          configurable: true,
          value: /* @__PURE__ */ __name(function entries() {
            webidl.brandCheck(this, object3);
            return makeIterator(this, "key+value");
          }, "entries")
        },
        forEach: {
          writable: true,
          enumerable: true,
          configurable: true,
          value: /* @__PURE__ */ __name(function forEach2(callbackfn, thisArg = globalThis) {
            webidl.brandCheck(this, object3);
            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(object3.prototype, {
        ...properties,
        [Symbol.iterator]: {
          writable: true,
          enumerable: false,
          configurable: true,
          value: properties.entries.value
        }
      });
    }
    __name(iteratorMixin, "iteratorMixin");
    async function fullyReadBody(body, processBody, processBodyError) {
      const successSteps = processBody;
      const errorSteps = processBodyError;
      let reader;
      try {
        reader = body.stream.getReader();
      } catch (e4) {
        errorSteps(e4);
        return;
      }
      try {
        successSteps(await readAllBytes(reader));
      } catch (e4) {
        errorSteps(e4);
      }
    }
    __name(fullyReadBody, "fullyReadBody");
    function isReadableStreamLike(stream2) {
      return stream2 instanceof ReadableStream || stream2[Symbol.toStringTag] === "ReadableStream" && typeof stream2.tee === "function";
    }
    __name(isReadableStreamLike, "isReadableStreamLike");
    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) {
      assert4(!invalidIsomorphicEncodeValueRegex.test(input));
      return input;
    }
    __name(isomorphicEncode, "isomorphicEncode");
    async function readAllBytes(reader) {
      const bytes = [];
      let byteLength = 0;
      while (true) {
        const { done, value: chunk } = await reader.read();
        if (done) {
          return Buffer.concat(bytes, byteLength);
        }
        if (!isUint8Array(chunk)) {
          throw new TypeError("Received non-Uint8Array chunk");
        }
        bytes.push(chunk);
        byteLength += chunk.length;
      }
    }
    __name(readAllBytes, "readAllBytes");
    function urlIsLocal(url2) {
      assert4("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) {
      assert4("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 ? zlib4.createInflate(this.#zlibOptions) : zlib4.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 {
            assert4(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,
      createDeferredPromise,
      ReadableStreamFrom: ReadableStreamFrom2,
      tryUpgradeRequestToAPotentiallyTrustworthyURL,
      clampAndCoarsenConnectionTimingInfo,
      coarsenedSharedCurrentTime,
      determineRequestsReferrer: determineRequestsReferrer3,
      makePolicyContainer,
      clonePolicyContainer,
      appendFetchMetadata,
      appendRequestOriginHeader,
      TAOCheck,
      corsCheck,
      crossOriginResourcePolicyCheck,
      createOpaqueTimingInfo,
      setRequestReferrerPolicyOnRedirect,
      isValidHTTPToken,
      requestBadPort,
      requestCurrentURL,
      responseURL,
      responseLocationURL,
      isBlobLike: isBlobLike3,
      isURLPotentiallyTrustworthy,
      isValidReasonPhrase,
      sameOrigin,
      normalizeMethod,
      serializeJavascriptValueToJSONString,
      iteratorMixin,
      createIterator,
      isValidHeaderName,
      isValidHeaderValue,
      isErrorLike,
      fullyReadBody,
      bytesMatch,
      isReadableStreamLike,
      readableStreamClose,
      isomorphicEncode,
      urlIsLocal,
      urlHasHttpsScheme,
      urlIsHttpHttpsScheme,
      readAllBytes,
      simpleRangeHeaderValue,
      buildContentRange,
      parseMetadata,
      createInflate,
      extractMimeType,
      getDecodeSplit,
      utf8DecodeBytes,
      environmentSettingsObject
    };
  }
});

// packages/core/node_modules/undici/lib/web/fetch/symbols.js
var require_symbols2 = __commonJS({
  "packages/core/node_modules/undici/lib/web/fetch/symbols.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    module2.exports = {
      kUrl: Symbol("url"),
      kHeaders: Symbol("headers"),
      kSignal: Symbol("signal"),
      kState: Symbol("state"),
      kDispatcher: Symbol("dispatcher")
    };
  }
});

// packages/core/node_modules/undici/lib/web/fetch/file.js
var require_file = __commonJS({
  "packages/core/node_modules/undici/lib/web/fetch/file.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var { Blob: Blob6, File: File6 } = __require("node:buffer");
    var { kState } = require_symbols2();
    var { webidl } = require_webidl();
    var FileLike = class _FileLike {
      static {
        __name(this, "FileLike");
      }
      constructor(blobLike, fileName, options2 = {}) {
        const n3 = fileName;
        const t5 = options2.type;
        const d2 = options2.lastModified ?? Date.now();
        this[kState] = {
          blobLike,
          name: n3,
          type: t5,
          lastModified: d2
        };
      }
      stream(...args) {
        webidl.brandCheck(this, _FileLike);
        return this[kState].blobLike.stream(...args);
      }
      arrayBuffer(...args) {
        webidl.brandCheck(this, _FileLike);
        return this[kState].blobLike.arrayBuffer(...args);
      }
      slice(...args) {
        webidl.brandCheck(this, _FileLike);
        return this[kState].blobLike.slice(...args);
      }
      text(...args) {
        webidl.brandCheck(this, _FileLike);
        return this[kState].blobLike.text(...args);
      }
      get size() {
        webidl.brandCheck(this, _FileLike);
        return this[kState].blobLike.size;
      }
      get type() {
        webidl.brandCheck(this, _FileLike);
        return this[kState].blobLike.type;
      }
      get name() {
        webidl.brandCheck(this, _FileLike);
        return this[kState].name;
      }
      get lastModified() {
        webidl.brandCheck(this, _FileLike);
        return this[kState].lastModified;
      }
      get [Symbol.toStringTag]() {
        return "File";
      }
    };
    webidl.converters.Blob = webidl.interfaceConverter(Blob6);
    function isFileLike4(object3) {
      return object3 instanceof File6 || object3 && (typeof object3.stream === "function" || typeof object3.arrayBuffer === "function") && object3[Symbol.toStringTag] === "File";
    }
    __name(isFileLike4, "isFileLike");
    module2.exports = { FileLike, isFileLike: isFileLike4 };
  }
});

// packages/core/node_modules/undici/lib/web/fetch/formdata.js
var require_formdata = __commonJS({
  "packages/core/node_modules/undici/lib/web/fetch/formdata.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var { isBlobLike: isBlobLike3, iteratorMixin } = require_util2();
    var { kState } = require_symbols2();
    var { kEnumerableProperty } = require_util();
    var { FileLike, isFileLike: isFileLike4 } = require_file();
    var { webidl } = require_webidl();
    var { File: NativeFile } = __require("node:buffer");
    var nodeUtil = __require("node:util");
    var File6 = globalThis.File ?? NativeFile;
    var FormData6 = class _FormData {
      static {
        __name(this, "FormData");
      }
      constructor(form) {
        webidl.util.markAsUncloneable(this);
        if (form !== void 0) {
          throw webidl.errors.conversionFailed({
            prefix: "FormData constructor",
            argument: "Argument 1",
            types: ["undefined"]
          });
        }
        this[kState] = [];
      }
      append(name3, value, filename = void 0) {
        webidl.brandCheck(this, _FormData);
        const prefix = "FormData.append";
        webidl.argumentLengthCheck(arguments, 2, prefix);
        if (arguments.length === 3 && !isBlobLike3(value)) {
          throw new TypeError(
            "Failed to execute 'append' on 'FormData': parameter 2 is not of type 'Blob'"
          );
        }
        name3 = webidl.converters.USVString(name3, prefix, "name");
        value = isBlobLike3(value) ? webidl.converters.Blob(value, prefix, "value", { strict: false }) : webidl.converters.USVString(value, prefix, "value");
        filename = arguments.length === 3 ? webidl.converters.USVString(filename, prefix, "filename") : void 0;
        const entry = makeEntry(name3, value, filename);
        this[kState].push(entry);
      }
      delete(name3) {
        webidl.brandCheck(this, _FormData);
        const prefix = "FormData.delete";
        webidl.argumentLengthCheck(arguments, 1, prefix);
        name3 = webidl.converters.USVString(name3, prefix, "name");
        this[kState] = this[kState].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, prefix, "name");
        const idx = this[kState].findIndex((entry) => entry.name === name3);
        if (idx === -1) {
          return null;
        }
        return this[kState][idx].value;
      }
      getAll(name3) {
        webidl.brandCheck(this, _FormData);
        const prefix = "FormData.getAll";
        webidl.argumentLengthCheck(arguments, 1, prefix);
        name3 = webidl.converters.USVString(name3, prefix, "name");
        return this[kState].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, prefix, "name");
        return this[kState].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);
        if (arguments.length === 3 && !isBlobLike3(value)) {
          throw new TypeError(
            "Failed to execute 'set' on 'FormData': parameter 2 is not of type 'Blob'"
          );
        }
        name3 = webidl.converters.USVString(name3, prefix, "name");
        value = isBlobLike3(value) ? webidl.converters.Blob(value, prefix, "name", { strict: false }) : webidl.converters.USVString(value, prefix, "name");
        filename = arguments.length === 3 ? webidl.converters.USVString(filename, prefix, "name") : void 0;
        const entry = makeEntry(name3, value, filename);
        const idx = this[kState].findIndex((entry2) => entry2.name === name3);
        if (idx !== -1) {
          this[kState] = [
            ...this[kState].slice(0, idx),
            entry,
            ...this[kState].slice(idx + 1).filter((entry2) => entry2.name !== name3)
          ];
        } else {
          this[kState].push(entry);
        }
      }
      [nodeUtil.inspect.custom](depth, options2) {
        const state = this[kState].reduce((a2, b2) => {
          if (a2[b2.name]) {
            if (Array.isArray(a2[b2.name])) {
              a2[b2.name].push(b2.value);
            } else {
              a2[b2.name] = [a2[b2.name], b2.value];
            }
          } else {
            a2[b2.name] = b2.value;
          }
          return a2;
        }, { __proto__: null });
        options2.depth ??= depth;
        options2.colors ??= true;
        const output = nodeUtil.formatWithOptions(options2, state);
        return `FormData ${output.slice(output.indexOf("]") + 2)}`;
      }
    };
    iteratorMixin("FormData", FormData6, kState, "name", "value");
    Object.defineProperties(FormData6.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 (!isFileLike4(value)) {
          value = value instanceof Blob ? new File6([value], "blob", { type: value.type }) : new FileLike(value, "blob", { type: value.type });
        }
        if (filename !== void 0) {
          const options2 = {
            type: value.type,
            lastModified: value.lastModified
          };
          value = value instanceof NativeFile ? new File6([value], filename, options2) : new FileLike(value, filename, options2);
        }
      }
      return { name: name3, value };
    }
    __name(makeEntry, "makeEntry");
    module2.exports = { FormData: FormData6, makeEntry };
  }
});

// packages/core/node_modules/undici/lib/web/fetch/formdata-parser.js
var require_formdata_parser = __commonJS({
  "packages/core/node_modules/undici/lib/web/fetch/formdata-parser.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var { isUSVString, bufferToLowerCasedHeaderName } = require_util();
    var { utf8DecodeBytes } = require_util2();
    var { HTTP_TOKEN_CODEPOINTS, isomorphicDecode } = require_data_url();
    var { isFileLike: isFileLike4 } = require_file();
    var { makeEntry } = require_formdata();
    var assert4 = __require("node:assert");
    var { File: NodeFile } = __require("node:buffer");
    var File6 = globalThis.File ?? NodeFile;
    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 i3 = 0; i3 < chars.length; ++i3) {
        if ((chars.charCodeAt(i3) & ~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 i3 = 0; i3 < length; ++i3) {
        const cp3 = boundary.charCodeAt(i3);
        if (!(cp3 >= 48 && cp3 <= 57 || cp3 >= 65 && cp3 <= 90 || cp3 >= 97 && cp3 <= 122 || cp3 === 39 || cp3 === 45 || cp3 === 95)) {
          return false;
        }
      }
      return true;
    }
    __name(validateBoundary, "validateBoundary");
    function multipartFormDataParser(input, mimeType) {
      assert4(mimeType !== "failure" && mimeType.essence === "multipart/form-data");
      const boundaryString = mimeType.parameters.get("boundary");
      if (boundaryString === void 0) {
        return "failure";
      }
      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 {
          return "failure";
        }
        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) {
          return "failure";
        }
        position.position += 2;
        const result = parseMultipartFormDataHeaders(input, position);
        if (result === "failure") {
          return "failure";
        }
        let { name: name3, filename, contentType, encoding } = result;
        position.position += 2;
        let body;
        {
          const boundaryIndex = input.indexOf(boundary.subarray(2), position.position);
          if (boundaryIndex === -1) {
            return "failure";
          }
          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) {
          return "failure";
        } else {
          position.position += 2;
        }
        let value;
        if (filename !== null) {
          contentType ??= "text/plain";
          if (!isAsciiString(contentType)) {
            contentType = "";
          }
          value = new File6([body], filename, { type: contentType });
        } else {
          value = utf8DecodeBytes(Buffer.from(body));
        }
        assert4(isUSVString(name3));
        assert4(typeof value === "string" && isUSVString(value) || isFileLike4(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) {
            return "failure";
          }
          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())) {
          return "failure";
        }
        if (input[position.position] !== 58) {
          return "failure";
        }
        position.position++;
        collectASequenceOfBytes(
          (char) => char === 32 || char === 9,
          input,
          position
        );
        switch (bufferToLowerCasedHeaderName(headerName)) {
          case "content-disposition": {
            name3 = filename = null;
            if (!bufferStartsWith(input, formDataNameBuffer, position)) {
              return "failure";
            }
            position.position += 17;
            name3 = parseMultipartFormDataName(input, position);
            if (name3 === null) {
              return "failure";
            }
            if (bufferStartsWith(input, filenameBuffer, position)) {
              let check2 = position.position + filenameBuffer.length;
              if (input[check2] === 42) {
                position.position += 1;
                check2 += 1;
              }
              if (input[check2] !== 61 || input[check2 + 1] !== 34) {
                return "failure";
              }
              position.position += 12;
              filename = parseMultipartFormDataName(input, position);
              if (filename === null) {
                return "failure";
              }
            }
            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) {
          return "failure";
        } else {
          position.position += 2;
        }
      }
    }
    __name(parseMultipartFormDataHeaders, "parseMultipartFormDataHeaders");
    function parseMultipartFormDataName(input, position) {
      assert4(input[position.position - 1] === 34);
      let name3 = collectASequenceOfBytes(
        (char) => char !== 10 && char !== 13 && char !== 34,
        input,
        position
      );
      if (input[position.position] !== 34) {
        return null;
      } 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 i3 = 0; i3 < start.length; i3++) {
        if (start[i3] !== buffer[position.position + i3]) {
          return false;
        }
      }
      return true;
    }
    __name(bufferStartsWith, "bufferStartsWith");
    module2.exports = {
      multipartFormDataParser,
      validateBoundary
    };
  }
});

// packages/core/node_modules/undici/lib/web/fetch/body.js
var require_body = __commonJS({
  "packages/core/node_modules/undici/lib/web/fetch/body.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var util3 = require_util();
    var {
      ReadableStreamFrom: ReadableStreamFrom2,
      isBlobLike: isBlobLike3,
      isReadableStreamLike,
      readableStreamClose,
      createDeferredPromise,
      fullyReadBody,
      extractMimeType,
      utf8DecodeBytes
    } = require_util2();
    var { FormData: FormData6 } = require_formdata();
    var { kState } = require_symbols2();
    var { webidl } = require_webidl();
    var { Blob: Blob6 } = __require("node:buffer");
    var assert4 = __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 random2;
    try {
      const crypto14 = __require("node:crypto");
      random2 = /* @__PURE__ */ __name((max) => crypto14.randomInt(0, max), "random");
    } catch {
      random2 = /* @__PURE__ */ __name((max) => Math.floor(Math.random(max)), "random");
    }
    var textEncoder = new TextEncoder();
    function noop8() {
    }
    __name(noop8, "noop");
    var hasFinalizationRegistry = globalThis.FinalizationRegistry && process.version.indexOf("v18") !== 0;
    var streamRegistry;
    if (hasFinalizationRegistry) {
      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(noop8);
        }
      });
    }
    function extractBody(object3, keepalive = false) {
      let stream2 = null;
      if (object3 instanceof ReadableStream) {
        stream2 = object3;
      } else if (isBlobLike3(object3)) {
        stream2 = object3.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"
        });
      }
      assert4(isReadableStreamLike(stream2));
      let action = null;
      let source2 = null;
      let length = null;
      let type = null;
      if (typeof object3 === "string") {
        source2 = object3;
        type = "text/plain;charset=UTF-8";
      } else if (object3 instanceof URLSearchParams) {
        source2 = object3.toString();
        type = "application/x-www-form-urlencoded;charset=UTF-8";
      } else if (isArrayBuffer(object3)) {
        source2 = new Uint8Array(object3.slice());
      } else if (ArrayBuffer.isView(object3)) {
        source2 = new Uint8Array(object3.buffer.slice(object3.byteOffset, object3.byteOffset + object3.byteLength));
      } else if (util3.isFormDataLike(object3)) {
        const boundary = `----formdata-undici-0${`${random2(1e11)}`.padStart(11, "0")}`;
        const prefix = `--${boundary}\r
Content-Disposition: form-data`;
        const escape7 = /* @__PURE__ */ __name((str2) => str2.replace(/\n/g, "%0A").replace(/\r/g, "%0D").replace(/"/g, "%22"), "escape");
        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 object3) {
          if (typeof value === "string") {
            const chunk2 = textEncoder.encode(prefix + `; name="${escape7(normalizeLinefeeds(name3))}"\r
\r
${normalizeLinefeeds(value)}\r
`);
            blobParts.push(chunk2);
            length += chunk2.byteLength;
          } else {
            const chunk2 = textEncoder.encode(`${prefix}; name="${escape7(normalizeLinefeeds(name3))}"` + (value.name ? `; filename="${escape7(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 = object3;
        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 (isBlobLike3(object3)) {
        source2 = object3;
        length = object3.size;
        if (object3.type) {
          type = object3.type;
        }
      } else if (typeof object3[Symbol.asyncIterator] === "function") {
        if (keepalive) {
          throw new TypeError("keepalive");
        }
        if (util3.isDisturbed(object3) || object3.locked) {
          throw new TypeError(
            "Response body object should not be disturbed or locked"
          );
        }
        stream2 = object3 instanceof ReadableStream ? object3 : ReadableStreamFrom2(object3);
      }
      if (typeof source2 === "string" || util3.isBuffer(source2)) {
        length = Buffer.byteLength(source2);
      }
      if (action != null) {
        let iterator;
        stream2 = new ReadableStream({
          async start() {
            iterator = action(object3)[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(object3, keepalive = false) {
      if (object3 instanceof ReadableStream) {
        assert4(!util3.isDisturbed(object3), "The body has already been consumed.");
        assert4(!object3.locked, "The stream is locked.");
      }
      return extractBody(object3, keepalive);
    }
    __name(safelyExtractBody, "safelyExtractBody");
    function cloneBody(instance, body) {
      const [out1, 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) {
      const methods = {
        blob() {
          return consumeBody3(this, (bytes) => {
            let mimeType = bodyMimeType(this);
            if (mimeType === null) {
              mimeType = "";
            } else if (mimeType) {
              mimeType = serializeAMimeType(mimeType);
            }
            return new Blob6([bytes], { type: mimeType });
          }, instance);
        },
        arrayBuffer() {
          return consumeBody3(this, (bytes) => {
            return new Uint8Array(bytes).buffer;
          }, instance);
        },
        text() {
          return consumeBody3(this, utf8DecodeBytes, instance);
        },
        json() {
          return consumeBody3(this, parseJSONFromBytes, instance);
        },
        formData() {
          return consumeBody3(this, (value) => {
            const mimeType = bodyMimeType(this);
            if (mimeType !== null) {
              switch (mimeType.essence) {
                case "multipart/form-data": {
                  const parsed = multipartFormDataParser(value, mimeType);
                  if (parsed === "failure") {
                    throw new TypeError("Failed to parse body as FormData.");
                  }
                  const fd = new FormData6();
                  fd[kState] = parsed;
                  return fd;
                }
                case "application/x-www-form-urlencoded": {
                  const entries = new URLSearchParams(value.toString());
                  const fd = new FormData6();
                  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);
        },
        bytes() {
          return consumeBody3(this, (bytes) => {
            return new Uint8Array(bytes);
          }, instance);
        }
      };
      return methods;
    }
    __name(bodyMixinMethods, "bodyMixinMethods");
    function mixinBody(prototype) {
      Object.assign(prototype.prototype, bodyMixinMethods(prototype));
    }
    __name(mixinBody, "mixinBody");
    async function consumeBody3(object3, convertBytesToJSValue, instance) {
      webidl.brandCheck(object3, instance);
      if (bodyUnusable(object3)) {
        throw new TypeError("Body is unusable: Body has already been read");
      }
      throwIfAborted(object3[kState]);
      const promise = createDeferredPromise();
      const errorSteps = /* @__PURE__ */ __name((error2) => promise.reject(error2), "errorSteps");
      const successSteps = /* @__PURE__ */ __name((data) => {
        try {
          promise.resolve(convertBytesToJSValue(data));
        } catch (e4) {
          errorSteps(e4);
        }
      }, "successSteps");
      if (object3[kState].body == null) {
        successSteps(Buffer.allocUnsafe(0));
        return promise.promise;
      }
      await fullyReadBody(object3[kState].body, successSteps, errorSteps);
      return promise.promise;
    }
    __name(consumeBody3, "consumeBody");
    function bodyUnusable(object3) {
      const body = object3[kState].body;
      return body != null && (body.stream.locked || util3.isDisturbed(body.stream));
    }
    __name(bodyUnusable, "bodyUnusable");
    function parseJSONFromBytes(bytes) {
      return JSON.parse(utf8DecodeBytes(bytes));
    }
    __name(parseJSONFromBytes, "parseJSONFromBytes");
    function bodyMimeType(requestOrResponse) {
      const headers = requestOrResponse[kState].headersList;
      const mimeType = extractMimeType(headers);
      if (mimeType === "failure") {
        return null;
      }
      return mimeType;
    }
    __name(bodyMimeType, "bodyMimeType");
    module2.exports = {
      extractBody,
      safelyExtractBody,
      cloneBody,
      mixinBody,
      streamRegistry,
      hasFinalizationRegistry,
      bodyUnusable
    };
  }
});

// packages/core/node_modules/undici/lib/dispatcher/client-h1.js
var require_client_h1 = __commonJS({
  "packages/core/node_modules/undici/lib/dispatcher/client-h1.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var assert4 = __require("node:assert");
    var util3 = 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
    } = require_symbols();
    var constants4 = require_constants2();
    var EMPTY_BUF = Buffer.alloc(0);
    var FastBuffer = Buffer[Symbol.species];
    var addListener = util3.addListener;
    var removeAllListeners = util3.removeAllListeners;
    var extractBody;
    async function lazyllhttp() {
      const llhttpWasmData = process.env.JEST_WORKER_ID ? require_llhttp_wasm() : void 0;
      let mod2;
      try {
        mod2 = await WebAssembly.compile(require_llhttp_simd_wasm());
      } catch (e4) {
        mod2 = await WebAssembly.compile(llhttpWasmData || require_llhttp_wasm());
      }
      return await WebAssembly.instantiate(mod2, {
        env: {
          /* eslint-disable camelcase */
          wasm_on_url: /* @__PURE__ */ __name((p2, at2, len) => {
            return 0;
          }, "wasm_on_url"),
          wasm_on_status: /* @__PURE__ */ __name((p2, at2, len) => {
            assert4(currentParser.ptr === p2);
            const start = at2 - currentBufferPtr + currentBufferRef.byteOffset;
            return currentParser.onStatus(new FastBuffer(currentBufferRef.buffer, start, len)) || 0;
          }, "wasm_on_status"),
          wasm_on_message_begin: /* @__PURE__ */ __name((p2) => {
            assert4(currentParser.ptr === p2);
            return currentParser.onMessageBegin() || 0;
          }, "wasm_on_message_begin"),
          wasm_on_header_field: /* @__PURE__ */ __name((p2, at2, len) => {
            assert4(currentParser.ptr === p2);
            const start = at2 - currentBufferPtr + currentBufferRef.byteOffset;
            return currentParser.onHeaderField(new FastBuffer(currentBufferRef.buffer, start, len)) || 0;
          }, "wasm_on_header_field"),
          wasm_on_header_value: /* @__PURE__ */ __name((p2, at2, len) => {
            assert4(currentParser.ptr === p2);
            const start = at2 - currentBufferPtr + currentBufferRef.byteOffset;
            return currentParser.onHeaderValue(new FastBuffer(currentBufferRef.buffer, start, len)) || 0;
          }, "wasm_on_header_value"),
          wasm_on_headers_complete: /* @__PURE__ */ __name((p2, statusCode, upgrade, shouldKeepAlive) => {
            assert4(currentParser.ptr === p2);
            return currentParser.onHeadersComplete(statusCode, Boolean(upgrade), Boolean(shouldKeepAlive)) || 0;
          }, "wasm_on_headers_complete"),
          wasm_on_body: /* @__PURE__ */ __name((p2, at2, len) => {
            assert4(currentParser.ptr === p2);
            const start = at2 - currentBufferPtr + currentBufferRef.byteOffset;
            return currentParser.onBody(new FastBuffer(currentBufferRef.buffer, start, len)) || 0;
          }, "wasm_on_body"),
          wasm_on_message_complete: /* @__PURE__ */ __name((p2) => {
            assert4(currentParser.ptr === p2);
            return currentParser.onMessageComplete() || 0;
          }, "wasm_on_message_complete")
          /* eslint-enable camelcase */
        }
      });
    }
    __name(lazyllhttp, "lazyllhttp");
    var llhttpInstance = null;
    var llhttpPromise = lazyllhttp();
    llhttpPromise.catch();
    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");
      }
      constructor(client, socket, { exports: exports3 }) {
        assert4(Number.isFinite(client[kMaxHeadersSize]) && client[kMaxHeadersSize] > 0);
        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 = null;
        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;
        }
        assert4(this.ptr != null);
        assert4(currentParser == null);
        this.llhttp.llhttp_resume(this.ptr);
        assert4(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);
        }
      }
      execute(data) {
        assert4(this.ptr != null);
        assert4(currentParser == null);
        assert4(!this.paused);
        const { socket, llhttp } = this;
        if (data.length > currentBufferSize) {
          if (currentBufferPtr) {
            llhttp.free(currentBufferPtr);
          }
          currentBufferSize = Math.ceil(data.length / 4096) * 4096;
          currentBufferPtr = llhttp.malloc(currentBufferSize);
        }
        new Uint8Array(llhttp.memory.buffer, currentBufferPtr, currentBufferSize).set(data);
        try {
          let ret;
          try {
            currentBufferRef = data;
            currentParser = this;
            ret = llhttp.llhttp_execute(this.ptr, currentBufferPtr, data.length);
          } catch (err) {
            throw err;
          } finally {
            currentParser = null;
            currentBufferRef = null;
          }
          const offset = llhttp.llhttp_get_error_pos(this.ptr) - currentBufferPtr;
          if (ret === constants4.ERROR.PAUSED_UPGRADE) {
            this.onUpgrade(data.slice(offset));
          } else if (ret === constants4.ERROR.PAUSED) {
            this.paused = true;
            socket.unshift(data.slice(offset));
          } else if (ret !== constants4.ERROR.OK) {
            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.slice(offset));
          }
        } catch (err) {
          util3.destroy(socket, err);
        }
      }
      destroy() {
        assert4(this.ptr != null);
        assert4(currentParser == 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;
      }
      onStatus(buf) {
        this.statusText = buf.toString();
      }
      onMessageBegin() {
        const { socket, client } = this;
        if (socket.destroyed) {
          return -1;
        }
        const request4 = client[kQueue][client[kRunningIdx]];
        if (!request4) {
          return -1;
        }
        request4.onResponseStarted();
      }
      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);
      }
      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 = util3.bufferToLowerCasedHeaderName(key);
          if (headerName === "keep-alive") {
            this.keepAlive += buf.toString();
          } else if (headerName === "connection") {
            this.connection += buf.toString();
          }
        } else if (key.length === 14 && util3.bufferToLowerCasedHeaderName(key) === "content-length") {
          this.contentLength += buf.toString();
        }
        this.trackHeader(buf.length);
      }
      trackHeader(len) {
        this.headersSize += len;
        if (this.headersSize >= this.headersMaxSize) {
          util3.destroy(this.socket, new HeadersOverflowError());
        }
      }
      onUpgrade(head) {
        const { upgrade, client, socket, headers, statusCode } = this;
        assert4(upgrade);
        assert4(client[kSocket] === socket);
        assert4(!socket.destroyed);
        assert4(!this.paused);
        assert4((headers.length & 1) === 0);
        const request4 = client[kQueue][client[kRunningIdx]];
        assert4(request4);
        assert4(request4.upgrade || request4.method === "CONNECT");
        this.statusCode = null;
        this.statusText = "";
        this.shouldKeepAlive = null;
        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) {
          util3.destroy(socket, err);
        }
        client[kResume]();
      }
      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;
        }
        assert4(!this.upgrade);
        assert4(this.statusCode < 200);
        if (statusCode === 100) {
          util3.destroy(socket, new SocketError("bad response", util3.getSocketInfo(socket)));
          return -1;
        }
        if (upgrade && !request4.upgrade) {
          util3.destroy(socket, new SocketError("bad upgrade", util3.getSocketInfo(socket)));
          return -1;
        }
        assert4(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") {
          assert4(client[kRunning] === 1);
          this.upgrade = true;
          return 2;
        }
        if (upgrade) {
          assert4(client[kRunning] === 1);
          this.upgrade = true;
          return 2;
        }
        assert4((this.headers.length & 1) === 0);
        this.headers = [];
        this.headersSize = 0;
        if (this.shouldKeepAlive && client[kPipelining]) {
          const keepAliveTimeout = this.keepAlive ? util3.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;
      }
      onBody(buf) {
        const { client, socket, statusCode, maxResponseSize } = this;
        if (socket.destroyed) {
          return -1;
        }
        const request4 = client[kQueue][client[kRunningIdx]];
        assert4(request4);
        assert4(this.timeoutType === TIMEOUT_BODY);
        if (this.timeout) {
          if (this.timeout.refresh) {
            this.timeout.refresh();
          }
        }
        assert4(statusCode >= 200);
        if (maxResponseSize > -1 && this.bytesRead + buf.length > maxResponseSize) {
          util3.destroy(socket, new ResponseExceededMaxSizeError());
          return -1;
        }
        this.bytesRead += buf.length;
        if (request4.onData(buf) === false) {
          return constants4.ERROR.PAUSED;
        }
      }
      onMessageComplete() {
        const { client, socket, statusCode, upgrade, headers, contentLength, bytesRead, shouldKeepAlive } = this;
        if (socket.destroyed && (!statusCode || shouldKeepAlive)) {
          return -1;
        }
        if (upgrade) {
          return;
        }
        assert4(statusCode >= 100);
        assert4((this.headers.length & 1) === 0);
        const request4 = client[kQueue][client[kRunningIdx]];
        assert4(request4);
        this.statusCode = null;
        this.statusText = "";
        this.bytesRead = 0;
        this.contentLength = "";
        this.keepAlive = "";
        this.connection = "";
        this.headers = [];
        this.headersSize = 0;
        if (statusCode < 200) {
          return;
        }
        if (request4.method !== "HEAD" && contentLength && bytesRead !== parseInt(contentLength, 10)) {
          util3.destroy(socket, new ResponseContentLengthMismatchError());
          return -1;
        }
        request4.onComplete(headers);
        client[kQueue][client[kRunningIdx]++] = null;
        if (socket[kWriting]) {
          assert4(client[kRunning] === 0);
          util3.destroy(socket, new InformationalError("reset"));
          return constants4.ERROR.PAUSED;
        } else if (!shouldKeepAlive) {
          util3.destroy(socket, new InformationalError("reset"));
          return constants4.ERROR.PAUSED;
        } else if (socket[kReset2] && client[kRunning] === 0) {
          util3.destroy(socket, new InformationalError("reset"));
          return constants4.ERROR.PAUSED;
        } else if (client[kPipelining] == null || client[kPipelining] === 1) {
          setImmediate(() => client[kResume]());
        } else {
          client[kResume]();
        }
      }
    };
    function onParserTimeout(parser6) {
      const { socket, timeoutType, client, paused } = parser6.deref();
      if (timeoutType === TIMEOUT_HEADERS) {
        if (!socket[kWriting] || socket.writableNeedDrain || client[kRunning] > 1) {
          assert4(!paused, "cannot be paused while waiting for headers");
          util3.destroy(socket, new HeadersTimeoutError());
        }
      } else if (timeoutType === TIMEOUT_BODY) {
        if (!paused) {
          util3.destroy(socket, new BodyTimeoutError());
        }
      } else if (timeoutType === TIMEOUT_KEEP_ALIVE) {
        assert4(client[kRunning] === 0 && client[kKeepAliveTimeoutValue]);
        util3.destroy(socket, new InformationalError("socket idle timeout"));
      }
    }
    __name(onParserTimeout, "onParserTimeout");
    async function connectH1(client, socket) {
      client[kSocket] = socket;
      if (!llhttpInstance) {
        llhttpInstance = await llhttpPromise;
        llhttpPromise = null;
      }
      socket[kNoRef] = false;
      socket[kWriting] = false;
      socket[kReset2] = false;
      socket[kBlocking] = false;
      socket[kParser] = new Parser4(client, socket, llhttpInstance);
      addListener(socket, "error", function(err) {
        assert4(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);
      });
      addListener(socket, "readable", function() {
        const parser6 = this[kParser];
        if (parser6) {
          parser6.readMore();
        }
      });
      addListener(socket, "end", function() {
        const parser6 = this[kParser];
        if (parser6.statusCode && !parser6.shouldKeepAlive) {
          parser6.onMessageComplete();
          return;
        }
        util3.destroy(this, new SocketError("other side closed", util3.getSocketInfo(this)));
      });
      addListener(socket, "close", function() {
        const client2 = this[kClient];
        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", util3.getSocketInfo(this));
        client2[kSocket] = null;
        client2[kHTTPContext] = null;
        if (client2.destroyed) {
          assert4(client2[kPending] === 0);
          const requests = client2[kQueue].splice(client2[kRunningIdx]);
          for (let i3 = 0; i3 < requests.length; i3++) {
            const request4 = requests[i3];
            util3.errorRequest(client2, request4, err);
          }
        } else if (client2[kRunning] > 0 && err.code !== "UND_ERR_INFO") {
          const request4 = client2[kQueue][client2[kRunningIdx]];
          client2[kQueue][client2[kRunningIdx]++] = null;
          util3.errorRequest(client2, request4, err);
        }
        client2[kPendingIdx] = client2[kRunningIdx];
        assert4(client2[kRunning] === 0);
        client2.emit("disconnect", client2[kUrl], [client2], err);
        client2[kResume]();
      });
      let closed = false;
      socket.on("close", () => {
        closed = true;
      });
      return {
        version: "h1",
        defaultPipelining: 1,
        write(...args) {
          return writeH1(client, ...args);
        },
        resume() {
          resumeH1(client);
        },
        destroy(err, callback) {
          if (closed) {
            queueMicrotask(callback);
          } else {
            socket.destroy(err).on("close", callback);
          }
        },
        get destroyed() {
          return socket.destroyed;
        },
        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 && util3.bodyLength(request4.body) !== 0 && (util3.isStream(request4.body) || util3.isAsyncIterable(request4.body) || util3.isFormDataLike(request4.body))) {
              return true;
            }
          }
          return false;
        }
      };
    }
    __name(connectH1, "connectH1");
    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: path125, 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 (util3.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 (util3.isBlobLike(body) && request4.contentType == null && body.type) {
        headers.push("content-type", body.type);
      }
      if (body && typeof body.read === "function") {
        body.read(0);
      }
      const bodyLength = util3.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]) {
          util3.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;
        }
        util3.errorRequest(client, request4, err || new RequestAbortedError());
        util3.destroy(body);
        util3.destroy(socket, new InformationalError("aborted"));
      }, "abort");
      try {
        request4.onConnect(abort);
      } catch (err) {
        util3.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} ${path125} 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 n3 = 0; n3 < headers.length; n3 += 2) {
          const key = headers[n3 + 0];
          const val = headers[n3 + 1];
          if (Array.isArray(val)) {
            for (let i3 = 0; i3 < val.length; i3++) {
              header += `${key}: ${val[i3]}\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 (util3.isBuffer(body)) {
        writeBuffer(abort, body, client, request4, socket, contentLength, header, expectsPayload);
      } else if (util3.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 (util3.isStream(body)) {
        writeStream(abort, body, client, request4, socket, contentLength, header, expectsPayload);
      } else if (util3.isIterable(body)) {
        writeIterable(abort, body, client, request4, socket, contentLength, header, expectsPayload);
      } else {
        assert4(false);
      }
      return true;
    }
    __name(writeH1, "writeH1");
    function writeStream(abort, body, client, request4, socket, contentLength, header, expectsPayload) {
      assert4(contentLength !== 0 || client[kRunning] === 0, "stream body cannot be pipelined");
      let finished2 = false;
      const writer = new AsyncWriter({ abort, socket, request: request4, contentLength, client, expectsPayload, header });
      const onData = /* @__PURE__ */ __name(function(chunk) {
        if (finished2) {
          return;
        }
        try {
          if (!writer.write(chunk) && this.pause) {
            this.pause();
          }
        } catch (err) {
          util3.destroy(this, err);
        }
      }, "onData");
      const onDrain = /* @__PURE__ */ __name(function() {
        if (finished2) {
          return;
        }
        if (body.resume) {
          body.resume();
        }
      }, "onDrain");
      const onClose = /* @__PURE__ */ __name(function() {
        queueMicrotask(() => {
          body.removeListener("error", onFinished);
        });
        if (!finished2) {
          const err = new RequestAbortedError();
          queueMicrotask(() => onFinished(err));
        }
      }, "onClose");
      const onFinished = /* @__PURE__ */ __name(function(err) {
        if (finished2) {
          return;
        }
        finished2 = true;
        assert4(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 (er2) {
            err = er2;
          }
        }
        writer.destroy(err);
        if (err && (err.code !== "UND_ERR_INFO" || err.message !== "reset")) {
          util3.destroy(body, err);
        } else {
          util3.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 {
            assert4(contentLength === null, "no body must not have content length");
            socket.write(`${header}\r
`, "latin1");
          }
        } else if (util3.isBuffer(body)) {
          assert4(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) {
      assert4(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) {
      assert4(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((resolve30, reject) => {
        assert4(callback === null);
        if (socket[kError]) {
          reject(socket[kError]);
        } else {
          callback = resolve30;
        }
      }), "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");
      }
      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;
      }
      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;
      }
      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]();
      }
      destroy(err) {
        const { socket, client, abort } = this;
        socket[kWriting] = false;
        if (err) {
          assert4(client[kRunning] <= 1, "pipeline should only contain this request");
          abort(err);
        }
      }
    };
    module2.exports = connectH1;
  }
});

// packages/core/node_modules/undici/lib/dispatcher/client-h2.js
var require_client_h2 = __commonJS({
  "packages/core/node_modules/undici/lib/dispatcher/client-h2.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var assert4 = __require("node:assert");
    var { pipeline: pipeline3 } = __require("node:stream");
    var util3 = 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
    } = require_symbols();
    var kOpenStreams = Symbol("open streams");
    var extractBody;
    var h2ExperimentalWarned = false;
    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;
      if (!h2ExperimentalWarned) {
        h2ExperimentalWarned = true;
        process.emitWarning("H2 support is experimental, expect them to change at any time.", {
          code: "UNDICI-H2"
        });
      }
      const session = http22.connect(client[kUrl], {
        createConnection: /* @__PURE__ */ __name(() => socket, "createConnection"),
        peerMaxConcurrentStreams: client[kMaxConcurrentStreams]
      });
      session[kOpenStreams] = 0;
      session[kClient] = client;
      session[kSocket] = socket;
      util3.addListener(session, "error", onHttp2SessionError);
      util3.addListener(session, "frameError", onHttp2FrameError);
      util3.addListener(session, "end", onHttp2SessionEnd);
      util3.addListener(session, "goaway", onHTTP2GoAway);
      util3.addListener(session, "close", function() {
        const { [kClient]: client2 } = this;
        const { [kSocket]: socket2 } = client2;
        const err = this[kSocket][kError] || this[kError] || new SocketError("closed", util3.getSocketInfo(socket2));
        client2[kHTTP2Session] = null;
        if (client2.destroyed) {
          assert4(client2[kPending] === 0);
          const requests = client2[kQueue].splice(client2[kRunningIdx]);
          for (let i3 = 0; i3 < requests.length; i3++) {
            const request4 = requests[i3];
            util3.errorRequest(client2, request4, err);
          }
        }
      });
      session.unref();
      client[kHTTP2Session] = session;
      socket[kHTTP2Session] = session;
      util3.addListener(socket, "error", function(err) {
        assert4(err.code !== "ERR_TLS_CERT_ALTNAME_INVALID");
        this[kError] = err;
        this[kClient][kOnError](err);
      });
      util3.addListener(socket, "end", function() {
        util3.destroy(this, new SocketError("other side closed", util3.getSocketInfo(this)));
      });
      util3.addListener(socket, "close", function() {
        const err = this[kError] || new SocketError("closed", util3.getSocketInfo(this));
        client[kSocket] = null;
        if (this[kHTTP2Session] != null) {
          this[kHTTP2Session].destroy(err);
        }
        client[kPendingIdx] = client[kRunningIdx];
        assert4(client[kRunning] === 0);
        client.emit("disconnect", client[kUrl], [client], err);
        client[kResume]();
      });
      let closed = false;
      socket.on("close", () => {
        closed = true;
      });
      return {
        version: "h2",
        defaultPipelining: Infinity,
        write(...args) {
          return writeH2(client, ...args);
        },
        resume() {
          resumeH2(client);
        },
        destroy(err, callback) {
          if (closed) {
            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) {
      assert4(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", util3.getSocketInfo(this[kSocket]));
      this.destroy(err);
      util3.destroy(this[kSocket], err);
    }
    __name(onHttp2SessionEnd, "onHttp2SessionEnd");
    function onHTTP2GoAway(code2) {
      const err = this[kError] || new SocketError(`HTTP/2: "GOAWAY" frame received with code ${code2}`, util3.getSocketInfo(this));
      const client = this[kClient];
      client[kSocket] = null;
      client[kHTTPContext] = null;
      if (this[kHTTP2Session] != null) {
        this[kHTTP2Session].destroy(err);
        this[kHTTP2Session] = null;
      }
      util3.destroy(this[kSocket], err);
      if (client[kRunningIdx] < client[kQueue].length) {
        const request4 = client[kQueue][client[kRunningIdx]];
        client[kQueue][client[kRunningIdx]++] = null;
        util3.errorRequest(client, request4, err);
        client[kPendingIdx] = client[kRunningIdx];
      }
      assert4(client[kRunning] === 0);
      client.emit("disconnect", client[kUrl], [client], err);
      client[kResume]();
    }
    __name(onHTTP2GoAway, "onHTTP2GoAway");
    function shouldSendContentLength(method) {
      return method !== "GET" && method !== "HEAD" && method !== "OPTIONS" && method !== "TRACE" && method !== "CONNECT";
    }
    __name(shouldSendContentLength, "shouldSendContentLength");
    function writeH2(client, request4) {
      const session = client[kHTTP2Session];
      const { method, path: path125, host, upgrade, expectContinue, signal, headers: reqHeaders } = request4;
      let { body } = request4;
      if (upgrade) {
        util3.errorRequest(client, request4, new Error("Upgrade not supported for H2"));
        return false;
      }
      const headers = {};
      for (let n3 = 0; n3 < reqHeaders.length; n3 += 2) {
        const key = reqHeaders[n3 + 0];
        const val = reqHeaders[n3 + 1];
        if (Array.isArray(val)) {
          for (let i3 = 0; i3 < val.length; i3++) {
            if (headers[key]) {
              headers[key] += `,${val[i3]}`;
            } else {
              headers[key] = val[i3];
            }
          }
        } else {
          headers[key] = val;
        }
      }
      let stream2;
      const { hostname: hostname4, port } = client[kUrl];
      headers[HTTP2_HEADER_AUTHORITY] = host || `${hostname4}${port ? `:${port}` : ""}`;
      headers[HTTP2_HEADER_METHOD] = method;
      const abort = /* @__PURE__ */ __name((err) => {
        if (request4.aborted || request4.completed) {
          return;
        }
        err = err || new RequestAbortedError();
        util3.errorRequest(client, request4, err);
        if (stream2 != null) {
          util3.destroy(stream2, err);
        }
        util3.destroy(body, err);
        client[kQueue][client[kRunningIdx]++] = null;
        client[kResume]();
      }, "abort");
      try {
        request4.onConnect(abort);
      } catch (err) {
        util3.errorRequest(client, request4, err);
      }
      if (request4.aborted) {
        return false;
      }
      if (method === "CONNECT") {
        session.ref();
        stream2 = session.request(headers, { endStream: false, signal });
        if (stream2.id && !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();
        });
        return true;
      }
      headers[HTTP2_HEADER_PATH] = path125;
      headers[HTTP2_HEADER_SCHEME] = "https";
      const expectsPayload = method === "PUT" || method === "POST" || method === "PATCH";
      if (body && typeof body.read === "function") {
        body.read(0);
      }
      let contentLength = util3.bodyLength(body);
      if (util3.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]) {
          util3.errorRequest(client, request4, new RequestContentLengthMismatchError());
          return false;
        }
        process.emitWarning(new RequestContentLengthMismatchError());
      }
      if (contentLength != null) {
        assert4(body, "no body must not have content length");
        headers[HTTP2_HEADER_CONTENT_LENGTH] = `${contentLength}`;
      }
      session.ref();
      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.once("response", (headers2) => {
        const { [HTTP2_HEADER_STATUS]: statusCode, ...realHeaders } = headers2;
        request4.onResponseStarted();
        if (request4.aborted) {
          const err = new RequestAbortedError();
          util3.errorRequest(client, request4, err);
          util3.destroy(stream2, err);
          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", () => {
        if (stream2.state?.state == null || stream2.state.state < 6) {
          request4.onComplete([]);
        }
        if (session[kOpenStreams] === 0) {
          session.unref();
        }
        abort(new InformationalError("HTTP/2: stream half-closed (remote)"));
        client[kQueue][client[kRunningIdx]++] = null;
        client[kPendingIdx] = client[kRunningIdx];
        client[kResume]();
      });
      stream2.once("close", () => {
        session[kOpenStreams] -= 1;
        if (session[kOpenStreams] === 0) {
          session.unref();
        }
      });
      stream2.once("error", function(err) {
        abort(err);
      });
      stream2.once("frameError", (type, code2) => {
        abort(new InformationalError(`HTTP/2: "frameError" received - type ${type}, code ${code2}`));
      });
      return true;
      function writeBodyH2() {
        if (!body || contentLength === 0) {
          writeBuffer(
            abort,
            stream2,
            null,
            client,
            request4,
            client[kSocket],
            contentLength,
            expectsPayload
          );
        } else if (util3.isBuffer(body)) {
          writeBuffer(
            abort,
            stream2,
            body,
            client,
            request4,
            client[kSocket],
            contentLength,
            expectsPayload
          );
        } else if (util3.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 (util3.isStream(body)) {
          writeStream(
            abort,
            client[kSocket],
            expectsPayload,
            stream2,
            body,
            client,
            request4,
            contentLength
          );
        } else if (util3.isIterable(body)) {
          writeIterable(
            abort,
            stream2,
            body,
            client,
            request4,
            client[kSocket],
            contentLength,
            expectsPayload
          );
        } else {
          assert4(false);
        }
      }
      __name(writeBodyH2, "writeBodyH2");
    }
    __name(writeH2, "writeH2");
    function writeBuffer(abort, h2stream, body, client, request4, socket, contentLength, expectsPayload) {
      try {
        if (body != null && util3.isBuffer(body)) {
          assert4(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 (error2) {
        abort(error2);
      }
    }
    __name(writeBuffer, "writeBuffer");
    function writeStream(abort, socket, expectsPayload, h2stream, body, client, request4, contentLength) {
      assert4(contentLength !== 0 || client[kRunning] === 0, "stream body cannot be pipelined");
      const pipe2 = pipeline3(
        body,
        h2stream,
        (err) => {
          if (err) {
            util3.destroy(pipe2, err);
            abort(err);
          } else {
            util3.removeAllListeners(pipe2);
            request4.onRequestSent();
            if (!expectsPayload) {
              socket[kReset2] = true;
            }
            client[kResume]();
          }
        }
      );
      util3.addListener(pipe2, "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) {
      assert4(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) {
      assert4(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((resolve30, reject) => {
        assert4(callback === null);
        if (socket[kError]) {
          reject(socket[kError]);
        } else {
          callback = resolve30;
        }
      }), "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;
  }
});

// packages/core/node_modules/undici/lib/handler/redirect-handler.js
var require_redirect_handler = __commonJS({
  "packages/core/node_modules/undici/lib/handler/redirect-handler.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var util3 = require_util();
    var { kBodyUsed } = require_symbols();
    var assert4 = __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 BodyAsyncIterable = class {
      static {
        __name(this, "BodyAsyncIterable");
      }
      constructor(body) {
        this[kBody] = body;
        this[kBodyUsed] = false;
      }
      async *[Symbol.asyncIterator]() {
        assert4(!this[kBodyUsed], "disturbed");
        this[kBodyUsed] = true;
        yield* this[kBody];
      }
    };
    var RedirectHandler = class {
      static {
        __name(this, "RedirectHandler");
      }
      constructor(dispatch, maxRedirections, opts, handler) {
        if (maxRedirections != null && (!Number.isInteger(maxRedirections) || maxRedirections < 0)) {
          throw new InvalidArgumentError("maxRedirections must be a positive number");
        }
        util3.validateHandler(handler, opts.method, opts.upgrade);
        this.dispatch = dispatch;
        this.location = null;
        this.abort = null;
        this.opts = { ...opts, maxRedirections: 0 };
        this.maxRedirections = maxRedirections;
        this.handler = handler;
        this.history = [];
        this.redirectionLimitReached = false;
        if (util3.isStream(this.opts.body)) {
          if (util3.bodyLength(this.opts.body) === 0) {
            this.opts.body.on("data", function() {
              assert4(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) && util3.isIterable(this.opts.body)) {
          this.opts.body = new BodyAsyncIterable(this.opts.body);
        }
      }
      onConnect(abort) {
        this.abort = abort;
        this.handler.onConnect(abort, { history: this.history });
      }
      onUpgrade(statusCode, headers, socket) {
        this.handler.onUpgrade(statusCode, headers, socket);
      }
      onError(error2) {
        this.handler.onError(error2);
      }
      onHeaders(statusCode, headers, resume, statusText) {
        this.location = this.history.length >= this.maxRedirections || util3.isDisturbed(this.opts.body) ? null : parseLocation(statusCode, headers);
        if (this.opts.throwOnMaxRedirect && this.history.length >= this.maxRedirections) {
          if (this.request) {
            this.request.abort(new Error("max redirects"));
          }
          this.redirectionLimitReached = true;
          this.abort(new Error("max redirects"));
          return;
        }
        if (this.opts.origin) {
          this.history.push(new URL(this.opts.path, this.opts.origin));
        }
        if (!this.location) {
          return this.handler.onHeaders(statusCode, headers, resume, statusText);
        }
        const { origin, pathname, search } = util3.parseURL(new URL(this.location, this.opts.origin && new URL(this.opts.path, this.opts.origin)));
        const path125 = search ? `${pathname}${search}` : pathname;
        this.opts.headers = cleanRequestHeaders(this.opts.headers, statusCode === 303, this.opts.origin !== origin);
        this.opts.path = path125;
        this.opts.origin = origin;
        this.opts.maxRedirections = 0;
        this.opts.query = null;
        if (statusCode === 303 && this.opts.method !== "HEAD") {
          this.opts.method = "GET";
          this.opts.body = null;
        }
      }
      onData(chunk) {
        if (this.location) {
        } else {
          return this.handler.onData(chunk);
        }
      }
      onComplete(trailers) {
        if (this.location) {
          this.location = null;
          this.abort = null;
          this.dispatch(this.opts, this);
        } else {
          this.handler.onComplete(trailers);
        }
      }
      onBodySent(chunk) {
        if (this.handler.onBodySent) {
          this.handler.onBodySent(chunk);
        }
      }
    };
    function parseLocation(statusCode, headers) {
      if (redirectableStatusCodes.indexOf(statusCode) === -1) {
        return null;
      }
      for (let i3 = 0; i3 < headers.length; i3 += 2) {
        if (headers[i3].length === 8 && util3.headerNameToString(headers[i3]) === "location") {
          return headers[i3 + 1];
        }
      }
    }
    __name(parseLocation, "parseLocation");
    function shouldRemoveHeader(header, removeContent, unknownOrigin) {
      if (header.length === 4) {
        return util3.headerNameToString(header) === "host";
      }
      if (removeContent && util3.headerNameToString(header).startsWith("content-")) {
        return true;
      }
      if (unknownOrigin && (header.length === 13 || header.length === 6 || header.length === 19)) {
        const name3 = util3.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 i3 = 0; i3 < headers.length; i3 += 2) {
          if (!shouldRemoveHeader(headers[i3], removeContent, unknownOrigin)) {
            ret.push(headers[i3], headers[i3 + 1]);
          }
        }
      } else if (headers && typeof headers === "object") {
        for (const key of Object.keys(headers)) {
          if (!shouldRemoveHeader(key, removeContent, unknownOrigin)) {
            ret.push(key, headers[key]);
          }
        }
      } else {
        assert4(headers == null, "headers must be an object or an array");
      }
      return ret;
    }
    __name(cleanRequestHeaders, "cleanRequestHeaders");
    module2.exports = RedirectHandler;
  }
});

// packages/core/node_modules/undici/lib/interceptor/redirect-interceptor.js
var require_redirect_interceptor = __commonJS({
  "packages/core/node_modules/undici/lib/interceptor/redirect-interceptor.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 } = opts;
          if (!maxRedirections) {
            return dispatch(opts, handler);
          }
          const redirectHandler = new RedirectHandler(dispatch, maxRedirections, opts, handler);
          opts = { ...opts, maxRedirections: 0 };
          return dispatch(opts, redirectHandler);
        }, "Intercept");
      };
    }
    __name(createRedirectInterceptor, "createRedirectInterceptor");
    module2.exports = createRedirectInterceptor;
  }
});

// packages/core/node_modules/undici/lib/dispatcher/client.js
var require_client = __commonJS({
  "packages/core/node_modules/undici/lib/dispatcher/client.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var assert4 = __require("node:assert");
    var net2 = __require("node:net");
    var http7 = __require("node:http");
    var util3 = require_util();
    var { channels } = require_diagnostics();
    var Request6 = 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,
      kMaxRedirections,
      kMaxRequests,
      kCounter,
      kClose,
      kDestroy,
      kDispatch,
      kInterceptors,
      kLocalAddress,
      kMaxResponseSize,
      kOnError,
      kHTTPContext,
      kMaxConcurrentStreams,
      kResume
    } = require_symbols();
    var connectH1 = require_client_h1();
    var connectH2 = require_client_h2();
    var deprecatedInterceptorWarned = false;
    var kClosedResolve = Symbol("kClosedResolve");
    var noop8 = /* @__PURE__ */ __name(() => {
    }, "noop");
    function getPipelining(client) {
      return client[kPipelining] ?? client[kHTTPContext]?.defaultPipelining ?? 1;
    }
    __name(getPipelining, "getPipelining");
    var Client3 = class extends DispatcherBase {
      static {
        __name(this, "Client");
      }
      /**
       *
       * @param {string|URL} url
       * @param {import('../../types/client.js').Client.Options} options
       */
      constructor(url2, {
        interceptors,
        maxHeaderSize,
        headersTimeout,
        socketTimeout,
        requestTimeout,
        connectTimeout,
        bodyTimeout,
        idleTimeout,
        keepAlive,
        keepAliveTimeout,
        maxKeepAliveTimeout,
        keepAliveMaxTimeout,
        keepAliveTimeoutThreshold,
        socketPath,
        pipelining,
        tls,
        strictContentLength,
        maxCachedSessions,
        maxRedirections,
        connect: connect2,
        maxRequestsPerClient,
        localAddress,
        maxResponseSize,
        autoSelectFamily,
        autoSelectFamilyAttemptTimeout,
        // h2
        maxConcurrentStreams,
        allowH2
      } = {}) {
        super();
        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 && !Number.isFinite(maxHeaderSize)) {
          throw new InvalidArgumentError("invalid maxHeaderSize");
        }
        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 (maxRedirections != null && (!Number.isInteger(maxRedirections) || maxRedirections < 0)) {
          throw new InvalidArgumentError("maxRedirections must be a positive number");
        }
        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");
        }
        if (typeof connect2 !== "function") {
          connect2 = buildConnector({
            ...tls,
            maxCachedSessions,
            allowH2,
            socketPath,
            timeout: connectTimeout,
            ...autoSelectFamily ? { autoSelectFamily, autoSelectFamilyAttemptTimeout } : void 0,
            ...connect2
          });
        }
        if (interceptors?.Client && Array.isArray(interceptors.Client)) {
          this[kInterceptors] = interceptors.Client;
          if (!deprecatedInterceptorWarned) {
            deprecatedInterceptorWarned = true;
            process.emitWarning("Client.Options#interceptor is deprecated. Use Dispatcher#compose instead.", {
              code: "UNDICI-CLIENT-INTERCEPTOR-DEPRECATED"
            });
          }
        } else {
          this[kInterceptors] = [createRedirectInterceptor({ maxRedirections })];
        }
        this[kUrl] = util3.parseOrigin(url2);
        this[kConnector] = connect2;
        this[kPipelining] = pipelining != null ? pipelining : 1;
        this[kMaxHeadersSize] = maxHeaderSize || http7.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[kMaxRedirections] = maxRedirections;
        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 [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 Request6(origin, opts, handler);
        this[kQueue].push(request4);
        if (this[kResuming]) {
        } else if (util3.bodyLength(request4.body) == null && util3.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((resolve30) => {
          if (this[kSize]) {
            this[kClosedResolve] = resolve30;
          } else {
            resolve30(null);
          }
        });
      }
      async [kDestroy](err) {
        return new Promise((resolve30) => {
          const requests = this[kQueue].splice(this[kPendingIdx]);
          for (let i3 = 0; i3 < requests.length; i3++) {
            const request4 = requests[i3];
            util3.errorRequest(this, request4, err);
          }
          const callback = /* @__PURE__ */ __name(() => {
            if (this[kClosedResolve]) {
              this[kClosedResolve]();
              this[kClosedResolve] = null;
            }
            resolve30(null);
          }, "callback");
          if (this[kHTTPContext]) {
            this[kHTTPContext].destroy(err, callback);
            this[kHTTPContext] = null;
          } else {
            queueMicrotask(callback);
          }
          this[kResume]();
        });
      }
    };
    var createRedirectInterceptor = require_redirect_interceptor();
    function onError2(client, err) {
      if (client[kRunning] === 0 && err.code !== "UND_ERR_INFO" && err.code !== "UND_ERR_SOCKET") {
        assert4(client[kPendingIdx] === client[kRunningIdx]);
        const requests = client[kQueue].splice(client[kRunningIdx]);
        for (let i3 = 0; i3 < requests.length; i3++) {
          const request4 = requests[i3];
          util3.errorRequest(client, request4, err);
        }
        assert4(client[kSize] === 0);
      }
    }
    __name(onError2, "onError");
    async function connect(client) {
      assert4(!client[kConnecting]);
      assert4(!client[kHTTPContext]);
      let { host, hostname: hostname4, protocol, port } = client[kUrl];
      if (hostname4[0] === "[") {
        const idx = hostname4.indexOf("]");
        assert4(idx !== -1);
        const ip = hostname4.substring(1, idx);
        assert4(net2.isIP(ip));
        hostname4 = ip;
      }
      client[kConnecting] = true;
      if (channels.beforeConnect.hasSubscribers) {
        channels.beforeConnect.publish({
          connectParams: {
            host,
            hostname: hostname4,
            protocol,
            port,
            version: client[kHTTPContext]?.version,
            servername: client[kServerName],
            localAddress: client[kLocalAddress]
          },
          connector: client[kConnector]
        });
      }
      try {
        const socket = await new Promise((resolve30, reject) => {
          client[kConnector]({
            host,
            hostname: hostname4,
            protocol,
            port,
            servername: client[kServerName],
            localAddress: client[kLocalAddress]
          }, (err, socket2) => {
            if (err) {
              reject(err);
            } else {
              resolve30(socket2);
            }
          });
        });
        if (client.destroyed) {
          util3.destroy(socket.on("error", noop8), new ClientDestroyedError());
          return;
        }
        assert4(socket);
        try {
          client[kHTTPContext] = socket.alpnProtocol === "h2" ? await connectH2(client, socket) : await connectH1(client, socket);
        } catch (err) {
          socket.destroy().on("error", noop8);
          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: hostname4,
              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: hostname4,
              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") {
          assert4(client[kRunning] === 0);
          while (client[kPending] > 0 && client[kQueue][client[kPendingIdx]].servername === client[kServerName]) {
            const request4 = client[kQueue][client[kPendingIdx]++];
            util3.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) {
          assert4(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 = Client3;
  }
});

// packages/core/node_modules/undici/lib/dispatcher/fixed-queue.js
var require_fixed_queue = __commonJS({
  "packages/core/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);
        this.next = null;
      }
      isEmpty() {
        return this.top === this.bottom;
      }
      isFull() {
        return (this.top + 1 & kMask) === this.bottom;
      }
      push(data) {
        this.list[this.top] = data;
        this.top = this.top + 1 & kMask;
      }
      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();
      }
      isEmpty() {
        return this.head.isEmpty();
      }
      push(data) {
        if (this.head.isFull()) {
          this.head = this.head.next = new FixedCircularBuffer();
        }
        this.head.push(data);
      }
      shift() {
        const tail = this.tail;
        const next = tail.shift();
        if (tail.isEmpty() && tail.next !== null) {
          this.tail = tail.next;
        }
        return next;
      }
    };
  }
});

// packages/core/node_modules/undici/lib/dispatcher/pool-stats.js
var require_pool_stats = __commonJS({
  "packages/core/node_modules/undici/lib/dispatcher/pool-stats.js"(exports2, module2) {
    init_esbuild_shims();
    var { kFree, kConnected, kPending, kQueued, kRunning, kSize } = require_symbols();
    var kPool = Symbol("pool");
    var PoolStats = class {
      static {
        __name(this, "PoolStats");
      }
      constructor(pool) {
        this[kPool] = pool;
      }
      get connected() {
        return this[kPool][kConnected];
      }
      get free() {
        return this[kPool][kFree];
      }
      get pending() {
        return this[kPool][kPending];
      }
      get queued() {
        return this[kPool][kQueued];
      }
      get running() {
        return this[kPool][kRunning];
      }
      get size() {
        return this[kPool][kSize];
      }
    };
    module2.exports = PoolStats;
  }
});

// packages/core/node_modules/undici/lib/dispatcher/pool-base.js
var require_pool_base = __commonJS({
  "packages/core/node_modules/undici/lib/dispatcher/pool-base.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    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 PoolStats = require_pool_stats();
    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 kStats = Symbol("stats");
    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((c4) => c4.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);
        };
        this[kStats] = new PoolStats(this);
      }
      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 this[kStats];
      }
      async [kClose]() {
        if (this[kQueue].isEmpty()) {
          await Promise.all(this[kClients].map((c4) => c4.close()));
        } else {
          await new Promise((resolve30) => {
            this[kClosedResolve] = resolve30;
          });
        }
      }
      async [kDestroy](err) {
        while (true) {
          const item = this[kQueue].shift();
          if (!item) {
            break;
          }
          item.handler.onError(err);
        }
        await Promise.all(this[kClients].map((c4) => c4.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
    };
  }
});

// packages/core/node_modules/undici/lib/dispatcher/pool.js
var require_pool = __commonJS({
  "packages/core/node_modules/undici/lib/dispatcher/pool.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var {
      PoolBase,
      kClients,
      kNeedDrain,
      kAddClient,
      kGetDispatcher
    } = require_pool_base();
    var Client3 = require_client();
    var {
      InvalidArgumentError
    } = require_errors();
    var util3 = require_util();
    var { kUrl, kInterceptors } = require_symbols();
    var buildConnector = require_connect();
    var kOptions = Symbol("options");
    var kConnections = Symbol("connections");
    var kFactory = Symbol("factory");
    function defaultFactory(origin, opts) {
      return new Client3(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,
        ...options2
      } = {}) {
        super();
        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");
        }
        if (typeof connect !== "function") {
          connect = buildConnector({
            ...tls,
            maxCachedSessions,
            allowH2,
            socketPath,
            timeout: connectTimeout,
            ...autoSelectFamily ? { autoSelectFamily, autoSelectFamilyAttemptTimeout } : void 0,
            ...connect
          });
        }
        this[kInterceptors] = options2.interceptors?.Pool && Array.isArray(options2.interceptors.Pool) ? options2.interceptors.Pool : [];
        this[kConnections] = connections || null;
        this[kUrl] = util3.parseOrigin(origin);
        this[kOptions] = { ...util3.deepClone(options2), connect, allowH2 };
        this[kOptions].interceptors = options2.interceptors ? { ...options2.interceptors } : void 0;
        this[kFactory] = factory;
        this.on("connectionError", (origin2, targets, error2) => {
          for (const target of targets) {
            const idx = this[kClients].indexOf(target);
            if (idx !== -1) {
              this[kClients].splice(idx, 1);
            }
          }
        });
      }
      [kGetDispatcher]() {
        for (const client of this[kClients]) {
          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;
  }
});

// packages/core/node_modules/undici/lib/dispatcher/balanced-pool.js
var require_balanced_pool = __commonJS({
  "packages/core/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, kInterceptors } = 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(a2, b2) {
      if (a2 === 0) return b2;
      while (b2 !== 0) {
        const t5 = b2;
        b2 = a2 % b2;
        a2 = t5;
      }
      return a2;
    }
    __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 } = {}) {
        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];
        }
        if (typeof factory !== "function") {
          throw new InvalidArgumentError("factory must be a function.");
        }
        this[kInterceptors] = opts.interceptors?.BalancedPool && Array.isArray(opts.interceptors.BalancedPool) ? opts.interceptors.BalancedPool : [];
        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 i3 = 0; i3 < this[kClients].length; i3++) {
          result = getGreatestCommonDivisor(this[kClients][i3][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((p2) => p2[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((a2, b2) => a2 && b2, 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;
  }
});

// packages/core/node_modules/undici/lib/dispatcher/agent.js
var require_agent = __commonJS({
  "packages/core/node_modules/undici/lib/dispatcher/agent.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var { InvalidArgumentError } = require_errors();
    var { kClients, kRunning, kClose, kDestroy, kDispatch, kInterceptors } = require_symbols();
    var DispatcherBase = require_dispatcher_base();
    var Pool = require_pool();
    var Client3 = require_client();
    var util3 = require_util();
    var createRedirectInterceptor = require_redirect_interceptor();
    var kOnConnect = Symbol("onConnect");
    var kOnDisconnect = Symbol("onDisconnect");
    var kOnConnectionError = Symbol("onConnectionError");
    var kMaxRedirections = Symbol("maxRedirections");
    var kOnDrain = Symbol("onDrain");
    var kFactory = Symbol("factory");
    var kOptions = Symbol("options");
    function defaultFactory(origin, opts) {
      return opts && opts.connections === 1 ? new Client3(origin, opts) : new Pool(origin, opts);
    }
    __name(defaultFactory, "defaultFactory");
    var Agent4 = class extends DispatcherBase {
      static {
        __name(this, "Agent");
      }
      constructor({ factory = defaultFactory, maxRedirections = 0, connect, ...options2 } = {}) {
        super();
        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");
        }
        if (!Number.isInteger(maxRedirections) || maxRedirections < 0) {
          throw new InvalidArgumentError("maxRedirections must be a positive number");
        }
        if (connect && typeof connect !== "function") {
          connect = { ...connect };
        }
        this[kInterceptors] = options2.interceptors?.Agent && Array.isArray(options2.interceptors.Agent) ? options2.interceptors.Agent : [createRedirectInterceptor({ maxRedirections })];
        this[kOptions] = { ...util3.deepClone(options2), connect };
        this[kOptions].interceptors = options2.interceptors ? { ...options2.interceptors } : void 0;
        this[kMaxRedirections] = maxRedirections;
        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 client of this[kClients].values()) {
          ret += client[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.");
        }
        let dispatcher = this[kClients].get(key);
        if (!dispatcher) {
          dispatcher = this[kFactory](opts.origin, this[kOptions]).on("drain", this[kOnDrain]).on("connect", this[kOnConnect]).on("disconnect", this[kOnDisconnect]).on("connectionError", this[kOnConnectionError]);
          this[kClients].set(key, dispatcher);
        }
        return dispatcher.dispatch(opts, handler);
      }
      async [kClose]() {
        const closePromises = [];
        for (const client of this[kClients].values()) {
          closePromises.push(client.close());
        }
        this[kClients].clear();
        await Promise.all(closePromises);
      }
      async [kDestroy](err) {
        const destroyPromises = [];
        for (const client of this[kClients].values()) {
          destroyPromises.push(client.destroy(err));
        }
        this[kClients].clear();
        await Promise.all(destroyPromises);
      }
    };
    module2.exports = Agent4;
  }
});

// packages/core/node_modules/undici/lib/dispatcher/proxy-agent.js
var require_proxy_agent = __commonJS({
  "packages/core/node_modules/undici/lib/dispatcher/proxy-agent.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var { kProxy, kClose, kDestroy, kDispatch, kInterceptors } = require_symbols();
    var { URL: URL5 } = __require("node:url");
    var Agent4 = require_agent();
    var Pool = require_pool();
    var DispatcherBase = require_dispatcher_base();
    var { InvalidArgumentError, RequestAbortedError, SecureProxyConnectionError } = require_errors();
    var buildConnector = require_connect();
    var Client3 = 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 noop8 = /* @__PURE__ */ __name(() => {
    }, "noop");
    function defaultAgentFactory(origin, opts) {
      if (opts.connections === 1) {
        return new Client3(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 Client3(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: path125 = "/",
          headers = {}
        } = opts;
        opts.path = origin + path125;
        if (!("host" in headers) && !("Host" in headers)) {
          const { host } = new URL5(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 ProxyAgent6 = class extends DispatcherBase {
      static {
        __name(this, "ProxyAgent");
      }
      constructor(opts) {
        super();
        if (!opts || typeof opts === "object" && !(opts instanceof URL5) && !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;
        const url2 = this.#getUrl(opts);
        const { href, origin, port, protocol, username, password, hostname: proxyHostname } = url2;
        this[kProxy] = { uri: href, protocol };
        this[kInterceptors] = opts.interceptors?.ProxyAgent && Array.isArray(opts.interceptors.ProxyAgent) ? opts.interceptors.ProxyAgent : [];
        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 URL5(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 Agent4({
          ...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
                },
                servername: this[kProxyTls]?.servername || proxyHostname
              });
              if (statusCode !== 200) {
                socket.on("error", noop8).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 URL5(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 URL5(opts);
        } else if (opts instanceof URL5) {
          return opts;
        } else {
          return new URL5(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 i3 = 0; i3 < headers.length; i3 += 2) {
          headersPair[headers[i3]] = headers[i3 + 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 = ProxyAgent6;
  }
});

// packages/core/node_modules/undici/lib/dispatcher/env-http-proxy-agent.js
var require_env_http_proxy_agent = __commonJS({
  "packages/core/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 ProxyAgent6 = require_proxy_agent();
    var Agent4 = require_agent();
    var DEFAULT_PORTS = {
      "http:": 80,
      "https:": 443
    };
    var experimentalWarned = false;
    var EnvHttpProxyAgent2 = class extends DispatcherBase {
      static {
        __name(this, "EnvHttpProxyAgent");
      }
      #noProxyValue = null;
      #noProxyEntries = null;
      #opts = null;
      constructor(opts = {}) {
        super();
        this.#opts = opts;
        if (!experimentalWarned) {
          experimentalWarned = true;
          process.emitWarning("EnvHttpProxyAgent is experimental, expect them to change at any time.", {
            code: "UNDICI-EHPA"
          });
        }
        const { httpProxy, httpsProxy, noProxy, ...agentOpts } = opts;
        this[kNoProxyAgent] = new Agent4(agentOpts);
        const HTTP_PROXY = httpProxy ?? process.env.http_proxy ?? process.env.HTTP_PROXY;
        if (HTTP_PROXY) {
          this[kHttpProxyAgent] = new ProxyAgent6({ ...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 ProxyAgent6({ ...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: hostname4, port } = url2;
        hostname4 = hostname4.replace(/:\d*$/, "").toLowerCase();
        port = Number.parseInt(port, 10) || DEFAULT_PORTS[protocol] || 0;
        if (!this.#shouldProxy(hostname4, port)) {
          return this[kNoProxyAgent];
        }
        if (protocol === "https:") {
          return this[kHttpsProxyAgent];
        }
        return this[kHttpProxyAgent];
      }
      #shouldProxy(hostname4, port) {
        if (this.#noProxyChanged) {
          this.#parseNoProxy();
        }
        if (this.#noProxyEntries.length === 0) {
          return true;
        }
        if (this.#noProxyValue === "*") {
          return false;
        }
        for (let i3 = 0; i3 < this.#noProxyEntries.length; i3++) {
          const entry = this.#noProxyEntries[i3];
          if (entry.port && entry.port !== port) {
            continue;
          }
          if (!/^[.*]/.test(entry.hostname)) {
            if (hostname4 === entry.hostname) {
              return false;
            }
          } else {
            if (hostname4.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 i3 = 0; i3 < noProxySplit.length; i3++) {
          const entry = noProxySplit[i3];
          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;
  }
});

// packages/core/node_modules/undici/lib/handler/retry-handler.js
var require_retry_handler = __commonJS({
  "packages/core/node_modules/undici/lib/handler/retry-handler.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var assert4 = __require("node:assert");
    var { kRetryHandlerDefaultRetry } = require_symbols();
    var { RequestRetryError } = require_errors();
    var {
      isDisturbed,
      parseHeaders,
      parseRangeHeader,
      wrapRequestBody
    } = require_util();
    function calculateRetryAfterHeader(retryAfter) {
      const current = Date.now();
      return new Date(retryAfter).getTime() - current;
    }
    __name(calculateRetryAfterHeader, "calculateRetryAfterHeader");
    var RetryHandler = class _RetryHandler {
      static {
        __name(this, "RetryHandler");
      }
      constructor(opts, handlers) {
        const { retryOptions, ...dispatchOpts } = opts;
        const {
          // Retry scoped
          retry: retryFn,
          maxRetries,
          maxTimeout,
          minTimeout,
          timeoutFactor,
          // Response scoped
          methods,
          errorCodes,
          retryAfter,
          statusCodes
        } = retryOptions ?? {};
        this.dispatch = handlers.dispatch;
        this.handler = handlers.handler;
        this.opts = { ...dispatchOpts, body: wrapRequestBody(opts.body) };
        this.abort = null;
        this.aborted = false;
        this.retryOpts = {
          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.start = 0;
        this.end = null;
        this.etag = null;
        this.resume = null;
        this.handler.onConnect((reason) => {
          this.aborted = true;
          if (this.abort) {
            this.abort(reason);
          } else {
            this.reason = reason;
          }
        });
      }
      onRequestSent() {
        if (this.handler.onRequestSent) {
          this.handler.onRequestSent();
        }
      }
      onUpgrade(statusCode, headers, socket) {
        if (this.handler.onUpgrade) {
          this.handler.onUpgrade(statusCode, headers, socket);
        }
      }
      onConnect(abort) {
        if (this.aborted) {
          abort(this.reason);
        } else {
          this.abort = abort;
        }
      }
      onBodySent(chunk) {
        if (this.handler.onBodySent) return this.handler.onBodySent(chunk);
      }
      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(retryAfterHeader) : retryAfterHeader * 1e3;
        }
        const retryTimeout = retryAfterHeader > 0 ? Math.min(retryAfterHeader, maxTimeout) : Math.min(minTimeout * timeoutFactor ** (counter - 1), maxTimeout);
        setTimeout(() => cb(null), retryTimeout);
      }
      onHeaders(statusCode, rawHeaders, resume, statusMessage) {
        const headers = parseHeaders(rawHeaders);
        this.retryCount += 1;
        if (statusCode >= 300) {
          if (this.retryOpts.statusCodes.includes(statusCode) === false) {
            return this.handler.onHeaders(
              statusCode,
              rawHeaders,
              resume,
              statusMessage
            );
          } else {
            this.abort(
              new RequestRetryError("Request failed", statusCode, {
                headers,
                data: {
                  count: this.retryCount
                }
              })
            );
            return false;
          }
        }
        if (this.resume != null) {
          this.resume = null;
          if (statusCode !== 206 && (this.start > 0 || statusCode !== 200)) {
            this.abort(
              new RequestRetryError("server does not support the range header and the payload was partially consumed", statusCode, {
                headers,
                data: { count: this.retryCount }
              })
            );
            return false;
          }
          const contentRange = parseRangeHeader(headers["content-range"]);
          if (!contentRange) {
            this.abort(
              new RequestRetryError("Content-Range mismatch", statusCode, {
                headers,
                data: { count: this.retryCount }
              })
            );
            return false;
          }
          if (this.etag != null && this.etag !== headers.etag) {
            this.abort(
              new RequestRetryError("ETag mismatch", statusCode, {
                headers,
                data: { count: this.retryCount }
              })
            );
            return false;
          }
          const { start, size, end = size - 1 } = contentRange;
          assert4(this.start === start, "content-range mismatch");
          assert4(this.end == null || this.end === end, "content-range mismatch");
          this.resume = resume;
          return true;
        }
        if (this.end == null) {
          if (statusCode === 206) {
            const range = parseRangeHeader(headers["content-range"]);
            if (range == null) {
              return this.handler.onHeaders(
                statusCode,
                rawHeaders,
                resume,
                statusMessage
              );
            }
            const { start, size, end = size - 1 } = range;
            assert4(
              start != null && Number.isFinite(start),
              "content-range mismatch"
            );
            assert4(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;
          }
          assert4(Number.isFinite(this.start));
          assert4(
            this.end == null || Number.isFinite(this.end),
            "invalid content-length"
          );
          this.resume = resume;
          this.etag = headers.etag != null ? headers.etag : null;
          if (this.etag != null && this.etag.startsWith("W/")) {
            this.etag = null;
          }
          return this.handler.onHeaders(
            statusCode,
            rawHeaders,
            resume,
            statusMessage
          );
        }
        const err = new RequestRetryError("Request failed", statusCode, {
          headers,
          data: { count: this.retryCount }
        });
        this.abort(err);
        return false;
      }
      onData(chunk) {
        this.start += chunk.length;
        return this.handler.onData(chunk);
      }
      onComplete(rawTrailers) {
        this.retryCount = 0;
        return this.handler.onComplete(rawTrailers);
      }
      onError(err) {
        if (this.aborted || isDisturbed(this.opts.body)) {
          return this.handler.onError(err);
        }
        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 }
          },
          onRetry.bind(this)
        );
        function onRetry(err2) {
          if (err2 != null || this.aborted || isDisturbed(this.opts.body)) {
            return this.handler.onError(err2);
          }
          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 (err3) {
            this.handler.onError(err3);
          }
        }
        __name(onRetry, "onRetry");
      }
    };
    module2.exports = RetryHandler;
  }
});

// packages/core/node_modules/undici/lib/dispatcher/retry-agent.js
var require_retry_agent = __commonJS({
  "packages/core/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;
  }
});

// packages/core/node_modules/undici/lib/api/readable.js
var require_readable = __commonJS({
  "packages/core/node_modules/undici/lib/api/readable.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var assert4 = __require("node:assert");
    var { Readable: Readable6 } = __require("node:stream");
    var { RequestAbortedError, NotSupportedError, InvalidArgumentError, AbortError: AbortError4 } = require_errors();
    var util3 = 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 noop8 = /* @__PURE__ */ __name(() => {
    }, "noop");
    var BodyReadable = class extends Readable6 {
      static {
        __name(this, "BodyReadable");
      }
      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[kBody] = null;
        this[kContentType] = contentType;
        this[kContentLength] = contentLength;
        this[kReading] = false;
      }
      destroy(err) {
        if (!err && !this._readableState.endEmitted) {
          err = new RequestAbortedError();
        }
        if (err) {
          this[kAbort]();
        }
        return super.destroy(err);
      }
      _destroy(err, callback) {
        if (!this[kReading]) {
          setImmediate(() => {
            callback(err);
          });
        } else {
          callback(err);
        }
      }
      on(ev, ...args) {
        if (ev === "data" || ev === "readable") {
          this[kReading] = true;
        }
        return super.on(ev, ...args);
      }
      addListener(ev, ...args) {
        return this.on(ev, ...args);
      }
      off(ev, ...args) {
        const ret = super.off(ev, ...args);
        if (ev === "data" || ev === "readable") {
          this[kReading] = this.listenerCount("data") > 0 || this.listenerCount("readable") > 0;
        }
        return ret;
      }
      removeListener(ev, ...args) {
        return this.off(ev, ...args);
      }
      push(chunk) {
        if (this[kConsume] && chunk !== null) {
          consumePush(this[kConsume], chunk);
          return this[kReading] ? super.push(chunk) : true;
        }
        return super.push(chunk);
      }
      // https://fetch.spec.whatwg.org/#dom-body-text
      async text() {
        return consume(this, "text");
      }
      // https://fetch.spec.whatwg.org/#dom-body-json
      async json() {
        return consume(this, "json");
      }
      // https://fetch.spec.whatwg.org/#dom-body-blob
      async blob() {
        return consume(this, "blob");
      }
      // https://fetch.spec.whatwg.org/#dom-body-bytes
      async bytes() {
        return consume(this, "bytes");
      }
      // https://fetch.spec.whatwg.org/#dom-body-arraybuffer
      async arrayBuffer() {
        return consume(this, "arrayBuffer");
      }
      // https://fetch.spec.whatwg.org/#dom-body-formdata
      async formData() {
        throw new NotSupportedError();
      }
      // https://fetch.spec.whatwg.org/#dom-body-bodyused
      get bodyUsed() {
        return util3.isDisturbed(this);
      }
      // https://fetch.spec.whatwg.org/#dom-body-body
      get body() {
        if (!this[kBody]) {
          this[kBody] = ReadableStreamFrom2(this);
          if (this[kConsume]) {
            this[kBody].getReader();
            assert4(this[kBody].locked);
          }
        }
        return this[kBody];
      }
      async dump(opts) {
        let limit2 = Number.isFinite(opts?.limit) ? opts.limit : 128 * 1024;
        const signal = opts?.signal;
        if (signal != null && (typeof signal !== "object" || !("aborted" in signal))) {
          throw new InvalidArgumentError("signal must be an AbortSignal");
        }
        signal?.throwIfAborted();
        if (this._readableState.closeEmitted) {
          return null;
        }
        return await new Promise((resolve30, reject) => {
          if (this[kContentLength] > limit2) {
            this.destroy(new AbortError4());
          }
          const onAbort = /* @__PURE__ */ __name(() => {
            this.destroy(signal.reason ?? new AbortError4());
          }, "onAbort");
          signal?.addEventListener("abort", onAbort);
          this.on("close", function() {
            signal?.removeEventListener("abort", onAbort);
            if (signal?.aborted) {
              reject(signal.reason ?? new AbortError4());
            } else {
              resolve30(null);
            }
          }).on("error", noop8).on("data", function(chunk) {
            limit2 -= chunk.length;
            if (limit2 <= 0) {
              this.destroy();
            }
          }).resume();
        });
      }
    };
    function isLocked(self2) {
      return self2[kBody] && self2[kBody].locked === true || self2[kConsume];
    }
    __name(isLocked, "isLocked");
    function isUnusable(self2) {
      return util3.isDisturbed(self2) || isLocked(self2);
    }
    __name(isUnusable, "isUnusable");
    async function consume(stream2, type) {
      assert4(!stream2[kConsume]);
      return new Promise((resolve30, reject) => {
        if (isUnusable(stream2)) {
          const rState = stream2._readableState;
          if (rState.destroyed && rState.closeEmitted === false) {
            stream2.on("error", (err) => {
              reject(err);
            }).on("close", () => {
              reject(new TypeError("unusable"));
            });
          } else {
            reject(rState.errored ?? new TypeError("unusable"));
          }
        } else {
          queueMicrotask(() => {
            stream2[kConsume] = {
              type,
              stream: stream2,
              resolve: resolve30,
              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 n3 = start; n3 < end; n3++) {
          consumePush(consume2, state.buffer[n3]);
        }
      } else {
        for (const chunk of state.buffer) {
          consumePush(consume2, chunk);
        }
      }
      if (state.endEmitted) {
        consumeEnd(this[kConsume]);
      } else {
        consume2.stream.on("end", function() {
          consumeEnd(this[kConsume]);
        });
      }
      consume2.stream.resume();
      while (consume2.stream.read() != null) {
      }
    }
    __name(consumeStart, "consumeStart");
    function chunksDecode(chunks, length) {
      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;
      return buffer.utf8Slice(start, bufferLength);
    }
    __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 i3 = 0; i3 < chunks.length; ++i3) {
        const chunk = chunks[i3];
        buffer.set(chunk, offset);
        offset += chunk.length;
      }
      return buffer;
    }
    __name(chunksConcat, "chunksConcat");
    function consumeEnd(consume2) {
      const { type, body, resolve: resolve30, stream: stream2, length } = consume2;
      try {
        if (type === "text") {
          resolve30(chunksDecode(body, length));
        } else if (type === "json") {
          resolve30(JSON.parse(chunksDecode(body, length)));
        } else if (type === "arrayBuffer") {
          resolve30(chunksConcat(body, length).buffer);
        } else if (type === "blob") {
          resolve30(new Blob(body, { type: stream2[kContentType] }));
        } else if (type === "bytes") {
          resolve30(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 };
  }
});

// packages/core/node_modules/undici/lib/api/util.js
var require_util3 = __commonJS({
  "packages/core/node_modules/undici/lib/api/util.js"(exports2, module2) {
    init_esbuild_shims();
    var assert4 = __require("node:assert");
    var {
      ResponseStatusCodeError
    } = require_errors();
    var { chunksDecode } = require_readable();
    var CHUNK_LIMIT = 128 * 1024;
    async function getResolveErrorBodyCallback({ callback, body, contentType, statusCode, statusMessage, headers }) {
      assert4(body);
      let chunks = [];
      let length = 0;
      try {
        for await (const chunk of body) {
          chunks.push(chunk);
          length += chunk.length;
          if (length > CHUNK_LIMIT) {
            chunks = [];
            length = 0;
            break;
          }
        }
      } catch {
        chunks = [];
        length = 0;
      }
      const message = `Response status code ${statusCode}${statusMessage ? `: ${statusMessage}` : ""}`;
      if (statusCode === 204 || !contentType || !length) {
        queueMicrotask(() => callback(new ResponseStatusCodeError(message, statusCode, headers)));
        return;
      }
      const stackTraceLimit = Error.stackTraceLimit;
      Error.stackTraceLimit = 0;
      let payload;
      try {
        if (isContentTypeApplicationJson(contentType)) {
          payload = JSON.parse(chunksDecode(chunks, length));
        } else if (isContentTypeText(contentType)) {
          payload = chunksDecode(chunks, length);
        }
      } catch {
      } finally {
        Error.stackTraceLimit = stackTraceLimit;
      }
      queueMicrotask(() => callback(new ResponseStatusCodeError(message, statusCode, headers, payload)));
    }
    __name(getResolveErrorBodyCallback, "getResolveErrorBodyCallback");
    var isContentTypeApplicationJson = /* @__PURE__ */ __name((contentType) => {
      return contentType.length > 15 && contentType[11] === "/" && contentType[0] === "a" && contentType[1] === "p" && contentType[2] === "p" && contentType[3] === "l" && contentType[4] === "i" && contentType[5] === "c" && contentType[6] === "a" && contentType[7] === "t" && contentType[8] === "i" && contentType[9] === "o" && contentType[10] === "n" && contentType[12] === "j" && contentType[13] === "s" && contentType[14] === "o" && contentType[15] === "n";
    }, "isContentTypeApplicationJson");
    var isContentTypeText = /* @__PURE__ */ __name((contentType) => {
      return contentType.length > 4 && contentType[4] === "/" && contentType[0] === "t" && contentType[1] === "e" && contentType[2] === "x" && contentType[3] === "t";
    }, "isContentTypeText");
    module2.exports = {
      getResolveErrorBodyCallback,
      isContentTypeApplicationJson,
      isContentTypeText
    };
  }
});

// packages/core/node_modules/undici/lib/api/api-request.js
var require_api_request = __commonJS({
  "packages/core/node_modules/undici/lib/api/api-request.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var assert4 = __require("node:assert");
    var { Readable: Readable6 } = require_readable();
    var { InvalidArgumentError, RequestAbortedError } = require_errors();
    var util3 = require_util();
    var { getResolveErrorBodyCallback } = require_util3();
    var { AsyncResource } = __require("node:async_hooks");
    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, throwOnError, 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 (util3.isStream(body)) {
            util3.destroy(body.on("error", util3.nop), 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.throwOnError = throwOnError;
        this.highWaterMark = highWaterMark;
        this.signal = signal;
        this.reason = null;
        this.removeAbortListener = null;
        if (util3.isStream(body)) {
          body.on("error", (err) => {
            this.onError(err);
          });
        }
        if (this.signal) {
          if (this.signal.aborted) {
            this.reason = this.signal.reason ?? new RequestAbortedError();
          } else {
            this.removeAbortListener = util3.addAbortListener(this.signal, () => {
              this.reason = this.signal.reason ?? new RequestAbortedError();
              if (this.res) {
                util3.destroy(this.res.on("error", util3.nop), this.reason);
              } else if (this.abort) {
                this.abort(this.reason);
              }
              if (this.removeAbortListener) {
                this.res?.off("close", this.removeAbortListener);
                this.removeAbortListener();
                this.removeAbortListener = null;
              }
            });
          }
        }
      }
      onConnect(abort, context2) {
        if (this.reason) {
          abort(this.reason);
          return;
        }
        assert4(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" ? util3.parseRawHeaders(rawHeaders) : util3.parseHeaders(rawHeaders);
        if (statusCode < 200) {
          if (this.onInfo) {
            this.onInfo({ statusCode, headers });
          }
          return;
        }
        const parsedHeaders = responseHeaders === "raw" ? util3.parseHeaders(rawHeaders) : headers;
        const contentType = parsedHeaders["content-type"];
        const contentLength = parsedHeaders["content-length"];
        const res = new Readable6({
          resume,
          abort,
          contentType,
          contentLength: this.method !== "HEAD" && contentLength ? Number(contentLength) : null,
          highWaterMark
        });
        if (this.removeAbortListener) {
          res.on("close", this.removeAbortListener);
        }
        this.callback = null;
        this.res = res;
        if (callback !== null) {
          if (this.throwOnError && statusCode >= 400) {
            this.runInAsyncScope(
              getResolveErrorBodyCallback,
              null,
              { callback, body: res, contentType, statusCode, statusMessage, headers }
            );
          } else {
            this.runInAsyncScope(callback, null, null, {
              statusCode,
              headers,
              trailers: this.trailers,
              opaque,
              body: res,
              context: context2
            });
          }
        }
      }
      onData(chunk) {
        return this.res.push(chunk);
      }
      onComplete(trailers) {
        util3.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(() => {
            util3.destroy(res, err);
          });
        }
        if (body) {
          this.body = null;
          util3.destroy(body, err);
        }
        if (this.removeAbortListener) {
          res?.off("close", this.removeAbortListener);
          this.removeAbortListener();
          this.removeAbortListener = null;
        }
      }
    };
    function request4(opts, callback) {
      if (callback === void 0) {
        return new Promise((resolve30, reject) => {
          request4.call(this, opts, (err, data) => {
            return err ? reject(err) : resolve30(data);
          });
        });
      }
      try {
        this.dispatch(opts, new RequestHandler(opts, callback));
      } 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;
  }
});

// packages/core/node_modules/undici/lib/api/abort-signal.js
var require_abort_signal = __commonJS({
  "packages/core/node_modules/undici/lib/api/abort-signal.js"(exports2, module2) {
    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
    };
  }
});

// packages/core/node_modules/undici/lib/api/api-stream.js
var require_api_stream = __commonJS({
  "packages/core/node_modules/undici/lib/api/api-stream.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var assert4 = __require("node:assert");
    var { finished: finished2, PassThrough: PassThrough8 } = __require("node:stream");
    var { InvalidArgumentError, InvalidReturnValueError } = require_errors();
    var util3 = require_util();
    var { getResolveErrorBodyCallback } = require_util3();
    var { AsyncResource } = __require("node:async_hooks");
    var { addSignal, removeSignal } = require_abort_signal();
    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, throwOnError } = 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 (util3.isStream(body)) {
            util3.destroy(body.on("error", util3.nop), 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;
        this.throwOnError = throwOnError || false;
        if (util3.isStream(body)) {
          body.on("error", (err) => {
            this.onError(err);
          });
        }
        addSignal(this, signal);
      }
      onConnect(abort, context2) {
        if (this.reason) {
          abort(this.reason);
          return;
        }
        assert4(this.callback);
        this.abort = abort;
        this.context = context2;
      }
      onHeaders(statusCode, rawHeaders, resume, statusMessage) {
        const { factory, opaque, context: context2, callback, responseHeaders } = this;
        const headers = responseHeaders === "raw" ? util3.parseRawHeaders(rawHeaders) : util3.parseHeaders(rawHeaders);
        if (statusCode < 200) {
          if (this.onInfo) {
            this.onInfo({ statusCode, headers });
          }
          return;
        }
        this.factory = null;
        let res;
        if (this.throwOnError && statusCode >= 400) {
          const parsedHeaders = responseHeaders === "raw" ? util3.parseHeaders(rawHeaders) : headers;
          const contentType = parsedHeaders["content-type"];
          res = new PassThrough8();
          this.callback = null;
          this.runInAsyncScope(
            getResolveErrorBodyCallback,
            null,
            { callback, body: res, contentType, statusCode, statusMessage, headers }
          );
        } else {
          if (factory === null) {
            return;
          }
          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");
          }
          finished2(res, { readable: false }, (err) => {
            const { callback: callback2, res: res2, opaque: opaque2, trailers, abort } = this;
            this.res = null;
            if (err || !res2.readable) {
              util3.destroy(res2, err);
            }
            this.callback = null;
            this.runInAsyncScope(callback2, 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 = util3.parseHeaders(trailers);
        res.end();
      }
      onError(err) {
        const { res, callback, opaque, body } = this;
        removeSignal(this);
        this.factory = null;
        if (res) {
          this.res = null;
          util3.destroy(res, err);
        } else if (callback) {
          this.callback = null;
          queueMicrotask(() => {
            this.runInAsyncScope(callback, null, err, { opaque });
          });
        }
        if (body) {
          this.body = null;
          util3.destroy(body, err);
        }
      }
    };
    function stream2(opts, factory, callback) {
      if (callback === void 0) {
        return new Promise((resolve30, reject) => {
          stream2.call(this, opts, factory, (err, data) => {
            return err ? reject(err) : resolve30(data);
          });
        });
      }
      try {
        this.dispatch(opts, new StreamHandler(opts, factory, callback));
      } catch (err) {
        if (typeof callback !== "function") {
          throw err;
        }
        const opaque = opts?.opaque;
        queueMicrotask(() => callback(err, { opaque }));
      }
    }
    __name(stream2, "stream");
    module2.exports = stream2;
  }
});

// packages/core/node_modules/undici/lib/api/api-pipeline.js
var require_api_pipeline = __commonJS({
  "packages/core/node_modules/undici/lib/api/api-pipeline.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var {
      Readable: Readable6,
      Duplex,
      PassThrough: PassThrough8
    } = __require("node:stream");
    var {
      InvalidArgumentError,
      InvalidReturnValueError,
      RequestAbortedError
    } = require_errors();
    var util3 = require_util();
    var { AsyncResource } = __require("node:async_hooks");
    var { addSignal, removeSignal } = require_abort_signal();
    var assert4 = __require("node:assert");
    var kResume = Symbol("resume");
    var PipelineRequest = class extends Readable6 {
      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 Readable6 {
      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", util3.nop);
        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();
            }
            util3.destroy(body, err);
            util3.destroy(req, err);
            util3.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 { ret, res } = this;
        if (this.reason) {
          abort(this.reason);
          return;
        }
        assert4(!res, "pipeline cannot be retried");
        assert4(!ret.destroyed);
        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" ? util3.parseRawHeaders(rawHeaders) : util3.parseHeaders(rawHeaders);
            this.onInfo({ statusCode, headers });
          }
          return;
        }
        this.res = new PipelineResponse(resume);
        let body;
        try {
          this.handler = null;
          const headers = this.responseHeaders === "raw" ? util3.parseRawHeaders(rawHeaders) : util3.parseHeaders(rawHeaders);
          body = this.runInAsyncScope(handler, null, {
            statusCode,
            headers,
            opaque,
            body: this.res,
            context: context2
          });
        } catch (err) {
          this.res.on("error", util3.nop);
          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;
          util3.destroy(ret, err);
        }).on("end", () => {
          const { ret } = this;
          ret.push(null);
        }).on("close", () => {
          const { ret } = this;
          if (!ret._readableState.ended) {
            util3.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;
        util3.destroy(ret, err);
      }
    };
    function pipeline3(opts, handler) {
      try {
        const pipelineHandler = new PipelineHandler(opts, handler);
        this.dispatch({ ...opts, body: pipelineHandler.req }, pipelineHandler);
        return pipelineHandler.ret;
      } catch (err) {
        return new PassThrough8().destroy(err);
      }
    }
    __name(pipeline3, "pipeline");
    module2.exports = pipeline3;
  }
});

// packages/core/node_modules/undici/lib/api/api-upgrade.js
var require_api_upgrade = __commonJS({
  "packages/core/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 util3 = require_util();
    var { addSignal, removeSignal } = require_abort_signal();
    var assert4 = __require("node:assert");
    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;
        }
        assert4(this.callback);
        this.abort = abort;
        this.context = null;
      }
      onHeaders() {
        throw new SocketError("bad upgrade", null);
      }
      onUpgrade(statusCode, rawHeaders, socket) {
        assert4(statusCode === 101);
        const { callback, opaque, context: context2 } = this;
        removeSignal(this);
        this.callback = null;
        const headers = this.responseHeaders === "raw" ? util3.parseRawHeaders(rawHeaders) : util3.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((resolve30, reject) => {
          upgrade.call(this, opts, (err, data) => {
            return err ? reject(err) : resolve30(data);
          });
        });
      }
      try {
        const upgradeHandler = new UpgradeHandler(opts, callback);
        this.dispatch({
          ...opts,
          method: opts.method || "GET",
          upgrade: opts.protocol || "Websocket"
        }, upgradeHandler);
      } catch (err) {
        if (typeof callback !== "function") {
          throw err;
        }
        const opaque = opts?.opaque;
        queueMicrotask(() => callback(err, { opaque }));
      }
    }
    __name(upgrade, "upgrade");
    module2.exports = upgrade;
  }
});

// packages/core/node_modules/undici/lib/api/api-connect.js
var require_api_connect = __commonJS({
  "packages/core/node_modules/undici/lib/api/api-connect.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var assert4 = __require("node:assert");
    var { AsyncResource } = __require("node:async_hooks");
    var { InvalidArgumentError, SocketError } = require_errors();
    var util3 = 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;
        }
        assert4(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" ? util3.parseRawHeaders(rawHeaders) : util3.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((resolve30, reject) => {
          connect.call(this, opts, (err, data) => {
            return err ? reject(err) : resolve30(data);
          });
        });
      }
      try {
        const connectHandler = new ConnectHandler(opts, callback);
        this.dispatch({ ...opts, method: "CONNECT" }, connectHandler);
      } catch (err) {
        if (typeof callback !== "function") {
          throw err;
        }
        const opaque = opts?.opaque;
        queueMicrotask(() => callback(err, { opaque }));
      }
    }
    __name(connect, "connect");
    module2.exports = connect;
  }
});

// packages/core/node_modules/undici/lib/api/index.js
var require_api = __commonJS({
  "packages/core/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();
  }
});

// packages/core/node_modules/undici/lib/mock/mock-errors.js
var require_mock_errors = __commonJS({
  "packages/core/node_modules/undici/lib/mock/mock-errors.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var { UndiciError } = require_errors();
    var kMockNotMatchedError = Symbol.for("undici.error.UND_MOCK_ERR_MOCK_NOT_MATCHED");
    var MockNotMatchedError = class _MockNotMatchedError extends UndiciError {
      static {
        __name(this, "MockNotMatchedError");
      }
      constructor(message) {
        super(message);
        Error.captureStackTrace(this, _MockNotMatchedError);
        this.name = "MockNotMatchedError";
        this.message = message || "The request does not match any registered mock dispatches";
        this.code = "UND_MOCK_ERR_MOCK_NOT_MATCHED";
      }
      static [Symbol.hasInstance](instance) {
        return instance && instance[kMockNotMatchedError] === true;
      }
      [kMockNotMatchedError] = true;
    };
    module2.exports = {
      MockNotMatchedError
    };
  }
});

// packages/core/node_modules/undici/lib/mock/mock-symbols.js
var require_mock_symbols = __commonJS({
  "packages/core/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"),
      kOrigin: Symbol("origin"),
      kIsMockActive: Symbol("is mock active"),
      kNetConnect: Symbol("net connect"),
      kGetNetConnect: Symbol("get net connect"),
      kConnected: Symbol("connected")
    };
  }
});

// packages/core/node_modules/undici/lib/mock/mock-utils.js
var require_mock_utils = __commonJS({
  "packages/core/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 { buildURL } = require_util();
    var { STATUS_CODES } = __require("node:http");
    var {
      types: {
        isPromise: isPromise2
      }
    } = __require("node:util");
    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 i3 = 0; i3 < headers.length; i3 += 2) {
          if (headers[i3].toLocaleLowerCase() === key.toLocaleLowerCase()) {
            return headers[i3 + 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 clone4 = headers.slice();
      const entries = [];
      for (let index = 0; index < clone4.length; index += 2) {
        entries.push([clone4[index], clone4[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 safeUrl(path125) {
      if (typeof path125 !== "string") {
        return path125;
      }
      const pathSegments = path125.split("?");
      if (pathSegments.length !== 2) {
        return path125;
      }
      const qp = new URLSearchParams(pathSegments.pop());
      qp.sort();
      return [...pathSegments, qp.toString()].join("?");
    }
    __name(safeUrl, "safeUrl");
    function matchKey(mockDispatch2, { path: path125, method, body, headers }) {
      const pathMatch = matchValue(mockDispatch2.path, path125);
      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 {
        return data.toString();
      }
    }
    __name(getResponseData, "getResponseData");
    function getMockDispatch(mockDispatches, key) {
      const basePath = key.query ? buildURL(key.path, key.query) : key.path;
      const resolvedPath = typeof basePath === "string" ? safeUrl(basePath) : basePath;
      let matchedMockDispatches = mockDispatches.filter(({ consumed }) => !consumed).filter(({ path: path125 }) => matchValue(safeUrl(path125), 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) {
      const baseData = { timesInvoked: 0, times: 1, persist: false, consumed: false };
      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 buildKey(opts) {
      const { path: path125, method, body, headers, query } = opts;
      return {
        path: path125,
        method,
        body,
        headers,
        query
      };
    }
    __name(buildKey, "buildKey");
    function generateKeyValues(data) {
      const keys = Object.keys(data);
      const result = [];
      for (let i3 = 0; i3 < keys.length; ++i3) {
        const key = keys[i3];
        const value = data[key];
        const name3 = Buffer.from(`${key}`);
        if (Array.isArray(value)) {
          for (let j2 = 0; j2 < value.length; ++j2) {
            result.push(name3, Buffer.from(`${value[j2]}`));
          }
        } 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: error2 }, delay: delay4, persist } = mockDispatch2;
      const { timesInvoked, times } = mockDispatch2;
      mockDispatch2.consumed = !persist && timesInvoked >= times;
      mockDispatch2.pending = timesInvoked < times;
      if (error2 !== null) {
        deleteMockDispatch(this[kDispatches], key);
        handler.onError(error2);
        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 (error2) {
            if (error2 instanceof MockNotMatchedError) {
              const netConnect = agent[kGetNetConnect]();
              if (netConnect === false) {
                throw new MockNotMatchedError(`${error2.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(`${error2.message}: subsequent request to origin ${origin} was not allowed (net.connect is not enabled for this origin)`);
              }
            } else {
              throw error2;
            }
          }
        } 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 buildMockOptions(opts) {
      if (opts) {
        const { agent, ...mockOptions } = opts;
        return mockOptions;
      }
    }
    __name(buildMockOptions, "buildMockOptions");
    module2.exports = {
      getResponseData,
      getMockDispatch,
      addMockDispatch,
      deleteMockDispatch,
      buildKey,
      generateKeyValues,
      matchValue,
      getResponse,
      getStatusText: getStatusText2,
      mockDispatch,
      buildMockDispatch,
      checkNetConnect,
      buildMockOptions,
      getHeaderByName,
      buildHeadersFromArray
    };
  }
});

// packages/core/node_modules/undici/lib/mock/mock-interceptor.js
var require_mock_interceptor = __commonJS({
  "packages/core/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
    } = require_mock_symbols();
    var { InvalidArgumentError } = require_errors();
    var { buildURL } = 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 = buildURL(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[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);
          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);
        return new MockScope(newMockDispatch);
      }
      /**
       * Mock an undici request with a defined error.
       */
      replyWithError(error2) {
        if (typeof error2 === "undefined") {
          throw new InvalidArgumentError("error must be defined");
        }
        const newMockDispatch = addMockDispatch(this[kDispatches], this[kDispatchKey], { error: error2 });
        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;
  }
});

// packages/core/node_modules/undici/lib/mock/mock-client.js
var require_mock_client = __commonJS({
  "packages/core/node_modules/undici/lib/mock/mock-client.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var { promisify: promisify13 } = __require("node:util");
    var Client3 = require_client();
    var { buildMockDispatch } = require_mock_utils();
    var {
      kDispatches,
      kMockAgent,
      kClose,
      kOriginalClose,
      kOrigin,
      kOriginalDispatch,
      kConnected
    } = require_mock_symbols();
    var { MockInterceptor } = require_mock_interceptor();
    var Symbols = require_symbols();
    var { InvalidArgumentError } = require_errors();
    var MockClient = class extends Client3 {
      static {
        __name(this, "MockClient");
      }
      constructor(origin, opts) {
        super(origin, opts);
        if (!opts || !opts.agent || typeof opts.agent.dispatch !== "function") {
          throw new InvalidArgumentError("Argument opts.agent must implement Agent");
        }
        this[kMockAgent] = opts.agent;
        this[kOrigin] = origin;
        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, this[kDispatches]);
      }
      async [kClose]() {
        await promisify13(this[kOriginalClose])();
        this[kConnected] = 0;
        this[kMockAgent][Symbols.kClients].delete(this[kOrigin]);
      }
    };
    module2.exports = MockClient;
  }
});

// packages/core/node_modules/undici/lib/mock/mock-pool.js
var require_mock_pool = __commonJS({
  "packages/core/node_modules/undici/lib/mock/mock-pool.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var { promisify: promisify13 } = __require("node:util");
    var Pool = require_pool();
    var { buildMockDispatch } = require_mock_utils();
    var {
      kDispatches,
      kMockAgent,
      kClose,
      kOriginalClose,
      kOrigin,
      kOriginalDispatch,
      kConnected
    } = 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) {
        super(origin, opts);
        if (!opts || !opts.agent || typeof opts.agent.dispatch !== "function") {
          throw new InvalidArgumentError("Argument opts.agent must implement Agent");
        }
        this[kMockAgent] = opts.agent;
        this[kOrigin] = origin;
        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, this[kDispatches]);
      }
      async [kClose]() {
        await promisify13(this[kOriginalClose])();
        this[kConnected] = 0;
        this[kMockAgent][Symbols.kClients].delete(this[kOrigin]);
      }
    };
    module2.exports = MockPool;
  }
});

// packages/core/node_modules/undici/lib/mock/pluralizer.js
var require_pluralizer = __commonJS({
  "packages/core/node_modules/undici/lib/mock/pluralizer.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var singulars = {
      pronoun: "it",
      is: "is",
      was: "was",
      this: "this"
    };
    var plurals = {
      pronoun: "they",
      is: "are",
      was: "were",
      this: "these"
    };
    module2.exports = class Pluralizer {
      static {
        __name(this, "Pluralizer");
      }
      constructor(singular, plural) {
        this.singular = singular;
        this.plural = plural;
      }
      pluralize(count) {
        const one = count === 1;
        const keys = one ? singulars : plurals;
        const noun = one ? this.singular : this.plural;
        return { ...keys, count, noun };
      }
    };
  }
});

// packages/core/node_modules/undici/lib/mock/pending-interceptors-formatter.js
var require_pending_interceptors_formatter = __commonJS({
  "packages/core/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: path125, data: { statusCode }, persist, times, timesInvoked, origin }) => ({
            Method: method,
            Origin: origin,
            Path: path125,
            "Status code": statusCode,
            Persistent: persist ? PERSISTENT : NOT_PERSISTENT,
            Invocations: timesInvoked,
            Remaining: persist ? Infinity : times - timesInvoked
          })
        );
        this.logger.table(withPrettyHeaders);
        return this.transform.read().toString();
      }
    };
  }
});

// packages/core/node_modules/undici/lib/mock/mock-agent.js
var require_mock_agent = __commonJS({
  "packages/core/node_modules/undici/lib/mock/mock-agent.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var { kClients } = require_symbols();
    var Agent4 = require_agent();
    var {
      kAgent,
      kMockAgentSet,
      kMockAgentGet,
      kDispatches,
      kIsMockActive,
      kNetConnect,
      kGetNetConnect,
      kOptions,
      kFactory
    } = require_mock_symbols();
    var MockClient = require_mock_client();
    var MockPool = require_mock_pool();
    var { matchValue, buildMockOptions } = require_mock_utils();
    var { InvalidArgumentError, UndiciError } = require_errors();
    var Dispatcher = require_dispatcher();
    var Pluralizer = require_pluralizer();
    var PendingInterceptorsFormatter = require_pending_interceptors_formatter();
    var MockAgent = class extends Dispatcher {
      static {
        __name(this, "MockAgent");
      }
      constructor(opts) {
        super(opts);
        this[kNetConnect] = true;
        this[kIsMockActive] = true;
        if (opts?.agent && typeof opts.agent.dispatch !== "function") {
          throw new InvalidArgumentError("Argument opts.agent must implement Agent");
        }
        const agent = opts?.agent ? opts.agent : new Agent4(opts);
        this[kAgent] = agent;
        this[kClients] = agent[kClients];
        this[kOptions] = buildMockOptions(opts);
      }
      get(origin) {
        let dispatcher = this[kMockAgentGet](origin);
        if (!dispatcher) {
          dispatcher = this[kFactory](origin);
          this[kMockAgentSet](origin, dispatcher);
        }
        return dispatcher;
      }
      dispatch(opts, handler) {
        this.get(opts.origin);
        return this[kAgent].dispatch(opts, handler);
      }
      async close() {
        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;
      }
      // This is required to bypass issues caused by using global symbols - see:
      // https://github.com/nodejs/undici/issues/1447
      get isMockActive() {
        return this[kIsMockActive];
      }
      [kMockAgentSet](origin, dispatcher) {
        this[kClients].set(origin, 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 client = this[kClients].get(origin);
        if (client) {
          return client;
        }
        if (typeof origin !== "string") {
          const dispatcher = this[kFactory]("http://localhost:9999");
          this[kMockAgentSet](origin, dispatcher);
          return dispatcher;
        }
        for (const [keyMatcher, nonExplicitDispatcher] of Array.from(this[kClients])) {
          if (nonExplicitDispatcher && typeof keyMatcher !== "string" && matchValue(keyMatcher, origin)) {
            const dispatcher = this[kFactory](origin);
            this[kMockAgentSet](origin, dispatcher);
            dispatcher[kDispatches] = nonExplicitDispatcher[kDispatches];
            return dispatcher;
          }
        }
      }
      [kGetNetConnect]() {
        return this[kNetConnect];
      }
      pendingInterceptors() {
        const mockAgentClients = this[kClients];
        return Array.from(mockAgentClients.entries()).flatMap(([origin, scope]) => scope[kDispatches].map((dispatch) => ({ ...dispatch, origin }))).filter(({ pending }) => pending);
      }
      assertNoPendingInterceptors({ pendingInterceptorsFormatter = new PendingInterceptorsFormatter() } = {}) {
        const pending = this.pendingInterceptors();
        if (pending.length === 0) {
          return;
        }
        const pluralizer = new Pluralizer("interceptor", "interceptors").pluralize(pending.length);
        throw new UndiciError(`
${pluralizer.count} ${pluralizer.noun} ${pluralizer.is} pending:

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

// packages/core/node_modules/undici/lib/global.js
var require_global2 = __commonJS({
  "packages/core/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 Agent4 = require_agent();
    if (getGlobalDispatcher() === void 0) {
      setGlobalDispatcher3(new Agent4());
    }
    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
    };
  }
});

// packages/core/node_modules/undici/lib/handler/decorator-handler.js
var require_decorator_handler = __commonJS({
  "packages/core/node_modules/undici/lib/handler/decorator-handler.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    module2.exports = class DecoratorHandler {
      static {
        __name(this, "DecoratorHandler");
      }
      #handler;
      constructor(handler) {
        if (typeof handler !== "object" || handler === null) {
          throw new TypeError("handler must be an object");
        }
        this.#handler = handler;
      }
      onConnect(...args) {
        return this.#handler.onConnect?.(...args);
      }
      onError(...args) {
        return this.#handler.onError?.(...args);
      }
      onUpgrade(...args) {
        return this.#handler.onUpgrade?.(...args);
      }
      onResponseStarted(...args) {
        return this.#handler.onResponseStarted?.(...args);
      }
      onHeaders(...args) {
        return this.#handler.onHeaders?.(...args);
      }
      onData(...args) {
        return this.#handler.onData?.(...args);
      }
      onComplete(...args) {
        return this.#handler.onComplete?.(...args);
      }
      onBodySent(...args) {
        return this.#handler.onBodySent?.(...args);
      }
    };
  }
});

// packages/core/node_modules/undici/lib/interceptor/redirect.js
var require_redirect = __commonJS({
  "packages/core/node_modules/undici/lib/interceptor/redirect.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var RedirectHandler = require_redirect_handler();
    module2.exports = (opts) => {
      const globalMaxRedirections = opts?.maxRedirections;
      return (dispatch) => {
        return /* @__PURE__ */ __name(function redirectInterceptor(opts2, handler) {
          const { maxRedirections = globalMaxRedirections, ...baseOpts } = opts2;
          if (!maxRedirections) {
            return dispatch(opts2, handler);
          }
          const redirectHandler = new RedirectHandler(
            dispatch,
            maxRedirections,
            opts2,
            handler
          );
          return dispatch(baseOpts, redirectHandler);
        }, "redirectInterceptor");
      };
    };
  }
});

// packages/core/node_modules/undici/lib/interceptor/retry.js
var require_retry = __commonJS({
  "packages/core/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");
      };
    };
  }
});

// packages/core/node_modules/undici/lib/interceptor/dump.js
var require_dump = __commonJS({
  "packages/core/node_modules/undici/lib/interceptor/dump.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var util3 = require_util();
    var { InvalidArgumentError, RequestAbortedError } = require_errors();
    var DecoratorHandler = require_decorator_handler();
    var DumpHandler = class extends DecoratorHandler {
      static {
        __name(this, "DumpHandler");
      }
      #maxSize = 1024 * 1024;
      #abort = null;
      #dumped = false;
      #aborted = false;
      #size = 0;
      #reason = null;
      #handler = null;
      constructor({ maxSize }, handler) {
        super(handler);
        if (maxSize != null && (!Number.isFinite(maxSize) || maxSize < 1)) {
          throw new InvalidArgumentError("maxSize must be a number greater than 0");
        }
        this.#maxSize = maxSize ?? this.#maxSize;
        this.#handler = handler;
      }
      onConnect(abort) {
        this.#abort = abort;
        this.#handler.onConnect(this.#customAbort.bind(this));
      }
      #customAbort(reason) {
        this.#aborted = true;
        this.#reason = reason;
      }
      // TODO: will require adjustment after new hooks are out
      onHeaders(statusCode, rawHeaders, resume, statusMessage) {
        const headers = util3.parseHeaders(rawHeaders);
        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) {
          return true;
        }
        return this.#handler.onHeaders(
          statusCode,
          rawHeaders,
          resume,
          statusMessage
        );
      }
      onError(err) {
        if (this.#dumped) {
          return;
        }
        err = this.#reason ?? err;
        this.#handler.onError(err);
      }
      onData(chunk) {
        this.#size = this.#size + chunk.length;
        if (this.#size >= this.#maxSize) {
          this.#dumped = true;
          if (this.#aborted) {
            this.#handler.onError(this.#reason);
          } else {
            this.#handler.onComplete([]);
          }
        }
        return true;
      }
      onComplete(trailers) {
        if (this.#dumped) {
          return;
        }
        if (this.#aborted) {
          this.#handler.onError(this.reason);
          return;
        }
        this.#handler.onComplete(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 },
            handler
          );
          return dispatch(opts, dumpHandler);
        }, "Intercept");
      };
    }
    __name(createDumpInterceptor, "createDumpInterceptor");
    module2.exports = createDumpInterceptor;
  }
});

// packages/core/node_modules/undici/lib/interceptor/dns.js
var require_dns = __commonJS({
  "packages/core/node_modules/undici/lib/interceptor/dns.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var { isIP: isIP3 } = __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.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,
              `${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,
            `${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;
      }
      setRecords(origin, addresses) {
        const timestamp = Date.now();
        const records = { records: { 4: null, 6: null } };
        for (const record2 of addresses) {
          record2.timestamp = timestamp;
          if (typeof record2.ttl === "number") {
            record2.ttl = Math.min(record2.ttl, this.#maxTTL);
          } else {
            record2.ttl = this.#maxTTL;
          }
          const familyRecords = records.records[record2.family] ?? { ips: [] };
          familyRecords.ips.push(record2);
          records.records[record2.family] = familyRecords;
        }
        this.#records.set(origin.hostname, records);
      }
      getHandler(meta, opts) {
        return new DNSDispatchHandler(this, meta, opts);
      }
    };
    var DNSDispatchHandler = class extends DecoratorHandler {
      static {
        __name(this, "DNSDispatchHandler");
      }
      #state = null;
      #opts = null;
      #dispatch = null;
      #handler = null;
      #origin = null;
      constructor(state, { origin, handler, dispatch }, opts) {
        super(handler);
        this.#origin = origin;
        this.#handler = handler;
        this.#opts = { ...opts };
        this.#state = state;
        this.#dispatch = dispatch;
      }
      onError(err) {
        switch (err.code) {
          case "ETIMEDOUT":
          case "ECONNREFUSED": {
            if (this.#state.dualStack) {
              this.#state.runLookup(this.#origin, this.#opts, (err2, newOrigin) => {
                if (err2) {
                  return this.#handler.onError(err2);
                }
                const dispatchOpts = {
                  ...this.#opts,
                  origin: newOrigin
                };
                this.#dispatch(dispatchOpts, this);
              });
              return;
            }
            this.#handler.onError(err);
            return;
          }
          case "ENOTFOUND":
            this.#state.deleteRecord(this.#origin);
          // eslint-disable-next-line no-fallthrough
          default:
            this.#handler.onError(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 (isIP3(origin.hostname) !== 0) {
            return dispatch(origDispatchOpts, handler);
          }
          instance.runLookup(origin, origDispatchOpts, (err, newOrigin) => {
            if (err) {
              return handler.onError(err);
            }
            let dispatchOpts = null;
            dispatchOpts = {
              ...origDispatchOpts,
              servername: origin.hostname,
              // For SNI on TLS
              origin: newOrigin,
              headers: {
                host: origin.hostname,
                ...origDispatchOpts.headers
              }
            };
            dispatch(
              dispatchOpts,
              instance.getHandler({ origin, dispatch, handler }, origDispatchOpts)
            );
          });
          return true;
        }, "dnsInterceptor");
      };
    };
  }
});

// packages/core/node_modules/undici/lib/web/fetch/headers.js
var require_headers = __commonJS({
  "packages/core/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 assert4 = __require("node:assert");
    var util3 = __require("node:util");
    var kHeadersMap = Symbol("headers map");
    var kHeadersSortedMap = Symbol("headers map sorted");
    function isHTTPWhiteSpaceCharCode(code2) {
      return code2 === 10 || code2 === 13 || code2 === 9 || code2 === 32;
    }
    __name(isHTTPWhiteSpaceCharCode, "isHTTPWhiteSpaceCharCode");
    function headerValueNormalize(potentialValue) {
      let i3 = 0;
      let j2 = potentialValue.length;
      while (j2 > i3 && isHTTPWhiteSpaceCharCode(potentialValue.charCodeAt(j2 - 1))) --j2;
      while (j2 > i3 && isHTTPWhiteSpaceCharCode(potentialValue.charCodeAt(i3))) ++i3;
      return i3 === 0 && j2 === potentialValue.length ? potentialValue : potentialValue.substring(i3, j2);
    }
    __name(headerValueNormalize, "headerValueNormalize");
    function fill(headers, object3) {
      if (Array.isArray(object3)) {
        for (let i3 = 0; i3 < object3.length; ++i3) {
          const header = object3[i3];
          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 object3 === "object" && object3 !== null) {
        const keys = Object.keys(object3);
        for (let i3 = 0; i3 < keys.length; ++i3) {
          appendHeader(headers, keys[i3], object3[keys[i3]]);
        }
      } 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 compareHeaderName(a2, b2) {
      return a2[0] < b2[0] ? -1 : 1;
    }
    __name(compareHeaderName, "compareHeaderName");
    var HeadersList = class _HeadersList {
      static {
        __name(this, "HeadersList");
      }
      /** @type {[string, string][]|null} */
      cookies = null;
      constructor(init) {
        if (init instanceof _HeadersList) {
          this[kHeadersMap] = new Map(init[kHeadersMap]);
          this[kHeadersSortedMap] = init[kHeadersSortedMap];
          this.cookies = init.cookies === null ? null : [...init.cookies];
        } else {
          this[kHeadersMap] = new Map(init);
          this[kHeadersSortedMap] = null;
        }
      }
      /**
       * @see https://fetch.spec.whatwg.org/#header-list-contains
       * @param {string} name
       * @param {boolean} isLowerCase
       */
      contains(name3, isLowerCase) {
        return this[kHeadersMap].has(isLowerCase ? name3 : name3.toLowerCase());
      }
      clear() {
        this[kHeadersMap].clear();
        this[kHeadersSortedMap] = 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[kHeadersSortedMap] = null;
        const lowercaseName = isLowerCase ? name3 : name3.toLowerCase();
        const exists2 = this[kHeadersMap].get(lowercaseName);
        if (exists2) {
          const delimiter2 = lowercaseName === "cookie" ? "; " : ", ";
          this[kHeadersMap].set(lowercaseName, {
            name: exists2.name,
            value: `${exists2.value}${delimiter2}${value}`
          });
        } else {
          this[kHeadersMap].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[kHeadersSortedMap] = null;
        const lowercaseName = isLowerCase ? name3 : name3.toLowerCase();
        if (lowercaseName === "set-cookie") {
          this.cookies = [value];
        }
        this[kHeadersMap].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[kHeadersSortedMap] = null;
        if (!isLowerCase) name3 = name3.toLowerCase();
        if (name3 === "set-cookie") {
          this.cookies = null;
        }
        this[kHeadersMap].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[kHeadersMap].get(isLowerCase ? name3 : name3.toLowerCase())?.value ?? null;
      }
      *[Symbol.iterator]() {
        for (const { 0: name3, 1: { value } } of this[kHeadersMap]) {
          yield [name3, value];
        }
      }
      get entries() {
        const headers = {};
        if (this[kHeadersMap].size !== 0) {
          for (const { name: name3, value } of this[kHeadersMap].values()) {
            headers[name3] = value;
          }
        }
        return headers;
      }
      rawValues() {
        return this[kHeadersMap].values();
      }
      get entriesList() {
        const headers = [];
        if (this[kHeadersMap].size !== 0) {
          for (const { 0: lowerName, 1: { name: name3, value } } of this[kHeadersMap]) {
            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[kHeadersMap].size;
        const array2 = new Array(size);
        if (size <= 32) {
          if (size === 0) {
            return array2;
          }
          const iterator = this[kHeadersMap][Symbol.iterator]();
          const firstValue = iterator.next().value;
          array2[0] = [firstValue[0], firstValue[1].value];
          assert4(firstValue[1].value !== null);
          for (let i3 = 1, j2 = 0, right3 = 0, left3 = 0, pivot = 0, x3, value; i3 < size; ++i3) {
            value = iterator.next().value;
            x3 = array2[i3] = [value[0], value[1].value];
            assert4(x3[1] !== null);
            left3 = 0;
            right3 = i3;
            while (left3 < right3) {
              pivot = left3 + (right3 - left3 >> 1);
              if (array2[pivot][0] <= x3[0]) {
                left3 = pivot + 1;
              } else {
                right3 = pivot;
              }
            }
            if (i3 !== pivot) {
              j2 = i3;
              while (j2 > left3) {
                array2[j2] = array2[--j2];
              }
              array2[left3] = x3;
            }
          }
          if (!iterator.next().done) {
            throw new TypeError("Unreachable");
          }
          return array2;
        } else {
          let i3 = 0;
          for (const { 0: name3, 1: { value } } of this[kHeadersMap]) {
            array2[i3++] = [name3, value];
            assert4(value !== null);
          }
          return array2.sort(compareHeaderName);
        }
      }
    };
    var Headers6 = class _Headers {
      static {
        __name(this, "Headers");
      }
      #guard;
      #headersList;
      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 contructor", "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 [];
      }
      // https://fetch.spec.whatwg.org/#concept-header-list-sort-and-combine
      get [kHeadersSortedMap]() {
        if (this.#headersList[kHeadersSortedMap]) {
          return this.#headersList[kHeadersSortedMap];
        }
        const headers = [];
        const names = this.#headersList.toSortedArray();
        const cookies = this.#headersList.cookies;
        if (cookies === null || cookies.length === 1) {
          return this.#headersList[kHeadersSortedMap] = names;
        }
        for (let i3 = 0; i3 < names.length; ++i3) {
          const { 0: name3, 1: value } = names[i3];
          if (name3 === "set-cookie") {
            for (let j2 = 0; j2 < cookies.length; ++j2) {
              headers.push([name3, cookies[j2]]);
            }
          } else {
            headers.push([name3, value]);
          }
        }
        return this.#headersList[kHeadersSortedMap] = headers;
      }
      [util3.inspect.custom](depth, options2) {
        options2.depth ??= depth;
        return `Headers ${util3.formatWithOptions(options2, this.#headersList.entries)}`;
      }
      static getHeadersGuard(o3) {
        return o3.#guard;
      }
      static setHeadersGuard(o3, guard) {
        o3.#guard = guard;
      }
      static getHeadersList(o3) {
        return o3.#headersList;
      }
      static setHeadersList(o3, list3) {
        o3.#headersList = list3;
      }
    };
    var { getHeadersGuard, setHeadersGuard, getHeadersList, setHeadersList } = Headers6;
    Reflect.deleteProperty(Headers6, "getHeadersGuard");
    Reflect.deleteProperty(Headers6, "setHeadersGuard");
    Reflect.deleteProperty(Headers6, "getHeadersList");
    Reflect.deleteProperty(Headers6, "setHeadersList");
    iteratorMixin("Headers", Headers6, kHeadersSortedMap, 0, 1);
    Object.defineProperties(Headers6.prototype, {
      append: kEnumerableProperty,
      delete: kEnumerableProperty,
      get: kEnumerableProperty,
      has: kEnumerableProperty,
      set: kEnumerableProperty,
      getSetCookie: kEnumerableProperty,
      [Symbol.toStringTag]: {
        value: "Headers",
        configurable: true
      },
      [util3.inspect.custom]: {
        enumerable: false
      }
    });
    webidl.converters.HeadersInit = function(V3, prefix, argument) {
      if (webidl.util.Type(V3) === "Object") {
        const iterator = Reflect.get(V3, Symbol.iterator);
        if (!util3.types.isProxy(V3) && iterator === Headers6.prototype.entries) {
          try {
            return getHeadersList(V3).entriesList;
          } catch {
          }
        }
        if (typeof iterator === "function") {
          return webidl.converters["sequence<sequence<ByteString>>"](V3, prefix, argument, iterator.bind(V3));
        }
        return webidl.converters["record<ByteString, ByteString>"](V3, 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: Headers6,
      HeadersList,
      getHeadersGuard,
      setHeadersGuard,
      setHeadersList,
      getHeadersList
    };
  }
});

// packages/core/node_modules/undici/lib/web/fetch/response.js
var require_response = __commonJS({
  "packages/core/node_modules/undici/lib/web/fetch/response.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var { Headers: Headers6, HeadersList, fill, getHeadersGuard, setHeadersGuard, setHeadersList } = require_headers();
    var { extractBody, cloneBody, mixinBody, hasFinalizationRegistry, streamRegistry, bodyUnusable } = require_body();
    var util3 = require_util();
    var nodeUtil = __require("node:util");
    var { kEnumerableProperty } = util3;
    var {
      isValidReasonPhrase,
      isCancelled,
      isAborted: isAborted2,
      isBlobLike: isBlobLike3,
      serializeJavascriptValueToJSONString,
      isErrorLike,
      isomorphicEncode,
      environmentSettingsObject: relevantRealm
    } = require_util2();
    var {
      redirectStatusSet,
      nullBodyStatus
    } = require_constants3();
    var { kState, kHeaders } = require_symbols2();
    var { webidl } = require_webidl();
    var { FormData: FormData6 } = require_formdata();
    var { URLSerializer } = require_data_url();
    var { kConstruct } = require_symbols();
    var assert4 = __require("node:assert");
    var { types: types7 } = __require("node:util");
    var textEncoder = new TextEncoder("utf-8");
    var Response6 = class _Response {
      static {
        __name(this, "Response");
      }
      // 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 = {}) {
        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[kState].status = status;
        const value = isomorphicEncode(URLSerializer(parsedURL));
        responseObject[kState].headersList.append("location", value, true);
        return responseObject;
      }
      // https://fetch.spec.whatwg.org/#dom-response
      constructor(body = null, init = {}) {
        webidl.util.markAsUncloneable(this);
        if (body === kConstruct) {
          return;
        }
        if (body !== null) {
          body = webidl.converters.BodyInit(body);
        }
        init = webidl.converters.ResponseInit(init);
        this[kState] = makeResponse({});
        this[kHeaders] = new Headers6(kConstruct);
        setHeadersGuard(this[kHeaders], "response");
        setHeadersList(this[kHeaders], this[kState].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[kState].type;
      }
      // Returns response’s URL, if it has one; otherwise the empty string.
      get url() {
        webidl.brandCheck(this, _Response);
        const urlList = this[kState].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[kState].urlList.length > 1;
      }
      // Returns response’s status.
      get status() {
        webidl.brandCheck(this, _Response);
        return this[kState].status;
      }
      // Returns whether response’s status is an ok status.
      get ok() {
        webidl.brandCheck(this, _Response);
        return this[kState].status >= 200 && this[kState].status <= 299;
      }
      // Returns response’s status message.
      get statusText() {
        webidl.brandCheck(this, _Response);
        return this[kState].statusText;
      }
      // Returns response’s headers as Headers.
      get headers() {
        webidl.brandCheck(this, _Response);
        return this[kHeaders];
      }
      get body() {
        webidl.brandCheck(this, _Response);
        return this[kState].body ? this[kState].body.stream : null;
      }
      get bodyUsed() {
        webidl.brandCheck(this, _Response);
        return !!this[kState].body && util3.isDisturbed(this[kState].body.stream);
      }
      // Returns a clone of response.
      clone() {
        webidl.brandCheck(this, _Response);
        if (bodyUnusable(this)) {
          throw webidl.errors.exception({
            header: "Response.clone",
            message: "Body has already been consumed."
          });
        }
        const clonedResponse = cloneResponse(this[kState]);
        if (hasFinalizationRegistry && this[kState].body?.stream) {
          streamRegistry.register(this, new WeakRef(this[kState].body.stream));
        }
        return fromInnerResponse(clonedResponse, getHeadersGuard(this[kHeaders]));
      }
      [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)}`;
      }
    };
    mixinBody(Response6);
    Object.defineProperties(Response6.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(Response6, {
      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(newResponse, 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, p2) {
          return p2 in state ? state[p2] : target[p2];
        },
        set(target, p2, value) {
          assert4(!(p2 in state));
          target[p2] = 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 {
        assert4(false);
      }
    }
    __name(filterResponse, "filterResponse");
    function makeAppropriateNetworkError(fetchParams, err = null) {
      assert4(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) {
        response[kState].status = init.status;
      }
      if ("statusText" in init && init.statusText != null) {
        response[kState].statusText = init.statusText;
      }
      if ("headers" in init && init.headers != null) {
        fill(response[kHeaders], init.headers);
      }
      if (body) {
        if (nullBodyStatus.includes(response.status)) {
          throw webidl.errors.exception({
            header: "Response constructor",
            message: `Invalid response status code ${response.status}`
          });
        }
        response[kState].body = body.body;
        if (body.type != null && !response[kState].headersList.contains("content-type", true)) {
          response[kState].headersList.append("content-type", body.type, true);
        }
      }
    }
    __name(initializeResponse, "initializeResponse");
    function fromInnerResponse(innerResponse, guard) {
      const response = new Response6(kConstruct);
      response[kState] = innerResponse;
      response[kHeaders] = new Headers6(kConstruct);
      setHeadersList(response[kHeaders], innerResponse.headersList);
      setHeadersGuard(response[kHeaders], guard);
      if (hasFinalizationRegistry && innerResponse.body?.stream) {
        streamRegistry.register(response, new WeakRef(innerResponse.body.stream));
      }
      return response;
    }
    __name(fromInnerResponse, "fromInnerResponse");
    webidl.converters.ReadableStream = webidl.interfaceConverter(
      ReadableStream
    );
    webidl.converters.FormData = webidl.interfaceConverter(
      FormData6
    );
    webidl.converters.URLSearchParams = webidl.interfaceConverter(
      URLSearchParams
    );
    webidl.converters.XMLHttpRequestBodyInit = function(V3, prefix, name3) {
      if (typeof V3 === "string") {
        return webidl.converters.USVString(V3, prefix, name3);
      }
      if (isBlobLike3(V3)) {
        return webidl.converters.Blob(V3, prefix, name3, { strict: false });
      }
      if (ArrayBuffer.isView(V3) || types7.isArrayBuffer(V3)) {
        return webidl.converters.BufferSource(V3, prefix, name3);
      }
      if (util3.isFormDataLike(V3)) {
        return webidl.converters.FormData(V3, prefix, name3, { strict: false });
      }
      if (V3 instanceof URLSearchParams) {
        return webidl.converters.URLSearchParams(V3, prefix, name3);
      }
      return webidl.converters.DOMString(V3, prefix, name3);
    };
    webidl.converters.BodyInit = function(V3, prefix, argument) {
      if (V3 instanceof ReadableStream) {
        return webidl.converters.ReadableStream(V3, prefix, argument);
      }
      if (V3?.[Symbol.asyncIterator]) {
        return V3;
      }
      return webidl.converters.XMLHttpRequestBodyInit(V3, 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
      }
    ]);
    module2.exports = {
      isNetworkError,
      makeNetworkError,
      makeResponse,
      makeAppropriateNetworkError,
      filterResponse,
      Response: Response6,
      cloneResponse,
      fromInnerResponse
    };
  }
});

// packages/core/node_modules/undici/lib/web/fetch/dispatcher-weakref.js
var require_dispatcher_weakref = __commonJS({
  "packages/core/node_modules/undici/lib/web/fetch/dispatcher-weakref.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var { kConnected, kSize } = require_symbols();
    var CompatWeakRef = class {
      static {
        __name(this, "CompatWeakRef");
      }
      constructor(value) {
        this.value = value;
      }
      deref() {
        return this.value[kConnected] === 0 && this.value[kSize] === 0 ? void 0 : this.value;
      }
    };
    var CompatFinalizer = class {
      static {
        __name(this, "CompatFinalizer");
      }
      constructor(finalizer) {
        this.finalizer = finalizer;
      }
      register(dispatcher, key) {
        if (dispatcher.on) {
          dispatcher.on("disconnect", () => {
            if (dispatcher[kConnected] === 0 && dispatcher[kSize] === 0) {
              this.finalizer(key);
            }
          });
        }
      }
      unregister(key) {
      }
    };
    module2.exports = function() {
      if (process.env.NODE_V8_COVERAGE && process.version.startsWith("v18")) {
        process._rawDebug("Using compatibility WeakRef and FinalizationRegistry");
        return {
          WeakRef: CompatWeakRef,
          FinalizationRegistry: CompatFinalizer
        };
      }
      return { WeakRef, FinalizationRegistry };
    };
  }
});

// packages/core/node_modules/undici/lib/web/fetch/request.js
var require_request2 = __commonJS({
  "packages/core/node_modules/undici/lib/web/fetch/request.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var { extractBody, mixinBody, cloneBody, bodyUnusable } = require_body();
    var { Headers: Headers6, fill: fillHeaders, HeadersList, setHeadersGuard, getHeadersGuard, setHeadersList, getHeadersList } = require_headers();
    var { FinalizationRegistry: FinalizationRegistry2 } = require_dispatcher_weakref()();
    var util3 = require_util();
    var nodeUtil = __require("node:util");
    var {
      isValidHTTPToken,
      sameOrigin,
      environmentSettingsObject
    } = require_util2();
    var {
      forbiddenMethodsSet,
      corsSafeListedMethodsSet,
      referrerPolicy,
      requestRedirect,
      requestMode,
      requestCredentials,
      requestCache,
      requestDuplex
    } = require_constants3();
    var { kEnumerableProperty, normalizedMethodRecordsBase, normalizedMethodRecords } = util3;
    var { kHeaders, kSignal, kState, kDispatcher } = require_symbols2();
    var { webidl } = require_webidl();
    var { URLSerializer } = require_data_url();
    var { kConstruct } = require_symbols();
    var assert4 = __require("node:assert");
    var { getMaxListeners, setMaxListeners, getEventListeners, defaultMaxListeners } = __require("node:events");
    var kAbortController = Symbol("abortController");
    var requestFinalizer = new FinalizationRegistry2(({ signal, abort }) => {
      signal.removeEventListener("abort", abort);
    });
    var dependentControllerMap = /* @__PURE__ */ new WeakMap();
    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 Request6 = class _Request {
      static {
        __name(this, "Request");
      }
      // https://fetch.spec.whatwg.org/#dom-request
      constructor(input, init = {}) {
        webidl.util.markAsUncloneable(this);
        if (input === kConstruct) {
          return;
        }
        const prefix = "Request constructor";
        webidl.argumentLengthCheck(arguments, 1, prefix);
        input = webidl.converters.RequestInfo(input, prefix, "input");
        init = webidl.converters.RequestInit(init, prefix, "init");
        let request4 = null;
        let fallbackMode = null;
        const baseUrl = environmentSettingsObject.settingsObject.baseUrl;
        let signal = null;
        if (typeof input === "string") {
          this[kDispatcher] = 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 {
          this[kDispatcher] = init.dispatcher || input[kDispatcher];
          assert4(input instanceof _Request);
          request4 = input[kState];
          signal = input[kSignal];
        }
        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[kState] = request4;
        const ac = new AbortController();
        this[kSignal] = ac.signal;
        if (signal != null) {
          if (!signal || typeof signal.aborted !== "boolean" || typeof signal.addEventListener !== "function") {
            throw new TypeError(
              "Failed to construct 'Request': member signal is not of type AbortSignal."
            );
          }
          if (signal.aborted) {
            ac.abort(signal.reason);
          } else {
            this[kAbortController] = ac;
            const acRef = new WeakRef(ac);
            const abort = buildAbort(acRef);
            try {
              if (typeof getMaxListeners === "function" && getMaxListeners(signal) === defaultMaxListeners) {
                setMaxListeners(1500, signal);
              } else if (getEventListeners(signal, "abort").length >= defaultMaxListeners) {
                setMaxListeners(1500, signal);
              }
            } catch {
            }
            util3.addAbortListener(signal, abort);
            requestFinalizer.register(ac, { signal, abort }, abort);
          }
        }
        this[kHeaders] = new Headers6(kConstruct);
        setHeadersList(this[kHeaders], request4.headersList);
        setHeadersGuard(this[kHeaders], "request");
        if (mode === "no-cors") {
          if (!corsSafeListedMethodsSet.has(request4.method)) {
            throw new TypeError(
              `'${request4.method} is unsupported in no-cors mode.`
            );
          }
          setHeadersGuard(this[kHeaders], "request-no-cors");
        }
        if (initHasKey) {
          const headersList = getHeadersList(this[kHeaders]);
          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[kHeaders], headers);
          }
        }
        const inputBody = input instanceof _Request ? input[kState].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[kHeaders]).contains("content-type", true)) {
            this[kHeaders].append("content-type", contentType);
          }
        }
        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)) {
            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[kState].body = finalBody;
      }
      // Returns request’s HTTP method, which is "GET" by default.
      get method() {
        webidl.brandCheck(this, _Request);
        return this[kState].method;
      }
      // Returns the URL of request as a string.
      get url() {
        webidl.brandCheck(this, _Request);
        return URLSerializer(this[kState].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[kHeaders];
      }
      // Returns the kind of resource requested by request, e.g., "document"
      // or "script".
      get destination() {
        webidl.brandCheck(this, _Request);
        return this[kState].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[kState].referrer === "no-referrer") {
          return "";
        }
        if (this[kState].referrer === "client") {
          return "about:client";
        }
        return this[kState].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[kState].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[kState].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() {
        return this[kState].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[kState].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[kState].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[kState].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[kState].keepalive;
      }
      // Returns a boolean indicating whether or not request is for a reload
      // navigation.
      get isReloadNavigation() {
        webidl.brandCheck(this, _Request);
        return this[kState].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[kState].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[kSignal];
      }
      get body() {
        webidl.brandCheck(this, _Request);
        return this[kState].body ? this[kState].body.stream : null;
      }
      get bodyUsed() {
        webidl.brandCheck(this, _Request);
        return !!this[kState].body && util3.isDisturbed(this[kState].body.stream);
      }
      get duplex() {
        webidl.brandCheck(this, _Request);
        return "half";
      }
      // Returns a clone of request.
      clone() {
        webidl.brandCheck(this, _Request);
        if (bodyUnusable(this)) {
          throw new TypeError("unusable");
        }
        const clonedRequest = cloneRequest(this[kState]);
        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);
          util3.addAbortListener(
            ac.signal,
            buildAbort(acRef)
          );
        }
        return fromInnerRequest(clonedRequest, ac.signal, getHeadersGuard(this[kHeaders]));
      }
      [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)}`;
      }
    };
    mixinBody(Request6);
    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(newRequest, request4.body);
      }
      return newRequest;
    }
    __name(cloneRequest, "cloneRequest");
    function fromInnerRequest(innerRequest, signal, guard) {
      const request4 = new Request6(kConstruct);
      request4[kState] = innerRequest;
      request4[kSignal] = signal;
      request4[kHeaders] = new Headers6(kConstruct);
      setHeadersList(request4[kHeaders], innerRequest.headersList);
      setHeadersGuard(request4[kHeaders], guard);
      return request4;
    }
    __name(fromInnerRequest, "fromInnerRequest");
    Object.defineProperties(Request6.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.converters.Request = webidl.interfaceConverter(
      Request6
    );
    webidl.converters.RequestInfo = function(V3, prefix, argument) {
      if (typeof V3 === "string") {
        return webidl.converters.USVString(V3, prefix, argument);
      }
      if (V3 instanceof Request6) {
        return webidl.converters.Request(V3, prefix, argument);
      }
      return webidl.converters.USVString(V3, prefix, argument);
    };
    webidl.converters.AbortSignal = webidl.interfaceConverter(
      AbortSignal
    );
    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",
            { strict: false }
          )
        )
      },
      {
        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: Request6, makeRequest, fromInnerRequest, cloneRequest };
  }
});

// packages/core/node_modules/undici/lib/web/fetch/index.js
var require_fetch = __commonJS({
  "packages/core/node_modules/undici/lib/web/fetch/index.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var {
      makeNetworkError,
      makeAppropriateNetworkError,
      filterResponse,
      makeResponse,
      fromInnerResponse
    } = require_response();
    var { HeadersList } = require_headers();
    var { Request: Request6, cloneRequest } = require_request2();
    var zlib4 = __require("node:zlib");
    var {
      bytesMatch,
      makePolicyContainer,
      clonePolicyContainer,
      requestBadPort,
      TAOCheck,
      appendRequestOriginHeader,
      responseLocationURL,
      requestCurrentURL,
      setRequestReferrerPolicyOnRedirect,
      tryUpgradeRequestToAPotentiallyTrustworthyURL,
      createOpaqueTimingInfo,
      appendFetchMetadata,
      corsCheck,
      crossOriginResourcePolicyCheck,
      determineRequestsReferrer: determineRequestsReferrer3,
      coarsenedSharedCurrentTime,
      createDeferredPromise,
      isBlobLike: isBlobLike3,
      sameOrigin,
      isCancelled,
      isAborted: isAborted2,
      isErrorLike,
      fullyReadBody,
      readableStreamClose,
      isomorphicEncode,
      urlIsLocal,
      urlIsHttpHttpsScheme,
      urlHasHttpsScheme,
      clampAndCoarsenConnectionTimingInfo,
      simpleRangeHeaderValue,
      buildContentRange,
      createInflate,
      extractMimeType
    } = require_util2();
    var { kState, kDispatcher } = require_symbols2();
    var assert4 = __require("node:assert");
    var { safelyExtractBody, extractBody } = require_body();
    var {
      redirectStatusSet,
      nullBodyStatus,
      safeMethodsSet,
      requestBodyHeader,
      subresourceSet
    } = require_constants3();
    var EE3 = __require("node:events");
    var { Readable: Readable6, pipeline: pipeline3, finished: finished2 } = __require("node:stream");
    var { addAbortListener, isErrored, isReadable: isReadable2, 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 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(error2) {
        if (this.state !== "ongoing") {
          return;
        }
        this.state = "aborted";
        if (!error2) {
          error2 = new DOMException("The operation was aborted.", "AbortError");
        }
        this.serializedAbortReason = error2;
        this.connection?.destroy(error2);
        this.emit("terminated", error2);
      }
    };
    function handleFetchDone(response) {
      finalizeAndReportTiming(response, "fetch");
    }
    __name(handleFetchDone, "handleFetchDone");
    function fetch5(input, init = void 0) {
      webidl.argumentLengthCheck(arguments, 1, "globalThis.fetch");
      let p2 = createDeferredPromise();
      let requestObject;
      try {
        requestObject = new Request6(input, init);
      } catch (e4) {
        p2.reject(e4);
        return p2.promise;
      }
      const request4 = requestObject[kState];
      if (requestObject.signal.aborted) {
        abortFetch(p2, request4, null, requestObject.signal.reason);
        return p2.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;
          assert4(controller != null);
          controller.abort(requestObject.signal.reason);
          const realResponse = responseObject?.deref();
          abortFetch(p2, request4, realResponse, requestObject.signal.reason);
        }
      );
      const processResponse = /* @__PURE__ */ __name((response) => {
        if (locallyAborted) {
          return;
        }
        if (response.aborted) {
          abortFetch(p2, request4, responseObject, controller.serializedAbortReason);
          return;
        }
        if (response.type === "error") {
          p2.reject(new TypeError("fetch failed", { cause: response.error }));
          return;
        }
        responseObject = new WeakRef(fromInnerResponse(response, "immutable"));
        p2.resolve(responseObject.deref());
        p2 = null;
      }, "processResponse");
      controller = fetching({
        request: request4,
        processResponseEndOfBody: handleFetchDone,
        processResponse,
        dispatcher: requestObject[kDispatcher]
        // undici
      });
      return p2.promise;
    }
    __name(fetch5, "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
      );
    }
    __name(finalizeAndReportTiming, "finalizeAndReportTiming");
    var markResourceTiming = performance.markResourceTiming;
    function abortFetch(p2, request4, responseObject, error2) {
      if (p2) {
        p2.reject(error2);
      }
      if (request4.body != null && isReadable2(request4.body?.stream)) {
        request4.body.stream.cancel(error2).catch((err) => {
          if (err.code === "ERR_INVALID_STATE") {
            return;
          }
          throw err;
        });
      }
      if (responseObject == null) {
        return;
      }
      const response = responseObject[kState];
      if (response.body != null && isReadable2(response.body?.stream)) {
        response.body.stream.cancel(error2).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
    }) {
      assert4(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
      };
      assert4(!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).catch((err) => {
        fetchParams.controller.terminate(err);
      });
      return fetchParams.controller;
    }
    __name(fetching, "fetching");
    async function mainFetch(fetchParams, recursive = false) {
      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 = determineRequestsReferrer3(request4);
      }
      if (response === null) {
        response = await (async () => {
          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";
            return await schemeFetch(fetchParams);
          }
          if (request4.mode === "same-origin") {
            return makeNetworkError('request mode cannot be "same-origin"');
          }
          if (request4.mode === "no-cors") {
            if (request4.redirect !== "follow") {
              return makeNetworkError(
                'redirect mode cannot be "follow" for "no-cors" request'
              );
            }
            request4.responseTainting = "opaque";
            return await schemeFetch(fetchParams);
          }
          if (!urlIsHttpHttpsScheme(requestCurrentURL(request4))) {
            return makeNetworkError("URL scheme must be a HTTP(S) scheme");
          }
          request4.responseTainting = "cors";
          return 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 {
          assert4(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");
        await fullyReadBody(response.body, processBody, processBodyError);
      } else {
        fetchFinale(fetchParams, response);
      }
    }
    __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" || !isBlobLike3(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 (fetchParams.request.url.protocol !== "https:") {
            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 {
        finished2(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 {
          assert4(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) {
        assert4(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 (httpRequest.referrer instanceof URL) {
        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);
      }
      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) {
      assert4(!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((e4) => {
          if (isCancelled(fetchParams)) {
            return;
          }
          if (e4.name === "AbortError") {
            fetchParams.controller.abort();
          } else {
            fetchParams.controller.terminate(e4);
          }
        }, "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(async () => {
        await fetchParams.controller.resume();
      }, "pullAlgorithm");
      const cancelAlgorithm = /* @__PURE__ */ __name((reason) => {
        if (!isCancelled(fetchParams)) {
          fetchParams.controller.abort(reason);
        }
      }, "cancelAlgorithm");
      const stream2 = new ReadableStream(
        {
          async start(controller) {
            fetchParams.controller.controller = controller;
          },
          async pull(controller) {
            await pullAlgorithm(controller);
          },
          async cancel(reason) {
            await cancelAlgorithm(reason);
          },
          type: "bytes"
        }
      );
      response.body = { stream: stream2, source: null, length: null };
      fetchParams.controller.onAborted = onAborted;
      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((resolve30, 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;
              }
              let codings = [];
              let location = "";
              const headersList = new HeadersList();
              for (let i3 = 0; i3 < rawHeaders.length; i3 += 2) {
                headersList.append(bufferToLowerCasedHeaderName(rawHeaders[i3]), rawHeaders[i3 + 1].toString("latin1"), true);
              }
              const contentEncoding = headersList.get("content-encoding", true);
              if (contentEncoding) {
                codings = contentEncoding.toLowerCase().split(",").map((x3) => x3.trim());
              }
              location = headersList.get("location", true);
              this.body = new Readable6({ 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 i3 = codings.length - 1; i3 >= 0; --i3) {
                  const coding = codings[i3];
                  if (coding === "x-gzip" || coding === "gzip") {
                    decoders.push(zlib4.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: zlib4.constants.Z_SYNC_FLUSH,
                      finishFlush: zlib4.constants.Z_SYNC_FLUSH
                    }));
                  } else if (coding === "deflate") {
                    decoders.push(createInflate({
                      flush: zlib4.constants.Z_SYNC_FLUSH,
                      finishFlush: zlib4.constants.Z_SYNC_FLUSH
                    }));
                  } else if (coding === "br") {
                    decoders.push(zlib4.createBrotliDecompress({
                      flush: zlib4.constants.BROTLI_OPERATION_FLUSH,
                      finishFlush: zlib4.constants.BROTLI_OPERATION_FLUSH
                    }));
                  } else {
                    decoders.length = 0;
                    break;
                  }
                }
              }
              const onError2 = this.onError.bind(this);
              resolve30({
                status,
                statusText,
                headersList,
                body: decoders.length ? pipeline3(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);
              }
              if (fetchParams.controller.onAborted) {
                fetchParams.controller.off("terminated", fetchParams.controller.onAborted);
              }
              fetchParams.controller.ended = true;
              this.body.push(null);
            },
            onError(error2) {
              if (this.abort) {
                fetchParams.controller.off("terminated", this.abort);
              }
              this.body?.destroy(error2);
              fetchParams.controller.terminate(error2);
              reject(error2);
            },
            onUpgrade(status, rawHeaders, socket) {
              if (status !== 101) {
                return;
              }
              const headersList = new HeadersList();
              for (let i3 = 0; i3 < rawHeaders.length; i3 += 2) {
                headersList.append(bufferToLowerCasedHeaderName(rawHeaders[i3]), rawHeaders[i3 + 1].toString("latin1"), true);
              }
              resolve30({
                status,
                statusText: STATUS_CODES[status],
                headersList,
                socket
              });
              return true;
            }
          }
        ));
      }
      __name(dispatch, "dispatch");
    }
    __name(httpNetworkFetch, "httpNetworkFetch");
    module2.exports = {
      fetch: fetch5,
      Fetch,
      fetching,
      finalizeAndReportTiming
    };
  }
});

// packages/core/node_modules/undici/lib/web/fileapi/symbols.js
var require_symbols3 = __commonJS({
  "packages/core/node_modules/undici/lib/web/fileapi/symbols.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    module2.exports = {
      kState: Symbol("FileReader state"),
      kResult: Symbol("FileReader result"),
      kError: Symbol("FileReader error"),
      kLastProgressEventFired: Symbol("FileReader last progress event fired timestamp"),
      kEvents: Symbol("FileReader events"),
      kAborted: Symbol("FileReader aborted")
    };
  }
});

// packages/core/node_modules/undici/lib/web/fileapi/progressevent.js
var require_progressevent = __commonJS({
  "packages/core/node_modules/undici/lib/web/fileapi/progressevent.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var { webidl } = require_webidl();
    var kState = Symbol("ProgressEvent state");
    var ProgressEvent = class _ProgressEvent extends Event {
      static {
        __name(this, "ProgressEvent");
      }
      constructor(type, eventInitDict = {}) {
        type = webidl.converters.DOMString(type, "ProgressEvent constructor", "type");
        eventInitDict = webidl.converters.ProgressEventInit(eventInitDict ?? {});
        super(type, eventInitDict);
        this[kState] = {
          lengthComputable: eventInitDict.lengthComputable,
          loaded: eventInitDict.loaded,
          total: eventInitDict.total
        };
      }
      get lengthComputable() {
        webidl.brandCheck(this, _ProgressEvent);
        return this[kState].lengthComputable;
      }
      get loaded() {
        webidl.brandCheck(this, _ProgressEvent);
        return this[kState].loaded;
      }
      get total() {
        webidl.brandCheck(this, _ProgressEvent);
        return this[kState].total;
      }
    };
    webidl.converters.ProgressEventInit = webidl.dictionaryConverter([
      {
        key: "lengthComputable",
        converter: webidl.converters.boolean,
        defaultValue: /* @__PURE__ */ __name(() => false, "defaultValue")
      },
      {
        key: "loaded",
        converter: webidl.converters["unsigned long long"],
        defaultValue: /* @__PURE__ */ __name(() => 0, "defaultValue")
      },
      {
        key: "total",
        converter: webidl.converters["unsigned long long"],
        defaultValue: /* @__PURE__ */ __name(() => 0, "defaultValue")
      },
      {
        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")
      }
    ]);
    module2.exports = {
      ProgressEvent
    };
  }
});

// packages/core/node_modules/undici/lib/web/fileapi/encoding.js
var require_encoding = __commonJS({
  "packages/core/node_modules/undici/lib/web/fileapi/encoding.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    function getEncoding(label) {
      if (!label) {
        return "failure";
      }
      switch (label.trim().toLowerCase()) {
        case "unicode-1-1-utf-8":
        case "unicode11utf8":
        case "unicode20utf8":
        case "utf-8":
        case "utf8":
        case "x-unicode20utf8":
          return "UTF-8";
        case "866":
        case "cp866":
        case "csibm866":
        case "ibm866":
          return "IBM866";
        case "csisolatin2":
        case "iso-8859-2":
        case "iso-ir-101":
        case "iso8859-2":
        case "iso88592":
        case "iso_8859-2":
        case "iso_8859-2:1987":
        case "l2":
        case "latin2":
          return "ISO-8859-2";
        case "csisolatin3":
        case "iso-8859-3":
        case "iso-ir-109":
        case "iso8859-3":
        case "iso88593":
        case "iso_8859-3":
        case "iso_8859-3:1988":
        case "l3":
        case "latin3":
          return "ISO-8859-3";
        case "csisolatin4":
        case "iso-8859-4":
        case "iso-ir-110":
        case "iso8859-4":
        case "iso88594":
        case "iso_8859-4":
        case "iso_8859-4:1988":
        case "l4":
        case "latin4":
          return "ISO-8859-4";
        case "csisolatincyrillic":
        case "cyrillic":
        case "iso-8859-5":
        case "iso-ir-144":
        case "iso8859-5":
        case "iso88595":
        case "iso_8859-5":
        case "iso_8859-5:1988":
          return "ISO-8859-5";
        case "arabic":
        case "asmo-708":
        case "csiso88596e":
        case "csiso88596i":
        case "csisolatinarabic":
        case "ecma-114":
        case "iso-8859-6":
        case "iso-8859-6-e":
        case "iso-8859-6-i":
        case "iso-ir-127":
        case "iso8859-6":
        case "iso88596":
        case "iso_8859-6":
        case "iso_8859-6:1987":
          return "ISO-8859-6";
        case "csisolatingreek":
        case "ecma-118":
        case "elot_928":
        case "greek":
        case "greek8":
        case "iso-8859-7":
        case "iso-ir-126":
        case "iso8859-7":
        case "iso88597":
        case "iso_8859-7":
        case "iso_8859-7:1987":
        case "sun_eu_greek":
          return "ISO-8859-7";
        case "csiso88598e":
        case "csisolatinhebrew":
        case "hebrew":
        case "iso-8859-8":
        case "iso-8859-8-e":
        case "iso-ir-138":
        case "iso8859-8":
        case "iso88598":
        case "iso_8859-8":
        case "iso_8859-8:1988":
        case "visual":
          return "ISO-8859-8";
        case "csiso88598i":
        case "iso-8859-8-i":
        case "logical":
          return "ISO-8859-8-I";
        case "csisolatin6":
        case "iso-8859-10":
        case "iso-ir-157":
        case "iso8859-10":
        case "iso885910":
        case "l6":
        case "latin6":
          return "ISO-8859-10";
        case "iso-8859-13":
        case "iso8859-13":
        case "iso885913":
          return "ISO-8859-13";
        case "iso-8859-14":
        case "iso8859-14":
        case "iso885914":
          return "ISO-8859-14";
        case "csisolatin9":
        case "iso-8859-15":
        case "iso8859-15":
        case "iso885915":
        case "iso_8859-15":
        case "l9":
          return "ISO-8859-15";
        case "iso-8859-16":
          return "ISO-8859-16";
        case "cskoi8r":
        case "koi":
        case "koi8":
        case "koi8-r":
        case "koi8_r":
          return "KOI8-R";
        case "koi8-ru":
        case "koi8-u":
          return "KOI8-U";
        case "csmacintosh":
        case "mac":
        case "macintosh":
        case "x-mac-roman":
          return "macintosh";
        case "iso-8859-11":
        case "iso8859-11":
        case "iso885911":
        case "tis-620":
        case "windows-874":
          return "windows-874";
        case "cp1250":
        case "windows-1250":
        case "x-cp1250":
          return "windows-1250";
        case "cp1251":
        case "windows-1251":
        case "x-cp1251":
          return "windows-1251";
        case "ansi_x3.4-1968":
        case "ascii":
        case "cp1252":
        case "cp819":
        case "csisolatin1":
        case "ibm819":
        case "iso-8859-1":
        case "iso-ir-100":
        case "iso8859-1":
        case "iso88591":
        case "iso_8859-1":
        case "iso_8859-1:1987":
        case "l1":
        case "latin1":
        case "us-ascii":
        case "windows-1252":
        case "x-cp1252":
          return "windows-1252";
        case "cp1253":
        case "windows-1253":
        case "x-cp1253":
          return "windows-1253";
        case "cp1254":
        case "csisolatin5":
        case "iso-8859-9":
        case "iso-ir-148":
        case "iso8859-9":
        case "iso88599":
        case "iso_8859-9":
        case "iso_8859-9:1989":
        case "l5":
        case "latin5":
        case "windows-1254":
        case "x-cp1254":
          return "windows-1254";
        case "cp1255":
        case "windows-1255":
        case "x-cp1255":
          return "windows-1255";
        case "cp1256":
        case "windows-1256":
        case "x-cp1256":
          return "windows-1256";
        case "cp1257":
        case "windows-1257":
        case "x-cp1257":
          return "windows-1257";
        case "cp1258":
        case "windows-1258":
        case "x-cp1258":
          return "windows-1258";
        case "x-mac-cyrillic":
        case "x-mac-ukrainian":
          return "x-mac-cyrillic";
        case "chinese":
        case "csgb2312":
        case "csiso58gb231280":
        case "gb2312":
        case "gb_2312":
        case "gb_2312-80":
        case "gbk":
        case "iso-ir-58":
        case "x-gbk":
          return "GBK";
        case "gb18030":
          return "gb18030";
        case "big5":
        case "big5-hkscs":
        case "cn-big5":
        case "csbig5":
        case "x-x-big5":
          return "Big5";
        case "cseucpkdfmtjapanese":
        case "euc-jp":
        case "x-euc-jp":
          return "EUC-JP";
        case "csiso2022jp":
        case "iso-2022-jp":
          return "ISO-2022-JP";
        case "csshiftjis":
        case "ms932":
        case "ms_kanji":
        case "shift-jis":
        case "shift_jis":
        case "sjis":
        case "windows-31j":
        case "x-sjis":
          return "Shift_JIS";
        case "cseuckr":
        case "csksc56011987":
        case "euc-kr":
        case "iso-ir-149":
        case "korean":
        case "ks_c_5601-1987":
        case "ks_c_5601-1989":
        case "ksc5601":
        case "ksc_5601":
        case "windows-949":
          return "EUC-KR";
        case "csiso2022kr":
        case "hz-gb-2312":
        case "iso-2022-cn":
        case "iso-2022-cn-ext":
        case "iso-2022-kr":
        case "replacement":
          return "replacement";
        case "unicodefffe":
        case "utf-16be":
          return "UTF-16BE";
        case "csunicode":
        case "iso-10646-ucs-2":
        case "ucs-2":
        case "unicode":
        case "unicodefeff":
        case "utf-16":
        case "utf-16le":
          return "UTF-16LE";
        case "x-user-defined":
          return "x-user-defined";
        default:
          return "failure";
      }
    }
    __name(getEncoding, "getEncoding");
    module2.exports = {
      getEncoding
    };
  }
});

// packages/core/node_modules/undici/lib/web/fileapi/util.js
var require_util4 = __commonJS({
  "packages/core/node_modules/undici/lib/web/fileapi/util.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var {
      kState,
      kError,
      kResult,
      kAborted,
      kLastProgressEventFired
    } = require_symbols3();
    var { ProgressEvent } = require_progressevent();
    var { getEncoding } = require_encoding();
    var { serializeAMimeType, parseMIMEType } = require_data_url();
    var { types: types7 } = __require("node:util");
    var { StringDecoder: StringDecoder3 } = __require("string_decoder");
    var { btoa: btoa2 } = __require("node:buffer");
    var staticPropertyDescriptors = {
      enumerable: true,
      writable: false,
      configurable: false
    };
    function readOperation(fr2, blob, type, encodingName) {
      if (fr2[kState] === "loading") {
        throw new DOMException("Invalid state", "InvalidStateError");
      }
      fr2[kState] = "loading";
      fr2[kResult] = null;
      fr2[kError] = null;
      const stream2 = blob.stream();
      const reader = stream2.getReader();
      const bytes = [];
      let chunkPromise = reader.read();
      let isFirstChunk = true;
      (async () => {
        while (!fr2[kAborted]) {
          try {
            const { done, value } = await chunkPromise;
            if (isFirstChunk && !fr2[kAborted]) {
              queueMicrotask(() => {
                fireAProgressEvent("loadstart", fr2);
              });
            }
            isFirstChunk = false;
            if (!done && types7.isUint8Array(value)) {
              bytes.push(value);
              if ((fr2[kLastProgressEventFired] === void 0 || Date.now() - fr2[kLastProgressEventFired] >= 50) && !fr2[kAborted]) {
                fr2[kLastProgressEventFired] = Date.now();
                queueMicrotask(() => {
                  fireAProgressEvent("progress", fr2);
                });
              }
              chunkPromise = reader.read();
            } else if (done) {
              queueMicrotask(() => {
                fr2[kState] = "done";
                try {
                  const result = packageData(bytes, type, blob.type, encodingName);
                  if (fr2[kAborted]) {
                    return;
                  }
                  fr2[kResult] = result;
                  fireAProgressEvent("load", fr2);
                } catch (error2) {
                  fr2[kError] = error2;
                  fireAProgressEvent("error", fr2);
                }
                if (fr2[kState] !== "loading") {
                  fireAProgressEvent("loadend", fr2);
                }
              });
              break;
            }
          } catch (error2) {
            if (fr2[kAborted]) {
              return;
            }
            queueMicrotask(() => {
              fr2[kState] = "done";
              fr2[kError] = error2;
              fireAProgressEvent("error", fr2);
              if (fr2[kState] !== "loading") {
                fireAProgressEvent("loadend", fr2);
              }
            });
            break;
          }
        }
      })();
    }
    __name(readOperation, "readOperation");
    function fireAProgressEvent(e4, reader) {
      const event = new ProgressEvent(e4, {
        bubbles: false,
        cancelable: false
      });
      reader.dispatchEvent(event);
    }
    __name(fireAProgressEvent, "fireAProgressEvent");
    function packageData(bytes, type, mimeType, encodingName) {
      switch (type) {
        case "DataURL": {
          let dataURL = "data:";
          const parsed = parseMIMEType(mimeType || "application/octet-stream");
          if (parsed !== "failure") {
            dataURL += serializeAMimeType(parsed);
          }
          dataURL += ";base64,";
          const decoder = new StringDecoder3("latin1");
          for (const chunk of bytes) {
            dataURL += btoa2(decoder.write(chunk));
          }
          dataURL += btoa2(decoder.end());
          return dataURL;
        }
        case "Text": {
          let encoding = "failure";
          if (encodingName) {
            encoding = getEncoding(encodingName);
          }
          if (encoding === "failure" && mimeType) {
            const type2 = parseMIMEType(mimeType);
            if (type2 !== "failure") {
              encoding = getEncoding(type2.parameters.get("charset"));
            }
          }
          if (encoding === "failure") {
            encoding = "UTF-8";
          }
          return decode2(bytes, encoding);
        }
        case "ArrayBuffer": {
          const sequence = combineByteSequences(bytes);
          return sequence.buffer;
        }
        case "BinaryString": {
          let binaryString = "";
          const decoder = new StringDecoder3("latin1");
          for (const chunk of bytes) {
            binaryString += decoder.write(chunk);
          }
          binaryString += decoder.end();
          return binaryString;
        }
      }
    }
    __name(packageData, "packageData");
    function decode2(ioQueue, encoding) {
      const bytes = combineByteSequences(ioQueue);
      const BOMEncoding = BOMSniffing(bytes);
      let slice = 0;
      if (BOMEncoding !== null) {
        encoding = BOMEncoding;
        slice = BOMEncoding === "UTF-8" ? 3 : 2;
      }
      const sliced = bytes.slice(slice);
      return new TextDecoder(encoding).decode(sliced);
    }
    __name(decode2, "decode");
    function BOMSniffing(ioQueue) {
      const [a2, b2, c4] = ioQueue;
      if (a2 === 239 && b2 === 187 && c4 === 191) {
        return "UTF-8";
      } else if (a2 === 254 && b2 === 255) {
        return "UTF-16BE";
      } else if (a2 === 255 && b2 === 254) {
        return "UTF-16LE";
      }
      return null;
    }
    __name(BOMSniffing, "BOMSniffing");
    function combineByteSequences(sequences) {
      const size = sequences.reduce((a2, b2) => {
        return a2 + b2.byteLength;
      }, 0);
      let offset = 0;
      return sequences.reduce((a2, b2) => {
        a2.set(b2, offset);
        offset += b2.byteLength;
        return a2;
      }, new Uint8Array(size));
    }
    __name(combineByteSequences, "combineByteSequences");
    module2.exports = {
      staticPropertyDescriptors,
      readOperation,
      fireAProgressEvent
    };
  }
});

// packages/core/node_modules/undici/lib/web/fileapi/filereader.js
var require_filereader = __commonJS({
  "packages/core/node_modules/undici/lib/web/fileapi/filereader.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var {
      staticPropertyDescriptors,
      readOperation,
      fireAProgressEvent
    } = require_util4();
    var {
      kState,
      kError,
      kResult,
      kEvents,
      kAborted
    } = require_symbols3();
    var { webidl } = require_webidl();
    var { kEnumerableProperty } = require_util();
    var FileReader = class _FileReader extends EventTarget {
      static {
        __name(this, "FileReader");
      }
      constructor() {
        super();
        this[kState] = "empty";
        this[kResult] = null;
        this[kError] = null;
        this[kEvents] = {
          loadend: null,
          error: null,
          abort: null,
          load: null,
          progress: null,
          loadstart: null
        };
      }
      /**
       * @see https://w3c.github.io/FileAPI/#dfn-readAsArrayBuffer
       * @param {import('buffer').Blob} blob
       */
      readAsArrayBuffer(blob) {
        webidl.brandCheck(this, _FileReader);
        webidl.argumentLengthCheck(arguments, 1, "FileReader.readAsArrayBuffer");
        blob = webidl.converters.Blob(blob, { strict: false });
        readOperation(this, blob, "ArrayBuffer");
      }
      /**
       * @see https://w3c.github.io/FileAPI/#readAsBinaryString
       * @param {import('buffer').Blob} blob
       */
      readAsBinaryString(blob) {
        webidl.brandCheck(this, _FileReader);
        webidl.argumentLengthCheck(arguments, 1, "FileReader.readAsBinaryString");
        blob = webidl.converters.Blob(blob, { strict: false });
        readOperation(this, blob, "BinaryString");
      }
      /**
       * @see https://w3c.github.io/FileAPI/#readAsDataText
       * @param {import('buffer').Blob} blob
       * @param {string?} encoding
       */
      readAsText(blob, encoding = void 0) {
        webidl.brandCheck(this, _FileReader);
        webidl.argumentLengthCheck(arguments, 1, "FileReader.readAsText");
        blob = webidl.converters.Blob(blob, { strict: false });
        if (encoding !== void 0) {
          encoding = webidl.converters.DOMString(encoding, "FileReader.readAsText", "encoding");
        }
        readOperation(this, blob, "Text", encoding);
      }
      /**
       * @see https://w3c.github.io/FileAPI/#dfn-readAsDataURL
       * @param {import('buffer').Blob} blob
       */
      readAsDataURL(blob) {
        webidl.brandCheck(this, _FileReader);
        webidl.argumentLengthCheck(arguments, 1, "FileReader.readAsDataURL");
        blob = webidl.converters.Blob(blob, { strict: false });
        readOperation(this, blob, "DataURL");
      }
      /**
       * @see https://w3c.github.io/FileAPI/#dfn-abort
       */
      abort() {
        if (this[kState] === "empty" || this[kState] === "done") {
          this[kResult] = null;
          return;
        }
        if (this[kState] === "loading") {
          this[kState] = "done";
          this[kResult] = null;
        }
        this[kAborted] = true;
        fireAProgressEvent("abort", this);
        if (this[kState] !== "loading") {
          fireAProgressEvent("loadend", this);
        }
      }
      /**
       * @see https://w3c.github.io/FileAPI/#dom-filereader-readystate
       */
      get readyState() {
        webidl.brandCheck(this, _FileReader);
        switch (this[kState]) {
          case "empty":
            return this.EMPTY;
          case "loading":
            return this.LOADING;
          case "done":
            return this.DONE;
        }
      }
      /**
       * @see https://w3c.github.io/FileAPI/#dom-filereader-result
       */
      get result() {
        webidl.brandCheck(this, _FileReader);
        return this[kResult];
      }
      /**
       * @see https://w3c.github.io/FileAPI/#dom-filereader-error
       */
      get error() {
        webidl.brandCheck(this, _FileReader);
        return this[kError];
      }
      get onloadend() {
        webidl.brandCheck(this, _FileReader);
        return this[kEvents].loadend;
      }
      set onloadend(fn) {
        webidl.brandCheck(this, _FileReader);
        if (this[kEvents].loadend) {
          this.removeEventListener("loadend", this[kEvents].loadend);
        }
        if (typeof fn === "function") {
          this[kEvents].loadend = fn;
          this.addEventListener("loadend", fn);
        } else {
          this[kEvents].loadend = null;
        }
      }
      get onerror() {
        webidl.brandCheck(this, _FileReader);
        return this[kEvents].error;
      }
      set onerror(fn) {
        webidl.brandCheck(this, _FileReader);
        if (this[kEvents].error) {
          this.removeEventListener("error", this[kEvents].error);
        }
        if (typeof fn === "function") {
          this[kEvents].error = fn;
          this.addEventListener("error", fn);
        } else {
          this[kEvents].error = null;
        }
      }
      get onloadstart() {
        webidl.brandCheck(this, _FileReader);
        return this[kEvents].loadstart;
      }
      set onloadstart(fn) {
        webidl.brandCheck(this, _FileReader);
        if (this[kEvents].loadstart) {
          this.removeEventListener("loadstart", this[kEvents].loadstart);
        }
        if (typeof fn === "function") {
          this[kEvents].loadstart = fn;
          this.addEventListener("loadstart", fn);
        } else {
          this[kEvents].loadstart = null;
        }
      }
      get onprogress() {
        webidl.brandCheck(this, _FileReader);
        return this[kEvents].progress;
      }
      set onprogress(fn) {
        webidl.brandCheck(this, _FileReader);
        if (this[kEvents].progress) {
          this.removeEventListener("progress", this[kEvents].progress);
        }
        if (typeof fn === "function") {
          this[kEvents].progress = fn;
          this.addEventListener("progress", fn);
        } else {
          this[kEvents].progress = null;
        }
      }
      get onload() {
        webidl.brandCheck(this, _FileReader);
        return this[kEvents].load;
      }
      set onload(fn) {
        webidl.brandCheck(this, _FileReader);
        if (this[kEvents].load) {
          this.removeEventListener("load", this[kEvents].load);
        }
        if (typeof fn === "function") {
          this[kEvents].load = fn;
          this.addEventListener("load", fn);
        } else {
          this[kEvents].load = null;
        }
      }
      get onabort() {
        webidl.brandCheck(this, _FileReader);
        return this[kEvents].abort;
      }
      set onabort(fn) {
        webidl.brandCheck(this, _FileReader);
        if (this[kEvents].abort) {
          this.removeEventListener("abort", this[kEvents].abort);
        }
        if (typeof fn === "function") {
          this[kEvents].abort = fn;
          this.addEventListener("abort", fn);
        } else {
          this[kEvents].abort = null;
        }
      }
    };
    FileReader.EMPTY = FileReader.prototype.EMPTY = 0;
    FileReader.LOADING = FileReader.prototype.LOADING = 1;
    FileReader.DONE = FileReader.prototype.DONE = 2;
    Object.defineProperties(FileReader.prototype, {
      EMPTY: staticPropertyDescriptors,
      LOADING: staticPropertyDescriptors,
      DONE: staticPropertyDescriptors,
      readAsArrayBuffer: kEnumerableProperty,
      readAsBinaryString: kEnumerableProperty,
      readAsText: kEnumerableProperty,
      readAsDataURL: kEnumerableProperty,
      abort: kEnumerableProperty,
      readyState: kEnumerableProperty,
      result: kEnumerableProperty,
      error: kEnumerableProperty,
      onloadstart: kEnumerableProperty,
      onprogress: kEnumerableProperty,
      onload: kEnumerableProperty,
      onabort: kEnumerableProperty,
      onerror: kEnumerableProperty,
      onloadend: kEnumerableProperty,
      [Symbol.toStringTag]: {
        value: "FileReader",
        writable: false,
        enumerable: false,
        configurable: true
      }
    });
    Object.defineProperties(FileReader, {
      EMPTY: staticPropertyDescriptors,
      LOADING: staticPropertyDescriptors,
      DONE: staticPropertyDescriptors
    });
    module2.exports = {
      FileReader
    };
  }
});

// packages/core/node_modules/undici/lib/web/cache/symbols.js
var require_symbols4 = __commonJS({
  "packages/core/node_modules/undici/lib/web/cache/symbols.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    module2.exports = {
      kConstruct: require_symbols().kConstruct
    };
  }
});

// packages/core/node_modules/undici/lib/web/cache/util.js
var require_util5 = __commonJS({
  "packages/core/node_modules/undici/lib/web/cache/util.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var assert4 = __require("node:assert");
    var { URLSerializer } = require_data_url();
    var { isValidHeaderName } = require_util2();
    function urlEquals(A4, B2, excludeFragment = false) {
      const serializedA = URLSerializer(A4, excludeFragment);
      const serializedB = URLSerializer(B2, excludeFragment);
      return serializedA === serializedB;
    }
    __name(urlEquals, "urlEquals");
    function getFieldValues(header) {
      assert4(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
    };
  }
});

// packages/core/node_modules/undici/lib/web/cache/cache.js
var require_cache = __commonJS({
  "packages/core/node_modules/undici/lib/web/cache/cache.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var { kConstruct } = require_symbols4();
    var { urlEquals, getFieldValues } = require_util5();
    var { kEnumerableProperty, isDisturbed } = require_util();
    var { webidl } = require_webidl();
    var { Response: Response6, cloneResponse, fromInnerResponse } = require_response();
    var { Request: Request6, fromInnerRequest } = require_request2();
    var { kState } = require_symbols2();
    var { fetching } = require_fetch();
    var { urlIsHttpHttpsScheme, createDeferredPromise, readAllBytes } = require_util2();
    var assert4 = __require("node:assert");
    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, prefix, "request");
        options2 = webidl.converters.CacheQueryOptions(options2, prefix, "options");
        const p2 = this.#internalMatchAll(request4, options2, 1);
        if (p2.length === 0) {
          return;
        }
        return p2[0];
      }
      async matchAll(request4 = void 0, options2 = {}) {
        webidl.brandCheck(this, _Cache);
        const prefix = "Cache.matchAll";
        if (request4 !== void 0) request4 = webidl.converters.RequestInfo(request4, prefix, "request");
        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, prefix, "request");
        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 r5 = request4[kState];
          if (!urlIsHttpHttpsScheme(r5.url) || r5.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 r5 = new Request6(request4)[kState];
          if (!urlIsHttpHttpsScheme(r5.url)) {
            throw webidl.errors.exception({
              header: prefix,
              message: "Expected http/s scheme."
            });
          }
          r5.initiator = "fetch";
          r5.destination = "subresource";
          requestList.push(r5);
          const responsePromise = createDeferredPromise();
          fetchControllers.push(fetching({
            request: r5,
            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 p2 = Promise.all(responsePromises);
        const responses = await p2;
        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 (e4) {
          errorData = e4;
        }
        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, prefix, "request");
        response = webidl.converters.Response(response, prefix, "response");
        let innerRequest = null;
        if (request4 instanceof Request6) {
          innerRequest = request4[kState];
        } else {
          innerRequest = new Request6(request4)[kState];
        }
        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 = response[kState];
        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).then(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 (e4) {
          errorData = e4;
        }
        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, prefix, "request");
        options2 = webidl.converters.CacheQueryOptions(options2, prefix, "options");
        let r5 = null;
        if (request4 instanceof Request6) {
          r5 = request4[kState];
          if (r5.method !== "GET" && !options2.ignoreMethod) {
            return false;
          }
        } else {
          assert4(typeof request4 === "string");
          r5 = new Request6(request4)[kState];
        }
        const operations = [];
        const operation = {
          type: "delete",
          request: r5,
          options: options2
        };
        operations.push(operation);
        const cacheJobPromise = createDeferredPromise();
        let errorData = null;
        let requestResponses;
        try {
          requestResponses = this.#batchCacheOperations(operations);
        } catch (e4) {
          errorData = e4;
        }
        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, prefix, "request");
        options2 = webidl.converters.CacheQueryOptions(options2, prefix, "options");
        let r5 = null;
        if (request4 !== void 0) {
          if (request4 instanceof Request6) {
            r5 = request4[kState];
            if (r5.method !== "GET" && !options2.ignoreMethod) {
              return [];
            }
          } else if (typeof request4 === "string") {
            r5 = new Request6(request4)[kState];
          }
        }
        const promise = createDeferredPromise();
        const requests = [];
        if (request4 === void 0) {
          for (const requestResponse of this.#relevantRequestResponseList) {
            requests.push(requestResponse[0]);
          }
        } else {
          const requestResponses = this.#queryCache(r5, options2);
          for (const requestResponse of requestResponses) {
            requests.push(requestResponse[0]);
          }
        }
        queueMicrotask(() => {
          const requestList = [];
          for (const request5 of requests) {
            const requestObject = fromInnerRequest(
              request5,
              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);
                assert4(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 r5 = operation.request;
              if (!urlIsHttpHttpsScheme(r5.url)) {
                throw webidl.errors.exception({
                  header: "Cache.#batchCacheOperations",
                  message: "expected http or https scheme"
                });
              }
              if (r5.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);
                assert4(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 (e4) {
          this.#relevantRequestResponseList.length = 0;
          this.#relevantRequestResponseList = backupCache;
          throw e4;
        }
      }
      /**
       * @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 r5 = null;
        if (request4 !== void 0) {
          if (request4 instanceof Request6) {
            r5 = request4[kState];
            if (r5.method !== "GET" && !options2.ignoreMethod) {
              return [];
            }
          } else if (typeof request4 === "string") {
            r5 = new Request6(request4)[kState];
          }
        }
        const responses = [];
        if (request4 === void 0) {
          for (const requestResponse of this.#relevantRequestResponseList) {
            responses.push(requestResponse[1]);
          }
        } else {
          const requestResponses = this.#queryCache(r5, 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(Response6);
    webidl.converters["sequence<RequestInfo>"] = webidl.sequenceConverter(
      webidl.converters.RequestInfo
    );
    module2.exports = {
      Cache
    };
  }
});

// packages/core/node_modules/undici/lib/web/cache/cachestorage.js
var require_cachestorage = __commonJS({
  "packages/core/node_modules/undici/lib/web/cache/cachestorage.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var { kConstruct } = require_symbols4();
    var { Cache } = require_cache();
    var { webidl } = require_webidl();
    var { kEnumerableProperty } = require_util();
    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
    };
  }
});

// packages/core/node_modules/undici/lib/web/cookies/constants.js
var require_constants4 = __commonJS({
  "packages/core/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
    };
  }
});

// packages/core/node_modules/undici/lib/web/cookies/util.js
var require_util6 = __commonJS({
  "packages/core/node_modules/undici/lib/web/cookies/util.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    function isCTLExcludingHtab(value) {
      for (let i3 = 0; i3 < value.length; ++i3) {
        const code2 = value.charCodeAt(i3);
        if (code2 >= 0 && code2 <= 8 || code2 >= 10 && code2 <= 31 || code2 === 127) {
          return true;
        }
      }
      return false;
    }
    __name(isCTLExcludingHtab, "isCTLExcludingHtab");
    function validateCookieName(name3) {
      for (let i3 = 0; i3 < name3.length; ++i3) {
        const code2 = name3.charCodeAt(i3);
        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 i3 = 0;
      if (value[0] === '"') {
        if (len === 1 || value[len - 1] !== '"') {
          throw new Error("Invalid cookie value");
        }
        --len;
        ++i3;
      }
      while (i3 < len) {
        const code2 = value.charCodeAt(i3++);
        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(path125) {
      for (let i3 = 0; i3 < path125.length; ++i3) {
        const code2 = path125.charCodeAt(i3);
        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((_2, i3) => i3.toString().padStart(2, "0"));
    function toIMFDate(date4) {
      if (typeof date4 === "number") {
        date4 = new Date(date4);
      }
      return `${IMFDays[date4.getUTCDay()]}, ${IMFPaddedNumbers[date4.getUTCDate()]} ${IMFMonths[date4.getUTCMonth()]} ${date4.getUTCFullYear()} ${IMFPaddedNumbers[date4.getUTCHours()]}:${IMFPaddedNumbers[date4.getUTCMinutes()]}:${IMFPaddedNumbers[date4.getUTCSeconds()]} GMT`;
    }
    __name(toIMFDate, "toIMFDate");
    function validateCookieMaxAge(maxAge) {
      if (maxAge < 0) {
        throw new Error("Invalid cookie max-age");
      }
    }
    __name(validateCookieMaxAge, "validateCookieMaxAge");
    function stringify4(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(stringify4, "stringify");
    module2.exports = {
      isCTLExcludingHtab,
      validateCookieName,
      validateCookiePath,
      validateCookieValue,
      toIMFDate,
      stringify: stringify4
    };
  }
});

// packages/core/node_modules/undici/lib/web/cookies/parse.js
var require_parse = __commonJS({
  "packages/core/node_modules/undici/lib/web/cookies/parse.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var { maxNameValuePairSize, maxAttributeValueSize } = require_constants4();
    var { isCTLExcludingHtab } = require_util6();
    var { collectASequenceOfCodePointsFast } = require_data_url();
    var assert4 = __require("node:assert");
    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,
        ...parseUnparsedAttributes(unparsedAttributes)
      };
    }
    __name(parseSetCookie, "parseSetCookie");
    function parseUnparsedAttributes(unparsedAttributes, cookieAttributeList = {}) {
      if (unparsedAttributes.length === 0) {
        return cookieAttributeList;
      }
      assert4(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
    };
  }
});

// packages/core/node_modules/undici/lib/web/cookies/index.js
var require_cookies = __commonJS({
  "packages/core/node_modules/undici/lib/web/cookies/index.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var { parseSetCookie } = require_parse();
    var { stringify: stringify4 } = require_util6();
    var { webidl } = require_webidl();
    var { Headers: Headers6 } = require_headers();
    function getCookies(headers) {
      webidl.argumentLengthCheck(arguments, 1, "getCookies");
      webidl.brandCheck(headers, Headers6, { strict: false });
      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) {
      webidl.brandCheck(headers, Headers6, { strict: false });
      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");
      webidl.brandCheck(headers, Headers6, { strict: false });
      const cookies = headers.getSetCookie();
      if (!cookies) {
        return [];
      }
      return cookies.map((pair) => parseSetCookie(pair));
    }
    __name(getSetCookies, "getSetCookies");
    function setCookie(headers, cookie) {
      webidl.argumentLengthCheck(arguments, 2, "setCookie");
      webidl.brandCheck(headers, Headers6, { strict: false });
      cookie = webidl.converters.Cookie(cookie);
      const str2 = stringify4(cookie);
      if (str2) {
        headers.append("Set-Cookie", str2);
      }
    }
    __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
    };
  }
});

// packages/core/node_modules/undici/lib/web/websocket/events.js
var require_events = __commonJS({
  "packages/core/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 { MessagePort } = __require("node:worker_threads");
    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(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
    };
  }
});

// packages/core/node_modules/undici/lib/web/websocket/constants.js
var require_constants5 = __commonJS({
  "packages/core/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 = {
      NOT_SENT: 0,
      PROCESSING: 1,
      SENT: 2
    };
    var opcodes = {
      CONTINUATION: 0,
      TEXT: 1,
      BINARY: 2,
      CLOSE: 8,
      PING: 9,
      PONG: 10
    };
    var maxUnsigned16Bit = 2 ** 16 - 1;
    var parserStates = {
      INFO: 0,
      PAYLOADLENGTH_16: 2,
      PAYLOADLENGTH_64: 3,
      READ_DATA: 4
    };
    var emptyBuffer = Buffer.allocUnsafe(0);
    var sendHints = {
      string: 1,
      typedArray: 2,
      arrayBuffer: 3,
      blob: 4
    };
    module2.exports = {
      uid,
      sentCloseFrameState,
      staticPropertyDescriptors,
      states,
      opcodes,
      maxUnsigned16Bit,
      parserStates,
      emptyBuffer,
      sendHints
    };
  }
});

// packages/core/node_modules/undici/lib/web/websocket/symbols.js
var require_symbols5 = __commonJS({
  "packages/core/node_modules/undici/lib/web/websocket/symbols.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    module2.exports = {
      kWebSocketURL: Symbol("url"),
      kReadyState: Symbol("ready state"),
      kController: Symbol("controller"),
      kResponse: Symbol("response"),
      kBinaryType: Symbol("binary type"),
      kSentClose: Symbol("sent close"),
      kReceivedClose: Symbol("received close"),
      kByteParser: Symbol("byte parser")
    };
  }
});

// packages/core/node_modules/undici/lib/web/websocket/util.js
var require_util7 = __commonJS({
  "packages/core/node_modules/undici/lib/web/websocket/util.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var { kReadyState, kController, kResponse, kBinaryType, kWebSocketURL } = require_symbols5();
    var { states, opcodes } = require_constants5();
    var { ErrorEvent: ErrorEvent2, createFastMessageEvent } = require_events();
    var { isUtf8 } = __require("node:buffer");
    var { collectASequenceOfCodePointsFast, removeHTTPWhitespace } = require_data_url();
    function isConnecting(ws2) {
      return ws2[kReadyState] === states.CONNECTING;
    }
    __name(isConnecting, "isConnecting");
    function isEstablished(ws2) {
      return ws2[kReadyState] === states.OPEN;
    }
    __name(isEstablished, "isEstablished");
    function isClosing(ws2) {
      return ws2[kReadyState] === states.CLOSING;
    }
    __name(isClosing, "isClosing");
    function isClosed(ws2) {
      return ws2[kReadyState] === states.CLOSED;
    }
    __name(isClosed, "isClosed");
    function fireEvent(e4, target, eventFactory = (type, init) => new Event(type, init), eventInitDict = {}) {
      const event = eventFactory(e4, eventInitDict);
      target.dispatchEvent(event);
    }
    __name(fireEvent, "fireEvent");
    function websocketMessageReceived(ws2, type, data) {
      if (ws2[kReadyState] !== states.OPEN) {
        return;
      }
      let dataForEvent;
      if (type === opcodes.TEXT) {
        try {
          dataForEvent = utf8Decode(data);
        } catch {
          failWebsocketConnection(ws2, "Received invalid UTF-8 in text frame.");
          return;
        }
      } else if (type === opcodes.BINARY) {
        if (ws2[kBinaryType] === "blob") {
          dataForEvent = new Blob([data]);
        } else {
          dataForEvent = toArrayBuffer(data);
        }
      }
      fireEvent("message", ws2, createFastMessageEvent, {
        origin: ws2[kWebSocketURL].origin,
        data: dataForEvent
      });
    }
    __name(websocketMessageReceived, "websocketMessageReceived");
    function toArrayBuffer(buffer) {
      if (buffer.byteLength === buffer.buffer.byteLength) {
        return buffer.buffer;
      }
      return buffer.buffer.slice(buffer.byteOffset, buffer.byteOffset + buffer.byteLength);
    }
    __name(toArrayBuffer, "toArrayBuffer");
    function isValidSubprotocol(protocol) {
      if (protocol.length === 0) {
        return false;
      }
      for (let i3 = 0; i3 < protocol.length; ++i3) {
        const code2 = protocol.charCodeAt(i3);
        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 failWebsocketConnection(ws2, reason) {
      const { [kController]: controller, [kResponse]: response } = ws2;
      controller.abort();
      if (response?.socket && !response.socket.destroyed) {
        response.socket.destroy();
      }
      if (reason) {
        fireEvent("error", ws2, (type, init) => new ErrorEvent2(type, init), {
          error: new Error(reason),
          message: reason
        });
      }
    }
    __name(failWebsocketConnection, "failWebsocketConnection");
    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("=");
        extensionList.set(
          removeHTTPWhitespace(name3, true, false),
          removeHTTPWhitespace(value, false, true)
        );
        position.position++;
      }
      return extensionList;
    }
    __name(parseExtensions, "parseExtensions");
    function isValidClientWindowBits(value) {
      for (let i3 = 0; i3 < value.length; i3++) {
        const byte = value.charCodeAt(i3);
        if (byte < 48 || byte > 57) {
          return false;
        }
      }
      return true;
    }
    __name(isValidClientWindowBits, "isValidClientWindowBits");
    var hasIntl = typeof process.versions.icu === "string";
    var fatalDecoder = hasIntl ? new TextDecoder("utf-8", { fatal: true }) : void 0;
    var utf8Decode = hasIntl ? fatalDecoder.decode.bind(fatalDecoder) : 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,
      failWebsocketConnection,
      websocketMessageReceived,
      utf8Decode,
      isControlFrame,
      isContinuationFrame,
      isTextBinaryFrame,
      isValidOpcode,
      parseExtensions,
      isValidClientWindowBits
    };
  }
});

// packages/core/node_modules/undici/lib/web/websocket/frame.js
var require_frame = __commonJS({
  "packages/core/node_modules/undici/lib/web/websocket/frame.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var { maxUnsigned16Bit } = require_constants5();
    var BUFFER_SIZE = 16386;
    var crypto14;
    var buffer = null;
    var bufIdx = BUFFER_SIZE;
    try {
      crypto14 = __require("node:crypto");
    } catch {
      crypto14 = {
        // not full compatibility, but minimum.
        randomFillSync: /* @__PURE__ */ __name(function randomFillSync(buffer2, _offset, _size3) {
          for (let i3 = 0; i3 < buffer2.length; ++i3) {
            buffer2[i3] = Math.random() * 255 | 0;
          }
          return buffer2;
        }, "randomFillSync")
      };
    }
    function generateMask() {
      if (bufIdx === BUFFER_SIZE) {
        bufIdx = 0;
        crypto14.randomFillSync(buffer ??= Buffer.allocUnsafe(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 i3 = 0; i3 < bodyLength; ++i3) {
          buffer2[offset + i3] = frameData[i3] ^ maskKey[i3 & 3];
        }
        return buffer2;
      }
    };
    module2.exports = {
      WebsocketFrameSend
    };
  }
});

// packages/core/node_modules/undici/lib/web/websocket/connection.js
var require_connection = __commonJS({
  "packages/core/node_modules/undici/lib/web/websocket/connection.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var { uid, states, sentCloseFrameState, emptyBuffer, opcodes } = require_constants5();
    var {
      kReadyState,
      kSentClose,
      kByteParser,
      kReceivedClose,
      kResponse
    } = require_symbols5();
    var { fireEvent, failWebsocketConnection, isClosing, isClosed, isEstablished, parseExtensions } = require_util7();
    var { channels } = require_diagnostics();
    var { CloseEvent } = require_events();
    var { makeRequest } = require_request2();
    var { fetching } = require_fetch();
    var { Headers: Headers6, getHeadersList } = require_headers();
    var { getDecodeSplit } = require_util2();
    var { WebsocketFrameSend } = require_frame();
    var crypto14;
    try {
      crypto14 = __require("node:crypto");
    } catch {
    }
    function establishWebSocketConnection(url2, protocols, client, ws2, onEstablish, 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 Headers6(options2.headers));
        request4.headersList = headersList;
      }
      const keyValue = crypto14.randomBytes(16).toString("base64");
      request4.headersList.append("sec-websocket-key", keyValue);
      request4.headersList.append("sec-websocket-version", "13");
      for (const protocol of protocols) {
        request4.headersList.append("sec-websocket-protocol", protocol);
      }
      const permessageDeflate = "permessage-deflate; client_max_window_bits";
      request4.headersList.append("sec-websocket-extensions", permessageDeflate);
      const controller = fetching({
        request: request4,
        useParallelQueue: true,
        dispatcher: options2.dispatcher,
        processResponse(response) {
          if (response.type === "error" || response.status !== 101) {
            failWebsocketConnection(ws2, "Received network error or non-101 status code.");
            return;
          }
          if (protocols.length !== 0 && !response.headersList.get("Sec-WebSocket-Protocol")) {
            failWebsocketConnection(ws2, "Server did not respond with sent protocols.");
            return;
          }
          if (response.headersList.get("Upgrade")?.toLowerCase() !== "websocket") {
            failWebsocketConnection(ws2, 'Server did not set Upgrade header to "websocket".');
            return;
          }
          if (response.headersList.get("Connection")?.toLowerCase() !== "upgrade") {
            failWebsocketConnection(ws2, 'Server did not set Connection header to "upgrade".');
            return;
          }
          const secWSAccept = response.headersList.get("Sec-WebSocket-Accept");
          const digest = crypto14.createHash("sha1").update(keyValue + uid).digest("base64");
          if (secWSAccept !== digest) {
            failWebsocketConnection(ws2, "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(ws2, "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(ws2, "Protocol was not set in the opening handshake.");
              return;
            }
          }
          response.socket.on("data", onSocketData);
          response.socket.on("close", onSocketClose);
          response.socket.on("error", onSocketError);
          if (channels.open.hasSubscribers) {
            channels.open.publish({
              address: response.socket.address(),
              protocol: secProtocol,
              extensions: secExtension
            });
          }
          onEstablish(response, extensions);
        }
      });
      return controller;
    }
    __name(establishWebSocketConnection, "establishWebSocketConnection");
    function closeWebSocketConnection(ws2, code2, reason, reasonByteLength) {
      if (isClosing(ws2) || isClosed(ws2)) {
      } else if (!isEstablished(ws2)) {
        failWebsocketConnection(ws2, "Connection was closed before it was established.");
        ws2[kReadyState] = states.CLOSING;
      } else if (ws2[kSentClose] === sentCloseFrameState.NOT_SENT) {
        ws2[kSentClose] = sentCloseFrameState.PROCESSING;
        const frame = new WebsocketFrameSend();
        if (code2 !== void 0 && reason === void 0) {
          frame.frameData = Buffer.allocUnsafe(2);
          frame.frameData.writeUInt16BE(code2, 0);
        } else if (code2 !== void 0 && reason !== void 0) {
          frame.frameData = Buffer.allocUnsafe(2 + reasonByteLength);
          frame.frameData.writeUInt16BE(code2, 0);
          frame.frameData.write(reason, 2, "utf-8");
        } else {
          frame.frameData = emptyBuffer;
        }
        const socket = ws2[kResponse].socket;
        socket.write(frame.createFrame(opcodes.CLOSE));
        ws2[kSentClose] = sentCloseFrameState.SENT;
        ws2[kReadyState] = states.CLOSING;
      } else {
        ws2[kReadyState] = states.CLOSING;
      }
    }
    __name(closeWebSocketConnection, "closeWebSocketConnection");
    function onSocketData(chunk) {
      if (!this.ws[kByteParser].write(chunk)) {
        this.pause();
      }
    }
    __name(onSocketData, "onSocketData");
    function onSocketClose() {
      const { ws: ws2 } = this;
      const { [kResponse]: response } = ws2;
      response.socket.off("data", onSocketData);
      response.socket.off("close", onSocketClose);
      response.socket.off("error", onSocketError);
      const wasClean = ws2[kSentClose] === sentCloseFrameState.SENT && ws2[kReceivedClose];
      let code2 = 1005;
      let reason = "";
      const result = ws2[kByteParser].closingInfo;
      if (result && !result.error) {
        code2 = result.code ?? 1005;
        reason = result.reason;
      } else if (!ws2[kReceivedClose]) {
        code2 = 1006;
      }
      ws2[kReadyState] = states.CLOSED;
      fireEvent("close", ws2, (type, init) => new CloseEvent(type, init), {
        wasClean,
        code: code2,
        reason
      });
      if (channels.close.hasSubscribers) {
        channels.close.publish({
          websocket: ws2,
          code: code2,
          reason
        });
      }
    }
    __name(onSocketClose, "onSocketClose");
    function onSocketError(error2) {
      const { ws: ws2 } = this;
      ws2[kReadyState] = states.CLOSING;
      if (channels.socketError.hasSubscribers) {
        channels.socketError.publish(error2);
      }
      this.destroy();
    }
    __name(onSocketError, "onSocketError");
    module2.exports = {
      establishWebSocketConnection,
      closeWebSocketConnection
    };
  }
});

// packages/core/node_modules/undici/lib/web/websocket/permessage-deflate.js
var require_permessage_deflate = __commonJS({
  "packages/core/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_util7();
    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 };
  }
});

// packages/core/node_modules/undici/lib/web/websocket/receiver.js
var require_receiver = __commonJS({
  "packages/core/node_modules/undici/lib/web/websocket/receiver.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var { Writable: Writable3 } = __require("node:stream");
    var assert4 = __require("node:assert");
    var { parserStates, opcodes, states, emptyBuffer, sentCloseFrameState } = require_constants5();
    var { kReadyState, kSentClose, kResponse, kReceivedClose } = require_symbols5();
    var { channels } = require_diagnostics();
    var {
      isValidStatusCode,
      isValidOpcode,
      failWebsocketConnection,
      websocketMessageReceived,
      utf8Decode,
      isControlFrame,
      isTextBinaryFrame,
      isContinuationFrame
    } = require_util7();
    var { WebsocketFrameSend } = require_frame();
    var { closeWebSocketConnection } = require_connection();
    var { PerMessageDeflate } = require_permessage_deflate();
    var ByteParser = class extends Writable3 {
      static {
        __name(this, "ByteParser");
      }
      #buffers = [];
      #byteOffset = 0;
      #loop = false;
      #state = parserStates.INFO;
      #info = {};
      #fragments = [];
      /** @type {Map<string, PerMessageDeflate>} */
      #extensions;
      constructor(ws2, extensions) {
        super();
        this.ws = ws2;
        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, _2, 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.ws, "Invalid opcode received");
              return callback();
            }
            if (masked) {
              failWebsocketConnection(this.ws, "Frame cannot be masked");
              return callback();
            }
            if (rsv1 !== 0 && !this.#extensions.has("permessage-deflate")) {
              failWebsocketConnection(this.ws, "Expected RSV1 to be clear.");
              return;
            }
            if (rsv2 !== 0 || rsv3 !== 0) {
              failWebsocketConnection(this.ws, "RSV1, RSV2, RSV3 must be clear");
              return;
            }
            if (fragmented && !isTextBinaryFrame(opcode)) {
              failWebsocketConnection(this.ws, "Invalid frame type was fragmented.");
              return;
            }
            if (isTextBinaryFrame(opcode) && this.#fragments.length > 0) {
              failWebsocketConnection(this.ws, "Expected continuation frame");
              return;
            }
            if (this.#info.fragmented && fragmented) {
              failWebsocketConnection(this.ws, "Fragmented frame exceeded 125 bytes.");
              return;
            }
            if ((payloadLength > 125 || fragmented) && isControlFrame(opcode)) {
              failWebsocketConnection(this.ws, "Control frame either too large or fragmented");
              return;
            }
            if (isContinuationFrame(opcode) && this.#fragments.length === 0 && !this.#info.compressed) {
              failWebsocketConnection(this.ws, "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.ws, "Received payload length > 2^31 bytes.");
              return;
            }
            const lower3 = buffer.readUInt32BE(4);
            this.#info.payloadLength = (upper << 8) + lower3;
            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.#fragments.push(body);
                if (!this.#info.fragmented && this.#info.fin) {
                  const fullMessage = Buffer.concat(this.#fragments);
                  websocketMessageReceived(this.ws, this.#info.binaryType, fullMessage);
                  this.#fragments.length = 0;
                }
                this.#state = parserStates.INFO;
              } else {
                this.#extensions.get("permessage-deflate").decompress(body, this.#info.fin, (error2, data) => {
                  if (error2) {
                    closeWebSocketConnection(this.ws, 1007, error2.message, error2.message.length);
                    return;
                  }
                  this.#fragments.push(data);
                  if (!this.#info.fin) {
                    this.#state = parserStates.INFO;
                    this.#loop = true;
                    this.run(callback);
                    return;
                  }
                  websocketMessageReceived(this.ws, this.#info.binaryType, Buffer.concat(this.#fragments));
                  this.#loop = true;
                  this.#state = parserStates.INFO;
                  this.#fragments.length = 0;
                  this.run(callback);
                });
                this.#loop = false;
                break;
              }
            }
          }
        }
      }
      /**
       * Take n bytes from the buffered Buffers
       * @param {number} n
       * @returns {Buffer}
       */
      consume(n3) {
        if (n3 > this.#byteOffset) {
          throw new Error("Called consume() before buffers satiated.");
        } else if (n3 === 0) {
          return emptyBuffer;
        }
        if (this.#buffers[0].length === n3) {
          this.#byteOffset -= this.#buffers[0].length;
          return this.#buffers.shift();
        }
        const buffer = Buffer.allocUnsafe(n3);
        let offset = 0;
        while (offset !== n3) {
          const next = this.#buffers[0];
          const { length } = next;
          if (length + offset === n3) {
            buffer.set(this.#buffers.shift(), offset);
            break;
          } else if (length + offset > n3) {
            buffer.set(next.subarray(0, n3 - offset), offset);
            this.#buffers[0] = next.subarray(n3 - offset);
            break;
          } else {
            buffer.set(this.#buffers.shift(), offset);
            offset += next.length;
          }
        }
        this.#byteOffset -= n3;
        return buffer;
      }
      parseCloseBody(data) {
        assert4(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.ws, "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;
            closeWebSocketConnection(this.ws, code2, reason, reason.length);
            failWebsocketConnection(this.ws, reason);
            return false;
          }
          if (this.ws[kSentClose] !== sentCloseFrameState.SENT) {
            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.ws[kResponse].socket.write(
              closeFrame.createFrame(opcodes.CLOSE),
              (err) => {
                if (!err) {
                  this.ws[kSentClose] = sentCloseFrameState.SENT;
                }
              }
            );
          }
          this.ws[kReadyState] = states.CLOSING;
          this.ws[kReceivedClose] = true;
          return false;
        } else if (opcode === opcodes.PING) {
          if (!this.ws[kReceivedClose]) {
            const frame = new WebsocketFrameSend(body);
            this.ws[kResponse].socket.write(frame.createFrame(opcodes.PONG));
            if (channels.ping.hasSubscribers) {
              channels.ping.publish({
                payload: body
              });
            }
          }
        } else if (opcode === opcodes.PONG) {
          if (channels.pong.hasSubscribers) {
            channels.pong.publish({
              payload: body
            });
          }
        }
        return true;
      }
      get closingInfo() {
        return this.#info.closeInfo;
      }
    };
    module2.exports = {
      ByteParser
    };
  }
});

// packages/core/node_modules/undici/lib/web/websocket/sender.js
var require_sender = __commonJS({
  "packages/core/node_modules/undici/lib/web/websocket/sender.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var { WebsocketFrameSend } = require_frame();
    var { opcodes, sendHints } = require_constants5();
    var FixedQueue = require_fixed_queue();
    var FastBuffer = Buffer[Symbol.species];
    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) {
          const frame = createFrame(item, hint);
          if (!this.#running) {
            this.#socket.write(frame, cb);
          } else {
            const node2 = {
              promise: null,
              callback: cb,
              frame
            };
            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.string ? opcodes.TEXT : opcodes.BINARY);
    }
    __name(createFrame, "createFrame");
    function toBuffer(data, hint) {
      switch (hint) {
        case sendHints.string:
          return Buffer.from(data);
        case sendHints.arrayBuffer:
        case sendHints.blob:
          return new FastBuffer(data);
        case sendHints.typedArray:
          return new FastBuffer(data.buffer, data.byteOffset, data.byteLength);
      }
    }
    __name(toBuffer, "toBuffer");
    module2.exports = { SendQueue };
  }
});

// packages/core/node_modules/undici/lib/web/websocket/websocket.js
var require_websocket = __commonJS({
  "packages/core/node_modules/undici/lib/web/websocket/websocket.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var { webidl } = require_webidl();
    var { URLSerializer } = require_data_url();
    var { environmentSettingsObject } = require_util2();
    var { staticPropertyDescriptors, states, sentCloseFrameState, sendHints } = require_constants5();
    var {
      kWebSocketURL,
      kReadyState,
      kController,
      kBinaryType,
      kResponse,
      kSentClose,
      kByteParser
    } = require_symbols5();
    var {
      isConnecting,
      isEstablished,
      isClosing,
      isValidSubprotocol,
      fireEvent
    } = require_util7();
    var { establishWebSocketConnection, closeWebSocketConnection } = require_connection();
    var { ByteParser } = require_receiver();
    var { kEnumerableProperty, isBlobLike: isBlobLike3 } = require_util();
    var { getGlobalDispatcher } = require_global2();
    var { types: types7 } = __require("node:util");
    var { ErrorEvent: ErrorEvent2, CloseEvent } = require_events();
    var { SendQueue } = require_sender();
    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;
      /**
       * @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, prefix, "url");
        protocols = options2.protocols;
        const baseURL = environmentSettingsObject.settingsObject.baseUrl;
        let urlRecord;
        try {
          urlRecord = new URL(url2, baseURL);
        } catch (e4) {
          throw new DOMException(e4, "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: protocol, got ${urlRecord.protocol}`,
            "SyntaxError"
          );
        }
        if (urlRecord.hash || urlRecord.href.endsWith("#")) {
          throw new DOMException("Got fragment", "SyntaxError");
        }
        if (typeof protocols === "string") {
          protocols = [protocols];
        }
        if (protocols.length !== new Set(protocols.map((p2) => p2.toLowerCase())).size) {
          throw new DOMException("Invalid Sec-WebSocket-Protocol value", "SyntaxError");
        }
        if (protocols.length > 0 && !protocols.every((p2) => isValidSubprotocol(p2))) {
          throw new DOMException("Invalid Sec-WebSocket-Protocol value", "SyntaxError");
        }
        this[kWebSocketURL] = new URL(urlRecord.href);
        const client = environmentSettingsObject.settingsObject;
        this[kController] = establishWebSocketConnection(
          urlRecord,
          protocols,
          client,
          this,
          (response, extensions) => this.#onConnectionEstablished(response, extensions),
          options2
        );
        this[kReadyState] = _WebSocket.CONNECTING;
        this[kSentClose] = sentCloseFrameState.NOT_SENT;
        this[kBinaryType] = "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, prefix, "reason");
        }
        if (code2 !== void 0) {
          if (code2 !== 1e3 && (code2 < 3e3 || code2 > 4999)) {
            throw new DOMException("invalid code", "InvalidAccessError");
          }
        }
        let reasonByteLength = 0;
        if (reason !== void 0) {
          reasonByteLength = Buffer.byteLength(reason);
          if (reasonByteLength > 123) {
            throw new DOMException(
              `Reason must be less than 123 bytes; received ${reasonByteLength}`,
              "SyntaxError"
            );
          }
        }
        closeWebSocketConnection(this, code2, reason, reasonByteLength);
      }
      /**
       * @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)) {
          throw new DOMException("Sent before connected.", "InvalidStateError");
        }
        if (!isEstablished(this) || isClosing(this)) {
          return;
        }
        if (typeof data === "string") {
          const length = Buffer.byteLength(data);
          this.#bufferedAmount += length;
          this.#sendQueue.add(data, () => {
            this.#bufferedAmount -= length;
          }, sendHints.string);
        } else if (types7.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 (isBlobLike3(data)) {
          this.#bufferedAmount += data.size;
          this.#sendQueue.add(data, () => {
            this.#bufferedAmount -= data.size;
          }, sendHints.blob);
        }
      }
      get readyState() {
        webidl.brandCheck(this, _WebSocket);
        return this[kReadyState];
      }
      get bufferedAmount() {
        webidl.brandCheck(this, _WebSocket);
        return this.#bufferedAmount;
      }
      get url() {
        webidl.brandCheck(this, _WebSocket);
        return URLSerializer(this[kWebSocketURL]);
      }
      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[kBinaryType];
      }
      set binaryType(type) {
        webidl.brandCheck(this, _WebSocket);
        if (type !== "blob" && type !== "arraybuffer") {
          this[kBinaryType] = "blob";
        } else {
          this[kBinaryType] = type;
        }
      }
      /**
       * @see https://websockets.spec.whatwg.org/#feedback-from-the-protocol
       */
      #onConnectionEstablished(response, parsedExtensions) {
        this[kResponse] = response;
        const parser6 = new ByteParser(this, parsedExtensions);
        parser6.on("drain", onParserDrain);
        parser6.on("error", onParserError.bind(this));
        response.socket.ws = this;
        this[kByteParser] = parser6;
        this.#sendQueue = new SendQueue(response.socket);
        this[kReadyState] = 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);
      }
    };
    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(V3, prefix, argument) {
      if (webidl.util.Type(V3) === "Object" && Symbol.iterator in V3) {
        return webidl.converters["sequence<DOMString>"](V3);
      }
      return webidl.converters.DOMString(V3, 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(V3) {
      if (webidl.util.Type(V3) === "Object" && !(Symbol.iterator in V3)) {
        return webidl.converters.WebSocketInit(V3);
      }
      return { protocols: webidl.converters["DOMString or sequence<DOMString>"](V3) };
    };
    webidl.converters.WebSocketSendData = function(V3) {
      if (webidl.util.Type(V3) === "Object") {
        if (isBlobLike3(V3)) {
          return webidl.converters.Blob(V3, { strict: false });
        }
        if (ArrayBuffer.isView(V3) || types7.isArrayBuffer(V3)) {
          return webidl.converters.BufferSource(V3);
        }
      }
      return webidl.converters.USVString(V3);
    };
    function onParserDrain() {
      this.ws[kResponse].socket.resume();
    }
    __name(onParserDrain, "onParserDrain");
    function onParserError(err) {
      let message;
      let code2;
      if (err instanceof CloseEvent) {
        message = err.reason;
        code2 = err.code;
      } else {
        message = err.message;
      }
      fireEvent("error", this, () => new ErrorEvent2("error", { error: err, message }));
      closeWebSocketConnection(this, code2);
    }
    __name(onParserError, "onParserError");
    module2.exports = {
      WebSocket: WebSocket2
    };
  }
});

// packages/core/node_modules/undici/lib/web/eventsource/util.js
var require_util8 = __commonJS({
  "packages/core/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 i3 = 0; i3 < value.length; i3++) {
        if (value.charCodeAt(i3) < 48 || value.charCodeAt(i3) > 57) return false;
      }
      return true;
    }
    __name(isASCIINumber, "isASCIINumber");
    function delay4(ms) {
      return new Promise((resolve30) => {
        setTimeout(resolve30, ms).unref();
      });
    }
    __name(delay4, "delay");
    module2.exports = {
      isValidLastEventId,
      isASCIINumber,
      delay: delay4
    };
  }
});

// packages/core/node_modules/undici/lib/web/eventsource/eventsource-stream.js
var require_eventsource_stream = __commonJS({
  "packages/core/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_util8();
    var BOM = [239, 187, 191];
    var LF3 = 10;
    var CR3 = 13;
    var COLON3 = 58;
    var SPACE3 = 32;
    var EventSourceStream = class extends Transform2 {
      static {
        __name(this, "EventSourceStream");
      }
      /**
       * @type {eventSourceSettings}
       */
      state = null;
      /**
       * Leading byte-order-mark check.
       * @type {boolean}
       */
      checkBOM = true;
      /**
       * @type {boolean}
       */
      crlfCheck = false;
      /**
       * @type {boolean}
       */
      eventEndCheck = false;
      /**
       * @type {Buffer}
       */
      buffer = null;
      pos = 0;
      event = {
        data: void 0,
        event: void 0,
        id: void 0,
        retry: void 0
      };
      /**
       * @param {object} options
       * @param {eventSourceSettings} options.eventSourceSettings
       * @param {Function} [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] === LF3) {
                this.buffer = this.buffer.subarray(this.pos + 1);
                this.pos = 0;
                this.crlfCheck = false;
                continue;
              }
              this.crlfCheck = false;
            }
            if (this.buffer[this.pos] === LF3 || this.buffer[this.pos] === CR3) {
              if (this.buffer[this.pos] === CR3) {
                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] === LF3 || this.buffer[this.pos] === CR3) {
            if (this.buffer[this.pos] === CR3) {
              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 {EventStreamEvent} event
       */
      parseLine(line, event) {
        if (line.length === 0) {
          return;
        }
        const colonPosition = line.indexOf(COLON3);
        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] === SPACE3) {
            ++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
    };
  }
});

// packages/core/node_modules/undici/lib/web/eventsource/eventsource.js
var require_eventsource = __commonJS({
  "packages/core/node_modules/undici/lib/web/eventsource/eventsource.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var { pipeline: pipeline3 } = __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_util8();
    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 = null;
      #withCredentials = false;
      #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, prefix, "url");
        eventSourceInitDict = webidl.converters.EventSourceInitDict(eventSourceInitDict, prefix, "eventSourceInitDict");
        this.#dispatcher = eventSourceInitDict.dispatcher;
        this.#state = {
          lastEventId: "",
          reconnectionTime: defaultReconnectionTime
        };
        const settings = environmentSettingsObject;
        let urlRecord;
        try {
          urlRecord = new URL(url2, settings.settingsObject.baseUrl);
          this.#state.origin = urlRecord.origin;
        } catch (e4) {
          throw new DOMException(e4, "SyntaxError");
        }
        this.#url = urlRecord.href;
        let corsAttributeState = ANONYMOUS;
        if (eventSourceInitDict.withCredentials) {
          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 {0|1|2}
       * @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)) {
            this.dispatchEvent(new Event("error"));
            this.close();
          }
          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")
          });
          pipeline3(
            response.body.stream,
            eventSourceStream,
            (error2) => {
              if (error2?.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
      }
    ]);
    module2.exports = {
      EventSource: EventSource2,
      defaultReconnectionTime
    };
  }
});

// packages/core/node_modules/undici/index.js
var require_undici = __commonJS({
  "packages/core/node_modules/undici/index.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var Client3 = require_client();
    var Dispatcher = require_dispatcher();
    var Pool = require_pool();
    var BalancedPool = require_balanced_pool();
    var Agent4 = require_agent();
    var ProxyAgent6 = require_proxy_agent();
    var EnvHttpProxyAgent2 = require_env_http_proxy_agent();
    var RetryAgent = require_retry_agent();
    var errors = require_errors();
    var util3 = require_util();
    var { InvalidArgumentError } = errors;
    var api = require_api();
    var buildConnector = require_connect();
    var MockClient = require_mock_client();
    var MockAgent = require_mock_agent();
    var MockPool = require_mock_pool();
    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();
    var createRedirectInterceptor = require_redirect_interceptor();
    Object.assign(Dispatcher.prototype, api);
    module2.exports.Dispatcher = Dispatcher;
    module2.exports.Client = Client3;
    module2.exports.Pool = Pool;
    module2.exports.BalancedPool = BalancedPool;
    module2.exports.Agent = Agent4;
    module2.exports.ProxyAgent = ProxyAgent6;
    module2.exports.EnvHttpProxyAgent = EnvHttpProxyAgent2;
    module2.exports.RetryAgent = RetryAgent;
    module2.exports.RetryHandler = RetryHandler;
    module2.exports.DecoratorHandler = DecoratorHandler;
    module2.exports.RedirectHandler = RedirectHandler;
    module2.exports.createRedirectInterceptor = createRedirectInterceptor;
    module2.exports.interceptors = {
      redirect: require_redirect(),
      retry: require_retry(),
      dump: require_dump(),
      dns: require_dns()
    };
    module2.exports.buildConnector = buildConnector;
    module2.exports.errors = errors;
    module2.exports.util = {
      parseHeaders: util3.parseHeaders,
      headerNameToString: util3.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 path125 = opts.path;
          if (!opts.path.startsWith("/")) {
            path125 = `/${path125}`;
          }
          url2 = new URL(util3.parseOrigin(url2).origin + path125);
        } else {
          if (!opts) {
            opts = typeof url2 === "object" ? url2 : {};
          }
          url2 = util3.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 fetch5(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;
    module2.exports.File = globalThis.File ?? __require("node:buffer").File;
    module2.exports.FileReader = require_filereader().FileReader;
    var { setGlobalOrigin, getGlobalOrigin } = require_global();
    module2.exports.setGlobalOrigin = setGlobalOrigin;
    module2.exports.getGlobalOrigin = getGlobalOrigin;
    var { CacheStorage } = require_cachestorage();
    var { kConstruct } = require_symbols4();
    module2.exports.caches = new CacheStorage(kConstruct);
    var { deleteCookie, getCookies, getSetCookies, setCookie } = require_cookies();
    module2.exports.deleteCookie = deleteCookie;
    module2.exports.getCookies = getCookies;
    module2.exports.getSetCookies = getSetCookies;
    module2.exports.setCookie = setCookie;
    var { parseMIMEType, serializeAMimeType } = require_data_url();
    module2.exports.parseMIMEType = parseMIMEType;
    module2.exports.serializeAMimeType = serializeAMimeType;
    var { CloseEvent, ErrorEvent: ErrorEvent2, MessageEvent: MessageEvent2 } = require_events();
    module2.exports.WebSocket = require_websocket().WebSocket;
    module2.exports.CloseEvent = CloseEvent;
    module2.exports.ErrorEvent = ErrorEvent2;
    module2.exports.MessageEvent = MessageEvent2;
    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.MockPool = MockPool;
    module2.exports.MockAgent = MockAgent;
    module2.exports.mockErrors = mockErrors;
    var { EventSource: EventSource2 } = require_eventsource();
    module2.exports.EventSource = EventSource2;
  }
});

// packages/core/dist/src/utils/errors.js
function isNodeError(error2) {
  return error2 instanceof Error && "code" in error2;
}
function isAbortError(error2) {
  if (!error2 || typeof error2 !== "object") {
    return false;
  }
  if (error2 instanceof Error && error2.name === "AbortError") {
    return true;
  }
  if (isNodeError(error2) && error2.code === "ABORT_ERR") {
    return true;
  }
  return false;
}
function getErrorMessage(error2) {
  if (error2 instanceof Error) {
    return error2.message;
  }
  try {
    return String(error2);
  } catch {
    return "Failed to get error details";
  }
}
function toFriendlyError(error2) {
  if (error2 && typeof error2 === "object" && "response" in error2) {
    const gaxiosError = error2;
    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 error2;
}
function parseResponseData(error2) {
  if (typeof error2.response?.data === "string") {
    return JSON.parse(error2.response?.data);
  }
  return error2.response?.data;
}
var FatalError, FatalInputError, FatalSandboxError, FatalConfigError, FatalTurnLimitedError, FatalCancellationError, ForbiddenError, UnauthorizedError, BadRequestError;
var init_errors = __esm({
  "packages/core/dist/src/utils/errors.js"() {
    "use strict";
    init_esbuild_shims();
    __name(isNodeError, "isNodeError");
    __name(isAbortError, "isAbortError");
    __name(getErrorMessage, "getErrorMessage");
    FatalError = class extends Error {
      static {
        __name(this, "FatalError");
      }
      exitCode;
      constructor(message, exitCode) {
        super(message);
        this.exitCode = exitCode;
      }
    };
    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);
      }
    };
    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");
  }
});

// packages/core/dist/src/utils/paths.js
import fs from "node:fs";
import path from "node:path";
import os from "node:os";
import * as crypto2 from "node:crypto";
function tildeifyPath(path125) {
  const homeDir = os.homedir();
  if (path125.startsWith(homeDir)) {
    return path125.replace(homeDir, "~");
  }
  return path125;
}
function shortenPath(filePath, maxLen = 80) {
  if (filePath.length <= maxLen) {
    return filePath;
  }
  const separator = path.sep;
  const ellipsis = "...";
  if (maxLen < 10) {
    return filePath.substring(0, maxLen - 3) + ellipsis;
  }
  const parsedPath = path.parse(filePath);
  const root = parsedPath.root;
  const relativePath = filePath.substring(root.length);
  const segments = relativePath.split(separator).filter((s5) => s5 !== "");
  if (segments.length === 0) {
    return root.length <= maxLen ? root : root.substring(0, maxLen - 3) + ellipsis;
  }
  if (segments.length === 1) {
    const full = root + segments[0];
    if (full.length <= maxLen) {
      return full;
    }
    const keepLen = Math.floor((maxLen - 3) / 2);
    const start = full.substring(0, keepLen);
    const end = full.substring(full.length - keepLen);
    return `${start}${ellipsis}${end}`;
  }
  const startPart = root + segments[0];
  const endSegments = [];
  for (let i3 = segments.length - 1; i3 >= 1; i3--) {
    const segment = segments[i3];
    const endPart = [segment, ...endSegments].join(separator);
    const needsEllipsis = i3 > 1;
    let candidateResult;
    if (needsEllipsis) {
      candidateResult = startPart + separator + ellipsis + separator + endPart;
    } else {
      candidateResult = startPart + separator + endPart;
    }
    if (candidateResult.length <= maxLen) {
      endSegments.unshift(segment);
      if (i3 === 1) {
        return candidateResult;
      }
    } else {
      break;
    }
  }
  if (endSegments.length === 0) {
    const keepLen = Math.floor((maxLen - 3) / 2);
    const start = filePath.substring(0, keepLen);
    const end = filePath.substring(filePath.length - keepLen);
    return `${start}${ellipsis}${end}`;
  }
  return startPart + separator + ellipsis + separator + endSegments.join(separator);
}
function makeRelative(targetPath, rootDirectory) {
  const resolvedTargetPath = path.resolve(targetPath);
  const resolvedRootDirectory = path.resolve(rootDirectory);
  if (!isSubpath(resolvedRootDirectory, resolvedTargetPath)) {
    return resolvedTargetPath;
  }
  const relativePath = path.relative(resolvedRootDirectory, resolvedTargetPath);
  return relativePath || ".";
}
function escapePath(filePath) {
  let result = "";
  for (let i3 = 0; i3 < filePath.length; i3++) {
    const char = filePath[i3];
    let backslashCount = 0;
    for (let j2 = i3 - 1; j2 >= 0 && filePath[j2] === "\\"; j2--) {
      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) {
  const normalizedPath = os.platform() === "win32" ? projectRoot.toLowerCase() : projectRoot;
  return crypto2.createHash("sha256").update(normalizedPath).digest("hex");
}
function isSubpath(parentPath, childPath) {
  const isWindows9 = os.platform() === "win32";
  const pathModule2 = isWindows9 ? path.win32 : path;
  const relative11 = pathModule2.relative(parentPath, childPath);
  return !relative11.startsWith(`..${pathModule2.sep}`) && relative11 !== ".." && !pathModule2.isAbsolute(relative11);
}
function resolvePath(baseDir = process.cwd(), relativePath) {
  const homeDir = os.homedir();
  if (relativePath === "~") {
    return homeDir;
  } else if (relativePath.startsWith("~/")) {
    return path.join(homeDir, relativePath.slice(2));
  } else if (path.isAbsolute(relativePath)) {
    return relativePath;
  } else {
    return path.resolve(baseDir, relativePath);
  }
}
function validatePath(config2, resolvedPath, options2 = {}) {
  const { allowFiles = false } = options2;
  const workspaceContext = config2.getWorkspaceContext();
  if (!workspaceContext.isPathWithinWorkspace(resolvedPath)) {
    throw new Error("Path is not within workspace");
  }
  try {
    const stats = fs.statSync(resolvedPath);
    if (!allowFiles && !stats.isDirectory()) {
      throw new Error(`Path is not a directory: ${resolvedPath}`);
    }
  } catch (error2) {
    if (isNodeError(error2) && error2.code === "ENOENT") {
      throw new Error(`Path does not exist: ${resolvedPath}`);
    }
    throw error2;
  }
}
function resolveAndValidatePath(config2, relativePath, options2 = {}) {
  const targetDir = config2.getTargetDir();
  if (!relativePath) {
    return targetDir;
  }
  const resolvedPath = resolvePath(targetDir, relativePath);
  validatePath(config2, resolvedPath, options2);
  return resolvedPath;
}
var QWEN_DIR, SHELL_SPECIAL_CHARS;
var init_paths = __esm({
  "packages/core/dist/src/utils/paths.js"() {
    "use strict";
    init_esbuild_shims();
    init_errors();
    QWEN_DIR = ".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/config/storage.js
import * as path2 from "node:path";
import * as os2 from "node:os";
import * as fs2 from "node:fs";
var QWEN_DIR2, GOOGLE_ACCOUNTS_FILENAME, OAUTH_FILE, TMP_DIR_NAME, BIN_DIR_NAME, PROJECT_DIR_NAME, IDE_DIR_NAME, DEBUG_DIR_NAME, Storage;
var init_storage = __esm({
  "packages/core/dist/src/config/storage.js"() {
    "use strict";
    init_esbuild_shims();
    init_paths();
    QWEN_DIR2 = ".qwen";
    GOOGLE_ACCOUNTS_FILENAME = "google_accounts.json";
    OAUTH_FILE = "oauth_creds.json";
    TMP_DIR_NAME = "tmp";
    BIN_DIR_NAME = "bin";
    PROJECT_DIR_NAME = "projects";
    IDE_DIR_NAME = "ide";
    DEBUG_DIR_NAME = "debug";
    Storage = class _Storage {
      static {
        __name(this, "Storage");
      }
      targetDir;
      constructor(targetDir) {
        this.targetDir = targetDir;
      }
      static getGlobalQwenDir() {
        const homeDir = os2.homedir();
        if (!homeDir) {
          return path2.join(os2.tmpdir(), ".qwen");
        }
        return path2.join(homeDir, QWEN_DIR2);
      }
      static getMcpOAuthTokensPath() {
        return path2.join(_Storage.getGlobalQwenDir(), "mcp-oauth-tokens.json");
      }
      static getGlobalSettingsPath() {
        return path2.join(_Storage.getGlobalQwenDir(), "settings.json");
      }
      static getInstallationIdPath() {
        return path2.join(_Storage.getGlobalQwenDir(), "installation_id");
      }
      static getGoogleAccountsPath() {
        return path2.join(_Storage.getGlobalQwenDir(), GOOGLE_ACCOUNTS_FILENAME);
      }
      static getUserCommandsDir() {
        return path2.join(_Storage.getGlobalQwenDir(), "commands");
      }
      static getGlobalMemoryFilePath() {
        return path2.join(_Storage.getGlobalQwenDir(), "memory.md");
      }
      static getGlobalTempDir() {
        return path2.join(_Storage.getGlobalQwenDir(), TMP_DIR_NAME);
      }
      static getGlobalDebugDir() {
        return path2.join(_Storage.getGlobalQwenDir(), DEBUG_DIR_NAME);
      }
      static getDebugLogPath(sessionId) {
        return path2.join(_Storage.getGlobalDebugDir(), `${sessionId}.txt`);
      }
      static getGlobalIdeDir() {
        return path2.join(_Storage.getGlobalQwenDir(), IDE_DIR_NAME);
      }
      static getGlobalBinDir() {
        return path2.join(_Storage.getGlobalQwenDir(), BIN_DIR_NAME);
      }
      getQwenDir() {
        return path2.join(this.targetDir, QWEN_DIR2);
      }
      getProjectDir() {
        const projectId = this.sanitizeCwd(this.getProjectRoot());
        const projectsDir = path2.join(_Storage.getGlobalQwenDir(), PROJECT_DIR_NAME);
        return path2.join(projectsDir, projectId);
      }
      getProjectTempDir() {
        const hash = getProjectHash(this.getProjectRoot());
        const tempDir = _Storage.getGlobalTempDir();
        const targetDir = path2.join(tempDir, hash);
        return targetDir;
      }
      ensureProjectTempDirExists() {
        fs2.mkdirSync(this.getProjectTempDir(), { recursive: true });
      }
      static getOAuthCredsPath() {
        return path2.join(_Storage.getGlobalQwenDir(), OAUTH_FILE);
      }
      getProjectRoot() {
        return this.targetDir;
      }
      getHistoryDir() {
        const hash = getProjectHash(this.getProjectRoot());
        const historyDir = path2.join(_Storage.getGlobalQwenDir(), "history");
        const targetDir = path2.join(historyDir, hash);
        return targetDir;
      }
      getWorkspaceSettingsPath() {
        return path2.join(this.getQwenDir(), "settings.json");
      }
      getProjectCommandsDir() {
        return path2.join(this.getQwenDir(), "commands");
      }
      getProjectTempCheckpointsDir() {
        return path2.join(this.getProjectTempDir(), "checkpoints");
      }
      getExtensionsDir() {
        return path2.join(this.getQwenDir(), "extensions");
      }
      getExtensionsConfigPath() {
        return path2.join(this.getExtensionsDir(), "qwen-extension.json");
      }
      getUserSkillsDir() {
        return path2.join(_Storage.getGlobalQwenDir(), "skills");
      }
      getHistoryFilePath() {
        return path2.join(this.getProjectTempDir(), "shell_history");
      }
      sanitizeCwd(cwd7) {
        const normalizedCwd = os2.platform() === "win32" ? cwd7.toLowerCase() : cwd7;
        return normalizedCwd.replace(/[^a-zA-Z0-9]/g, "-");
      }
    };
  }
});

// packages/core/dist/src/utils/debugLogger.js
import { promises as fs3 } from "node:fs";
import { AsyncLocalStorage } from "node:async_hooks";
import util from "node:util";
function isDebugLogFileEnabled() {
  const value = process.env["QWEN_DEBUG_LOG_FILE"];
  if (!value)
    return true;
  const normalized2 = value.trim().toLowerCase();
  return !["0", "false", "off", "no"].includes(normalized2);
}
function getActiveSession() {
  return sessionContext.getStore() ?? globalSession;
}
function ensureDebugDirExists() {
  if (!ensureDebugDirPromise) {
    ensureDebugDirPromise = fs3.mkdir(Storage.getGlobalDebugDir(), { recursive: true }).then(() => void 0).catch(() => {
      hasWriteFailure = true;
      ensureDebugDirPromise = null;
    });
  }
  return ensureDebugDirPromise ?? Promise.resolve();
}
function formatArgs(args) {
  return args.map((arg) => {
    if (arg instanceof Error) {
      return arg.stack ?? `${arg.name}: ${arg.message}`;
    }
    return arg;
  }).map((arg) => typeof arg === "string" ? arg : util.inspect(arg)).join(" ");
}
function buildLogLine(level, message, tag2) {
  const timestamp = (/* @__PURE__ */ new Date()).toISOString();
  const tagPart = tag2 ? ` [${tag2}]` : "";
  return `${timestamp} [${level}]${tagPart} ${message}
`;
}
function writeLog(session, level, tag2, args) {
  if (!isDebugLogFileEnabled()) {
    return;
  }
  const sessionId = session.getSessionId();
  const logFilePath = Storage.getDebugLogPath(sessionId);
  const message = formatArgs(args);
  const line = buildLogLine(level, message, tag2);
  void ensureDebugDirExists().then(() => fs3.appendFile(logFilePath, line, "utf8")).catch(() => {
    hasWriteFailure = true;
  });
}
function isDebugLoggingDegraded() {
  return hasWriteFailure;
}
function setDebugLogSession(session) {
  globalSession = session ?? null;
}
function createDebugLogger(tag2) {
  return {
    debug: /* @__PURE__ */ __name((...args) => {
      const session = getActiveSession();
      if (!session)
        return;
      writeLog(session, "DEBUG", tag2, args);
    }, "debug"),
    info: /* @__PURE__ */ __name((...args) => {
      const session = getActiveSession();
      if (!session)
        return;
      writeLog(session, "INFO", tag2, args);
    }, "info"),
    warn: /* @__PURE__ */ __name((...args) => {
      const session = getActiveSession();
      if (!session)
        return;
      writeLog(session, "WARN", tag2, args);
    }, "warn"),
    error: /* @__PURE__ */ __name((...args) => {
      const session = getActiveSession();
      if (!session)
        return;
      writeLog(session, "ERROR", tag2, args);
    }, "error")
  };
}
var ensureDebugDirPromise, hasWriteFailure, globalSession, sessionContext;
var init_debugLogger = __esm({
  "packages/core/dist/src/utils/debugLogger.js"() {
    "use strict";
    init_esbuild_shims();
    init_storage();
    ensureDebugDirPromise = null;
    hasWriteFailure = false;
    globalSession = null;
    sessionContext = new AsyncLocalStorage();
    __name(isDebugLogFileEnabled, "isDebugLogFileEnabled");
    __name(getActiveSession, "getActiveSession");
    __name(ensureDebugDirExists, "ensureDebugDirExists");
    __name(formatArgs, "formatArgs");
    __name(buildLogLine, "buildLogLine");
    __name(writeLog, "writeLog");
    __name(isDebugLoggingDegraded, "isDebugLoggingDegraded");
    __name(setDebugLogSession, "setDebugLogSession");
    __name(createDebugLogger, "createDebugLogger");
  }
});

// packages/core/dist/src/utils/errorReporting.js
async function reportError2(error2, baseMessage, context2, type = "general") {
  let errorToReport;
  if (error2 instanceof Error) {
    errorToReport = { message: error2.message, stack: error2.stack };
  } else if (typeof error2 === "object" && error2 !== null && "message" in error2) {
    errorToReport = {
      message: String(error2.message)
    };
  } else {
    errorToReport = { message: String(error2) };
  }
  const reportContent = { error: errorToReport };
  if (context2) {
    reportContent.context = context2;
  }
  const reportLabel = `${baseMessage} [${type}]`;
  let stringifiedReportContent;
  try {
    stringifiedReportContent = JSON.stringify(reportContent, null, 2);
  } catch (stringifyError) {
    debugLogger.error(`${reportLabel} Could not stringify report content (likely due to context):`, stringifyError, error2);
    try {
      const minimalReportContent = { error: errorToReport };
      stringifiedReportContent = JSON.stringify(minimalReportContent, null, 2);
      debugLogger.error(reportLabel, stringifiedReportContent);
    } catch (minimalStringifyError) {
      debugLogger.error(`${reportLabel} Failed to stringify minimal error report:`, minimalStringifyError, error2);
    }
    return;
  }
  debugLogger.error(reportLabel, stringifiedReportContent);
}
var debugLogger;
var init_errorReporting = __esm({
  "packages/core/dist/src/utils/errorReporting.js"() {
    "use strict";
    init_esbuild_shims();
    init_debugLogger();
    debugLogger = createDebugLogger("ERROR_REPORT");
    __name(reportError2, "reportError");
  }
});

// node_modules/extend/index.js
var require_extend = __commonJS({
  "node_modules/extend/index.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var hasOwn3 = 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 isPlainObject7 = /* @__PURE__ */ __name(function isPlainObject8(obj) {
      if (!obj || toStr.call(obj) !== "[object Object]") {
        return false;
      }
      var hasOwnConstructor = hasOwn3.call(obj, "constructor");
      var hasIsPrototypeOf = obj.constructor && obj.constructor.prototype && hasOwn3.call(obj.constructor.prototype, "isPrototypeOf");
      if (obj.constructor && !hasOwnConstructor && !hasIsPrototypeOf) {
        return false;
      }
      var key;
      for (key in obj) {
      }
      return typeof key === "undefined" || hasOwn3.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 (!hasOwn3.call(obj, name3)) {
          return void 0;
        } else if (gOPD) {
          return gOPD(obj, name3).value;
        }
      }
      return obj[name3];
    }, "getProperty");
    module2.exports = /* @__PURE__ */ __name(function extend2() {
      var options2, name3, src, copy, copyIsArray, clone4;
      var target = arguments[0];
      var i3 = 1;
      var length = arguments.length;
      var deep = false;
      if (typeof target === "boolean") {
        deep = target;
        target = arguments[1] || {};
        i3 = 2;
      }
      if (target == null || typeof target !== "object" && typeof target !== "function") {
        target = {};
      }
      for (; i3 < length; ++i3) {
        options2 = arguments[i3];
        if (options2 != null) {
          for (name3 in options2) {
            src = getProperty2(target, name3);
            copy = getProperty2(options2, name3);
            if (target !== copy) {
              if (deep && copy && (isPlainObject7(copy) || (copyIsArray = isArray2(copy)))) {
                if (copyIsArray) {
                  copyIsArray = false;
                  clone4 = src && isArray2(src) ? src : [];
                } else {
                  clone4 = src && isPlainObject7(src) ? src : {};
                }
                setProperty2(target, { name: name3, newValue: extend2(deep, clone4, copy) });
              } else if (typeof copy !== "undefined") {
                setProperty2(target, { name: name3, newValue: copy });
              }
            }
          }
        }
      }
      return target;
    }, "extend");
  }
});

// packages/core/node_modules/gaxios/package.json
var require_package = __commonJS({
  "packages/core/node_modules/gaxios/package.json"(exports2, module2) {
    module2.exports = {
      name: "gaxios",
      version: "7.1.3",
      description: "A simple common HTTP client specifically for Google APIs and services.",
      main: "build/cjs/src/index.js",
      types: "build/cjs/src/index.d.ts",
      files: [
        "build/"
      ],
      exports: {
        ".": {
          import: {
            types: "./build/esm/src/index.d.ts",
            default: "./build/esm/src/index.js"
          },
          require: {
            types: "./build/cjs/src/index.d.ts",
            default: "./build/cjs/src/index.js"
          }
        }
      },
      scripts: {
        lint: "gts check --no-inline-config",
        test: "c8 mocha build/esm/test",
        "presystem-test": "npm run compile",
        "system-test": "mocha build/esm/system-test --timeout 80000",
        compile: "tsc -b ./tsconfig.json ./tsconfig.cjs.json && node utils/enable-esm.mjs",
        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: "jsdoc -c .jsdoc.js",
        "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"
      },
      repository: {
        type: "git",
        directory: "packages/gaxios",
        url: "https://github.com/googleapis/google-cloud-node-core.git"
      },
      keywords: [
        "google"
      ],
      engines: {
        node: ">=18"
      },
      author: "Google, LLC",
      license: "Apache-2.0",
      devDependencies: {
        "@babel/plugin-proposal-private-methods": "^7.18.6",
        "@types/cors": "^2.8.6",
        "@types/express": "^5.0.0",
        "@types/extend": "^3.0.1",
        "@types/mocha": "^10.0.10",
        "@types/multiparty": "4.2.1",
        "@types/mv": "^2.1.0",
        "@types/ncp": "^2.0.1",
        "@types/node": "^22.0.0",
        "@types/sinon": "^17.0.0",
        "@types/tmp": "0.2.6",
        assert: "^2.0.0",
        browserify: "^17.0.0",
        c8: "^10.0.0",
        cors: "^2.8.5",
        express: "^5.0.0",
        gts: "^6.0.0",
        "is-docker": "^3.0.0",
        jsdoc: "^4.0.0",
        "jsdoc-fresh": "^5.0.0",
        "jsdoc-region-tag": "^4.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.1",
        linkinator: "^6.1.2",
        mocha: "^11.1.0",
        multiparty: "^4.2.1",
        mv: "^2.1.1",
        ncp: "^2.0.0",
        nock: "^14.0.0-beta.13",
        "null-loader": "^4.0.0",
        "pack-n-play": "^4.0.0",
        puppeteer: "^24.0.0",
        sinon: "^21.0.0",
        "stream-browserify": "^3.0.0",
        tmp: "0.2.5",
        "ts-loader": "^9.5.2",
        typescript: "^5.8.3",
        webpack: "^5.35.0",
        "webpack-cli": "^6.0.1"
      },
      dependencies: {
        extend: "^3.0.2",
        "https-proxy-agent": "^7.0.1",
        "node-fetch": "^3.3.2",
        rimraf: "^5.0.1"
      },
      homepage: "https://github.com/googleapis/google-cloud-node-core/tree/main/packages/gaxios"
    };
  }
});

// packages/core/node_modules/gaxios/build/cjs/src/util.cjs
var require_util9 = __commonJS({
  "packages/core/node_modules/gaxios/build/cjs/src/util.cjs"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var pkg2 = require_package();
    module2.exports = { pkg: pkg2 };
  }
});

// packages/core/node_modules/gaxios/build/cjs/src/common.js
var require_common = __commonJS({
  "packages/core/node_modules/gaxios/build/cjs/src/common.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.GaxiosError = exports2.GAXIOS_ERROR_SYMBOL = void 0;
    exports2.defaultErrorRedactor = defaultErrorRedactor;
    var extend_1 = __importDefault(require_extend());
    var util_cjs_1 = __importDefault(require_util9());
    var pkg2 = util_cjs_1.default.pkg;
    exports2.GAXIOS_ERROR_SYMBOL = Symbol.for(`${pkg2.name}-gaxios-error`);
    var GaxiosError = class _GaxiosError extends Error {
      static {
        __name(this, "GaxiosError");
      }
      config;
      response;
      /**
       * An error code.
       * Can be a system error code, DOMException error name, or any error's 'code' property where it is a `string`.
       *
       * It is only a `number` when the cause is sourced from an API-level error (AIP-193).
       *
       * @see {@link https://nodejs.org/api/errors.html#errorcode error.code}
       * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/DOMException#error_names DOMException#error_names}
       * @see {@link https://google.aip.dev/193#http11json-representation AIP-193}
       *
       * @example
       * 'ECONNRESET'
       *
       * @example
       * 'TimeoutError'
       *
       * @example
       * 500
       */
      code;
      /**
       * An HTTP Status code.
       * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/Response/status Response#status}
       *
       * @example
       * 500
       */
      status;
      /**
       * @deprecated use {@link GaxiosError.cause} instead.
       *
       * @see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error/cause Error#cause}
       *
       * @privateRemarks
       *
       * We will want to remove this property later as the modern `cause` property is better suited
       * for displaying and relaying nested errors. Keeping this here makes the resulting
       * error log larger than it needs to be.
       *
       */
      error;
      /**
       * Support `instanceof` operator for `GaxiosError` across builds/duplicated files.
       *
       * @see {@link GAXIOS_ERROR_SYMBOL}
       * @see {@link GaxiosError[Symbol.hasInstance]}
       * @see {@link https://github.com/microsoft/TypeScript/issues/13965#issuecomment-278570200}
       * @see {@link https://stackoverflow.com/questions/46618852/require-and-instanceof}
       * @see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/@@hasInstance#reverting_to_default_instanceof_behavior}
       */
      [exports2.GAXIOS_ERROR_SYMBOL] = pkg2.version;
      /**
       * Support `instanceof` operator for `GaxiosError` across builds/duplicated files.
       *
       * @see {@link GAXIOS_ERROR_SYMBOL}
       * @see {@link GaxiosError[GAXIOS_ERROR_SYMBOL]}
       */
      static [Symbol.hasInstance](instance) {
        if (instance && typeof instance === "object" && exports2.GAXIOS_ERROR_SYMBOL in instance && instance[exports2.GAXIOS_ERROR_SYMBOL] === pkg2.version) {
          return true;
        }
        return Function.prototype[Symbol.hasInstance].call(_GaxiosError, instance);
      }
      constructor(message, config2, response, cause) {
        super(message, { cause });
        this.config = config2;
        this.response = response;
        this.error = cause instanceof Error ? cause : void 0;
        this.config = (0, extend_1.default)(true, {}, config2);
        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,
              // workaround for `node-fetch`'s `.data` deprecation...
              this.response?.bodyUsed ? this.response?.data : void 0
            );
          } catch {
          }
          this.status = this.response.status;
        }
        if (cause instanceof DOMException) {
          this.code = cause.name;
        } else if (cause && typeof cause === "object" && "code" in cause && (typeof cause.code === "string" || typeof cause.code === "number")) {
          this.code = cause.code;
        }
      }
      /**
       * An AIP-193 conforming error extractor.
       *
       * @see {@link https://google.aip.dev/193#http11json-representation AIP-193}
       *
       * @internal
       * @expiremental
       *
       * @param res the response object
       * @returns the extracted error information
       */
      static extractAPIErrorFromResponse(res, defaultErrorMessage = "The request failed") {
        let message = defaultErrorMessage;
        if (typeof res.data === "string") {
          message = res.data;
        }
        if (res.data && typeof res.data === "object" && "error" in res.data && res.data.error && !res.ok) {
          if (typeof res.data.error === "string") {
            return {
              message: res.data.error,
              code: res.status,
              status: res.statusText
            };
          }
          if (typeof res.data.error === "object") {
            message = "message" in res.data.error && typeof res.data.error.message === "string" ? res.data.error.message : message;
            const status = "status" in res.data.error && typeof res.data.error.status === "string" ? res.data.error.status : res.statusText;
            const code2 = "code" in res.data.error && typeof res.data.error.code === "number" ? res.data.error.code : res.status;
            if ("errors" in res.data.error && Array.isArray(res.data.error.errors)) {
              const errorMessages = [];
              for (const e4 of res.data.error.errors) {
                if (typeof e4 === "object" && "message" in e4 && typeof e4.message === "string") {
                  errorMessages.push(e4.message);
                }
              }
              return Object.assign({
                message: errorMessages.join("\n") || message,
                code: code2,
                status
              }, res.data.error);
            }
            return Object.assign({
              message,
              code: code2,
              status
            }, res.data.error);
          }
        }
        return {
          message,
          code: res.status,
          status: res.statusText
        };
      }
    };
    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;
        headers.forEach((_2, key) => {
          if (/^authentication$/i.test(key) || /^authorization$/i.test(key) || /secret/i.test(key))
            headers.set(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 (!obj || typeof obj !== "object") {
          return;
        } else if (obj instanceof FormData || obj instanceof URLSearchParams || // support `node-fetch` FormData/URLSearchParams
        "forEach" in obj && "set" in obj) {
          obj.forEach((_2, key) => {
            if (["grant_type", "assertion"].includes(key) || /secret/.test(key)) {
              obj.set(key, REDACT);
            }
          });
        } else {
          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);
        if (data.config.url.searchParams.has("token")) {
          data.config.url.searchParams.set("token", REDACT);
        }
        if (data.config.url.searchParams.has("client_secret")) {
          data.config.url.searchParams.set("client_secret", REDACT);
        }
      }
      if (data.response) {
        defaultErrorRedactor({ config: data.response.config });
        redactHeaders(data.response.headers);
        if (data.response.bodyUsed) {
          redactString(data.response, "data");
          redactObject(data.response.data);
        }
      }
      return data;
    }
    __name(defaultErrorRedactor, "defaultErrorRedactor");
  }
});

// packages/core/node_modules/gaxios/build/cjs/src/retry.js
var require_retry2 = __commonJS({
  "packages/core/node_modules/gaxios/build/cjs/src/retry.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.getRetryConfig = getRetryConfig;
    async function getRetryConfig(err) {
      let config2 = getConfig(err);
      if (!err || !err.config || !config2 && !err.config.retry) {
        return { shouldRetry: false };
      }
      config2 = config2 || {};
      config2.currentRetryAttempt = config2.currentRetryAttempt || 0;
      config2.retry = config2.retry === void 0 || config2.retry === null ? 3 : config2.retry;
      config2.httpMethodsToRetry = config2.httpMethodsToRetry || [
        "GET",
        "HEAD",
        "PUT",
        "OPTIONS",
        "DELETE"
      ];
      config2.noResponseRetries = config2.noResponseRetries === void 0 || config2.noResponseRetries === null ? 2 : config2.noResponseRetries;
      config2.retryDelayMultiplier = config2.retryDelayMultiplier ? config2.retryDelayMultiplier : 2;
      config2.timeOfFirstRequest = config2.timeOfFirstRequest ? config2.timeOfFirstRequest : Date.now();
      config2.totalTimeout = config2.totalTimeout ? config2.totalTimeout : Number.MAX_SAFE_INTEGER;
      config2.maxRetryDelay = config2.maxRetryDelay ? config2.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]
      ];
      config2.statusCodesToRetry = config2.statusCodesToRetry || retryRanges;
      err.config.retryConfig = config2;
      const shouldRetryFn = config2.shouldRetry || shouldRetryRequest;
      if (!await shouldRetryFn(err)) {
        return { shouldRetry: false, config: err.config };
      }
      const delay4 = getNextRetryDelay(config2);
      err.config.retryConfig.currentRetryAttempt += 1;
      const backoff = config2.retryBackoff ? config2.retryBackoff(err, delay4) : new Promise((resolve30) => {
        setTimeout(resolve30, delay4);
      });
      if (config2.onRetryAttempt) {
        await config2.onRetryAttempt(err);
      }
      await backoff;
      return { shouldRetry: true, config: err.config };
    }
    __name(getRetryConfig, "getRetryConfig");
    function shouldRetryRequest(err) {
      const config2 = getConfig(err);
      if (err.config.signal?.aborted && err.code !== "TimeoutError" || err.code === "AbortError") {
        return false;
      }
      if (!config2 || config2.retry === 0) {
        return false;
      }
      if (!err.response && (config2.currentRetryAttempt || 0) >= config2.noResponseRetries) {
        return false;
      }
      if (!config2.httpMethodsToRetry || !config2.httpMethodsToRetry.includes(err.config.method?.toUpperCase() || "GET")) {
        return false;
      }
      if (err.response && err.response.status) {
        let isInRange = false;
        for (const [min, max] of config2.statusCodesToRetry) {
          const status = err.response.status;
          if (status >= min && status <= max) {
            isInRange = true;
            break;
          }
        }
        if (!isInRange) {
          return false;
        }
      }
      config2.currentRetryAttempt = config2.currentRetryAttempt || 0;
      if (config2.currentRetryAttempt >= config2.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(config2) {
      const retryDelay = config2.currentRetryAttempt ? 0 : config2.retryDelay ?? 100;
      const calculatedDelay = retryDelay + (Math.pow(config2.retryDelayMultiplier, config2.currentRetryAttempt) - 1) / 2 * 1e3;
      const maxAllowableDelay = config2.totalTimeout - (Date.now() - config2.timeOfFirstRequest);
      return Math.min(calculatedDelay, maxAllowableDelay, config2.maxRetryDelay);
    }
    __name(getNextRetryDelay, "getNextRetryDelay");
  }
});

// packages/core/node_modules/gaxios/build/cjs/src/interceptor.js
var require_interceptor = __commonJS({
  "packages/core/node_modules/gaxios/build/cjs/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 s5 = 1e3;
    var m3 = s5 * 60;
    var h3 = m3 * 60;
    var d2 = h3 * 24;
    var w2 = d2 * 7;
    var y2 = d2 * 365.25;
    module2.exports = function(val, options2) {
      options2 = options2 || {};
      var type = typeof val;
      if (type === "string" && val.length > 0) {
        return parse14(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 parse14(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 n3 = parseFloat(match2[1]);
      var type = (match2[2] || "ms").toLowerCase();
      switch (type) {
        case "years":
        case "year":
        case "yrs":
        case "yr":
        case "y":
          return n3 * y2;
        case "weeks":
        case "week":
        case "w":
          return n3 * w2;
        case "days":
        case "day":
        case "d":
          return n3 * d2;
        case "hours":
        case "hour":
        case "hrs":
        case "hr":
        case "h":
          return n3 * h3;
        case "minutes":
        case "minute":
        case "mins":
        case "min":
        case "m":
          return n3 * m3;
        case "seconds":
        case "second":
        case "secs":
        case "sec":
        case "s":
          return n3 * s5;
        case "milliseconds":
        case "millisecond":
        case "msecs":
        case "msec":
        case "ms":
          return n3;
        default:
          return void 0;
      }
    }
    __name(parse14, "parse");
    function fmtShort(ms) {
      var msAbs = Math.abs(ms);
      if (msAbs >= d2) {
        return Math.round(ms / d2) + "d";
      }
      if (msAbs >= h3) {
        return Math.round(ms / h3) + "h";
      }
      if (msAbs >= m3) {
        return Math.round(ms / m3) + "m";
      }
      if (msAbs >= s5) {
        return Math.round(ms / s5) + "s";
      }
      return ms + "ms";
    }
    __name(fmtShort, "fmtShort");
    function fmtLong(ms) {
      var msAbs = Math.abs(ms);
      if (msAbs >= d2) {
        return plural(ms, msAbs, d2, "day");
      }
      if (msAbs >= h3) {
        return plural(ms, msAbs, h3, "hour");
      }
      if (msAbs >= m3) {
        return plural(ms, msAbs, m3, "minute");
      }
      if (msAbs >= s5) {
        return plural(ms, msAbs, s5, "second");
      }
      return ms + " ms";
    }
    __name(fmtLong, "fmtLong");
    function plural(ms, msAbs, n3, name3) {
      var isPlural = msAbs >= n3 * 1.5;
      return Math.round(ms / n3) + " " + 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 i3 = 0; i3 < namespace.length; i3++) {
          hash = (hash << 5) - hash + namespace.charCodeAt(i3);
          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 debug3(...args) {
          if (!debug3.enabled) {
            return;
          }
          const self2 = debug3;
          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(debug3, "debug");
        debug3.namespace = namespace;
        debug3.useColors = createDebug.useColors();
        debug3.color = createDebug.selectColor(namespace);
        debug3.extend = extend2;
        debug3.destroy = createDebug.destroy;
        Object.defineProperty(debug3, "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((v2) => {
            enableOverride = v2;
          }, "set")
        });
        if (typeof createDebug.init === "function") {
          createDebug.init(debug3);
        }
        return debug3;
      }
      __name(createDebug, "createDebug");
      function extend2(namespace, delimiter2) {
        const newDebug = createDebug(this.namespace + (typeof delimiter2 === "undefined" ? ":" : delimiter2) + namespace);
        newDebug.log = this.log;
        return newDebug;
      }
      __name(extend2, "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 = formatArgs2;
    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 m3;
      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 && (m3 = navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)) && parseInt(m3[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 formatArgs2(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 c4 = "color: " + this.color;
      args.splice(1, 0, c4, "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, c4);
    }
    __name(formatArgs2, "formatArgs");
    exports2.log = console.debug || console.log || (() => {
    });
    function save(namespaces) {
      try {
        if (namespaces) {
          exports2.storage.setItem("debug", namespaces);
        } else {
          exports2.storage.removeItem("debug");
        }
      } catch (error2) {
      }
    }
    __name(save, "save");
    function load() {
      let r5;
      try {
        r5 = exports2.storage.getItem("debug") || exports2.storage.getItem("DEBUG");
      } catch (error2) {
      }
      if (!r5 && typeof process !== "undefined" && "env" in process) {
        r5 = process.env.DEBUG;
      }
      return r5;
    }
    __name(load, "load");
    function localstorage() {
      try {
        return localStorage;
      } catch (error2) {
      }
    }
    __name(localstorage, "localstorage");
    module2.exports = require_common2()(exports2);
    var { formatters: formatters2 } = module2.exports;
    formatters2.j = function(v2) {
      try {
        return JSON.stringify(v2);
      } catch (error2) {
        return "[UnexpectedJSONParseError]: " + error2.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 os47 = __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 = os47.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 util3 = __require("util");
    exports2.init = init;
    exports2.log = log;
    exports2.formatArgs = formatArgs2;
    exports2.save = save;
    exports2.load = load;
    exports2.useColors = useColors;
    exports2.destroy = util3.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 (error2) {
    }
    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, (_2, k2) => {
        return k2.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 formatArgs2(args) {
      const { namespace: name3, useColors: useColors2 } = this;
      if (useColors2) {
        const c4 = this.color;
        const colorCode = "\x1B[3" + (c4 < 8 ? c4 : "8;5;" + c4);
        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(formatArgs2, "formatArgs");
    function getDate() {
      if (exports2.inspectOpts.hideDate) {
        return "";
      }
      return (/* @__PURE__ */ new Date()).toISOString() + " ";
    }
    __name(getDate, "getDate");
    function log(...args) {
      return process.stderr.write(util3.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(debug3) {
      debug3.inspectOpts = {};
      const keys = Object.keys(exports2.inspectOpts);
      for (let i3 = 0; i3 < keys.length; i3++) {
        debug3.inspectOpts[keys[i3]] = exports2.inspectOpts[keys[i3]];
      }
    }
    __name(init, "init");
    module2.exports = require_common2()(exports2);
    var { formatters: formatters2 } = module2.exports;
    formatters2.o = function(v2) {
      this.inspectOpts.colors = this.useColors;
      return util3.inspect(v2, this.inspectOpts).split("\n").map((str2) => str2.trim()).join(" ");
    };
    formatters2.O = function(v2) {
      this.inspectOpts.colors = this.useColors;
      return util3.inspect(v2, 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(o3, m3, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc2 = Object.getOwnPropertyDescriptor(m3, k2);
      if (!desc2 || ("get" in desc2 ? !m3.__esModule : desc2.writable || desc2.configurable)) {
        desc2 = { enumerable: true, get: /* @__PURE__ */ __name(function() {
          return m3[k2];
        }, "get") };
      }
      Object.defineProperty(o3, k22, desc2);
    } : function(o3, m3, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o3[k22] = m3[k2];
    });
    var __setModuleDefault = exports2 && exports2.__setModuleDefault || (Object.create ? function(o3, v2) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v2 });
    } : function(o3, v2) {
      o3["default"] = v2;
    });
    var __importStar = exports2 && exports2.__importStar || function(mod2) {
      if (mod2 && mod2.__esModule) return mod2;
      var result = {};
      if (mod2 != null) {
        for (var k2 in mod2) if (k2 !== "default" && Object.prototype.hasOwnProperty.call(mod2, k2)) __createBinding(result, mod2, k2);
      }
      __setModuleDefault(result, mod2);
      return result;
    };
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.req = exports2.json = exports2.toBuffer = void 0;
    var http7 = __importStar(__require("http"));
    var https7 = __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:") ? https7 : http7).request(url2, opts);
      const promise = new Promise((resolve30, reject) => {
        req2.once("response", resolve30).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(o3, m3, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc2 = Object.getOwnPropertyDescriptor(m3, k2);
      if (!desc2 || ("get" in desc2 ? !m3.__esModule : desc2.writable || desc2.configurable)) {
        desc2 = { enumerable: true, get: /* @__PURE__ */ __name(function() {
          return m3[k2];
        }, "get") };
      }
      Object.defineProperty(o3, k22, desc2);
    } : function(o3, m3, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o3[k22] = m3[k2];
    });
    var __setModuleDefault = exports2 && exports2.__setModuleDefault || (Object.create ? function(o3, v2) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v2 });
    } : function(o3, v2) {
      o3["default"] = v2;
    });
    var __importStar = exports2 && exports2.__importStar || function(mod2) {
      if (mod2 && mod2.__esModule) return mod2;
      var result = {};
      if (mod2 != null) {
        for (var k2 in mod2) if (k2 !== "default" && Object.prototype.hasOwnProperty.call(mod2, k2)) __createBinding(result, mod2, k2);
      }
      __setModuleDefault(result, mod2);
      return result;
    };
    var __exportStar = exports2 && exports2.__exportStar || function(m3, exports3) {
      for (var p2 in m3) if (p2 !== "default" && !Object.prototype.hasOwnProperty.call(exports3, p2)) __createBinding(exports3, m3, p2);
    };
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.Agent = void 0;
    var net2 = __importStar(__require("net"));
    var http7 = __importStar(__require("http"));
    var https_1 = __require("https");
    __exportStar(require_helpers(), exports2);
    var INTERNAL = Symbol("AgentBaseInternalState");
    var Agent4 = class extends http7.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((l3) => l3.indexOf("(https.js:") !== -1 || l3.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 http7.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(v2) {
        if (this[INTERNAL]) {
          this[INTERNAL].defaultPort = v2;
        }
      }
      get protocol() {
        return this[INTERNAL].protocol ?? (this.isSecureEndpoint() ? "https:" : "http:");
      }
      set protocol(v2) {
        if (this[INTERNAL]) {
          this[INTERNAL].protocol = v2;
        }
      }
    };
    exports2.Agent = Agent4;
  }
});

// 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 debug3 = (0, debug_1.default)("https-proxy-agent:parse-proxy-response");
    function parseProxyResponse(socket) {
      return new Promise((resolve30, reject) => {
        let buffersLength = 0;
        const buffers = [];
        function read3() {
          const b2 = socket.read();
          if (b2)
            ondata(b2);
          else
            socket.once("readable", read3);
        }
        __name(read3, "read");
        function cleanup() {
          socket.removeListener("end", onend);
          socket.removeListener("error", onerror);
          socket.removeListener("readable", read3);
        }
        __name(cleanup, "cleanup");
        function onend() {
          cleanup();
          debug3("onend");
          reject(new Error("Proxy connection ended before receiving CONNECT response"));
        }
        __name(onend, "onend");
        function onerror(err) {
          cleanup();
          debug3("onerror %o", err);
          reject(err);
        }
        __name(onerror, "onerror");
        function ondata(b2) {
          buffers.push(b2);
          buffersLength += b2.length;
          const buffered = Buffer.concat(buffers, buffersLength);
          const endOfHeaders = buffered.indexOf("\r\n\r\n");
          if (endOfHeaders === -1) {
            debug3("have not received end of HTTP headers yet...");
            read3();
            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;
            }
          }
          debug3("got proxy server response: %o %o", firstLine, headers);
          cleanup();
          resolve30({
            connect: {
              statusCode,
              statusText,
              headers
            },
            buffered
          });
        }
        __name(ondata, "ondata");
        socket.on("error", onerror);
        socket.on("end", onend);
        read3();
      });
    }
    __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(o3, m3, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc2 = Object.getOwnPropertyDescriptor(m3, k2);
      if (!desc2 || ("get" in desc2 ? !m3.__esModule : desc2.writable || desc2.configurable)) {
        desc2 = { enumerable: true, get: /* @__PURE__ */ __name(function() {
          return m3[k2];
        }, "get") };
      }
      Object.defineProperty(o3, k22, desc2);
    } : function(o3, m3, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o3[k22] = m3[k2];
    });
    var __setModuleDefault = exports2 && exports2.__setModuleDefault || (Object.create ? function(o3, v2) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v2 });
    } : function(o3, v2) {
      o3["default"] = v2;
    });
    var __importStar = exports2 && exports2.__importStar || function(mod2) {
      if (mod2 && mod2.__esModule) return mod2;
      var result = {};
      if (mod2 != null) {
        for (var k2 in mod2) if (k2 !== "default" && Object.prototype.hasOwnProperty.call(mod2, k2)) __createBinding(result, mod2, k2);
      }
      __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 debug3 = (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 HttpsProxyAgent2 = 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 ?? {};
        debug3("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 ? omit2(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:") {
          debug3("Creating `tls.Socket`: %o", this.connectOpts);
          socket = tls.connect(setServernameFromNonIpHost(this.connectOpts));
        } else {
          debug3("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) {
            debug3("Upgrading socket connection to TLS");
            return tls.connect({
              ...omit2(setServernameFromNonIpHost(opts), "host", "path", "port"),
              socket
            });
          }
          return socket;
        }
        socket.destroy();
        const fakeSocket = new net2.Socket({ writable: false });
        fakeSocket.readable = true;
        req.once("socket", (s5) => {
          debug3("Replaying proxy buffer for failed request");
          (0, assert_1.default)(s5.listenerCount("data") > 0);
          s5.push(buffered);
          s5.push(null);
        });
        return fakeSocket;
      }
    };
    HttpsProxyAgent2.protocols = ["http", "https"];
    exports2.HttpsProxyAgent = HttpsProxyAgent2;
    function resume(socket) {
      socket.resume();
    }
    __name(resume, "resume");
    function omit2(obj, ...keys) {
      const ret = {};
      let key;
      for (key in obj) {
        if (!keys.includes(key)) {
          ret[key] = obj[key];
        }
      }
      return ret;
    }
    __name(omit2, "omit");
  }
});

// node_modules/data-uri-to-buffer/dist/index.js
function dataUriToBuffer(uri) {
  if (!/^data:/i.test(uri)) {
    throw new TypeError('`uri` does not appear to be a Data URI (must begin with "data:")');
  }
  uri = uri.replace(/\r?\n/g, "");
  const firstComma = uri.indexOf(",");
  if (firstComma === -1 || firstComma <= 4) {
    throw new TypeError("malformed data: URI");
  }
  const meta = uri.substring(5, firstComma).split(";");
  let charset = "";
  let base642 = false;
  const type = meta[0] || "text/plain";
  let typeFull = type;
  for (let i3 = 1; i3 < meta.length; i3++) {
    if (meta[i3] === "base64") {
      base642 = true;
    } else if (meta[i3]) {
      typeFull += `;${meta[i3]}`;
      if (meta[i3].indexOf("charset=") === 0) {
        charset = meta[i3].substring(8);
      }
    }
  }
  if (!meta[0] && !charset.length) {
    typeFull += ";charset=US-ASCII";
    charset = "US-ASCII";
  }
  const encoding = base642 ? "base64" : "ascii";
  const data = unescape(uri.substring(firstComma + 1));
  const buffer = Buffer.from(data, encoding);
  buffer.type = type;
  buffer.typeFull = typeFull;
  buffer.charset = charset;
  return buffer;
}
var dist_default;
var init_dist = __esm({
  "node_modules/data-uri-to-buffer/dist/index.js"() {
    init_esbuild_shims();
    __name(dataUriToBuffer, "dataUriToBuffer");
    dist_default = dataUriToBuffer;
  }
});

// node_modules/web-streams-polyfill/dist/ponyfill.es2018.js
var require_ponyfill_es2018 = __commonJS({
  "node_modules/web-streams-polyfill/dist/ponyfill.es2018.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) : (global2 = typeof globalThis !== "undefined" ? globalThis : global2 || self, factory(global2.WebStreamsPolyfill = {}));
    })(exports2, function(exports3) {
      "use strict";
      function noop8() {
        return void 0;
      }
      __name(noop8, "noop");
      function typeIsObject(x3) {
        return typeof x3 === "object" && x3 !== null || typeof x3 === "function";
      }
      __name(typeIsObject, "typeIsObject");
      const rethrowAssertionErrorRejection = noop8;
      function setFunctionName(fn, name3) {
        try {
          Object.defineProperty(fn, "name", {
            value: name3,
            configurable: true
          });
        } catch (_a8) {
        }
      }
      __name(setFunctionName, "setFunctionName");
      const originalPromise = Promise;
      const originalPromiseThen = Promise.prototype.then;
      const originalPromiseReject = Promise.reject.bind(originalPromise);
      function newPromise(executor) {
        return new originalPromise(executor);
      }
      __name(newPromise, "newPromise");
      function promiseResolvedWith(value) {
        return newPromise((resolve30) => resolve30(value));
      }
      __name(promiseResolvedWith, "promiseResolvedWith");
      function promiseRejectedWith(reason) {
        return originalPromiseReject(reason);
      }
      __name(promiseRejectedWith, "promiseRejectedWith");
      function PerformPromiseThen(promise, onFulfilled, onRejected) {
        return originalPromiseThen.call(promise, onFulfilled, onRejected);
      }
      __name(PerformPromiseThen, "PerformPromiseThen");
      function uponPromise(promise, onFulfilled, onRejected) {
        PerformPromiseThen(PerformPromiseThen(promise, onFulfilled, onRejected), void 0, rethrowAssertionErrorRejection);
      }
      __name(uponPromise, "uponPromise");
      function uponFulfillment(promise, onFulfilled) {
        uponPromise(promise, onFulfilled);
      }
      __name(uponFulfillment, "uponFulfillment");
      function uponRejection(promise, onRejected) {
        uponPromise(promise, void 0, onRejected);
      }
      __name(uponRejection, "uponRejection");
      function transformPromiseWith(promise, fulfillmentHandler, rejectionHandler) {
        return PerformPromiseThen(promise, fulfillmentHandler, rejectionHandler);
      }
      __name(transformPromiseWith, "transformPromiseWith");
      function setPromiseIsHandledToTrue(promise) {
        PerformPromiseThen(promise, void 0, rethrowAssertionErrorRejection);
      }
      __name(setPromiseIsHandledToTrue, "setPromiseIsHandledToTrue");
      let _queueMicrotask = /* @__PURE__ */ __name((callback) => {
        if (typeof queueMicrotask === "function") {
          _queueMicrotask = queueMicrotask;
        } else {
          const resolvedPromise = promiseResolvedWith(void 0);
          _queueMicrotask = /* @__PURE__ */ __name((cb) => PerformPromiseThen(resolvedPromise, cb), "_queueMicrotask");
        }
        return _queueMicrotask(callback);
      }, "_queueMicrotask");
      function reflectCall(F4, V3, args) {
        if (typeof F4 !== "function") {
          throw new TypeError("Argument is not a function");
        }
        return Function.prototype.apply.call(F4, V3, args);
      }
      __name(reflectCall, "reflectCall");
      function promiseCall(F4, V3, args) {
        try {
          return promiseResolvedWith(reflectCall(F4, V3, args));
        } catch (value) {
          return promiseRejectedWith(value);
        }
      }
      __name(promiseCall, "promiseCall");
      const QUEUE_MAX_ARRAY_SIZE = 16384;
      class SimpleQueue {
        static {
          __name(this, "SimpleQueue");
        }
        constructor() {
          this._cursor = 0;
          this._size = 0;
          this._front = {
            _elements: [],
            _next: void 0
          };
          this._back = this._front;
          this._cursor = 0;
          this._size = 0;
        }
        get length() {
          return this._size;
        }
        // For exception safety, this method is structured in order:
        // 1. Read state
        // 2. Calculate required state mutations
        // 3. Perform state mutations
        push(element) {
          const oldBack = this._back;
          let newBack = oldBack;
          if (oldBack._elements.length === QUEUE_MAX_ARRAY_SIZE - 1) {
            newBack = {
              _elements: [],
              _next: void 0
            };
          }
          oldBack._elements.push(element);
          if (newBack !== oldBack) {
            this._back = newBack;
            oldBack._next = newBack;
          }
          ++this._size;
        }
        // Like push(), shift() follows the read -> calculate -> mutate pattern for
        // exception safety.
        shift() {
          const oldFront = this._front;
          let newFront = oldFront;
          const oldCursor = this._cursor;
          let newCursor = oldCursor + 1;
          const elements = oldFront._elements;
          const element = elements[oldCursor];
          if (newCursor === QUEUE_MAX_ARRAY_SIZE) {
            newFront = oldFront._next;
            newCursor = 0;
          }
          --this._size;
          this._cursor = newCursor;
          if (oldFront !== newFront) {
            this._front = newFront;
          }
          elements[oldCursor] = void 0;
          return element;
        }
        // The tricky thing about forEach() is that it can be called
        // re-entrantly. The queue may be mutated inside the callback. It is easy to
        // see that push() within the callback has no negative effects since the end
        // of the queue is checked for on every iteration. If shift() is called
        // repeatedly within the callback then the next iteration may return an
        // element that has been removed. In this case the callback will be called
        // with undefined values until we either "catch up" with elements that still
        // exist or reach the back of the queue.
        forEach(callback) {
          let i3 = this._cursor;
          let node = this._front;
          let elements = node._elements;
          while (i3 !== elements.length || node._next !== void 0) {
            if (i3 === elements.length) {
              node = node._next;
              elements = node._elements;
              i3 = 0;
              if (elements.length === 0) {
                break;
              }
            }
            callback(elements[i3]);
            ++i3;
          }
        }
        // Return the element that would be returned if shift() was called now,
        // without modifying the queue.
        peek() {
          const front = this._front;
          const cursor = this._cursor;
          return front._elements[cursor];
        }
      }
      const AbortSteps = Symbol("[[AbortSteps]]");
      const ErrorSteps = Symbol("[[ErrorSteps]]");
      const CancelSteps = Symbol("[[CancelSteps]]");
      const PullSteps = Symbol("[[PullSteps]]");
      const ReleaseSteps = Symbol("[[ReleaseSteps]]");
      function ReadableStreamReaderGenericInitialize(reader, stream2) {
        reader._ownerReadableStream = stream2;
        stream2._reader = reader;
        if (stream2._state === "readable") {
          defaultReaderClosedPromiseInitialize(reader);
        } else if (stream2._state === "closed") {
          defaultReaderClosedPromiseInitializeAsResolved(reader);
        } else {
          defaultReaderClosedPromiseInitializeAsRejected(reader, stream2._storedError);
        }
      }
      __name(ReadableStreamReaderGenericInitialize, "ReadableStreamReaderGenericInitialize");
      function ReadableStreamReaderGenericCancel(reader, reason) {
        const stream2 = reader._ownerReadableStream;
        return ReadableStreamCancel(stream2, reason);
      }
      __name(ReadableStreamReaderGenericCancel, "ReadableStreamReaderGenericCancel");
      function ReadableStreamReaderGenericRelease(reader) {
        const stream2 = reader._ownerReadableStream;
        if (stream2._state === "readable") {
          defaultReaderClosedPromiseReject(reader, new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`));
        } else {
          defaultReaderClosedPromiseResetToRejected(reader, new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`));
        }
        stream2._readableStreamController[ReleaseSteps]();
        stream2._reader = void 0;
        reader._ownerReadableStream = void 0;
      }
      __name(ReadableStreamReaderGenericRelease, "ReadableStreamReaderGenericRelease");
      function readerLockException(name3) {
        return new TypeError("Cannot " + name3 + " a stream using a released reader");
      }
      __name(readerLockException, "readerLockException");
      function defaultReaderClosedPromiseInitialize(reader) {
        reader._closedPromise = newPromise((resolve30, reject) => {
          reader._closedPromise_resolve = resolve30;
          reader._closedPromise_reject = reject;
        });
      }
      __name(defaultReaderClosedPromiseInitialize, "defaultReaderClosedPromiseInitialize");
      function defaultReaderClosedPromiseInitializeAsRejected(reader, reason) {
        defaultReaderClosedPromiseInitialize(reader);
        defaultReaderClosedPromiseReject(reader, reason);
      }
      __name(defaultReaderClosedPromiseInitializeAsRejected, "defaultReaderClosedPromiseInitializeAsRejected");
      function defaultReaderClosedPromiseInitializeAsResolved(reader) {
        defaultReaderClosedPromiseInitialize(reader);
        defaultReaderClosedPromiseResolve(reader);
      }
      __name(defaultReaderClosedPromiseInitializeAsResolved, "defaultReaderClosedPromiseInitializeAsResolved");
      function defaultReaderClosedPromiseReject(reader, reason) {
        if (reader._closedPromise_reject === void 0) {
          return;
        }
        setPromiseIsHandledToTrue(reader._closedPromise);
        reader._closedPromise_reject(reason);
        reader._closedPromise_resolve = void 0;
        reader._closedPromise_reject = void 0;
      }
      __name(defaultReaderClosedPromiseReject, "defaultReaderClosedPromiseReject");
      function defaultReaderClosedPromiseResetToRejected(reader, reason) {
        defaultReaderClosedPromiseInitializeAsRejected(reader, reason);
      }
      __name(defaultReaderClosedPromiseResetToRejected, "defaultReaderClosedPromiseResetToRejected");
      function defaultReaderClosedPromiseResolve(reader) {
        if (reader._closedPromise_resolve === void 0) {
          return;
        }
        reader._closedPromise_resolve(void 0);
        reader._closedPromise_resolve = void 0;
        reader._closedPromise_reject = void 0;
      }
      __name(defaultReaderClosedPromiseResolve, "defaultReaderClosedPromiseResolve");
      const NumberIsFinite = Number.isFinite || function(x3) {
        return typeof x3 === "number" && isFinite(x3);
      };
      const MathTrunc = Math.trunc || function(v2) {
        return v2 < 0 ? Math.ceil(v2) : Math.floor(v2);
      };
      function isDictionary(x3) {
        return typeof x3 === "object" || typeof x3 === "function";
      }
      __name(isDictionary, "isDictionary");
      function assertDictionary(obj, context2) {
        if (obj !== void 0 && !isDictionary(obj)) {
          throw new TypeError(`${context2} is not an object.`);
        }
      }
      __name(assertDictionary, "assertDictionary");
      function assertFunction(x3, context2) {
        if (typeof x3 !== "function") {
          throw new TypeError(`${context2} is not a function.`);
        }
      }
      __name(assertFunction, "assertFunction");
      function isObject4(x3) {
        return typeof x3 === "object" && x3 !== null || typeof x3 === "function";
      }
      __name(isObject4, "isObject");
      function assertObject(x3, context2) {
        if (!isObject4(x3)) {
          throw new TypeError(`${context2} is not an object.`);
        }
      }
      __name(assertObject, "assertObject");
      function assertRequiredArgument(x3, position, context2) {
        if (x3 === void 0) {
          throw new TypeError(`Parameter ${position} is required in '${context2}'.`);
        }
      }
      __name(assertRequiredArgument, "assertRequiredArgument");
      function assertRequiredField(x3, field, context2) {
        if (x3 === void 0) {
          throw new TypeError(`${field} is required in '${context2}'.`);
        }
      }
      __name(assertRequiredField, "assertRequiredField");
      function convertUnrestrictedDouble(value) {
        return Number(value);
      }
      __name(convertUnrestrictedDouble, "convertUnrestrictedDouble");
      function censorNegativeZero(x3) {
        return x3 === 0 ? 0 : x3;
      }
      __name(censorNegativeZero, "censorNegativeZero");
      function integerPart(x3) {
        return censorNegativeZero(MathTrunc(x3));
      }
      __name(integerPart, "integerPart");
      function convertUnsignedLongLongWithEnforceRange(value, context2) {
        const lowerBound = 0;
        const upperBound = Number.MAX_SAFE_INTEGER;
        let x3 = Number(value);
        x3 = censorNegativeZero(x3);
        if (!NumberIsFinite(x3)) {
          throw new TypeError(`${context2} is not a finite number`);
        }
        x3 = integerPart(x3);
        if (x3 < lowerBound || x3 > upperBound) {
          throw new TypeError(`${context2} is outside the accepted range of ${lowerBound} to ${upperBound}, inclusive`);
        }
        if (!NumberIsFinite(x3) || x3 === 0) {
          return 0;
        }
        return x3;
      }
      __name(convertUnsignedLongLongWithEnforceRange, "convertUnsignedLongLongWithEnforceRange");
      function assertReadableStream(x3, context2) {
        if (!IsReadableStream(x3)) {
          throw new TypeError(`${context2} is not a ReadableStream.`);
        }
      }
      __name(assertReadableStream, "assertReadableStream");
      function AcquireReadableStreamDefaultReader(stream2) {
        return new ReadableStreamDefaultReader2(stream2);
      }
      __name(AcquireReadableStreamDefaultReader, "AcquireReadableStreamDefaultReader");
      function ReadableStreamAddReadRequest(stream2, readRequest) {
        stream2._reader._readRequests.push(readRequest);
      }
      __name(ReadableStreamAddReadRequest, "ReadableStreamAddReadRequest");
      function ReadableStreamFulfillReadRequest(stream2, chunk, done) {
        const reader = stream2._reader;
        const readRequest = reader._readRequests.shift();
        if (done) {
          readRequest._closeSteps();
        } else {
          readRequest._chunkSteps(chunk);
        }
      }
      __name(ReadableStreamFulfillReadRequest, "ReadableStreamFulfillReadRequest");
      function ReadableStreamGetNumReadRequests(stream2) {
        return stream2._reader._readRequests.length;
      }
      __name(ReadableStreamGetNumReadRequests, "ReadableStreamGetNumReadRequests");
      function ReadableStreamHasDefaultReader(stream2) {
        const reader = stream2._reader;
        if (reader === void 0) {
          return false;
        }
        if (!IsReadableStreamDefaultReader(reader)) {
          return false;
        }
        return true;
      }
      __name(ReadableStreamHasDefaultReader, "ReadableStreamHasDefaultReader");
      class ReadableStreamDefaultReader2 {
        static {
          __name(this, "ReadableStreamDefaultReader");
        }
        constructor(stream2) {
          assertRequiredArgument(stream2, 1, "ReadableStreamDefaultReader");
          assertReadableStream(stream2, "First parameter");
          if (IsReadableStreamLocked(stream2)) {
            throw new TypeError("This stream has already been locked for exclusive reading by another reader");
          }
          ReadableStreamReaderGenericInitialize(this, stream2);
          this._readRequests = new SimpleQueue();
        }
        /**
         * Returns a promise that will be fulfilled when the stream becomes closed,
         * or rejected if the stream ever errors or the reader's lock is released before the stream finishes closing.
         */
        get closed() {
          if (!IsReadableStreamDefaultReader(this)) {
            return promiseRejectedWith(defaultReaderBrandCheckException("closed"));
          }
          return this._closedPromise;
        }
        /**
         * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}.
         */
        cancel(reason = void 0) {
          if (!IsReadableStreamDefaultReader(this)) {
            return promiseRejectedWith(defaultReaderBrandCheckException("cancel"));
          }
          if (this._ownerReadableStream === void 0) {
            return promiseRejectedWith(readerLockException("cancel"));
          }
          return ReadableStreamReaderGenericCancel(this, reason);
        }
        /**
         * Returns a promise that allows access to the next chunk from the stream's internal queue, if available.
         *
         * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source.
         */
        read() {
          if (!IsReadableStreamDefaultReader(this)) {
            return promiseRejectedWith(defaultReaderBrandCheckException("read"));
          }
          if (this._ownerReadableStream === void 0) {
            return promiseRejectedWith(readerLockException("read from"));
          }
          let resolvePromise;
          let rejectPromise;
          const promise = newPromise((resolve30, reject) => {
            resolvePromise = resolve30;
            rejectPromise = reject;
          });
          const readRequest = {
            _chunkSteps: /* @__PURE__ */ __name((chunk) => resolvePromise({ value: chunk, done: false }), "_chunkSteps"),
            _closeSteps: /* @__PURE__ */ __name(() => resolvePromise({ value: void 0, done: true }), "_closeSteps"),
            _errorSteps: /* @__PURE__ */ __name((e4) => rejectPromise(e4), "_errorSteps")
          };
          ReadableStreamDefaultReaderRead(this, readRequest);
          return promise;
        }
        /**
         * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active.
         * If the associated stream is errored when the lock is released, the reader will appear errored in the same way
         * from now on; otherwise, the reader will appear closed.
         *
         * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by
         * the reader's {@link ReadableStreamDefaultReader.read | read()} method has not yet been settled. Attempting to
         * do so will throw a `TypeError` and leave the reader locked to the stream.
         */
        releaseLock() {
          if (!IsReadableStreamDefaultReader(this)) {
            throw defaultReaderBrandCheckException("releaseLock");
          }
          if (this._ownerReadableStream === void 0) {
            return;
          }
          ReadableStreamDefaultReaderRelease(this);
        }
      }
      Object.defineProperties(ReadableStreamDefaultReader2.prototype, {
        cancel: { enumerable: true },
        read: { enumerable: true },
        releaseLock: { enumerable: true },
        closed: { enumerable: true }
      });
      setFunctionName(ReadableStreamDefaultReader2.prototype.cancel, "cancel");
      setFunctionName(ReadableStreamDefaultReader2.prototype.read, "read");
      setFunctionName(ReadableStreamDefaultReader2.prototype.releaseLock, "releaseLock");
      if (typeof Symbol.toStringTag === "symbol") {
        Object.defineProperty(ReadableStreamDefaultReader2.prototype, Symbol.toStringTag, {
          value: "ReadableStreamDefaultReader",
          configurable: true
        });
      }
      function IsReadableStreamDefaultReader(x3) {
        if (!typeIsObject(x3)) {
          return false;
        }
        if (!Object.prototype.hasOwnProperty.call(x3, "_readRequests")) {
          return false;
        }
        return x3 instanceof ReadableStreamDefaultReader2;
      }
      __name(IsReadableStreamDefaultReader, "IsReadableStreamDefaultReader");
      function ReadableStreamDefaultReaderRead(reader, readRequest) {
        const stream2 = reader._ownerReadableStream;
        stream2._disturbed = true;
        if (stream2._state === "closed") {
          readRequest._closeSteps();
        } else if (stream2._state === "errored") {
          readRequest._errorSteps(stream2._storedError);
        } else {
          stream2._readableStreamController[PullSteps](readRequest);
        }
      }
      __name(ReadableStreamDefaultReaderRead, "ReadableStreamDefaultReaderRead");
      function ReadableStreamDefaultReaderRelease(reader) {
        ReadableStreamReaderGenericRelease(reader);
        const e4 = new TypeError("Reader was released");
        ReadableStreamDefaultReaderErrorReadRequests(reader, e4);
      }
      __name(ReadableStreamDefaultReaderRelease, "ReadableStreamDefaultReaderRelease");
      function ReadableStreamDefaultReaderErrorReadRequests(reader, e4) {
        const readRequests = reader._readRequests;
        reader._readRequests = new SimpleQueue();
        readRequests.forEach((readRequest) => {
          readRequest._errorSteps(e4);
        });
      }
      __name(ReadableStreamDefaultReaderErrorReadRequests, "ReadableStreamDefaultReaderErrorReadRequests");
      function defaultReaderBrandCheckException(name3) {
        return new TypeError(`ReadableStreamDefaultReader.prototype.${name3} can only be used on a ReadableStreamDefaultReader`);
      }
      __name(defaultReaderBrandCheckException, "defaultReaderBrandCheckException");
      const AsyncIteratorPrototype = Object.getPrototypeOf(Object.getPrototypeOf(async function* () {
      }).prototype);
      class ReadableStreamAsyncIteratorImpl {
        static {
          __name(this, "ReadableStreamAsyncIteratorImpl");
        }
        constructor(reader, preventCancel) {
          this._ongoingPromise = void 0;
          this._isFinished = false;
          this._reader = reader;
          this._preventCancel = preventCancel;
        }
        next() {
          const nextSteps = /* @__PURE__ */ __name(() => this._nextSteps(), "nextSteps");
          this._ongoingPromise = this._ongoingPromise ? transformPromiseWith(this._ongoingPromise, nextSteps, nextSteps) : nextSteps();
          return this._ongoingPromise;
        }
        return(value) {
          const returnSteps = /* @__PURE__ */ __name(() => this._returnSteps(value), "returnSteps");
          return this._ongoingPromise ? transformPromiseWith(this._ongoingPromise, returnSteps, returnSteps) : returnSteps();
        }
        _nextSteps() {
          if (this._isFinished) {
            return Promise.resolve({ value: void 0, done: true });
          }
          const reader = this._reader;
          let resolvePromise;
          let rejectPromise;
          const promise = newPromise((resolve30, reject) => {
            resolvePromise = resolve30;
            rejectPromise = reject;
          });
          const readRequest = {
            _chunkSteps: /* @__PURE__ */ __name((chunk) => {
              this._ongoingPromise = void 0;
              _queueMicrotask(() => resolvePromise({ value: chunk, done: false }));
            }, "_chunkSteps"),
            _closeSteps: /* @__PURE__ */ __name(() => {
              this._ongoingPromise = void 0;
              this._isFinished = true;
              ReadableStreamReaderGenericRelease(reader);
              resolvePromise({ value: void 0, done: true });
            }, "_closeSteps"),
            _errorSteps: /* @__PURE__ */ __name((reason) => {
              this._ongoingPromise = void 0;
              this._isFinished = true;
              ReadableStreamReaderGenericRelease(reader);
              rejectPromise(reason);
            }, "_errorSteps")
          };
          ReadableStreamDefaultReaderRead(reader, readRequest);
          return promise;
        }
        _returnSteps(value) {
          if (this._isFinished) {
            return Promise.resolve({ value, done: true });
          }
          this._isFinished = true;
          const reader = this._reader;
          if (!this._preventCancel) {
            const result = ReadableStreamReaderGenericCancel(reader, value);
            ReadableStreamReaderGenericRelease(reader);
            return transformPromiseWith(result, () => ({ value, done: true }));
          }
          ReadableStreamReaderGenericRelease(reader);
          return promiseResolvedWith({ value, done: true });
        }
      }
      const ReadableStreamAsyncIteratorPrototype = {
        next() {
          if (!IsReadableStreamAsyncIterator(this)) {
            return promiseRejectedWith(streamAsyncIteratorBrandCheckException("next"));
          }
          return this._asyncIteratorImpl.next();
        },
        return(value) {
          if (!IsReadableStreamAsyncIterator(this)) {
            return promiseRejectedWith(streamAsyncIteratorBrandCheckException("return"));
          }
          return this._asyncIteratorImpl.return(value);
        }
      };
      Object.setPrototypeOf(ReadableStreamAsyncIteratorPrototype, AsyncIteratorPrototype);
      function AcquireReadableStreamAsyncIterator(stream2, preventCancel) {
        const reader = AcquireReadableStreamDefaultReader(stream2);
        const impl = new ReadableStreamAsyncIteratorImpl(reader, preventCancel);
        const iterator = Object.create(ReadableStreamAsyncIteratorPrototype);
        iterator._asyncIteratorImpl = impl;
        return iterator;
      }
      __name(AcquireReadableStreamAsyncIterator, "AcquireReadableStreamAsyncIterator");
      function IsReadableStreamAsyncIterator(x3) {
        if (!typeIsObject(x3)) {
          return false;
        }
        if (!Object.prototype.hasOwnProperty.call(x3, "_asyncIteratorImpl")) {
          return false;
        }
        try {
          return x3._asyncIteratorImpl instanceof ReadableStreamAsyncIteratorImpl;
        } catch (_a8) {
          return false;
        }
      }
      __name(IsReadableStreamAsyncIterator, "IsReadableStreamAsyncIterator");
      function streamAsyncIteratorBrandCheckException(name3) {
        return new TypeError(`ReadableStreamAsyncIterator.${name3} can only be used on a ReadableSteamAsyncIterator`);
      }
      __name(streamAsyncIteratorBrandCheckException, "streamAsyncIteratorBrandCheckException");
      const NumberIsNaN = Number.isNaN || function(x3) {
        return x3 !== x3;
      };
      var _a7, _b2, _c2;
      function CreateArrayFromList(elements) {
        return elements.slice();
      }
      __name(CreateArrayFromList, "CreateArrayFromList");
      function CopyDataBlockBytes(dest, destOffset, src, srcOffset, n3) {
        new Uint8Array(dest).set(new Uint8Array(src, srcOffset, n3), destOffset);
      }
      __name(CopyDataBlockBytes, "CopyDataBlockBytes");
      let TransferArrayBuffer = /* @__PURE__ */ __name((O2) => {
        if (typeof O2.transfer === "function") {
          TransferArrayBuffer = /* @__PURE__ */ __name((buffer) => buffer.transfer(), "TransferArrayBuffer");
        } else if (typeof structuredClone === "function") {
          TransferArrayBuffer = /* @__PURE__ */ __name((buffer) => structuredClone(buffer, { transfer: [buffer] }), "TransferArrayBuffer");
        } else {
          TransferArrayBuffer = /* @__PURE__ */ __name((buffer) => buffer, "TransferArrayBuffer");
        }
        return TransferArrayBuffer(O2);
      }, "TransferArrayBuffer");
      let IsDetachedBuffer = /* @__PURE__ */ __name((O2) => {
        if (typeof O2.detached === "boolean") {
          IsDetachedBuffer = /* @__PURE__ */ __name((buffer) => buffer.detached, "IsDetachedBuffer");
        } else {
          IsDetachedBuffer = /* @__PURE__ */ __name((buffer) => buffer.byteLength === 0, "IsDetachedBuffer");
        }
        return IsDetachedBuffer(O2);
      }, "IsDetachedBuffer");
      function ArrayBufferSlice(buffer, begin, end) {
        if (buffer.slice) {
          return buffer.slice(begin, end);
        }
        const length = end - begin;
        const slice = new ArrayBuffer(length);
        CopyDataBlockBytes(slice, 0, buffer, begin, length);
        return slice;
      }
      __name(ArrayBufferSlice, "ArrayBufferSlice");
      function GetMethod(receiver, prop) {
        const func = receiver[prop];
        if (func === void 0 || func === null) {
          return void 0;
        }
        if (typeof func !== "function") {
          throw new TypeError(`${String(prop)} is not a function`);
        }
        return func;
      }
      __name(GetMethod, "GetMethod");
      function CreateAsyncFromSyncIterator(syncIteratorRecord) {
        const syncIterable = {
          [Symbol.iterator]: () => syncIteratorRecord.iterator
        };
        const asyncIterator = async function* () {
          return yield* syncIterable;
        }();
        const nextMethod = asyncIterator.next;
        return { iterator: asyncIterator, nextMethod, done: false };
      }
      __name(CreateAsyncFromSyncIterator, "CreateAsyncFromSyncIterator");
      const SymbolAsyncIterator = (_c2 = (_a7 = Symbol.asyncIterator) !== null && _a7 !== void 0 ? _a7 : (_b2 = Symbol.for) === null || _b2 === void 0 ? void 0 : _b2.call(Symbol, "Symbol.asyncIterator")) !== null && _c2 !== void 0 ? _c2 : "@@asyncIterator";
      function GetIterator(obj, hint = "sync", method) {
        if (method === void 0) {
          if (hint === "async") {
            method = GetMethod(obj, SymbolAsyncIterator);
            if (method === void 0) {
              const syncMethod = GetMethod(obj, Symbol.iterator);
              const syncIteratorRecord = GetIterator(obj, "sync", syncMethod);
              return CreateAsyncFromSyncIterator(syncIteratorRecord);
            }
          } else {
            method = GetMethod(obj, Symbol.iterator);
          }
        }
        if (method === void 0) {
          throw new TypeError("The object is not iterable");
        }
        const iterator = reflectCall(method, obj, []);
        if (!typeIsObject(iterator)) {
          throw new TypeError("The iterator method must return an object");
        }
        const nextMethod = iterator.next;
        return { iterator, nextMethod, done: false };
      }
      __name(GetIterator, "GetIterator");
      function IteratorNext(iteratorRecord) {
        const result = reflectCall(iteratorRecord.nextMethod, iteratorRecord.iterator, []);
        if (!typeIsObject(result)) {
          throw new TypeError("The iterator.next() method must return an object");
        }
        return result;
      }
      __name(IteratorNext, "IteratorNext");
      function IteratorComplete(iterResult) {
        return Boolean(iterResult.done);
      }
      __name(IteratorComplete, "IteratorComplete");
      function IteratorValue(iterResult) {
        return iterResult.value;
      }
      __name(IteratorValue, "IteratorValue");
      function IsNonNegativeNumber(v2) {
        if (typeof v2 !== "number") {
          return false;
        }
        if (NumberIsNaN(v2)) {
          return false;
        }
        if (v2 < 0) {
          return false;
        }
        return true;
      }
      __name(IsNonNegativeNumber, "IsNonNegativeNumber");
      function CloneAsUint8Array(O2) {
        const buffer = ArrayBufferSlice(O2.buffer, O2.byteOffset, O2.byteOffset + O2.byteLength);
        return new Uint8Array(buffer);
      }
      __name(CloneAsUint8Array, "CloneAsUint8Array");
      function DequeueValue(container) {
        const pair = container._queue.shift();
        container._queueTotalSize -= pair.size;
        if (container._queueTotalSize < 0) {
          container._queueTotalSize = 0;
        }
        return pair.value;
      }
      __name(DequeueValue, "DequeueValue");
      function EnqueueValueWithSize(container, value, size) {
        if (!IsNonNegativeNumber(size) || size === Infinity) {
          throw new RangeError("Size must be a finite, non-NaN, non-negative number.");
        }
        container._queue.push({ value, size });
        container._queueTotalSize += size;
      }
      __name(EnqueueValueWithSize, "EnqueueValueWithSize");
      function PeekQueueValue(container) {
        const pair = container._queue.peek();
        return pair.value;
      }
      __name(PeekQueueValue, "PeekQueueValue");
      function ResetQueue(container) {
        container._queue = new SimpleQueue();
        container._queueTotalSize = 0;
      }
      __name(ResetQueue, "ResetQueue");
      function isDataViewConstructor(ctor) {
        return ctor === DataView;
      }
      __name(isDataViewConstructor, "isDataViewConstructor");
      function isDataView(view) {
        return isDataViewConstructor(view.constructor);
      }
      __name(isDataView, "isDataView");
      function arrayBufferViewElementSize(ctor) {
        if (isDataViewConstructor(ctor)) {
          return 1;
        }
        return ctor.BYTES_PER_ELEMENT;
      }
      __name(arrayBufferViewElementSize, "arrayBufferViewElementSize");
      class ReadableStreamBYOBRequest2 {
        static {
          __name(this, "ReadableStreamBYOBRequest");
        }
        constructor() {
          throw new TypeError("Illegal constructor");
        }
        /**
         * Returns the view for writing in to, or `null` if the BYOB request has already been responded to.
         */
        get view() {
          if (!IsReadableStreamBYOBRequest(this)) {
            throw byobRequestBrandCheckException("view");
          }
          return this._view;
        }
        respond(bytesWritten) {
          if (!IsReadableStreamBYOBRequest(this)) {
            throw byobRequestBrandCheckException("respond");
          }
          assertRequiredArgument(bytesWritten, 1, "respond");
          bytesWritten = convertUnsignedLongLongWithEnforceRange(bytesWritten, "First parameter");
          if (this._associatedReadableByteStreamController === void 0) {
            throw new TypeError("This BYOB request has been invalidated");
          }
          if (IsDetachedBuffer(this._view.buffer)) {
            throw new TypeError(`The BYOB request's buffer has been detached and so cannot be used as a response`);
          }
          ReadableByteStreamControllerRespond(this._associatedReadableByteStreamController, bytesWritten);
        }
        respondWithNewView(view) {
          if (!IsReadableStreamBYOBRequest(this)) {
            throw byobRequestBrandCheckException("respondWithNewView");
          }
          assertRequiredArgument(view, 1, "respondWithNewView");
          if (!ArrayBuffer.isView(view)) {
            throw new TypeError("You can only respond with array buffer views");
          }
          if (this._associatedReadableByteStreamController === void 0) {
            throw new TypeError("This BYOB request has been invalidated");
          }
          if (IsDetachedBuffer(view.buffer)) {
            throw new TypeError("The given view's buffer has been detached and so cannot be used as a response");
          }
          ReadableByteStreamControllerRespondWithNewView(this._associatedReadableByteStreamController, view);
        }
      }
      Object.defineProperties(ReadableStreamBYOBRequest2.prototype, {
        respond: { enumerable: true },
        respondWithNewView: { enumerable: true },
        view: { enumerable: true }
      });
      setFunctionName(ReadableStreamBYOBRequest2.prototype.respond, "respond");
      setFunctionName(ReadableStreamBYOBRequest2.prototype.respondWithNewView, "respondWithNewView");
      if (typeof Symbol.toStringTag === "symbol") {
        Object.defineProperty(ReadableStreamBYOBRequest2.prototype, Symbol.toStringTag, {
          value: "ReadableStreamBYOBRequest",
          configurable: true
        });
      }
      class ReadableByteStreamController2 {
        static {
          __name(this, "ReadableByteStreamController");
        }
        constructor() {
          throw new TypeError("Illegal constructor");
        }
        /**
         * Returns the current BYOB pull request, or `null` if there isn't one.
         */
        get byobRequest() {
          if (!IsReadableByteStreamController(this)) {
            throw byteStreamControllerBrandCheckException("byobRequest");
          }
          return ReadableByteStreamControllerGetBYOBRequest(this);
        }
        /**
         * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is
         * over-full. An underlying byte source ought to use this information to determine when and how to apply backpressure.
         */
        get desiredSize() {
          if (!IsReadableByteStreamController(this)) {
            throw byteStreamControllerBrandCheckException("desiredSize");
          }
          return ReadableByteStreamControllerGetDesiredSize(this);
        }
        /**
         * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from
         * the stream, but once those are read, the stream will become closed.
         */
        close() {
          if (!IsReadableByteStreamController(this)) {
            throw byteStreamControllerBrandCheckException("close");
          }
          if (this._closeRequested) {
            throw new TypeError("The stream has already been closed; do not close it again!");
          }
          const state = this._controlledReadableByteStream._state;
          if (state !== "readable") {
            throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be closed`);
          }
          ReadableByteStreamControllerClose(this);
        }
        enqueue(chunk) {
          if (!IsReadableByteStreamController(this)) {
            throw byteStreamControllerBrandCheckException("enqueue");
          }
          assertRequiredArgument(chunk, 1, "enqueue");
          if (!ArrayBuffer.isView(chunk)) {
            throw new TypeError("chunk must be an array buffer view");
          }
          if (chunk.byteLength === 0) {
            throw new TypeError("chunk must have non-zero byteLength");
          }
          if (chunk.buffer.byteLength === 0) {
            throw new TypeError(`chunk's buffer must have non-zero byteLength`);
          }
          if (this._closeRequested) {
            throw new TypeError("stream is closed or draining");
          }
          const state = this._controlledReadableByteStream._state;
          if (state !== "readable") {
            throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be enqueued to`);
          }
          ReadableByteStreamControllerEnqueue(this, chunk);
        }
        /**
         * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`.
         */
        error(e4 = void 0) {
          if (!IsReadableByteStreamController(this)) {
            throw byteStreamControllerBrandCheckException("error");
          }
          ReadableByteStreamControllerError(this, e4);
        }
        /** @internal */
        [CancelSteps](reason) {
          ReadableByteStreamControllerClearPendingPullIntos(this);
          ResetQueue(this);
          const result = this._cancelAlgorithm(reason);
          ReadableByteStreamControllerClearAlgorithms(this);
          return result;
        }
        /** @internal */
        [PullSteps](readRequest) {
          const stream2 = this._controlledReadableByteStream;
          if (this._queueTotalSize > 0) {
            ReadableByteStreamControllerFillReadRequestFromQueue(this, readRequest);
            return;
          }
          const autoAllocateChunkSize = this._autoAllocateChunkSize;
          if (autoAllocateChunkSize !== void 0) {
            let buffer;
            try {
              buffer = new ArrayBuffer(autoAllocateChunkSize);
            } catch (bufferE) {
              readRequest._errorSteps(bufferE);
              return;
            }
            const pullIntoDescriptor = {
              buffer,
              bufferByteLength: autoAllocateChunkSize,
              byteOffset: 0,
              byteLength: autoAllocateChunkSize,
              bytesFilled: 0,
              minimumFill: 1,
              elementSize: 1,
              viewConstructor: Uint8Array,
              readerType: "default"
            };
            this._pendingPullIntos.push(pullIntoDescriptor);
          }
          ReadableStreamAddReadRequest(stream2, readRequest);
          ReadableByteStreamControllerCallPullIfNeeded(this);
        }
        /** @internal */
        [ReleaseSteps]() {
          if (this._pendingPullIntos.length > 0) {
            const firstPullInto = this._pendingPullIntos.peek();
            firstPullInto.readerType = "none";
            this._pendingPullIntos = new SimpleQueue();
            this._pendingPullIntos.push(firstPullInto);
          }
        }
      }
      Object.defineProperties(ReadableByteStreamController2.prototype, {
        close: { enumerable: true },
        enqueue: { enumerable: true },
        error: { enumerable: true },
        byobRequest: { enumerable: true },
        desiredSize: { enumerable: true }
      });
      setFunctionName(ReadableByteStreamController2.prototype.close, "close");
      setFunctionName(ReadableByteStreamController2.prototype.enqueue, "enqueue");
      setFunctionName(ReadableByteStreamController2.prototype.error, "error");
      if (typeof Symbol.toStringTag === "symbol") {
        Object.defineProperty(ReadableByteStreamController2.prototype, Symbol.toStringTag, {
          value: "ReadableByteStreamController",
          configurable: true
        });
      }
      function IsReadableByteStreamController(x3) {
        if (!typeIsObject(x3)) {
          return false;
        }
        if (!Object.prototype.hasOwnProperty.call(x3, "_controlledReadableByteStream")) {
          return false;
        }
        return x3 instanceof ReadableByteStreamController2;
      }
      __name(IsReadableByteStreamController, "IsReadableByteStreamController");
      function IsReadableStreamBYOBRequest(x3) {
        if (!typeIsObject(x3)) {
          return false;
        }
        if (!Object.prototype.hasOwnProperty.call(x3, "_associatedReadableByteStreamController")) {
          return false;
        }
        return x3 instanceof ReadableStreamBYOBRequest2;
      }
      __name(IsReadableStreamBYOBRequest, "IsReadableStreamBYOBRequest");
      function ReadableByteStreamControllerCallPullIfNeeded(controller) {
        const shouldPull = ReadableByteStreamControllerShouldCallPull(controller);
        if (!shouldPull) {
          return;
        }
        if (controller._pulling) {
          controller._pullAgain = true;
          return;
        }
        controller._pulling = true;
        const pullPromise = controller._pullAlgorithm();
        uponPromise(pullPromise, () => {
          controller._pulling = false;
          if (controller._pullAgain) {
            controller._pullAgain = false;
            ReadableByteStreamControllerCallPullIfNeeded(controller);
          }
          return null;
        }, (e4) => {
          ReadableByteStreamControllerError(controller, e4);
          return null;
        });
      }
      __name(ReadableByteStreamControllerCallPullIfNeeded, "ReadableByteStreamControllerCallPullIfNeeded");
      function ReadableByteStreamControllerClearPendingPullIntos(controller) {
        ReadableByteStreamControllerInvalidateBYOBRequest(controller);
        controller._pendingPullIntos = new SimpleQueue();
      }
      __name(ReadableByteStreamControllerClearPendingPullIntos, "ReadableByteStreamControllerClearPendingPullIntos");
      function ReadableByteStreamControllerCommitPullIntoDescriptor(stream2, pullIntoDescriptor) {
        let done = false;
        if (stream2._state === "closed") {
          done = true;
        }
        const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor);
        if (pullIntoDescriptor.readerType === "default") {
          ReadableStreamFulfillReadRequest(stream2, filledView, done);
        } else {
          ReadableStreamFulfillReadIntoRequest(stream2, filledView, done);
        }
      }
      __name(ReadableByteStreamControllerCommitPullIntoDescriptor, "ReadableByteStreamControllerCommitPullIntoDescriptor");
      function ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor) {
        const bytesFilled = pullIntoDescriptor.bytesFilled;
        const elementSize = pullIntoDescriptor.elementSize;
        return new pullIntoDescriptor.viewConstructor(pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, bytesFilled / elementSize);
      }
      __name(ReadableByteStreamControllerConvertPullIntoDescriptor, "ReadableByteStreamControllerConvertPullIntoDescriptor");
      function ReadableByteStreamControllerEnqueueChunkToQueue(controller, buffer, byteOffset, byteLength) {
        controller._queue.push({ buffer, byteOffset, byteLength });
        controller._queueTotalSize += byteLength;
      }
      __name(ReadableByteStreamControllerEnqueueChunkToQueue, "ReadableByteStreamControllerEnqueueChunkToQueue");
      function ReadableByteStreamControllerEnqueueClonedChunkToQueue(controller, buffer, byteOffset, byteLength) {
        let clonedChunk;
        try {
          clonedChunk = ArrayBufferSlice(buffer, byteOffset, byteOffset + byteLength);
        } catch (cloneE) {
          ReadableByteStreamControllerError(controller, cloneE);
          throw cloneE;
        }
        ReadableByteStreamControllerEnqueueChunkToQueue(controller, clonedChunk, 0, byteLength);
      }
      __name(ReadableByteStreamControllerEnqueueClonedChunkToQueue, "ReadableByteStreamControllerEnqueueClonedChunkToQueue");
      function ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, firstDescriptor) {
        if (firstDescriptor.bytesFilled > 0) {
          ReadableByteStreamControllerEnqueueClonedChunkToQueue(controller, firstDescriptor.buffer, firstDescriptor.byteOffset, firstDescriptor.bytesFilled);
        }
        ReadableByteStreamControllerShiftPendingPullInto(controller);
      }
      __name(ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue, "ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue");
      function ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor) {
        const maxBytesToCopy = Math.min(controller._queueTotalSize, pullIntoDescriptor.byteLength - pullIntoDescriptor.bytesFilled);
        const maxBytesFilled = pullIntoDescriptor.bytesFilled + maxBytesToCopy;
        let totalBytesToCopyRemaining = maxBytesToCopy;
        let ready = false;
        const remainderBytes = maxBytesFilled % pullIntoDescriptor.elementSize;
        const maxAlignedBytes = maxBytesFilled - remainderBytes;
        if (maxAlignedBytes >= pullIntoDescriptor.minimumFill) {
          totalBytesToCopyRemaining = maxAlignedBytes - pullIntoDescriptor.bytesFilled;
          ready = true;
        }
        const queue = controller._queue;
        while (totalBytesToCopyRemaining > 0) {
          const headOfQueue = queue.peek();
          const bytesToCopy = Math.min(totalBytesToCopyRemaining, headOfQueue.byteLength);
          const destStart = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled;
          CopyDataBlockBytes(pullIntoDescriptor.buffer, destStart, headOfQueue.buffer, headOfQueue.byteOffset, bytesToCopy);
          if (headOfQueue.byteLength === bytesToCopy) {
            queue.shift();
          } else {
            headOfQueue.byteOffset += bytesToCopy;
            headOfQueue.byteLength -= bytesToCopy;
          }
          controller._queueTotalSize -= bytesToCopy;
          ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesToCopy, pullIntoDescriptor);
          totalBytesToCopyRemaining -= bytesToCopy;
        }
        return ready;
      }
      __name(ReadableByteStreamControllerFillPullIntoDescriptorFromQueue, "ReadableByteStreamControllerFillPullIntoDescriptorFromQueue");
      function ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, size, pullIntoDescriptor) {
        pullIntoDescriptor.bytesFilled += size;
      }
      __name(ReadableByteStreamControllerFillHeadPullIntoDescriptor, "ReadableByteStreamControllerFillHeadPullIntoDescriptor");
      function ReadableByteStreamControllerHandleQueueDrain(controller) {
        if (controller._queueTotalSize === 0 && controller._closeRequested) {
          ReadableByteStreamControllerClearAlgorithms(controller);
          ReadableStreamClose(controller._controlledReadableByteStream);
        } else {
          ReadableByteStreamControllerCallPullIfNeeded(controller);
        }
      }
      __name(ReadableByteStreamControllerHandleQueueDrain, "ReadableByteStreamControllerHandleQueueDrain");
      function ReadableByteStreamControllerInvalidateBYOBRequest(controller) {
        if (controller._byobRequest === null) {
          return;
        }
        controller._byobRequest._associatedReadableByteStreamController = void 0;
        controller._byobRequest._view = null;
        controller._byobRequest = null;
      }
      __name(ReadableByteStreamControllerInvalidateBYOBRequest, "ReadableByteStreamControllerInvalidateBYOBRequest");
      function ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller) {
        while (controller._pendingPullIntos.length > 0) {
          if (controller._queueTotalSize === 0) {
            return;
          }
          const pullIntoDescriptor = controller._pendingPullIntos.peek();
          if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) {
            ReadableByteStreamControllerShiftPendingPullInto(controller);
            ReadableByteStreamControllerCommitPullIntoDescriptor(controller._controlledReadableByteStream, pullIntoDescriptor);
          }
        }
      }
      __name(ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue, "ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue");
      function ReadableByteStreamControllerProcessReadRequestsUsingQueue(controller) {
        const reader = controller._controlledReadableByteStream._reader;
        while (reader._readRequests.length > 0) {
          if (controller._queueTotalSize === 0) {
            return;
          }
          const readRequest = reader._readRequests.shift();
          ReadableByteStreamControllerFillReadRequestFromQueue(controller, readRequest);
        }
      }
      __name(ReadableByteStreamControllerProcessReadRequestsUsingQueue, "ReadableByteStreamControllerProcessReadRequestsUsingQueue");
      function ReadableByteStreamControllerPullInto(controller, view, min, readIntoRequest) {
        const stream2 = controller._controlledReadableByteStream;
        const ctor = view.constructor;
        const elementSize = arrayBufferViewElementSize(ctor);
        const { byteOffset, byteLength } = view;
        const minimumFill = min * elementSize;
        let buffer;
        try {
          buffer = TransferArrayBuffer(view.buffer);
        } catch (e4) {
          readIntoRequest._errorSteps(e4);
          return;
        }
        const pullIntoDescriptor = {
          buffer,
          bufferByteLength: buffer.byteLength,
          byteOffset,
          byteLength,
          bytesFilled: 0,
          minimumFill,
          elementSize,
          viewConstructor: ctor,
          readerType: "byob"
        };
        if (controller._pendingPullIntos.length > 0) {
          controller._pendingPullIntos.push(pullIntoDescriptor);
          ReadableStreamAddReadIntoRequest(stream2, readIntoRequest);
          return;
        }
        if (stream2._state === "closed") {
          const emptyView = new ctor(pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, 0);
          readIntoRequest._closeSteps(emptyView);
          return;
        }
        if (controller._queueTotalSize > 0) {
          if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) {
            const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor);
            ReadableByteStreamControllerHandleQueueDrain(controller);
            readIntoRequest._chunkSteps(filledView);
            return;
          }
          if (controller._closeRequested) {
            const e4 = new TypeError("Insufficient bytes to fill elements in the given buffer");
            ReadableByteStreamControllerError(controller, e4);
            readIntoRequest._errorSteps(e4);
            return;
          }
        }
        controller._pendingPullIntos.push(pullIntoDescriptor);
        ReadableStreamAddReadIntoRequest(stream2, readIntoRequest);
        ReadableByteStreamControllerCallPullIfNeeded(controller);
      }
      __name(ReadableByteStreamControllerPullInto, "ReadableByteStreamControllerPullInto");
      function ReadableByteStreamControllerRespondInClosedState(controller, firstDescriptor) {
        if (firstDescriptor.readerType === "none") {
          ReadableByteStreamControllerShiftPendingPullInto(controller);
        }
        const stream2 = controller._controlledReadableByteStream;
        if (ReadableStreamHasBYOBReader(stream2)) {
          while (ReadableStreamGetNumReadIntoRequests(stream2) > 0) {
            const pullIntoDescriptor = ReadableByteStreamControllerShiftPendingPullInto(controller);
            ReadableByteStreamControllerCommitPullIntoDescriptor(stream2, pullIntoDescriptor);
          }
        }
      }
      __name(ReadableByteStreamControllerRespondInClosedState, "ReadableByteStreamControllerRespondInClosedState");
      function ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, pullIntoDescriptor) {
        ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesWritten, pullIntoDescriptor);
        if (pullIntoDescriptor.readerType === "none") {
          ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, pullIntoDescriptor);
          ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller);
          return;
        }
        if (pullIntoDescriptor.bytesFilled < pullIntoDescriptor.minimumFill) {
          return;
        }
        ReadableByteStreamControllerShiftPendingPullInto(controller);
        const remainderSize = pullIntoDescriptor.bytesFilled % pullIntoDescriptor.elementSize;
        if (remainderSize > 0) {
          const end = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled;
          ReadableByteStreamControllerEnqueueClonedChunkToQueue(controller, pullIntoDescriptor.buffer, end - remainderSize, remainderSize);
        }
        pullIntoDescriptor.bytesFilled -= remainderSize;
        ReadableByteStreamControllerCommitPullIntoDescriptor(controller._controlledReadableByteStream, pullIntoDescriptor);
        ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller);
      }
      __name(ReadableByteStreamControllerRespondInReadableState, "ReadableByteStreamControllerRespondInReadableState");
      function ReadableByteStreamControllerRespondInternal(controller, bytesWritten) {
        const firstDescriptor = controller._pendingPullIntos.peek();
        ReadableByteStreamControllerInvalidateBYOBRequest(controller);
        const state = controller._controlledReadableByteStream._state;
        if (state === "closed") {
          ReadableByteStreamControllerRespondInClosedState(controller, firstDescriptor);
        } else {
          ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, firstDescriptor);
        }
        ReadableByteStreamControllerCallPullIfNeeded(controller);
      }
      __name(ReadableByteStreamControllerRespondInternal, "ReadableByteStreamControllerRespondInternal");
      function ReadableByteStreamControllerShiftPendingPullInto(controller) {
        const descriptor2 = controller._pendingPullIntos.shift();
        return descriptor2;
      }
      __name(ReadableByteStreamControllerShiftPendingPullInto, "ReadableByteStreamControllerShiftPendingPullInto");
      function ReadableByteStreamControllerShouldCallPull(controller) {
        const stream2 = controller._controlledReadableByteStream;
        if (stream2._state !== "readable") {
          return false;
        }
        if (controller._closeRequested) {
          return false;
        }
        if (!controller._started) {
          return false;
        }
        if (ReadableStreamHasDefaultReader(stream2) && ReadableStreamGetNumReadRequests(stream2) > 0) {
          return true;
        }
        if (ReadableStreamHasBYOBReader(stream2) && ReadableStreamGetNumReadIntoRequests(stream2) > 0) {
          return true;
        }
        const desiredSize = ReadableByteStreamControllerGetDesiredSize(controller);
        if (desiredSize > 0) {
          return true;
        }
        return false;
      }
      __name(ReadableByteStreamControllerShouldCallPull, "ReadableByteStreamControllerShouldCallPull");
      function ReadableByteStreamControllerClearAlgorithms(controller) {
        controller._pullAlgorithm = void 0;
        controller._cancelAlgorithm = void 0;
      }
      __name(ReadableByteStreamControllerClearAlgorithms, "ReadableByteStreamControllerClearAlgorithms");
      function ReadableByteStreamControllerClose(controller) {
        const stream2 = controller._controlledReadableByteStream;
        if (controller._closeRequested || stream2._state !== "readable") {
          return;
        }
        if (controller._queueTotalSize > 0) {
          controller._closeRequested = true;
          return;
        }
        if (controller._pendingPullIntos.length > 0) {
          const firstPendingPullInto = controller._pendingPullIntos.peek();
          if (firstPendingPullInto.bytesFilled % firstPendingPullInto.elementSize !== 0) {
            const e4 = new TypeError("Insufficient bytes to fill elements in the given buffer");
            ReadableByteStreamControllerError(controller, e4);
            throw e4;
          }
        }
        ReadableByteStreamControllerClearAlgorithms(controller);
        ReadableStreamClose(stream2);
      }
      __name(ReadableByteStreamControllerClose, "ReadableByteStreamControllerClose");
      function ReadableByteStreamControllerEnqueue(controller, chunk) {
        const stream2 = controller._controlledReadableByteStream;
        if (controller._closeRequested || stream2._state !== "readable") {
          return;
        }
        const { buffer, byteOffset, byteLength } = chunk;
        if (IsDetachedBuffer(buffer)) {
          throw new TypeError("chunk's buffer is detached and so cannot be enqueued");
        }
        const transferredBuffer = TransferArrayBuffer(buffer);
        if (controller._pendingPullIntos.length > 0) {
          const firstPendingPullInto = controller._pendingPullIntos.peek();
          if (IsDetachedBuffer(firstPendingPullInto.buffer)) {
            throw new TypeError("The BYOB request's buffer has been detached and so cannot be filled with an enqueued chunk");
          }
          ReadableByteStreamControllerInvalidateBYOBRequest(controller);
          firstPendingPullInto.buffer = TransferArrayBuffer(firstPendingPullInto.buffer);
          if (firstPendingPullInto.readerType === "none") {
            ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, firstPendingPullInto);
          }
        }
        if (ReadableStreamHasDefaultReader(stream2)) {
          ReadableByteStreamControllerProcessReadRequestsUsingQueue(controller);
          if (ReadableStreamGetNumReadRequests(stream2) === 0) {
            ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);
          } else {
            if (controller._pendingPullIntos.length > 0) {
              ReadableByteStreamControllerShiftPendingPullInto(controller);
            }
            const transferredView = new Uint8Array(transferredBuffer, byteOffset, byteLength);
            ReadableStreamFulfillReadRequest(stream2, transferredView, false);
          }
        } else if (ReadableStreamHasBYOBReader(stream2)) {
          ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);
          ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller);
        } else {
          ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);
        }
        ReadableByteStreamControllerCallPullIfNeeded(controller);
      }
      __name(ReadableByteStreamControllerEnqueue, "ReadableByteStreamControllerEnqueue");
      function ReadableByteStreamControllerError(controller, e4) {
        const stream2 = controller._controlledReadableByteStream;
        if (stream2._state !== "readable") {
          return;
        }
        ReadableByteStreamControllerClearPendingPullIntos(controller);
        ResetQueue(controller);
        ReadableByteStreamControllerClearAlgorithms(controller);
        ReadableStreamError(stream2, e4);
      }
      __name(ReadableByteStreamControllerError, "ReadableByteStreamControllerError");
      function ReadableByteStreamControllerFillReadRequestFromQueue(controller, readRequest) {
        const entry = controller._queue.shift();
        controller._queueTotalSize -= entry.byteLength;
        ReadableByteStreamControllerHandleQueueDrain(controller);
        const view = new Uint8Array(entry.buffer, entry.byteOffset, entry.byteLength);
        readRequest._chunkSteps(view);
      }
      __name(ReadableByteStreamControllerFillReadRequestFromQueue, "ReadableByteStreamControllerFillReadRequestFromQueue");
      function ReadableByteStreamControllerGetBYOBRequest(controller) {
        if (controller._byobRequest === null && controller._pendingPullIntos.length > 0) {
          const firstDescriptor = controller._pendingPullIntos.peek();
          const view = new Uint8Array(firstDescriptor.buffer, firstDescriptor.byteOffset + firstDescriptor.bytesFilled, firstDescriptor.byteLength - firstDescriptor.bytesFilled);
          const byobRequest = Object.create(ReadableStreamBYOBRequest2.prototype);
          SetUpReadableStreamBYOBRequest(byobRequest, controller, view);
          controller._byobRequest = byobRequest;
        }
        return controller._byobRequest;
      }
      __name(ReadableByteStreamControllerGetBYOBRequest, "ReadableByteStreamControllerGetBYOBRequest");
      function ReadableByteStreamControllerGetDesiredSize(controller) {
        const state = controller._controlledReadableByteStream._state;
        if (state === "errored") {
          return null;
        }
        if (state === "closed") {
          return 0;
        }
        return controller._strategyHWM - controller._queueTotalSize;
      }
      __name(ReadableByteStreamControllerGetDesiredSize, "ReadableByteStreamControllerGetDesiredSize");
      function ReadableByteStreamControllerRespond(controller, bytesWritten) {
        const firstDescriptor = controller._pendingPullIntos.peek();
        const state = controller._controlledReadableByteStream._state;
        if (state === "closed") {
          if (bytesWritten !== 0) {
            throw new TypeError("bytesWritten must be 0 when calling respond() on a closed stream");
          }
        } else {
          if (bytesWritten === 0) {
            throw new TypeError("bytesWritten must be greater than 0 when calling respond() on a readable stream");
          }
          if (firstDescriptor.bytesFilled + bytesWritten > firstDescriptor.byteLength) {
            throw new RangeError("bytesWritten out of range");
          }
        }
        firstDescriptor.buffer = TransferArrayBuffer(firstDescriptor.buffer);
        ReadableByteStreamControllerRespondInternal(controller, bytesWritten);
      }
      __name(ReadableByteStreamControllerRespond, "ReadableByteStreamControllerRespond");
      function ReadableByteStreamControllerRespondWithNewView(controller, view) {
        const firstDescriptor = controller._pendingPullIntos.peek();
        const state = controller._controlledReadableByteStream._state;
        if (state === "closed") {
          if (view.byteLength !== 0) {
            throw new TypeError("The view's length must be 0 when calling respondWithNewView() on a closed stream");
          }
        } else {
          if (view.byteLength === 0) {
            throw new TypeError("The view's length must be greater than 0 when calling respondWithNewView() on a readable stream");
          }
        }
        if (firstDescriptor.byteOffset + firstDescriptor.bytesFilled !== view.byteOffset) {
          throw new RangeError("The region specified by view does not match byobRequest");
        }
        if (firstDescriptor.bufferByteLength !== view.buffer.byteLength) {
          throw new RangeError("The buffer of view has different capacity than byobRequest");
        }
        if (firstDescriptor.bytesFilled + view.byteLength > firstDescriptor.byteLength) {
          throw new RangeError("The region specified by view is larger than byobRequest");
        }
        const viewByteLength = view.byteLength;
        firstDescriptor.buffer = TransferArrayBuffer(view.buffer);
        ReadableByteStreamControllerRespondInternal(controller, viewByteLength);
      }
      __name(ReadableByteStreamControllerRespondWithNewView, "ReadableByteStreamControllerRespondWithNewView");
      function SetUpReadableByteStreamController(stream2, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, autoAllocateChunkSize) {
        controller._controlledReadableByteStream = stream2;
        controller._pullAgain = false;
        controller._pulling = false;
        controller._byobRequest = null;
        controller._queue = controller._queueTotalSize = void 0;
        ResetQueue(controller);
        controller._closeRequested = false;
        controller._started = false;
        controller._strategyHWM = highWaterMark;
        controller._pullAlgorithm = pullAlgorithm;
        controller._cancelAlgorithm = cancelAlgorithm;
        controller._autoAllocateChunkSize = autoAllocateChunkSize;
        controller._pendingPullIntos = new SimpleQueue();
        stream2._readableStreamController = controller;
        const startResult = startAlgorithm();
        uponPromise(promiseResolvedWith(startResult), () => {
          controller._started = true;
          ReadableByteStreamControllerCallPullIfNeeded(controller);
          return null;
        }, (r5) => {
          ReadableByteStreamControllerError(controller, r5);
          return null;
        });
      }
      __name(SetUpReadableByteStreamController, "SetUpReadableByteStreamController");
      function SetUpReadableByteStreamControllerFromUnderlyingSource(stream2, underlyingByteSource, highWaterMark) {
        const controller = Object.create(ReadableByteStreamController2.prototype);
        let startAlgorithm;
        let pullAlgorithm;
        let cancelAlgorithm;
        if (underlyingByteSource.start !== void 0) {
          startAlgorithm = /* @__PURE__ */ __name(() => underlyingByteSource.start(controller), "startAlgorithm");
        } else {
          startAlgorithm = /* @__PURE__ */ __name(() => void 0, "startAlgorithm");
        }
        if (underlyingByteSource.pull !== void 0) {
          pullAlgorithm = /* @__PURE__ */ __name(() => underlyingByteSource.pull(controller), "pullAlgorithm");
        } else {
          pullAlgorithm = /* @__PURE__ */ __name(() => promiseResolvedWith(void 0), "pullAlgorithm");
        }
        if (underlyingByteSource.cancel !== void 0) {
          cancelAlgorithm = /* @__PURE__ */ __name((reason) => underlyingByteSource.cancel(reason), "cancelAlgorithm");
        } else {
          cancelAlgorithm = /* @__PURE__ */ __name(() => promiseResolvedWith(void 0), "cancelAlgorithm");
        }
        const autoAllocateChunkSize = underlyingByteSource.autoAllocateChunkSize;
        if (autoAllocateChunkSize === 0) {
          throw new TypeError("autoAllocateChunkSize must be greater than 0");
        }
        SetUpReadableByteStreamController(stream2, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, autoAllocateChunkSize);
      }
      __name(SetUpReadableByteStreamControllerFromUnderlyingSource, "SetUpReadableByteStreamControllerFromUnderlyingSource");
      function SetUpReadableStreamBYOBRequest(request4, controller, view) {
        request4._associatedReadableByteStreamController = controller;
        request4._view = view;
      }
      __name(SetUpReadableStreamBYOBRequest, "SetUpReadableStreamBYOBRequest");
      function byobRequestBrandCheckException(name3) {
        return new TypeError(`ReadableStreamBYOBRequest.prototype.${name3} can only be used on a ReadableStreamBYOBRequest`);
      }
      __name(byobRequestBrandCheckException, "byobRequestBrandCheckException");
      function byteStreamControllerBrandCheckException(name3) {
        return new TypeError(`ReadableByteStreamController.prototype.${name3} can only be used on a ReadableByteStreamController`);
      }
      __name(byteStreamControllerBrandCheckException, "byteStreamControllerBrandCheckException");
      function convertReaderOptions(options2, context2) {
        assertDictionary(options2, context2);
        const mode = options2 === null || options2 === void 0 ? void 0 : options2.mode;
        return {
          mode: mode === void 0 ? void 0 : convertReadableStreamReaderMode(mode, `${context2} has member 'mode' that`)
        };
      }
      __name(convertReaderOptions, "convertReaderOptions");
      function convertReadableStreamReaderMode(mode, context2) {
        mode = `${mode}`;
        if (mode !== "byob") {
          throw new TypeError(`${context2} '${mode}' is not a valid enumeration value for ReadableStreamReaderMode`);
        }
        return mode;
      }
      __name(convertReadableStreamReaderMode, "convertReadableStreamReaderMode");
      function convertByobReadOptions(options2, context2) {
        var _a8;
        assertDictionary(options2, context2);
        const min = (_a8 = options2 === null || options2 === void 0 ? void 0 : options2.min) !== null && _a8 !== void 0 ? _a8 : 1;
        return {
          min: convertUnsignedLongLongWithEnforceRange(min, `${context2} has member 'min' that`)
        };
      }
      __name(convertByobReadOptions, "convertByobReadOptions");
      function AcquireReadableStreamBYOBReader(stream2) {
        return new ReadableStreamBYOBReader2(stream2);
      }
      __name(AcquireReadableStreamBYOBReader, "AcquireReadableStreamBYOBReader");
      function ReadableStreamAddReadIntoRequest(stream2, readIntoRequest) {
        stream2._reader._readIntoRequests.push(readIntoRequest);
      }
      __name(ReadableStreamAddReadIntoRequest, "ReadableStreamAddReadIntoRequest");
      function ReadableStreamFulfillReadIntoRequest(stream2, chunk, done) {
        const reader = stream2._reader;
        const readIntoRequest = reader._readIntoRequests.shift();
        if (done) {
          readIntoRequest._closeSteps(chunk);
        } else {
          readIntoRequest._chunkSteps(chunk);
        }
      }
      __name(ReadableStreamFulfillReadIntoRequest, "ReadableStreamFulfillReadIntoRequest");
      function ReadableStreamGetNumReadIntoRequests(stream2) {
        return stream2._reader._readIntoRequests.length;
      }
      __name(ReadableStreamGetNumReadIntoRequests, "ReadableStreamGetNumReadIntoRequests");
      function ReadableStreamHasBYOBReader(stream2) {
        const reader = stream2._reader;
        if (reader === void 0) {
          return false;
        }
        if (!IsReadableStreamBYOBReader(reader)) {
          return false;
        }
        return true;
      }
      __name(ReadableStreamHasBYOBReader, "ReadableStreamHasBYOBReader");
      class ReadableStreamBYOBReader2 {
        static {
          __name(this, "ReadableStreamBYOBReader");
        }
        constructor(stream2) {
          assertRequiredArgument(stream2, 1, "ReadableStreamBYOBReader");
          assertReadableStream(stream2, "First parameter");
          if (IsReadableStreamLocked(stream2)) {
            throw new TypeError("This stream has already been locked for exclusive reading by another reader");
          }
          if (!IsReadableByteStreamController(stream2._readableStreamController)) {
            throw new TypeError("Cannot construct a ReadableStreamBYOBReader for a stream not constructed with a byte source");
          }
          ReadableStreamReaderGenericInitialize(this, stream2);
          this._readIntoRequests = new SimpleQueue();
        }
        /**
         * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or
         * the reader's lock is released before the stream finishes closing.
         */
        get closed() {
          if (!IsReadableStreamBYOBReader(this)) {
            return promiseRejectedWith(byobReaderBrandCheckException("closed"));
          }
          return this._closedPromise;
        }
        /**
         * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}.
         */
        cancel(reason = void 0) {
          if (!IsReadableStreamBYOBReader(this)) {
            return promiseRejectedWith(byobReaderBrandCheckException("cancel"));
          }
          if (this._ownerReadableStream === void 0) {
            return promiseRejectedWith(readerLockException("cancel"));
          }
          return ReadableStreamReaderGenericCancel(this, reason);
        }
        read(view, rawOptions = {}) {
          if (!IsReadableStreamBYOBReader(this)) {
            return promiseRejectedWith(byobReaderBrandCheckException("read"));
          }
          if (!ArrayBuffer.isView(view)) {
            return promiseRejectedWith(new TypeError("view must be an array buffer view"));
          }
          if (view.byteLength === 0) {
            return promiseRejectedWith(new TypeError("view must have non-zero byteLength"));
          }
          if (view.buffer.byteLength === 0) {
            return promiseRejectedWith(new TypeError(`view's buffer must have non-zero byteLength`));
          }
          if (IsDetachedBuffer(view.buffer)) {
            return promiseRejectedWith(new TypeError("view's buffer has been detached"));
          }
          let options2;
          try {
            options2 = convertByobReadOptions(rawOptions, "options");
          } catch (e4) {
            return promiseRejectedWith(e4);
          }
          const min = options2.min;
          if (min === 0) {
            return promiseRejectedWith(new TypeError("options.min must be greater than 0"));
          }
          if (!isDataView(view)) {
            if (min > view.length) {
              return promiseRejectedWith(new RangeError("options.min must be less than or equal to view's length"));
            }
          } else if (min > view.byteLength) {
            return promiseRejectedWith(new RangeError("options.min must be less than or equal to view's byteLength"));
          }
          if (this._ownerReadableStream === void 0) {
            return promiseRejectedWith(readerLockException("read from"));
          }
          let resolvePromise;
          let rejectPromise;
          const promise = newPromise((resolve30, reject) => {
            resolvePromise = resolve30;
            rejectPromise = reject;
          });
          const readIntoRequest = {
            _chunkSteps: /* @__PURE__ */ __name((chunk) => resolvePromise({ value: chunk, done: false }), "_chunkSteps"),
            _closeSteps: /* @__PURE__ */ __name((chunk) => resolvePromise({ value: chunk, done: true }), "_closeSteps"),
            _errorSteps: /* @__PURE__ */ __name((e4) => rejectPromise(e4), "_errorSteps")
          };
          ReadableStreamBYOBReaderRead(this, view, min, readIntoRequest);
          return promise;
        }
        /**
         * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active.
         * If the associated stream is errored when the lock is released, the reader will appear errored in the same way
         * from now on; otherwise, the reader will appear closed.
         *
         * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by
         * the reader's {@link ReadableStreamBYOBReader.read | read()} method has not yet been settled. Attempting to
         * do so will throw a `TypeError` and leave the reader locked to the stream.
         */
        releaseLock() {
          if (!IsReadableStreamBYOBReader(this)) {
            throw byobReaderBrandCheckException("releaseLock");
          }
          if (this._ownerReadableStream === void 0) {
            return;
          }
          ReadableStreamBYOBReaderRelease(this);
        }
      }
      Object.defineProperties(ReadableStreamBYOBReader2.prototype, {
        cancel: { enumerable: true },
        read: { enumerable: true },
        releaseLock: { enumerable: true },
        closed: { enumerable: true }
      });
      setFunctionName(ReadableStreamBYOBReader2.prototype.cancel, "cancel");
      setFunctionName(ReadableStreamBYOBReader2.prototype.read, "read");
      setFunctionName(ReadableStreamBYOBReader2.prototype.releaseLock, "releaseLock");
      if (typeof Symbol.toStringTag === "symbol") {
        Object.defineProperty(ReadableStreamBYOBReader2.prototype, Symbol.toStringTag, {
          value: "ReadableStreamBYOBReader",
          configurable: true
        });
      }
      function IsReadableStreamBYOBReader(x3) {
        if (!typeIsObject(x3)) {
          return false;
        }
        if (!Object.prototype.hasOwnProperty.call(x3, "_readIntoRequests")) {
          return false;
        }
        return x3 instanceof ReadableStreamBYOBReader2;
      }
      __name(IsReadableStreamBYOBReader, "IsReadableStreamBYOBReader");
      function ReadableStreamBYOBReaderRead(reader, view, min, readIntoRequest) {
        const stream2 = reader._ownerReadableStream;
        stream2._disturbed = true;
        if (stream2._state === "errored") {
          readIntoRequest._errorSteps(stream2._storedError);
        } else {
          ReadableByteStreamControllerPullInto(stream2._readableStreamController, view, min, readIntoRequest);
        }
      }
      __name(ReadableStreamBYOBReaderRead, "ReadableStreamBYOBReaderRead");
      function ReadableStreamBYOBReaderRelease(reader) {
        ReadableStreamReaderGenericRelease(reader);
        const e4 = new TypeError("Reader was released");
        ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e4);
      }
      __name(ReadableStreamBYOBReaderRelease, "ReadableStreamBYOBReaderRelease");
      function ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e4) {
        const readIntoRequests = reader._readIntoRequests;
        reader._readIntoRequests = new SimpleQueue();
        readIntoRequests.forEach((readIntoRequest) => {
          readIntoRequest._errorSteps(e4);
        });
      }
      __name(ReadableStreamBYOBReaderErrorReadIntoRequests, "ReadableStreamBYOBReaderErrorReadIntoRequests");
      function byobReaderBrandCheckException(name3) {
        return new TypeError(`ReadableStreamBYOBReader.prototype.${name3} can only be used on a ReadableStreamBYOBReader`);
      }
      __name(byobReaderBrandCheckException, "byobReaderBrandCheckException");
      function ExtractHighWaterMark(strategy, defaultHWM) {
        const { highWaterMark } = strategy;
        if (highWaterMark === void 0) {
          return defaultHWM;
        }
        if (NumberIsNaN(highWaterMark) || highWaterMark < 0) {
          throw new RangeError("Invalid highWaterMark");
        }
        return highWaterMark;
      }
      __name(ExtractHighWaterMark, "ExtractHighWaterMark");
      function ExtractSizeAlgorithm(strategy) {
        const { size } = strategy;
        if (!size) {
          return () => 1;
        }
        return size;
      }
      __name(ExtractSizeAlgorithm, "ExtractSizeAlgorithm");
      function convertQueuingStrategy(init, context2) {
        assertDictionary(init, context2);
        const highWaterMark = init === null || init === void 0 ? void 0 : init.highWaterMark;
        const size = init === null || init === void 0 ? void 0 : init.size;
        return {
          highWaterMark: highWaterMark === void 0 ? void 0 : convertUnrestrictedDouble(highWaterMark),
          size: size === void 0 ? void 0 : convertQueuingStrategySize(size, `${context2} has member 'size' that`)
        };
      }
      __name(convertQueuingStrategy, "convertQueuingStrategy");
      function convertQueuingStrategySize(fn, context2) {
        assertFunction(fn, context2);
        return (chunk) => convertUnrestrictedDouble(fn(chunk));
      }
      __name(convertQueuingStrategySize, "convertQueuingStrategySize");
      function convertUnderlyingSink(original, context2) {
        assertDictionary(original, context2);
        const abort = original === null || original === void 0 ? void 0 : original.abort;
        const close = original === null || original === void 0 ? void 0 : original.close;
        const start = original === null || original === void 0 ? void 0 : original.start;
        const type = original === null || original === void 0 ? void 0 : original.type;
        const write2 = original === null || original === void 0 ? void 0 : original.write;
        return {
          abort: abort === void 0 ? void 0 : convertUnderlyingSinkAbortCallback(abort, original, `${context2} has member 'abort' that`),
          close: close === void 0 ? void 0 : convertUnderlyingSinkCloseCallback(close, original, `${context2} has member 'close' that`),
          start: start === void 0 ? void 0 : convertUnderlyingSinkStartCallback(start, original, `${context2} has member 'start' that`),
          write: write2 === void 0 ? void 0 : convertUnderlyingSinkWriteCallback(write2, original, `${context2} has member 'write' that`),
          type
        };
      }
      __name(convertUnderlyingSink, "convertUnderlyingSink");
      function convertUnderlyingSinkAbortCallback(fn, original, context2) {
        assertFunction(fn, context2);
        return (reason) => promiseCall(fn, original, [reason]);
      }
      __name(convertUnderlyingSinkAbortCallback, "convertUnderlyingSinkAbortCallback");
      function convertUnderlyingSinkCloseCallback(fn, original, context2) {
        assertFunction(fn, context2);
        return () => promiseCall(fn, original, []);
      }
      __name(convertUnderlyingSinkCloseCallback, "convertUnderlyingSinkCloseCallback");
      function convertUnderlyingSinkStartCallback(fn, original, context2) {
        assertFunction(fn, context2);
        return (controller) => reflectCall(fn, original, [controller]);
      }
      __name(convertUnderlyingSinkStartCallback, "convertUnderlyingSinkStartCallback");
      function convertUnderlyingSinkWriteCallback(fn, original, context2) {
        assertFunction(fn, context2);
        return (chunk, controller) => promiseCall(fn, original, [chunk, controller]);
      }
      __name(convertUnderlyingSinkWriteCallback, "convertUnderlyingSinkWriteCallback");
      function assertWritableStream(x3, context2) {
        if (!IsWritableStream(x3)) {
          throw new TypeError(`${context2} is not a WritableStream.`);
        }
      }
      __name(assertWritableStream, "assertWritableStream");
      function isAbortSignal3(value) {
        if (typeof value !== "object" || value === null) {
          return false;
        }
        try {
          return typeof value.aborted === "boolean";
        } catch (_a8) {
          return false;
        }
      }
      __name(isAbortSignal3, "isAbortSignal");
      const supportsAbortController2 = typeof AbortController === "function";
      function createAbortController() {
        if (supportsAbortController2) {
          return new AbortController();
        }
        return void 0;
      }
      __name(createAbortController, "createAbortController");
      class WritableStream2 {
        static {
          __name(this, "WritableStream");
        }
        constructor(rawUnderlyingSink = {}, rawStrategy = {}) {
          if (rawUnderlyingSink === void 0) {
            rawUnderlyingSink = null;
          } else {
            assertObject(rawUnderlyingSink, "First parameter");
          }
          const strategy = convertQueuingStrategy(rawStrategy, "Second parameter");
          const underlyingSink = convertUnderlyingSink(rawUnderlyingSink, "First parameter");
          InitializeWritableStream(this);
          const type = underlyingSink.type;
          if (type !== void 0) {
            throw new RangeError("Invalid type is specified");
          }
          const sizeAlgorithm = ExtractSizeAlgorithm(strategy);
          const highWaterMark = ExtractHighWaterMark(strategy, 1);
          SetUpWritableStreamDefaultControllerFromUnderlyingSink(this, underlyingSink, highWaterMark, sizeAlgorithm);
        }
        /**
         * Returns whether or not the writable stream is locked to a writer.
         */
        get locked() {
          if (!IsWritableStream(this)) {
            throw streamBrandCheckException$2("locked");
          }
          return IsWritableStreamLocked(this);
        }
        /**
         * Aborts the stream, signaling that the producer can no longer successfully write to the stream and it is to be
         * immediately moved to an errored state, with any queued-up writes discarded. This will also execute any abort
         * mechanism of the underlying sink.
         *
         * The returned promise will fulfill if the stream shuts down successfully, or reject if the underlying sink signaled
         * that there was an error doing so. Additionally, it will reject with a `TypeError` (without attempting to cancel
         * the stream) if the stream is currently locked.
         */
        abort(reason = void 0) {
          if (!IsWritableStream(this)) {
            return promiseRejectedWith(streamBrandCheckException$2("abort"));
          }
          if (IsWritableStreamLocked(this)) {
            return promiseRejectedWith(new TypeError("Cannot abort a stream that already has a writer"));
          }
          return WritableStreamAbort(this, reason);
        }
        /**
         * Closes the stream. The underlying sink will finish processing any previously-written chunks, before invoking its
         * close behavior. During this time any further attempts to write will fail (without erroring the stream).
         *
         * The method returns a promise that will fulfill if all remaining chunks are successfully written and the stream
         * successfully closes, or rejects if an error is encountered during this process. Additionally, it will reject with
         * a `TypeError` (without attempting to cancel the stream) if the stream is currently locked.
         */
        close() {
          if (!IsWritableStream(this)) {
            return promiseRejectedWith(streamBrandCheckException$2("close"));
          }
          if (IsWritableStreamLocked(this)) {
            return promiseRejectedWith(new TypeError("Cannot close a stream that already has a writer"));
          }
          if (WritableStreamCloseQueuedOrInFlight(this)) {
            return promiseRejectedWith(new TypeError("Cannot close an already-closing stream"));
          }
          return WritableStreamClose(this);
        }
        /**
         * Creates a {@link WritableStreamDefaultWriter | writer} and locks the stream to the new writer. While the stream
         * is locked, no other writer can be acquired until this one is released.
         *
         * This functionality is especially useful for creating abstractions that desire the ability to write to a stream
         * without interruption or interleaving. By getting a writer for the stream, you can ensure nobody else can write at
         * the same time, which would cause the resulting written data to be unpredictable and probably useless.
         */
        getWriter() {
          if (!IsWritableStream(this)) {
            throw streamBrandCheckException$2("getWriter");
          }
          return AcquireWritableStreamDefaultWriter(this);
        }
      }
      Object.defineProperties(WritableStream2.prototype, {
        abort: { enumerable: true },
        close: { enumerable: true },
        getWriter: { enumerable: true },
        locked: { enumerable: true }
      });
      setFunctionName(WritableStream2.prototype.abort, "abort");
      setFunctionName(WritableStream2.prototype.close, "close");
      setFunctionName(WritableStream2.prototype.getWriter, "getWriter");
      if (typeof Symbol.toStringTag === "symbol") {
        Object.defineProperty(WritableStream2.prototype, Symbol.toStringTag, {
          value: "WritableStream",
          configurable: true
        });
      }
      function AcquireWritableStreamDefaultWriter(stream2) {
        return new WritableStreamDefaultWriter2(stream2);
      }
      __name(AcquireWritableStreamDefaultWriter, "AcquireWritableStreamDefaultWriter");
      function CreateWritableStream(startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark = 1, sizeAlgorithm = () => 1) {
        const stream2 = Object.create(WritableStream2.prototype);
        InitializeWritableStream(stream2);
        const controller = Object.create(WritableStreamDefaultController2.prototype);
        SetUpWritableStreamDefaultController(stream2, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm);
        return stream2;
      }
      __name(CreateWritableStream, "CreateWritableStream");
      function InitializeWritableStream(stream2) {
        stream2._state = "writable";
        stream2._storedError = void 0;
        stream2._writer = void 0;
        stream2._writableStreamController = void 0;
        stream2._writeRequests = new SimpleQueue();
        stream2._inFlightWriteRequest = void 0;
        stream2._closeRequest = void 0;
        stream2._inFlightCloseRequest = void 0;
        stream2._pendingAbortRequest = void 0;
        stream2._backpressure = false;
      }
      __name(InitializeWritableStream, "InitializeWritableStream");
      function IsWritableStream(x3) {
        if (!typeIsObject(x3)) {
          return false;
        }
        if (!Object.prototype.hasOwnProperty.call(x3, "_writableStreamController")) {
          return false;
        }
        return x3 instanceof WritableStream2;
      }
      __name(IsWritableStream, "IsWritableStream");
      function IsWritableStreamLocked(stream2) {
        if (stream2._writer === void 0) {
          return false;
        }
        return true;
      }
      __name(IsWritableStreamLocked, "IsWritableStreamLocked");
      function WritableStreamAbort(stream2, reason) {
        var _a8;
        if (stream2._state === "closed" || stream2._state === "errored") {
          return promiseResolvedWith(void 0);
        }
        stream2._writableStreamController._abortReason = reason;
        (_a8 = stream2._writableStreamController._abortController) === null || _a8 === void 0 ? void 0 : _a8.abort(reason);
        const state = stream2._state;
        if (state === "closed" || state === "errored") {
          return promiseResolvedWith(void 0);
        }
        if (stream2._pendingAbortRequest !== void 0) {
          return stream2._pendingAbortRequest._promise;
        }
        let wasAlreadyErroring = false;
        if (state === "erroring") {
          wasAlreadyErroring = true;
          reason = void 0;
        }
        const promise = newPromise((resolve30, reject) => {
          stream2._pendingAbortRequest = {
            _promise: void 0,
            _resolve: resolve30,
            _reject: reject,
            _reason: reason,
            _wasAlreadyErroring: wasAlreadyErroring
          };
        });
        stream2._pendingAbortRequest._promise = promise;
        if (!wasAlreadyErroring) {
          WritableStreamStartErroring(stream2, reason);
        }
        return promise;
      }
      __name(WritableStreamAbort, "WritableStreamAbort");
      function WritableStreamClose(stream2) {
        const state = stream2._state;
        if (state === "closed" || state === "errored") {
          return promiseRejectedWith(new TypeError(`The stream (in ${state} state) is not in the writable state and cannot be closed`));
        }
        const promise = newPromise((resolve30, reject) => {
          const closeRequest = {
            _resolve: resolve30,
            _reject: reject
          };
          stream2._closeRequest = closeRequest;
        });
        const writer = stream2._writer;
        if (writer !== void 0 && stream2._backpressure && state === "writable") {
          defaultWriterReadyPromiseResolve(writer);
        }
        WritableStreamDefaultControllerClose(stream2._writableStreamController);
        return promise;
      }
      __name(WritableStreamClose, "WritableStreamClose");
      function WritableStreamAddWriteRequest(stream2) {
        const promise = newPromise((resolve30, reject) => {
          const writeRequest = {
            _resolve: resolve30,
            _reject: reject
          };
          stream2._writeRequests.push(writeRequest);
        });
        return promise;
      }
      __name(WritableStreamAddWriteRequest, "WritableStreamAddWriteRequest");
      function WritableStreamDealWithRejection(stream2, error2) {
        const state = stream2._state;
        if (state === "writable") {
          WritableStreamStartErroring(stream2, error2);
          return;
        }
        WritableStreamFinishErroring(stream2);
      }
      __name(WritableStreamDealWithRejection, "WritableStreamDealWithRejection");
      function WritableStreamStartErroring(stream2, reason) {
        const controller = stream2._writableStreamController;
        stream2._state = "erroring";
        stream2._storedError = reason;
        const writer = stream2._writer;
        if (writer !== void 0) {
          WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, reason);
        }
        if (!WritableStreamHasOperationMarkedInFlight(stream2) && controller._started) {
          WritableStreamFinishErroring(stream2);
        }
      }
      __name(WritableStreamStartErroring, "WritableStreamStartErroring");
      function WritableStreamFinishErroring(stream2) {
        stream2._state = "errored";
        stream2._writableStreamController[ErrorSteps]();
        const storedError = stream2._storedError;
        stream2._writeRequests.forEach((writeRequest) => {
          writeRequest._reject(storedError);
        });
        stream2._writeRequests = new SimpleQueue();
        if (stream2._pendingAbortRequest === void 0) {
          WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream2);
          return;
        }
        const abortRequest = stream2._pendingAbortRequest;
        stream2._pendingAbortRequest = void 0;
        if (abortRequest._wasAlreadyErroring) {
          abortRequest._reject(storedError);
          WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream2);
          return;
        }
        const promise = stream2._writableStreamController[AbortSteps](abortRequest._reason);
        uponPromise(promise, () => {
          abortRequest._resolve();
          WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream2);
          return null;
        }, (reason) => {
          abortRequest._reject(reason);
          WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream2);
          return null;
        });
      }
      __name(WritableStreamFinishErroring, "WritableStreamFinishErroring");
      function WritableStreamFinishInFlightWrite(stream2) {
        stream2._inFlightWriteRequest._resolve(void 0);
        stream2._inFlightWriteRequest = void 0;
      }
      __name(WritableStreamFinishInFlightWrite, "WritableStreamFinishInFlightWrite");
      function WritableStreamFinishInFlightWriteWithError(stream2, error2) {
        stream2._inFlightWriteRequest._reject(error2);
        stream2._inFlightWriteRequest = void 0;
        WritableStreamDealWithRejection(stream2, error2);
      }
      __name(WritableStreamFinishInFlightWriteWithError, "WritableStreamFinishInFlightWriteWithError");
      function WritableStreamFinishInFlightClose(stream2) {
        stream2._inFlightCloseRequest._resolve(void 0);
        stream2._inFlightCloseRequest = void 0;
        const state = stream2._state;
        if (state === "erroring") {
          stream2._storedError = void 0;
          if (stream2._pendingAbortRequest !== void 0) {
            stream2._pendingAbortRequest._resolve();
            stream2._pendingAbortRequest = void 0;
          }
        }
        stream2._state = "closed";
        const writer = stream2._writer;
        if (writer !== void 0) {
          defaultWriterClosedPromiseResolve(writer);
        }
      }
      __name(WritableStreamFinishInFlightClose, "WritableStreamFinishInFlightClose");
      function WritableStreamFinishInFlightCloseWithError(stream2, error2) {
        stream2._inFlightCloseRequest._reject(error2);
        stream2._inFlightCloseRequest = void 0;
        if (stream2._pendingAbortRequest !== void 0) {
          stream2._pendingAbortRequest._reject(error2);
          stream2._pendingAbortRequest = void 0;
        }
        WritableStreamDealWithRejection(stream2, error2);
      }
      __name(WritableStreamFinishInFlightCloseWithError, "WritableStreamFinishInFlightCloseWithError");
      function WritableStreamCloseQueuedOrInFlight(stream2) {
        if (stream2._closeRequest === void 0 && stream2._inFlightCloseRequest === void 0) {
          return false;
        }
        return true;
      }
      __name(WritableStreamCloseQueuedOrInFlight, "WritableStreamCloseQueuedOrInFlight");
      function WritableStreamHasOperationMarkedInFlight(stream2) {
        if (stream2._inFlightWriteRequest === void 0 && stream2._inFlightCloseRequest === void 0) {
          return false;
        }
        return true;
      }
      __name(WritableStreamHasOperationMarkedInFlight, "WritableStreamHasOperationMarkedInFlight");
      function WritableStreamMarkCloseRequestInFlight(stream2) {
        stream2._inFlightCloseRequest = stream2._closeRequest;
        stream2._closeRequest = void 0;
      }
      __name(WritableStreamMarkCloseRequestInFlight, "WritableStreamMarkCloseRequestInFlight");
      function WritableStreamMarkFirstWriteRequestInFlight(stream2) {
        stream2._inFlightWriteRequest = stream2._writeRequests.shift();
      }
      __name(WritableStreamMarkFirstWriteRequestInFlight, "WritableStreamMarkFirstWriteRequestInFlight");
      function WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream2) {
        if (stream2._closeRequest !== void 0) {
          stream2._closeRequest._reject(stream2._storedError);
          stream2._closeRequest = void 0;
        }
        const writer = stream2._writer;
        if (writer !== void 0) {
          defaultWriterClosedPromiseReject(writer, stream2._storedError);
        }
      }
      __name(WritableStreamRejectCloseAndClosedPromiseIfNeeded, "WritableStreamRejectCloseAndClosedPromiseIfNeeded");
      function WritableStreamUpdateBackpressure(stream2, backpressure) {
        const writer = stream2._writer;
        if (writer !== void 0 && backpressure !== stream2._backpressure) {
          if (backpressure) {
            defaultWriterReadyPromiseReset(writer);
          } else {
            defaultWriterReadyPromiseResolve(writer);
          }
        }
        stream2._backpressure = backpressure;
      }
      __name(WritableStreamUpdateBackpressure, "WritableStreamUpdateBackpressure");
      class WritableStreamDefaultWriter2 {
        static {
          __name(this, "WritableStreamDefaultWriter");
        }
        constructor(stream2) {
          assertRequiredArgument(stream2, 1, "WritableStreamDefaultWriter");
          assertWritableStream(stream2, "First parameter");
          if (IsWritableStreamLocked(stream2)) {
            throw new TypeError("This stream has already been locked for exclusive writing by another writer");
          }
          this._ownerWritableStream = stream2;
          stream2._writer = this;
          const state = stream2._state;
          if (state === "writable") {
            if (!WritableStreamCloseQueuedOrInFlight(stream2) && stream2._backpressure) {
              defaultWriterReadyPromiseInitialize(this);
            } else {
              defaultWriterReadyPromiseInitializeAsResolved(this);
            }
            defaultWriterClosedPromiseInitialize(this);
          } else if (state === "erroring") {
            defaultWriterReadyPromiseInitializeAsRejected(this, stream2._storedError);
            defaultWriterClosedPromiseInitialize(this);
          } else if (state === "closed") {
            defaultWriterReadyPromiseInitializeAsResolved(this);
            defaultWriterClosedPromiseInitializeAsResolved(this);
          } else {
            const storedError = stream2._storedError;
            defaultWriterReadyPromiseInitializeAsRejected(this, storedError);
            defaultWriterClosedPromiseInitializeAsRejected(this, storedError);
          }
        }
        /**
         * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or
         * the writer’s lock is released before the stream finishes closing.
         */
        get closed() {
          if (!IsWritableStreamDefaultWriter(this)) {
            return promiseRejectedWith(defaultWriterBrandCheckException("closed"));
          }
          return this._closedPromise;
        }
        /**
         * Returns the desired size to fill the stream’s internal queue. It can be negative, if the queue is over-full.
         * A producer can use this information to determine the right amount of data to write.
         *
         * It will be `null` if the stream cannot be successfully written to (due to either being errored, or having an abort
         * queued up). It will return zero if the stream is closed. And the getter will throw an exception if invoked when
         * the writer’s lock is released.
         */
        get desiredSize() {
          if (!IsWritableStreamDefaultWriter(this)) {
            throw defaultWriterBrandCheckException("desiredSize");
          }
          if (this._ownerWritableStream === void 0) {
            throw defaultWriterLockException("desiredSize");
          }
          return WritableStreamDefaultWriterGetDesiredSize(this);
        }
        /**
         * Returns a promise that will be fulfilled when the desired size to fill the stream’s internal queue transitions
         * from non-positive to positive, signaling that it is no longer applying backpressure. Once the desired size dips
         * back to zero or below, the getter will return a new promise that stays pending until the next transition.
         *
         * If the stream becomes errored or aborted, or the writer’s lock is released, the returned promise will become
         * rejected.
         */
        get ready() {
          if (!IsWritableStreamDefaultWriter(this)) {
            return promiseRejectedWith(defaultWriterBrandCheckException("ready"));
          }
          return this._readyPromise;
        }
        /**
         * If the reader is active, behaves the same as {@link WritableStream.abort | stream.abort(reason)}.
         */
        abort(reason = void 0) {
          if (!IsWritableStreamDefaultWriter(this)) {
            return promiseRejectedWith(defaultWriterBrandCheckException("abort"));
          }
          if (this._ownerWritableStream === void 0) {
            return promiseRejectedWith(defaultWriterLockException("abort"));
          }
          return WritableStreamDefaultWriterAbort(this, reason);
        }
        /**
         * If the reader is active, behaves the same as {@link WritableStream.close | stream.close()}.
         */
        close() {
          if (!IsWritableStreamDefaultWriter(this)) {
            return promiseRejectedWith(defaultWriterBrandCheckException("close"));
          }
          const stream2 = this._ownerWritableStream;
          if (stream2 === void 0) {
            return promiseRejectedWith(defaultWriterLockException("close"));
          }
          if (WritableStreamCloseQueuedOrInFlight(stream2)) {
            return promiseRejectedWith(new TypeError("Cannot close an already-closing stream"));
          }
          return WritableStreamDefaultWriterClose(this);
        }
        /**
         * Releases the writer’s lock on the corresponding stream. After the lock is released, the writer is no longer active.
         * If the associated stream is errored when the lock is released, the writer will appear errored in the same way from
         * now on; otherwise, the writer will appear closed.
         *
         * Note that the lock can still be released even if some ongoing writes have not yet finished (i.e. even if the
         * promises returned from previous calls to {@link WritableStreamDefaultWriter.write | write()} have not yet settled).
         * It’s not necessary to hold the lock on the writer for the duration of the write; the lock instead simply prevents
         * other producers from writing in an interleaved manner.
         */
        releaseLock() {
          if (!IsWritableStreamDefaultWriter(this)) {
            throw defaultWriterBrandCheckException("releaseLock");
          }
          const stream2 = this._ownerWritableStream;
          if (stream2 === void 0) {
            return;
          }
          WritableStreamDefaultWriterRelease(this);
        }
        write(chunk = void 0) {
          if (!IsWritableStreamDefaultWriter(this)) {
            return promiseRejectedWith(defaultWriterBrandCheckException("write"));
          }
          if (this._ownerWritableStream === void 0) {
            return promiseRejectedWith(defaultWriterLockException("write to"));
          }
          return WritableStreamDefaultWriterWrite(this, chunk);
        }
      }
      Object.defineProperties(WritableStreamDefaultWriter2.prototype, {
        abort: { enumerable: true },
        close: { enumerable: true },
        releaseLock: { enumerable: true },
        write: { enumerable: true },
        closed: { enumerable: true },
        desiredSize: { enumerable: true },
        ready: { enumerable: true }
      });
      setFunctionName(WritableStreamDefaultWriter2.prototype.abort, "abort");
      setFunctionName(WritableStreamDefaultWriter2.prototype.close, "close");
      setFunctionName(WritableStreamDefaultWriter2.prototype.releaseLock, "releaseLock");
      setFunctionName(WritableStreamDefaultWriter2.prototype.write, "write");
      if (typeof Symbol.toStringTag === "symbol") {
        Object.defineProperty(WritableStreamDefaultWriter2.prototype, Symbol.toStringTag, {
          value: "WritableStreamDefaultWriter",
          configurable: true
        });
      }
      function IsWritableStreamDefaultWriter(x3) {
        if (!typeIsObject(x3)) {
          return false;
        }
        if (!Object.prototype.hasOwnProperty.call(x3, "_ownerWritableStream")) {
          return false;
        }
        return x3 instanceof WritableStreamDefaultWriter2;
      }
      __name(IsWritableStreamDefaultWriter, "IsWritableStreamDefaultWriter");
      function WritableStreamDefaultWriterAbort(writer, reason) {
        const stream2 = writer._ownerWritableStream;
        return WritableStreamAbort(stream2, reason);
      }
      __name(WritableStreamDefaultWriterAbort, "WritableStreamDefaultWriterAbort");
      function WritableStreamDefaultWriterClose(writer) {
        const stream2 = writer._ownerWritableStream;
        return WritableStreamClose(stream2);
      }
      __name(WritableStreamDefaultWriterClose, "WritableStreamDefaultWriterClose");
      function WritableStreamDefaultWriterCloseWithErrorPropagation(writer) {
        const stream2 = writer._ownerWritableStream;
        const state = stream2._state;
        if (WritableStreamCloseQueuedOrInFlight(stream2) || state === "closed") {
          return promiseResolvedWith(void 0);
        }
        if (state === "errored") {
          return promiseRejectedWith(stream2._storedError);
        }
        return WritableStreamDefaultWriterClose(writer);
      }
      __name(WritableStreamDefaultWriterCloseWithErrorPropagation, "WritableStreamDefaultWriterCloseWithErrorPropagation");
      function WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer, error2) {
        if (writer._closedPromiseState === "pending") {
          defaultWriterClosedPromiseReject(writer, error2);
        } else {
          defaultWriterClosedPromiseResetToRejected(writer, error2);
        }
      }
      __name(WritableStreamDefaultWriterEnsureClosedPromiseRejected, "WritableStreamDefaultWriterEnsureClosedPromiseRejected");
      function WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, error2) {
        if (writer._readyPromiseState === "pending") {
          defaultWriterReadyPromiseReject(writer, error2);
        } else {
          defaultWriterReadyPromiseResetToRejected(writer, error2);
        }
      }
      __name(WritableStreamDefaultWriterEnsureReadyPromiseRejected, "WritableStreamDefaultWriterEnsureReadyPromiseRejected");
      function WritableStreamDefaultWriterGetDesiredSize(writer) {
        const stream2 = writer._ownerWritableStream;
        const state = stream2._state;
        if (state === "errored" || state === "erroring") {
          return null;
        }
        if (state === "closed") {
          return 0;
        }
        return WritableStreamDefaultControllerGetDesiredSize(stream2._writableStreamController);
      }
      __name(WritableStreamDefaultWriterGetDesiredSize, "WritableStreamDefaultWriterGetDesiredSize");
      function WritableStreamDefaultWriterRelease(writer) {
        const stream2 = writer._ownerWritableStream;
        const releasedError = new TypeError(`Writer was released and can no longer be used to monitor the stream's closedness`);
        WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, releasedError);
        WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer, releasedError);
        stream2._writer = void 0;
        writer._ownerWritableStream = void 0;
      }
      __name(WritableStreamDefaultWriterRelease, "WritableStreamDefaultWriterRelease");
      function WritableStreamDefaultWriterWrite(writer, chunk) {
        const stream2 = writer._ownerWritableStream;
        const controller = stream2._writableStreamController;
        const chunkSize = WritableStreamDefaultControllerGetChunkSize(controller, chunk);
        if (stream2 !== writer._ownerWritableStream) {
          return promiseRejectedWith(defaultWriterLockException("write to"));
        }
        const state = stream2._state;
        if (state === "errored") {
          return promiseRejectedWith(stream2._storedError);
        }
        if (WritableStreamCloseQueuedOrInFlight(stream2) || state === "closed") {
          return promiseRejectedWith(new TypeError("The stream is closing or closed and cannot be written to"));
        }
        if (state === "erroring") {
          return promiseRejectedWith(stream2._storedError);
        }
        const promise = WritableStreamAddWriteRequest(stream2);
        WritableStreamDefaultControllerWrite(controller, chunk, chunkSize);
        return promise;
      }
      __name(WritableStreamDefaultWriterWrite, "WritableStreamDefaultWriterWrite");
      const closeSentinel = {};
      class WritableStreamDefaultController2 {
        static {
          __name(this, "WritableStreamDefaultController");
        }
        constructor() {
          throw new TypeError("Illegal constructor");
        }
        /**
         * The reason which was passed to `WritableStream.abort(reason)` when the stream was aborted.
         *
         * @deprecated
         *  This property has been removed from the specification, see https://github.com/whatwg/streams/pull/1177.
         *  Use {@link WritableStreamDefaultController.signal}'s `reason` instead.
         */
        get abortReason() {
          if (!IsWritableStreamDefaultController(this)) {
            throw defaultControllerBrandCheckException$2("abortReason");
          }
          return this._abortReason;
        }
        /**
         * An `AbortSignal` that can be used to abort the pending write or close operation when the stream is aborted.
         */
        get signal() {
          if (!IsWritableStreamDefaultController(this)) {
            throw defaultControllerBrandCheckException$2("signal");
          }
          if (this._abortController === void 0) {
            throw new TypeError("WritableStreamDefaultController.prototype.signal is not supported");
          }
          return this._abortController.signal;
        }
        /**
         * Closes the controlled writable stream, making all future interactions with it fail with the given error `e`.
         *
         * This method is rarely used, since usually it suffices to return a rejected promise from one of the underlying
         * sink's methods. However, it can be useful for suddenly shutting down a stream in response to an event outside the
         * normal lifecycle of interactions with the underlying sink.
         */
        error(e4 = void 0) {
          if (!IsWritableStreamDefaultController(this)) {
            throw defaultControllerBrandCheckException$2("error");
          }
          const state = this._controlledWritableStream._state;
          if (state !== "writable") {
            return;
          }
          WritableStreamDefaultControllerError(this, e4);
        }
        /** @internal */
        [AbortSteps](reason) {
          const result = this._abortAlgorithm(reason);
          WritableStreamDefaultControllerClearAlgorithms(this);
          return result;
        }
        /** @internal */
        [ErrorSteps]() {
          ResetQueue(this);
        }
      }
      Object.defineProperties(WritableStreamDefaultController2.prototype, {
        abortReason: { enumerable: true },
        signal: { enumerable: true },
        error: { enumerable: true }
      });
      if (typeof Symbol.toStringTag === "symbol") {
        Object.defineProperty(WritableStreamDefaultController2.prototype, Symbol.toStringTag, {
          value: "WritableStreamDefaultController",
          configurable: true
        });
      }
      function IsWritableStreamDefaultController(x3) {
        if (!typeIsObject(x3)) {
          return false;
        }
        if (!Object.prototype.hasOwnProperty.call(x3, "_controlledWritableStream")) {
          return false;
        }
        return x3 instanceof WritableStreamDefaultController2;
      }
      __name(IsWritableStreamDefaultController, "IsWritableStreamDefaultController");
      function SetUpWritableStreamDefaultController(stream2, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm) {
        controller._controlledWritableStream = stream2;
        stream2._writableStreamController = controller;
        controller._queue = void 0;
        controller._queueTotalSize = void 0;
        ResetQueue(controller);
        controller._abortReason = void 0;
        controller._abortController = createAbortController();
        controller._started = false;
        controller._strategySizeAlgorithm = sizeAlgorithm;
        controller._strategyHWM = highWaterMark;
        controller._writeAlgorithm = writeAlgorithm;
        controller._closeAlgorithm = closeAlgorithm;
        controller._abortAlgorithm = abortAlgorithm;
        const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);
        WritableStreamUpdateBackpressure(stream2, backpressure);
        const startResult = startAlgorithm();
        const startPromise = promiseResolvedWith(startResult);
        uponPromise(startPromise, () => {
          controller._started = true;
          WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);
          return null;
        }, (r5) => {
          controller._started = true;
          WritableStreamDealWithRejection(stream2, r5);
          return null;
        });
      }
      __name(SetUpWritableStreamDefaultController, "SetUpWritableStreamDefaultController");
      function SetUpWritableStreamDefaultControllerFromUnderlyingSink(stream2, underlyingSink, highWaterMark, sizeAlgorithm) {
        const controller = Object.create(WritableStreamDefaultController2.prototype);
        let startAlgorithm;
        let writeAlgorithm;
        let closeAlgorithm;
        let abortAlgorithm;
        if (underlyingSink.start !== void 0) {
          startAlgorithm = /* @__PURE__ */ __name(() => underlyingSink.start(controller), "startAlgorithm");
        } else {
          startAlgorithm = /* @__PURE__ */ __name(() => void 0, "startAlgorithm");
        }
        if (underlyingSink.write !== void 0) {
          writeAlgorithm = /* @__PURE__ */ __name((chunk) => underlyingSink.write(chunk, controller), "writeAlgorithm");
        } else {
          writeAlgorithm = /* @__PURE__ */ __name(() => promiseResolvedWith(void 0), "writeAlgorithm");
        }
        if (underlyingSink.close !== void 0) {
          closeAlgorithm = /* @__PURE__ */ __name(() => underlyingSink.close(), "closeAlgorithm");
        } else {
          closeAlgorithm = /* @__PURE__ */ __name(() => promiseResolvedWith(void 0), "closeAlgorithm");
        }
        if (underlyingSink.abort !== void 0) {
          abortAlgorithm = /* @__PURE__ */ __name((reason) => underlyingSink.abort(reason), "abortAlgorithm");
        } else {
          abortAlgorithm = /* @__PURE__ */ __name(() => promiseResolvedWith(void 0), "abortAlgorithm");
        }
        SetUpWritableStreamDefaultController(stream2, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm);
      }
      __name(SetUpWritableStreamDefaultControllerFromUnderlyingSink, "SetUpWritableStreamDefaultControllerFromUnderlyingSink");
      function WritableStreamDefaultControllerClearAlgorithms(controller) {
        controller._writeAlgorithm = void 0;
        controller._closeAlgorithm = void 0;
        controller._abortAlgorithm = void 0;
        controller._strategySizeAlgorithm = void 0;
      }
      __name(WritableStreamDefaultControllerClearAlgorithms, "WritableStreamDefaultControllerClearAlgorithms");
      function WritableStreamDefaultControllerClose(controller) {
        EnqueueValueWithSize(controller, closeSentinel, 0);
        WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);
      }
      __name(WritableStreamDefaultControllerClose, "WritableStreamDefaultControllerClose");
      function WritableStreamDefaultControllerGetChunkSize(controller, chunk) {
        try {
          return controller._strategySizeAlgorithm(chunk);
        } catch (chunkSizeE) {
          WritableStreamDefaultControllerErrorIfNeeded(controller, chunkSizeE);
          return 1;
        }
      }
      __name(WritableStreamDefaultControllerGetChunkSize, "WritableStreamDefaultControllerGetChunkSize");
      function WritableStreamDefaultControllerGetDesiredSize(controller) {
        return controller._strategyHWM - controller._queueTotalSize;
      }
      __name(WritableStreamDefaultControllerGetDesiredSize, "WritableStreamDefaultControllerGetDesiredSize");
      function WritableStreamDefaultControllerWrite(controller, chunk, chunkSize) {
        try {
          EnqueueValueWithSize(controller, chunk, chunkSize);
        } catch (enqueueE) {
          WritableStreamDefaultControllerErrorIfNeeded(controller, enqueueE);
          return;
        }
        const stream2 = controller._controlledWritableStream;
        if (!WritableStreamCloseQueuedOrInFlight(stream2) && stream2._state === "writable") {
          const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);
          WritableStreamUpdateBackpressure(stream2, backpressure);
        }
        WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);
      }
      __name(WritableStreamDefaultControllerWrite, "WritableStreamDefaultControllerWrite");
      function WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller) {
        const stream2 = controller._controlledWritableStream;
        if (!controller._started) {
          return;
        }
        if (stream2._inFlightWriteRequest !== void 0) {
          return;
        }
        const state = stream2._state;
        if (state === "erroring") {
          WritableStreamFinishErroring(stream2);
          return;
        }
        if (controller._queue.length === 0) {
          return;
        }
        const value = PeekQueueValue(controller);
        if (value === closeSentinel) {
          WritableStreamDefaultControllerProcessClose(controller);
        } else {
          WritableStreamDefaultControllerProcessWrite(controller, value);
        }
      }
      __name(WritableStreamDefaultControllerAdvanceQueueIfNeeded, "WritableStreamDefaultControllerAdvanceQueueIfNeeded");
      function WritableStreamDefaultControllerErrorIfNeeded(controller, error2) {
        if (controller._controlledWritableStream._state === "writable") {
          WritableStreamDefaultControllerError(controller, error2);
        }
      }
      __name(WritableStreamDefaultControllerErrorIfNeeded, "WritableStreamDefaultControllerErrorIfNeeded");
      function WritableStreamDefaultControllerProcessClose(controller) {
        const stream2 = controller._controlledWritableStream;
        WritableStreamMarkCloseRequestInFlight(stream2);
        DequeueValue(controller);
        const sinkClosePromise = controller._closeAlgorithm();
        WritableStreamDefaultControllerClearAlgorithms(controller);
        uponPromise(sinkClosePromise, () => {
          WritableStreamFinishInFlightClose(stream2);
          return null;
        }, (reason) => {
          WritableStreamFinishInFlightCloseWithError(stream2, reason);
          return null;
        });
      }
      __name(WritableStreamDefaultControllerProcessClose, "WritableStreamDefaultControllerProcessClose");
      function WritableStreamDefaultControllerProcessWrite(controller, chunk) {
        const stream2 = controller._controlledWritableStream;
        WritableStreamMarkFirstWriteRequestInFlight(stream2);
        const sinkWritePromise = controller._writeAlgorithm(chunk);
        uponPromise(sinkWritePromise, () => {
          WritableStreamFinishInFlightWrite(stream2);
          const state = stream2._state;
          DequeueValue(controller);
          if (!WritableStreamCloseQueuedOrInFlight(stream2) && state === "writable") {
            const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);
            WritableStreamUpdateBackpressure(stream2, backpressure);
          }
          WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);
          return null;
        }, (reason) => {
          if (stream2._state === "writable") {
            WritableStreamDefaultControllerClearAlgorithms(controller);
          }
          WritableStreamFinishInFlightWriteWithError(stream2, reason);
          return null;
        });
      }
      __name(WritableStreamDefaultControllerProcessWrite, "WritableStreamDefaultControllerProcessWrite");
      function WritableStreamDefaultControllerGetBackpressure(controller) {
        const desiredSize = WritableStreamDefaultControllerGetDesiredSize(controller);
        return desiredSize <= 0;
      }
      __name(WritableStreamDefaultControllerGetBackpressure, "WritableStreamDefaultControllerGetBackpressure");
      function WritableStreamDefaultControllerError(controller, error2) {
        const stream2 = controller._controlledWritableStream;
        WritableStreamDefaultControllerClearAlgorithms(controller);
        WritableStreamStartErroring(stream2, error2);
      }
      __name(WritableStreamDefaultControllerError, "WritableStreamDefaultControllerError");
      function streamBrandCheckException$2(name3) {
        return new TypeError(`WritableStream.prototype.${name3} can only be used on a WritableStream`);
      }
      __name(streamBrandCheckException$2, "streamBrandCheckException$2");
      function defaultControllerBrandCheckException$2(name3) {
        return new TypeError(`WritableStreamDefaultController.prototype.${name3} can only be used on a WritableStreamDefaultController`);
      }
      __name(defaultControllerBrandCheckException$2, "defaultControllerBrandCheckException$2");
      function defaultWriterBrandCheckException(name3) {
        return new TypeError(`WritableStreamDefaultWriter.prototype.${name3} can only be used on a WritableStreamDefaultWriter`);
      }
      __name(defaultWriterBrandCheckException, "defaultWriterBrandCheckException");
      function defaultWriterLockException(name3) {
        return new TypeError("Cannot " + name3 + " a stream using a released writer");
      }
      __name(defaultWriterLockException, "defaultWriterLockException");
      function defaultWriterClosedPromiseInitialize(writer) {
        writer._closedPromise = newPromise((resolve30, reject) => {
          writer._closedPromise_resolve = resolve30;
          writer._closedPromise_reject = reject;
          writer._closedPromiseState = "pending";
        });
      }
      __name(defaultWriterClosedPromiseInitialize, "defaultWriterClosedPromiseInitialize");
      function defaultWriterClosedPromiseInitializeAsRejected(writer, reason) {
        defaultWriterClosedPromiseInitialize(writer);
        defaultWriterClosedPromiseReject(writer, reason);
      }
      __name(defaultWriterClosedPromiseInitializeAsRejected, "defaultWriterClosedPromiseInitializeAsRejected");
      function defaultWriterClosedPromiseInitializeAsResolved(writer) {
        defaultWriterClosedPromiseInitialize(writer);
        defaultWriterClosedPromiseResolve(writer);
      }
      __name(defaultWriterClosedPromiseInitializeAsResolved, "defaultWriterClosedPromiseInitializeAsResolved");
      function defaultWriterClosedPromiseReject(writer, reason) {
        if (writer._closedPromise_reject === void 0) {
          return;
        }
        setPromiseIsHandledToTrue(writer._closedPromise);
        writer._closedPromise_reject(reason);
        writer._closedPromise_resolve = void 0;
        writer._closedPromise_reject = void 0;
        writer._closedPromiseState = "rejected";
      }
      __name(defaultWriterClosedPromiseReject, "defaultWriterClosedPromiseReject");
      function defaultWriterClosedPromiseResetToRejected(writer, reason) {
        defaultWriterClosedPromiseInitializeAsRejected(writer, reason);
      }
      __name(defaultWriterClosedPromiseResetToRejected, "defaultWriterClosedPromiseResetToRejected");
      function defaultWriterClosedPromiseResolve(writer) {
        if (writer._closedPromise_resolve === void 0) {
          return;
        }
        writer._closedPromise_resolve(void 0);
        writer._closedPromise_resolve = void 0;
        writer._closedPromise_reject = void 0;
        writer._closedPromiseState = "resolved";
      }
      __name(defaultWriterClosedPromiseResolve, "defaultWriterClosedPromiseResolve");
      function defaultWriterReadyPromiseInitialize(writer) {
        writer._readyPromise = newPromise((resolve30, reject) => {
          writer._readyPromise_resolve = resolve30;
          writer._readyPromise_reject = reject;
        });
        writer._readyPromiseState = "pending";
      }
      __name(defaultWriterReadyPromiseInitialize, "defaultWriterReadyPromiseInitialize");
      function defaultWriterReadyPromiseInitializeAsRejected(writer, reason) {
        defaultWriterReadyPromiseInitialize(writer);
        defaultWriterReadyPromiseReject(writer, reason);
      }
      __name(defaultWriterReadyPromiseInitializeAsRejected, "defaultWriterReadyPromiseInitializeAsRejected");
      function defaultWriterReadyPromiseInitializeAsResolved(writer) {
        defaultWriterReadyPromiseInitialize(writer);
        defaultWriterReadyPromiseResolve(writer);
      }
      __name(defaultWriterReadyPromiseInitializeAsResolved, "defaultWriterReadyPromiseInitializeAsResolved");
      function defaultWriterReadyPromiseReject(writer, reason) {
        if (writer._readyPromise_reject === void 0) {
          return;
        }
        setPromiseIsHandledToTrue(writer._readyPromise);
        writer._readyPromise_reject(reason);
        writer._readyPromise_resolve = void 0;
        writer._readyPromise_reject = void 0;
        writer._readyPromiseState = "rejected";
      }
      __name(defaultWriterReadyPromiseReject, "defaultWriterReadyPromiseReject");
      function defaultWriterReadyPromiseReset(writer) {
        defaultWriterReadyPromiseInitialize(writer);
      }
      __name(defaultWriterReadyPromiseReset, "defaultWriterReadyPromiseReset");
      function defaultWriterReadyPromiseResetToRejected(writer, reason) {
        defaultWriterReadyPromiseInitializeAsRejected(writer, reason);
      }
      __name(defaultWriterReadyPromiseResetToRejected, "defaultWriterReadyPromiseResetToRejected");
      function defaultWriterReadyPromiseResolve(writer) {
        if (writer._readyPromise_resolve === void 0) {
          return;
        }
        writer._readyPromise_resolve(void 0);
        writer._readyPromise_resolve = void 0;
        writer._readyPromise_reject = void 0;
        writer._readyPromiseState = "fulfilled";
      }
      __name(defaultWriterReadyPromiseResolve, "defaultWriterReadyPromiseResolve");
      function getGlobals() {
        if (typeof globalThis !== "undefined") {
          return globalThis;
        } else if (typeof self !== "undefined") {
          return self;
        } else if (typeof globalThis !== "undefined") {
          return globalThis;
        }
        return void 0;
      }
      __name(getGlobals, "getGlobals");
      const globals = getGlobals();
      function isDOMExceptionConstructor(ctor) {
        if (!(typeof ctor === "function" || typeof ctor === "object")) {
          return false;
        }
        if (ctor.name !== "DOMException") {
          return false;
        }
        try {
          new ctor();
          return true;
        } catch (_a8) {
          return false;
        }
      }
      __name(isDOMExceptionConstructor, "isDOMExceptionConstructor");
      function getFromGlobal() {
        const ctor = globals === null || globals === void 0 ? void 0 : globals.DOMException;
        return isDOMExceptionConstructor(ctor) ? ctor : void 0;
      }
      __name(getFromGlobal, "getFromGlobal");
      function createPolyfill() {
        const ctor = /* @__PURE__ */ __name(function DOMException5(message, name3) {
          this.message = message || "";
          this.name = name3 || "Error";
          if (Error.captureStackTrace) {
            Error.captureStackTrace(this, this.constructor);
          }
        }, "DOMException");
        setFunctionName(ctor, "DOMException");
        ctor.prototype = Object.create(Error.prototype);
        Object.defineProperty(ctor.prototype, "constructor", { value: ctor, writable: true, configurable: true });
        return ctor;
      }
      __name(createPolyfill, "createPolyfill");
      const DOMException4 = getFromGlobal() || createPolyfill();
      function ReadableStreamPipeTo(source2, dest, preventClose, preventAbort, preventCancel, signal) {
        const reader = AcquireReadableStreamDefaultReader(source2);
        const writer = AcquireWritableStreamDefaultWriter(dest);
        source2._disturbed = true;
        let shuttingDown = false;
        let currentWrite = promiseResolvedWith(void 0);
        return newPromise((resolve30, reject) => {
          let abortAlgorithm;
          if (signal !== void 0) {
            abortAlgorithm = /* @__PURE__ */ __name(() => {
              const error2 = signal.reason !== void 0 ? signal.reason : new DOMException4("Aborted", "AbortError");
              const actions = [];
              if (!preventAbort) {
                actions.push(() => {
                  if (dest._state === "writable") {
                    return WritableStreamAbort(dest, error2);
                  }
                  return promiseResolvedWith(void 0);
                });
              }
              if (!preventCancel) {
                actions.push(() => {
                  if (source2._state === "readable") {
                    return ReadableStreamCancel(source2, error2);
                  }
                  return promiseResolvedWith(void 0);
                });
              }
              shutdownWithAction(() => Promise.all(actions.map((action) => action())), true, error2);
            }, "abortAlgorithm");
            if (signal.aborted) {
              abortAlgorithm();
              return;
            }
            signal.addEventListener("abort", abortAlgorithm);
          }
          function pipeLoop() {
            return newPromise((resolveLoop, rejectLoop) => {
              function next(done) {
                if (done) {
                  resolveLoop();
                } else {
                  PerformPromiseThen(pipeStep(), next, rejectLoop);
                }
              }
              __name(next, "next");
              next(false);
            });
          }
          __name(pipeLoop, "pipeLoop");
          function pipeStep() {
            if (shuttingDown) {
              return promiseResolvedWith(true);
            }
            return PerformPromiseThen(writer._readyPromise, () => {
              return newPromise((resolveRead, rejectRead) => {
                ReadableStreamDefaultReaderRead(reader, {
                  _chunkSteps: /* @__PURE__ */ __name((chunk) => {
                    currentWrite = PerformPromiseThen(WritableStreamDefaultWriterWrite(writer, chunk), void 0, noop8);
                    resolveRead(false);
                  }, "_chunkSteps"),
                  _closeSteps: /* @__PURE__ */ __name(() => resolveRead(true), "_closeSteps"),
                  _errorSteps: rejectRead
                });
              });
            });
          }
          __name(pipeStep, "pipeStep");
          isOrBecomesErrored(source2, reader._closedPromise, (storedError) => {
            if (!preventAbort) {
              shutdownWithAction(() => WritableStreamAbort(dest, storedError), true, storedError);
            } else {
              shutdown(true, storedError);
            }
            return null;
          });
          isOrBecomesErrored(dest, writer._closedPromise, (storedError) => {
            if (!preventCancel) {
              shutdownWithAction(() => ReadableStreamCancel(source2, storedError), true, storedError);
            } else {
              shutdown(true, storedError);
            }
            return null;
          });
          isOrBecomesClosed(source2, reader._closedPromise, () => {
            if (!preventClose) {
              shutdownWithAction(() => WritableStreamDefaultWriterCloseWithErrorPropagation(writer));
            } else {
              shutdown();
            }
            return null;
          });
          if (WritableStreamCloseQueuedOrInFlight(dest) || dest._state === "closed") {
            const destClosed = new TypeError("the destination writable stream closed before all data could be piped to it");
            if (!preventCancel) {
              shutdownWithAction(() => ReadableStreamCancel(source2, destClosed), true, destClosed);
            } else {
              shutdown(true, destClosed);
            }
          }
          setPromiseIsHandledToTrue(pipeLoop());
          function waitForWritesToFinish() {
            const oldCurrentWrite = currentWrite;
            return PerformPromiseThen(currentWrite, () => oldCurrentWrite !== currentWrite ? waitForWritesToFinish() : void 0);
          }
          __name(waitForWritesToFinish, "waitForWritesToFinish");
          function isOrBecomesErrored(stream2, promise, action) {
            if (stream2._state === "errored") {
              action(stream2._storedError);
            } else {
              uponRejection(promise, action);
            }
          }
          __name(isOrBecomesErrored, "isOrBecomesErrored");
          function isOrBecomesClosed(stream2, promise, action) {
            if (stream2._state === "closed") {
              action();
            } else {
              uponFulfillment(promise, action);
            }
          }
          __name(isOrBecomesClosed, "isOrBecomesClosed");
          function shutdownWithAction(action, originalIsError, originalError) {
            if (shuttingDown) {
              return;
            }
            shuttingDown = true;
            if (dest._state === "writable" && !WritableStreamCloseQueuedOrInFlight(dest)) {
              uponFulfillment(waitForWritesToFinish(), doTheRest);
            } else {
              doTheRest();
            }
            function doTheRest() {
              uponPromise(action(), () => finalize(originalIsError, originalError), (newError) => finalize(true, newError));
              return null;
            }
            __name(doTheRest, "doTheRest");
          }
          __name(shutdownWithAction, "shutdownWithAction");
          function shutdown(isError, error2) {
            if (shuttingDown) {
              return;
            }
            shuttingDown = true;
            if (dest._state === "writable" && !WritableStreamCloseQueuedOrInFlight(dest)) {
              uponFulfillment(waitForWritesToFinish(), () => finalize(isError, error2));
            } else {
              finalize(isError, error2);
            }
          }
          __name(shutdown, "shutdown");
          function finalize(isError, error2) {
            WritableStreamDefaultWriterRelease(writer);
            ReadableStreamReaderGenericRelease(reader);
            if (signal !== void 0) {
              signal.removeEventListener("abort", abortAlgorithm);
            }
            if (isError) {
              reject(error2);
            } else {
              resolve30(void 0);
            }
            return null;
          }
          __name(finalize, "finalize");
        });
      }
      __name(ReadableStreamPipeTo, "ReadableStreamPipeTo");
      class ReadableStreamDefaultController2 {
        static {
          __name(this, "ReadableStreamDefaultController");
        }
        constructor() {
          throw new TypeError("Illegal constructor");
        }
        /**
         * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is
         * over-full. An underlying source ought to use this information to determine when and how to apply backpressure.
         */
        get desiredSize() {
          if (!IsReadableStreamDefaultController(this)) {
            throw defaultControllerBrandCheckException$1("desiredSize");
          }
          return ReadableStreamDefaultControllerGetDesiredSize(this);
        }
        /**
         * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from
         * the stream, but once those are read, the stream will become closed.
         */
        close() {
          if (!IsReadableStreamDefaultController(this)) {
            throw defaultControllerBrandCheckException$1("close");
          }
          if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) {
            throw new TypeError("The stream is not in a state that permits close");
          }
          ReadableStreamDefaultControllerClose(this);
        }
        enqueue(chunk = void 0) {
          if (!IsReadableStreamDefaultController(this)) {
            throw defaultControllerBrandCheckException$1("enqueue");
          }
          if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) {
            throw new TypeError("The stream is not in a state that permits enqueue");
          }
          return ReadableStreamDefaultControllerEnqueue(this, chunk);
        }
        /**
         * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`.
         */
        error(e4 = void 0) {
          if (!IsReadableStreamDefaultController(this)) {
            throw defaultControllerBrandCheckException$1("error");
          }
          ReadableStreamDefaultControllerError(this, e4);
        }
        /** @internal */
        [CancelSteps](reason) {
          ResetQueue(this);
          const result = this._cancelAlgorithm(reason);
          ReadableStreamDefaultControllerClearAlgorithms(this);
          return result;
        }
        /** @internal */
        [PullSteps](readRequest) {
          const stream2 = this._controlledReadableStream;
          if (this._queue.length > 0) {
            const chunk = DequeueValue(this);
            if (this._closeRequested && this._queue.length === 0) {
              ReadableStreamDefaultControllerClearAlgorithms(this);
              ReadableStreamClose(stream2);
            } else {
              ReadableStreamDefaultControllerCallPullIfNeeded(this);
            }
            readRequest._chunkSteps(chunk);
          } else {
            ReadableStreamAddReadRequest(stream2, readRequest);
            ReadableStreamDefaultControllerCallPullIfNeeded(this);
          }
        }
        /** @internal */
        [ReleaseSteps]() {
        }
      }
      Object.defineProperties(ReadableStreamDefaultController2.prototype, {
        close: { enumerable: true },
        enqueue: { enumerable: true },
        error: { enumerable: true },
        desiredSize: { enumerable: true }
      });
      setFunctionName(ReadableStreamDefaultController2.prototype.close, "close");
      setFunctionName(ReadableStreamDefaultController2.prototype.enqueue, "enqueue");
      setFunctionName(ReadableStreamDefaultController2.prototype.error, "error");
      if (typeof Symbol.toStringTag === "symbol") {
        Object.defineProperty(ReadableStreamDefaultController2.prototype, Symbol.toStringTag, {
          value: "ReadableStreamDefaultController",
          configurable: true
        });
      }
      function IsReadableStreamDefaultController(x3) {
        if (!typeIsObject(x3)) {
          return false;
        }
        if (!Object.prototype.hasOwnProperty.call(x3, "_controlledReadableStream")) {
          return false;
        }
        return x3 instanceof ReadableStreamDefaultController2;
      }
      __name(IsReadableStreamDefaultController, "IsReadableStreamDefaultController");
      function ReadableStreamDefaultControllerCallPullIfNeeded(controller) {
        const shouldPull = ReadableStreamDefaultControllerShouldCallPull(controller);
        if (!shouldPull) {
          return;
        }
        if (controller._pulling) {
          controller._pullAgain = true;
          return;
        }
        controller._pulling = true;
        const pullPromise = controller._pullAlgorithm();
        uponPromise(pullPromise, () => {
          controller._pulling = false;
          if (controller._pullAgain) {
            controller._pullAgain = false;
            ReadableStreamDefaultControllerCallPullIfNeeded(controller);
          }
          return null;
        }, (e4) => {
          ReadableStreamDefaultControllerError(controller, e4);
          return null;
        });
      }
      __name(ReadableStreamDefaultControllerCallPullIfNeeded, "ReadableStreamDefaultControllerCallPullIfNeeded");
      function ReadableStreamDefaultControllerShouldCallPull(controller) {
        const stream2 = controller._controlledReadableStream;
        if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) {
          return false;
        }
        if (!controller._started) {
          return false;
        }
        if (IsReadableStreamLocked(stream2) && ReadableStreamGetNumReadRequests(stream2) > 0) {
          return true;
        }
        const desiredSize = ReadableStreamDefaultControllerGetDesiredSize(controller);
        if (desiredSize > 0) {
          return true;
        }
        return false;
      }
      __name(ReadableStreamDefaultControllerShouldCallPull, "ReadableStreamDefaultControllerShouldCallPull");
      function ReadableStreamDefaultControllerClearAlgorithms(controller) {
        controller._pullAlgorithm = void 0;
        controller._cancelAlgorithm = void 0;
        controller._strategySizeAlgorithm = void 0;
      }
      __name(ReadableStreamDefaultControllerClearAlgorithms, "ReadableStreamDefaultControllerClearAlgorithms");
      function ReadableStreamDefaultControllerClose(controller) {
        if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) {
          return;
        }
        const stream2 = controller._controlledReadableStream;
        controller._closeRequested = true;
        if (controller._queue.length === 0) {
          ReadableStreamDefaultControllerClearAlgorithms(controller);
          ReadableStreamClose(stream2);
        }
      }
      __name(ReadableStreamDefaultControllerClose, "ReadableStreamDefaultControllerClose");
      function ReadableStreamDefaultControllerEnqueue(controller, chunk) {
        if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) {
          return;
        }
        const stream2 = controller._controlledReadableStream;
        if (IsReadableStreamLocked(stream2) && ReadableStreamGetNumReadRequests(stream2) > 0) {
          ReadableStreamFulfillReadRequest(stream2, chunk, false);
        } else {
          let chunkSize;
          try {
            chunkSize = controller._strategySizeAlgorithm(chunk);
          } catch (chunkSizeE) {
            ReadableStreamDefaultControllerError(controller, chunkSizeE);
            throw chunkSizeE;
          }
          try {
            EnqueueValueWithSize(controller, chunk, chunkSize);
          } catch (enqueueE) {
            ReadableStreamDefaultControllerError(controller, enqueueE);
            throw enqueueE;
          }
        }
        ReadableStreamDefaultControllerCallPullIfNeeded(controller);
      }
      __name(ReadableStreamDefaultControllerEnqueue, "ReadableStreamDefaultControllerEnqueue");
      function ReadableStreamDefaultControllerError(controller, e4) {
        const stream2 = controller._controlledReadableStream;
        if (stream2._state !== "readable") {
          return;
        }
        ResetQueue(controller);
        ReadableStreamDefaultControllerClearAlgorithms(controller);
        ReadableStreamError(stream2, e4);
      }
      __name(ReadableStreamDefaultControllerError, "ReadableStreamDefaultControllerError");
      function ReadableStreamDefaultControllerGetDesiredSize(controller) {
        const state = controller._controlledReadableStream._state;
        if (state === "errored") {
          return null;
        }
        if (state === "closed") {
          return 0;
        }
        return controller._strategyHWM - controller._queueTotalSize;
      }
      __name(ReadableStreamDefaultControllerGetDesiredSize, "ReadableStreamDefaultControllerGetDesiredSize");
      function ReadableStreamDefaultControllerHasBackpressure(controller) {
        if (ReadableStreamDefaultControllerShouldCallPull(controller)) {
          return false;
        }
        return true;
      }
      __name(ReadableStreamDefaultControllerHasBackpressure, "ReadableStreamDefaultControllerHasBackpressure");
      function ReadableStreamDefaultControllerCanCloseOrEnqueue(controller) {
        const state = controller._controlledReadableStream._state;
        if (!controller._closeRequested && state === "readable") {
          return true;
        }
        return false;
      }
      __name(ReadableStreamDefaultControllerCanCloseOrEnqueue, "ReadableStreamDefaultControllerCanCloseOrEnqueue");
      function SetUpReadableStreamDefaultController(stream2, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm) {
        controller._controlledReadableStream = stream2;
        controller._queue = void 0;
        controller._queueTotalSize = void 0;
        ResetQueue(controller);
        controller._started = false;
        controller._closeRequested = false;
        controller._pullAgain = false;
        controller._pulling = false;
        controller._strategySizeAlgorithm = sizeAlgorithm;
        controller._strategyHWM = highWaterMark;
        controller._pullAlgorithm = pullAlgorithm;
        controller._cancelAlgorithm = cancelAlgorithm;
        stream2._readableStreamController = controller;
        const startResult = startAlgorithm();
        uponPromise(promiseResolvedWith(startResult), () => {
          controller._started = true;
          ReadableStreamDefaultControllerCallPullIfNeeded(controller);
          return null;
        }, (r5) => {
          ReadableStreamDefaultControllerError(controller, r5);
          return null;
        });
      }
      __name(SetUpReadableStreamDefaultController, "SetUpReadableStreamDefaultController");
      function SetUpReadableStreamDefaultControllerFromUnderlyingSource(stream2, underlyingSource, highWaterMark, sizeAlgorithm) {
        const controller = Object.create(ReadableStreamDefaultController2.prototype);
        let startAlgorithm;
        let pullAlgorithm;
        let cancelAlgorithm;
        if (underlyingSource.start !== void 0) {
          startAlgorithm = /* @__PURE__ */ __name(() => underlyingSource.start(controller), "startAlgorithm");
        } else {
          startAlgorithm = /* @__PURE__ */ __name(() => void 0, "startAlgorithm");
        }
        if (underlyingSource.pull !== void 0) {
          pullAlgorithm = /* @__PURE__ */ __name(() => underlyingSource.pull(controller), "pullAlgorithm");
        } else {
          pullAlgorithm = /* @__PURE__ */ __name(() => promiseResolvedWith(void 0), "pullAlgorithm");
        }
        if (underlyingSource.cancel !== void 0) {
          cancelAlgorithm = /* @__PURE__ */ __name((reason) => underlyingSource.cancel(reason), "cancelAlgorithm");
        } else {
          cancelAlgorithm = /* @__PURE__ */ __name(() => promiseResolvedWith(void 0), "cancelAlgorithm");
        }
        SetUpReadableStreamDefaultController(stream2, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm);
      }
      __name(SetUpReadableStreamDefaultControllerFromUnderlyingSource, "SetUpReadableStreamDefaultControllerFromUnderlyingSource");
      function defaultControllerBrandCheckException$1(name3) {
        return new TypeError(`ReadableStreamDefaultController.prototype.${name3} can only be used on a ReadableStreamDefaultController`);
      }
      __name(defaultControllerBrandCheckException$1, "defaultControllerBrandCheckException$1");
      function ReadableStreamTee(stream2, cloneForBranch2) {
        if (IsReadableByteStreamController(stream2._readableStreamController)) {
          return ReadableByteStreamTee(stream2);
        }
        return ReadableStreamDefaultTee(stream2);
      }
      __name(ReadableStreamTee, "ReadableStreamTee");
      function ReadableStreamDefaultTee(stream2, cloneForBranch2) {
        const reader = AcquireReadableStreamDefaultReader(stream2);
        let reading = false;
        let readAgain = false;
        let canceled1 = false;
        let canceled2 = false;
        let reason1;
        let reason2;
        let branch1;
        let branch2;
        let resolveCancelPromise;
        const cancelPromise = newPromise((resolve30) => {
          resolveCancelPromise = resolve30;
        });
        function pullAlgorithm() {
          if (reading) {
            readAgain = true;
            return promiseResolvedWith(void 0);
          }
          reading = true;
          const readRequest = {
            _chunkSteps: /* @__PURE__ */ __name((chunk) => {
              _queueMicrotask(() => {
                readAgain = false;
                const chunk1 = chunk;
                const chunk2 = chunk;
                if (!canceled1) {
                  ReadableStreamDefaultControllerEnqueue(branch1._readableStreamController, chunk1);
                }
                if (!canceled2) {
                  ReadableStreamDefaultControllerEnqueue(branch2._readableStreamController, chunk2);
                }
                reading = false;
                if (readAgain) {
                  pullAlgorithm();
                }
              });
            }, "_chunkSteps"),
            _closeSteps: /* @__PURE__ */ __name(() => {
              reading = false;
              if (!canceled1) {
                ReadableStreamDefaultControllerClose(branch1._readableStreamController);
              }
              if (!canceled2) {
                ReadableStreamDefaultControllerClose(branch2._readableStreamController);
              }
              if (!canceled1 || !canceled2) {
                resolveCancelPromise(void 0);
              }
            }, "_closeSteps"),
            _errorSteps: /* @__PURE__ */ __name(() => {
              reading = false;
            }, "_errorSteps")
          };
          ReadableStreamDefaultReaderRead(reader, readRequest);
          return promiseResolvedWith(void 0);
        }
        __name(pullAlgorithm, "pullAlgorithm");
        function cancel1Algorithm(reason) {
          canceled1 = true;
          reason1 = reason;
          if (canceled2) {
            const compositeReason = CreateArrayFromList([reason1, reason2]);
            const cancelResult = ReadableStreamCancel(stream2, compositeReason);
            resolveCancelPromise(cancelResult);
          }
          return cancelPromise;
        }
        __name(cancel1Algorithm, "cancel1Algorithm");
        function cancel2Algorithm(reason) {
          canceled2 = true;
          reason2 = reason;
          if (canceled1) {
            const compositeReason = CreateArrayFromList([reason1, reason2]);
            const cancelResult = ReadableStreamCancel(stream2, compositeReason);
            resolveCancelPromise(cancelResult);
          }
          return cancelPromise;
        }
        __name(cancel2Algorithm, "cancel2Algorithm");
        function startAlgorithm() {
        }
        __name(startAlgorithm, "startAlgorithm");
        branch1 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel1Algorithm);
        branch2 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel2Algorithm);
        uponRejection(reader._closedPromise, (r5) => {
          ReadableStreamDefaultControllerError(branch1._readableStreamController, r5);
          ReadableStreamDefaultControllerError(branch2._readableStreamController, r5);
          if (!canceled1 || !canceled2) {
            resolveCancelPromise(void 0);
          }
          return null;
        });
        return [branch1, branch2];
      }
      __name(ReadableStreamDefaultTee, "ReadableStreamDefaultTee");
      function ReadableByteStreamTee(stream2) {
        let reader = AcquireReadableStreamDefaultReader(stream2);
        let reading = false;
        let readAgainForBranch1 = false;
        let readAgainForBranch2 = false;
        let canceled1 = false;
        let canceled2 = false;
        let reason1;
        let reason2;
        let branch1;
        let branch2;
        let resolveCancelPromise;
        const cancelPromise = newPromise((resolve30) => {
          resolveCancelPromise = resolve30;
        });
        function forwardReaderError(thisReader) {
          uponRejection(thisReader._closedPromise, (r5) => {
            if (thisReader !== reader) {
              return null;
            }
            ReadableByteStreamControllerError(branch1._readableStreamController, r5);
            ReadableByteStreamControllerError(branch2._readableStreamController, r5);
            if (!canceled1 || !canceled2) {
              resolveCancelPromise(void 0);
            }
            return null;
          });
        }
        __name(forwardReaderError, "forwardReaderError");
        function pullWithDefaultReader() {
          if (IsReadableStreamBYOBReader(reader)) {
            ReadableStreamReaderGenericRelease(reader);
            reader = AcquireReadableStreamDefaultReader(stream2);
            forwardReaderError(reader);
          }
          const readRequest = {
            _chunkSteps: /* @__PURE__ */ __name((chunk) => {
              _queueMicrotask(() => {
                readAgainForBranch1 = false;
                readAgainForBranch2 = false;
                const chunk1 = chunk;
                let chunk2 = chunk;
                if (!canceled1 && !canceled2) {
                  try {
                    chunk2 = CloneAsUint8Array(chunk);
                  } catch (cloneE) {
                    ReadableByteStreamControllerError(branch1._readableStreamController, cloneE);
                    ReadableByteStreamControllerError(branch2._readableStreamController, cloneE);
                    resolveCancelPromise(ReadableStreamCancel(stream2, cloneE));
                    return;
                  }
                }
                if (!canceled1) {
                  ReadableByteStreamControllerEnqueue(branch1._readableStreamController, chunk1);
                }
                if (!canceled2) {
                  ReadableByteStreamControllerEnqueue(branch2._readableStreamController, chunk2);
                }
                reading = false;
                if (readAgainForBranch1) {
                  pull1Algorithm();
                } else if (readAgainForBranch2) {
                  pull2Algorithm();
                }
              });
            }, "_chunkSteps"),
            _closeSteps: /* @__PURE__ */ __name(() => {
              reading = false;
              if (!canceled1) {
                ReadableByteStreamControllerClose(branch1._readableStreamController);
              }
              if (!canceled2) {
                ReadableByteStreamControllerClose(branch2._readableStreamController);
              }
              if (branch1._readableStreamController._pendingPullIntos.length > 0) {
                ReadableByteStreamControllerRespond(branch1._readableStreamController, 0);
              }
              if (branch2._readableStreamController._pendingPullIntos.length > 0) {
                ReadableByteStreamControllerRespond(branch2._readableStreamController, 0);
              }
              if (!canceled1 || !canceled2) {
                resolveCancelPromise(void 0);
              }
            }, "_closeSteps"),
            _errorSteps: /* @__PURE__ */ __name(() => {
              reading = false;
            }, "_errorSteps")
          };
          ReadableStreamDefaultReaderRead(reader, readRequest);
        }
        __name(pullWithDefaultReader, "pullWithDefaultReader");
        function pullWithBYOBReader(view, forBranch2) {
          if (IsReadableStreamDefaultReader(reader)) {
            ReadableStreamReaderGenericRelease(reader);
            reader = AcquireReadableStreamBYOBReader(stream2);
            forwardReaderError(reader);
          }
          const byobBranch = forBranch2 ? branch2 : branch1;
          const otherBranch = forBranch2 ? branch1 : branch2;
          const readIntoRequest = {
            _chunkSteps: /* @__PURE__ */ __name((chunk) => {
              _queueMicrotask(() => {
                readAgainForBranch1 = false;
                readAgainForBranch2 = false;
                const byobCanceled = forBranch2 ? canceled2 : canceled1;
                const otherCanceled = forBranch2 ? canceled1 : canceled2;
                if (!otherCanceled) {
                  let clonedChunk;
                  try {
                    clonedChunk = CloneAsUint8Array(chunk);
                  } catch (cloneE) {
                    ReadableByteStreamControllerError(byobBranch._readableStreamController, cloneE);
                    ReadableByteStreamControllerError(otherBranch._readableStreamController, cloneE);
                    resolveCancelPromise(ReadableStreamCancel(stream2, cloneE));
                    return;
                  }
                  if (!byobCanceled) {
                    ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk);
                  }
                  ReadableByteStreamControllerEnqueue(otherBranch._readableStreamController, clonedChunk);
                } else if (!byobCanceled) {
                  ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk);
                }
                reading = false;
                if (readAgainForBranch1) {
                  pull1Algorithm();
                } else if (readAgainForBranch2) {
                  pull2Algorithm();
                }
              });
            }, "_chunkSteps"),
            _closeSteps: /* @__PURE__ */ __name((chunk) => {
              reading = false;
              const byobCanceled = forBranch2 ? canceled2 : canceled1;
              const otherCanceled = forBranch2 ? canceled1 : canceled2;
              if (!byobCanceled) {
                ReadableByteStreamControllerClose(byobBranch._readableStreamController);
              }
              if (!otherCanceled) {
                ReadableByteStreamControllerClose(otherBranch._readableStreamController);
              }
              if (chunk !== void 0) {
                if (!byobCanceled) {
                  ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk);
                }
                if (!otherCanceled && otherBranch._readableStreamController._pendingPullIntos.length > 0) {
                  ReadableByteStreamControllerRespond(otherBranch._readableStreamController, 0);
                }
              }
              if (!byobCanceled || !otherCanceled) {
                resolveCancelPromise(void 0);
              }
            }, "_closeSteps"),
            _errorSteps: /* @__PURE__ */ __name(() => {
              reading = false;
            }, "_errorSteps")
          };
          ReadableStreamBYOBReaderRead(reader, view, 1, readIntoRequest);
        }
        __name(pullWithBYOBReader, "pullWithBYOBReader");
        function pull1Algorithm() {
          if (reading) {
            readAgainForBranch1 = true;
            return promiseResolvedWith(void 0);
          }
          reading = true;
          const byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch1._readableStreamController);
          if (byobRequest === null) {
            pullWithDefaultReader();
          } else {
            pullWithBYOBReader(byobRequest._view, false);
          }
          return promiseResolvedWith(void 0);
        }
        __name(pull1Algorithm, "pull1Algorithm");
        function pull2Algorithm() {
          if (reading) {
            readAgainForBranch2 = true;
            return promiseResolvedWith(void 0);
          }
          reading = true;
          const byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch2._readableStreamController);
          if (byobRequest === null) {
            pullWithDefaultReader();
          } else {
            pullWithBYOBReader(byobRequest._view, true);
          }
          return promiseResolvedWith(void 0);
        }
        __name(pull2Algorithm, "pull2Algorithm");
        function cancel1Algorithm(reason) {
          canceled1 = true;
          reason1 = reason;
          if (canceled2) {
            const compositeReason = CreateArrayFromList([reason1, reason2]);
            const cancelResult = ReadableStreamCancel(stream2, compositeReason);
            resolveCancelPromise(cancelResult);
          }
          return cancelPromise;
        }
        __name(cancel1Algorithm, "cancel1Algorithm");
        function cancel2Algorithm(reason) {
          canceled2 = true;
          reason2 = reason;
          if (canceled1) {
            const compositeReason = CreateArrayFromList([reason1, reason2]);
            const cancelResult = ReadableStreamCancel(stream2, compositeReason);
            resolveCancelPromise(cancelResult);
          }
          return cancelPromise;
        }
        __name(cancel2Algorithm, "cancel2Algorithm");
        function startAlgorithm() {
          return;
        }
        __name(startAlgorithm, "startAlgorithm");
        branch1 = CreateReadableByteStream(startAlgorithm, pull1Algorithm, cancel1Algorithm);
        branch2 = CreateReadableByteStream(startAlgorithm, pull2Algorithm, cancel2Algorithm);
        forwardReaderError(reader);
        return [branch1, branch2];
      }
      __name(ReadableByteStreamTee, "ReadableByteStreamTee");
      function isReadableStreamLike(stream2) {
        return typeIsObject(stream2) && typeof stream2.getReader !== "undefined";
      }
      __name(isReadableStreamLike, "isReadableStreamLike");
      function ReadableStreamFrom2(source2) {
        if (isReadableStreamLike(source2)) {
          return ReadableStreamFromDefaultReader(source2.getReader());
        }
        return ReadableStreamFromIterable(source2);
      }
      __name(ReadableStreamFrom2, "ReadableStreamFrom");
      function ReadableStreamFromIterable(asyncIterable) {
        let stream2;
        const iteratorRecord = GetIterator(asyncIterable, "async");
        const startAlgorithm = noop8;
        function pullAlgorithm() {
          let nextResult;
          try {
            nextResult = IteratorNext(iteratorRecord);
          } catch (e4) {
            return promiseRejectedWith(e4);
          }
          const nextPromise = promiseResolvedWith(nextResult);
          return transformPromiseWith(nextPromise, (iterResult) => {
            if (!typeIsObject(iterResult)) {
              throw new TypeError("The promise returned by the iterator.next() method must fulfill with an object");
            }
            const done = IteratorComplete(iterResult);
            if (done) {
              ReadableStreamDefaultControllerClose(stream2._readableStreamController);
            } else {
              const value = IteratorValue(iterResult);
              ReadableStreamDefaultControllerEnqueue(stream2._readableStreamController, value);
            }
          });
        }
        __name(pullAlgorithm, "pullAlgorithm");
        function cancelAlgorithm(reason) {
          const iterator = iteratorRecord.iterator;
          let returnMethod;
          try {
            returnMethod = GetMethod(iterator, "return");
          } catch (e4) {
            return promiseRejectedWith(e4);
          }
          if (returnMethod === void 0) {
            return promiseResolvedWith(void 0);
          }
          let returnResult;
          try {
            returnResult = reflectCall(returnMethod, iterator, [reason]);
          } catch (e4) {
            return promiseRejectedWith(e4);
          }
          const returnPromise = promiseResolvedWith(returnResult);
          return transformPromiseWith(returnPromise, (iterResult) => {
            if (!typeIsObject(iterResult)) {
              throw new TypeError("The promise returned by the iterator.return() method must fulfill with an object");
            }
            return void 0;
          });
        }
        __name(cancelAlgorithm, "cancelAlgorithm");
        stream2 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, 0);
        return stream2;
      }
      __name(ReadableStreamFromIterable, "ReadableStreamFromIterable");
      function ReadableStreamFromDefaultReader(reader) {
        let stream2;
        const startAlgorithm = noop8;
        function pullAlgorithm() {
          let readPromise;
          try {
            readPromise = reader.read();
          } catch (e4) {
            return promiseRejectedWith(e4);
          }
          return transformPromiseWith(readPromise, (readResult) => {
            if (!typeIsObject(readResult)) {
              throw new TypeError("The promise returned by the reader.read() method must fulfill with an object");
            }
            if (readResult.done) {
              ReadableStreamDefaultControllerClose(stream2._readableStreamController);
            } else {
              const value = readResult.value;
              ReadableStreamDefaultControllerEnqueue(stream2._readableStreamController, value);
            }
          });
        }
        __name(pullAlgorithm, "pullAlgorithm");
        function cancelAlgorithm(reason) {
          try {
            return promiseResolvedWith(reader.cancel(reason));
          } catch (e4) {
            return promiseRejectedWith(e4);
          }
        }
        __name(cancelAlgorithm, "cancelAlgorithm");
        stream2 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, 0);
        return stream2;
      }
      __name(ReadableStreamFromDefaultReader, "ReadableStreamFromDefaultReader");
      function convertUnderlyingDefaultOrByteSource(source2, context2) {
        assertDictionary(source2, context2);
        const original = source2;
        const autoAllocateChunkSize = original === null || original === void 0 ? void 0 : original.autoAllocateChunkSize;
        const cancel = original === null || original === void 0 ? void 0 : original.cancel;
        const pull = original === null || original === void 0 ? void 0 : original.pull;
        const start = original === null || original === void 0 ? void 0 : original.start;
        const type = original === null || original === void 0 ? void 0 : original.type;
        return {
          autoAllocateChunkSize: autoAllocateChunkSize === void 0 ? void 0 : convertUnsignedLongLongWithEnforceRange(autoAllocateChunkSize, `${context2} has member 'autoAllocateChunkSize' that`),
          cancel: cancel === void 0 ? void 0 : convertUnderlyingSourceCancelCallback(cancel, original, `${context2} has member 'cancel' that`),
          pull: pull === void 0 ? void 0 : convertUnderlyingSourcePullCallback(pull, original, `${context2} has member 'pull' that`),
          start: start === void 0 ? void 0 : convertUnderlyingSourceStartCallback(start, original, `${context2} has member 'start' that`),
          type: type === void 0 ? void 0 : convertReadableStreamType(type, `${context2} has member 'type' that`)
        };
      }
      __name(convertUnderlyingDefaultOrByteSource, "convertUnderlyingDefaultOrByteSource");
      function convertUnderlyingSourceCancelCallback(fn, original, context2) {
        assertFunction(fn, context2);
        return (reason) => promiseCall(fn, original, [reason]);
      }
      __name(convertUnderlyingSourceCancelCallback, "convertUnderlyingSourceCancelCallback");
      function convertUnderlyingSourcePullCallback(fn, original, context2) {
        assertFunction(fn, context2);
        return (controller) => promiseCall(fn, original, [controller]);
      }
      __name(convertUnderlyingSourcePullCallback, "convertUnderlyingSourcePullCallback");
      function convertUnderlyingSourceStartCallback(fn, original, context2) {
        assertFunction(fn, context2);
        return (controller) => reflectCall(fn, original, [controller]);
      }
      __name(convertUnderlyingSourceStartCallback, "convertUnderlyingSourceStartCallback");
      function convertReadableStreamType(type, context2) {
        type = `${type}`;
        if (type !== "bytes") {
          throw new TypeError(`${context2} '${type}' is not a valid enumeration value for ReadableStreamType`);
        }
        return type;
      }
      __name(convertReadableStreamType, "convertReadableStreamType");
      function convertIteratorOptions(options2, context2) {
        assertDictionary(options2, context2);
        const preventCancel = options2 === null || options2 === void 0 ? void 0 : options2.preventCancel;
        return { preventCancel: Boolean(preventCancel) };
      }
      __name(convertIteratorOptions, "convertIteratorOptions");
      function convertPipeOptions(options2, context2) {
        assertDictionary(options2, context2);
        const preventAbort = options2 === null || options2 === void 0 ? void 0 : options2.preventAbort;
        const preventCancel = options2 === null || options2 === void 0 ? void 0 : options2.preventCancel;
        const preventClose = options2 === null || options2 === void 0 ? void 0 : options2.preventClose;
        const signal = options2 === null || options2 === void 0 ? void 0 : options2.signal;
        if (signal !== void 0) {
          assertAbortSignal(signal, `${context2} has member 'signal' that`);
        }
        return {
          preventAbort: Boolean(preventAbort),
          preventCancel: Boolean(preventCancel),
          preventClose: Boolean(preventClose),
          signal
        };
      }
      __name(convertPipeOptions, "convertPipeOptions");
      function assertAbortSignal(signal, context2) {
        if (!isAbortSignal3(signal)) {
          throw new TypeError(`${context2} is not an AbortSignal.`);
        }
      }
      __name(assertAbortSignal, "assertAbortSignal");
      function convertReadableWritablePair(pair, context2) {
        assertDictionary(pair, context2);
        const readable = pair === null || pair === void 0 ? void 0 : pair.readable;
        assertRequiredField(readable, "readable", "ReadableWritablePair");
        assertReadableStream(readable, `${context2} has member 'readable' that`);
        const writable = pair === null || pair === void 0 ? void 0 : pair.writable;
        assertRequiredField(writable, "writable", "ReadableWritablePair");
        assertWritableStream(writable, `${context2} has member 'writable' that`);
        return { readable, writable };
      }
      __name(convertReadableWritablePair, "convertReadableWritablePair");
      class ReadableStream5 {
        static {
          __name(this, "ReadableStream");
        }
        constructor(rawUnderlyingSource = {}, rawStrategy = {}) {
          if (rawUnderlyingSource === void 0) {
            rawUnderlyingSource = null;
          } else {
            assertObject(rawUnderlyingSource, "First parameter");
          }
          const strategy = convertQueuingStrategy(rawStrategy, "Second parameter");
          const underlyingSource = convertUnderlyingDefaultOrByteSource(rawUnderlyingSource, "First parameter");
          InitializeReadableStream(this);
          if (underlyingSource.type === "bytes") {
            if (strategy.size !== void 0) {
              throw new RangeError("The strategy for a byte stream cannot have a size function");
            }
            const highWaterMark = ExtractHighWaterMark(strategy, 0);
            SetUpReadableByteStreamControllerFromUnderlyingSource(this, underlyingSource, highWaterMark);
          } else {
            const sizeAlgorithm = ExtractSizeAlgorithm(strategy);
            const highWaterMark = ExtractHighWaterMark(strategy, 1);
            SetUpReadableStreamDefaultControllerFromUnderlyingSource(this, underlyingSource, highWaterMark, sizeAlgorithm);
          }
        }
        /**
         * Whether or not the readable stream is locked to a {@link ReadableStreamDefaultReader | reader}.
         */
        get locked() {
          if (!IsReadableStream(this)) {
            throw streamBrandCheckException$1("locked");
          }
          return IsReadableStreamLocked(this);
        }
        /**
         * Cancels the stream, signaling a loss of interest in the stream by a consumer.
         *
         * The supplied `reason` argument will be given to the underlying source's {@link UnderlyingSource.cancel | cancel()}
         * method, which might or might not use it.
         */
        cancel(reason = void 0) {
          if (!IsReadableStream(this)) {
            return promiseRejectedWith(streamBrandCheckException$1("cancel"));
          }
          if (IsReadableStreamLocked(this)) {
            return promiseRejectedWith(new TypeError("Cannot cancel a stream that already has a reader"));
          }
          return ReadableStreamCancel(this, reason);
        }
        getReader(rawOptions = void 0) {
          if (!IsReadableStream(this)) {
            throw streamBrandCheckException$1("getReader");
          }
          const options2 = convertReaderOptions(rawOptions, "First parameter");
          if (options2.mode === void 0) {
            return AcquireReadableStreamDefaultReader(this);
          }
          return AcquireReadableStreamBYOBReader(this);
        }
        pipeThrough(rawTransform, rawOptions = {}) {
          if (!IsReadableStream(this)) {
            throw streamBrandCheckException$1("pipeThrough");
          }
          assertRequiredArgument(rawTransform, 1, "pipeThrough");
          const transform2 = convertReadableWritablePair(rawTransform, "First parameter");
          const options2 = convertPipeOptions(rawOptions, "Second parameter");
          if (IsReadableStreamLocked(this)) {
            throw new TypeError("ReadableStream.prototype.pipeThrough cannot be used on a locked ReadableStream");
          }
          if (IsWritableStreamLocked(transform2.writable)) {
            throw new TypeError("ReadableStream.prototype.pipeThrough cannot be used on a locked WritableStream");
          }
          const promise = ReadableStreamPipeTo(this, transform2.writable, options2.preventClose, options2.preventAbort, options2.preventCancel, options2.signal);
          setPromiseIsHandledToTrue(promise);
          return transform2.readable;
        }
        pipeTo(destination, rawOptions = {}) {
          if (!IsReadableStream(this)) {
            return promiseRejectedWith(streamBrandCheckException$1("pipeTo"));
          }
          if (destination === void 0) {
            return promiseRejectedWith(`Parameter 1 is required in 'pipeTo'.`);
          }
          if (!IsWritableStream(destination)) {
            return promiseRejectedWith(new TypeError(`ReadableStream.prototype.pipeTo's first argument must be a WritableStream`));
          }
          let options2;
          try {
            options2 = convertPipeOptions(rawOptions, "Second parameter");
          } catch (e4) {
            return promiseRejectedWith(e4);
          }
          if (IsReadableStreamLocked(this)) {
            return promiseRejectedWith(new TypeError("ReadableStream.prototype.pipeTo cannot be used on a locked ReadableStream"));
          }
          if (IsWritableStreamLocked(destination)) {
            return promiseRejectedWith(new TypeError("ReadableStream.prototype.pipeTo cannot be used on a locked WritableStream"));
          }
          return ReadableStreamPipeTo(this, destination, options2.preventClose, options2.preventAbort, options2.preventCancel, options2.signal);
        }
        /**
         * Tees this readable stream, returning a two-element array containing the two resulting branches as
         * new {@link ReadableStream} instances.
         *
         * Teeing a stream will lock it, preventing any other consumer from acquiring a reader.
         * To cancel the stream, cancel both of the resulting branches; a composite cancellation reason will then be
         * propagated to the stream's underlying source.
         *
         * Note that the chunks seen in each branch will be the same object. If the chunks are not immutable,
         * this could allow interference between the two branches.
         */
        tee() {
          if (!IsReadableStream(this)) {
            throw streamBrandCheckException$1("tee");
          }
          const branches = ReadableStreamTee(this);
          return CreateArrayFromList(branches);
        }
        values(rawOptions = void 0) {
          if (!IsReadableStream(this)) {
            throw streamBrandCheckException$1("values");
          }
          const options2 = convertIteratorOptions(rawOptions, "First parameter");
          return AcquireReadableStreamAsyncIterator(this, options2.preventCancel);
        }
        [SymbolAsyncIterator](options2) {
          return this.values(options2);
        }
        /**
         * Creates a new ReadableStream wrapping the provided iterable or async iterable.
         *
         * This can be used to adapt various kinds of objects into a readable stream,
         * such as an array, an async generator, or a Node.js readable stream.
         */
        static from(asyncIterable) {
          return ReadableStreamFrom2(asyncIterable);
        }
      }
      Object.defineProperties(ReadableStream5, {
        from: { enumerable: true }
      });
      Object.defineProperties(ReadableStream5.prototype, {
        cancel: { enumerable: true },
        getReader: { enumerable: true },
        pipeThrough: { enumerable: true },
        pipeTo: { enumerable: true },
        tee: { enumerable: true },
        values: { enumerable: true },
        locked: { enumerable: true }
      });
      setFunctionName(ReadableStream5.from, "from");
      setFunctionName(ReadableStream5.prototype.cancel, "cancel");
      setFunctionName(ReadableStream5.prototype.getReader, "getReader");
      setFunctionName(ReadableStream5.prototype.pipeThrough, "pipeThrough");
      setFunctionName(ReadableStream5.prototype.pipeTo, "pipeTo");
      setFunctionName(ReadableStream5.prototype.tee, "tee");
      setFunctionName(ReadableStream5.prototype.values, "values");
      if (typeof Symbol.toStringTag === "symbol") {
        Object.defineProperty(ReadableStream5.prototype, Symbol.toStringTag, {
          value: "ReadableStream",
          configurable: true
        });
      }
      Object.defineProperty(ReadableStream5.prototype, SymbolAsyncIterator, {
        value: ReadableStream5.prototype.values,
        writable: true,
        configurable: true
      });
      function CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark = 1, sizeAlgorithm = () => 1) {
        const stream2 = Object.create(ReadableStream5.prototype);
        InitializeReadableStream(stream2);
        const controller = Object.create(ReadableStreamDefaultController2.prototype);
        SetUpReadableStreamDefaultController(stream2, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm);
        return stream2;
      }
      __name(CreateReadableStream, "CreateReadableStream");
      function CreateReadableByteStream(startAlgorithm, pullAlgorithm, cancelAlgorithm) {
        const stream2 = Object.create(ReadableStream5.prototype);
        InitializeReadableStream(stream2);
        const controller = Object.create(ReadableByteStreamController2.prototype);
        SetUpReadableByteStreamController(stream2, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, 0, void 0);
        return stream2;
      }
      __name(CreateReadableByteStream, "CreateReadableByteStream");
      function InitializeReadableStream(stream2) {
        stream2._state = "readable";
        stream2._reader = void 0;
        stream2._storedError = void 0;
        stream2._disturbed = false;
      }
      __name(InitializeReadableStream, "InitializeReadableStream");
      function IsReadableStream(x3) {
        if (!typeIsObject(x3)) {
          return false;
        }
        if (!Object.prototype.hasOwnProperty.call(x3, "_readableStreamController")) {
          return false;
        }
        return x3 instanceof ReadableStream5;
      }
      __name(IsReadableStream, "IsReadableStream");
      function IsReadableStreamLocked(stream2) {
        if (stream2._reader === void 0) {
          return false;
        }
        return true;
      }
      __name(IsReadableStreamLocked, "IsReadableStreamLocked");
      function ReadableStreamCancel(stream2, reason) {
        stream2._disturbed = true;
        if (stream2._state === "closed") {
          return promiseResolvedWith(void 0);
        }
        if (stream2._state === "errored") {
          return promiseRejectedWith(stream2._storedError);
        }
        ReadableStreamClose(stream2);
        const reader = stream2._reader;
        if (reader !== void 0 && IsReadableStreamBYOBReader(reader)) {
          const readIntoRequests = reader._readIntoRequests;
          reader._readIntoRequests = new SimpleQueue();
          readIntoRequests.forEach((readIntoRequest) => {
            readIntoRequest._closeSteps(void 0);
          });
        }
        const sourceCancelPromise = stream2._readableStreamController[CancelSteps](reason);
        return transformPromiseWith(sourceCancelPromise, noop8);
      }
      __name(ReadableStreamCancel, "ReadableStreamCancel");
      function ReadableStreamClose(stream2) {
        stream2._state = "closed";
        const reader = stream2._reader;
        if (reader === void 0) {
          return;
        }
        defaultReaderClosedPromiseResolve(reader);
        if (IsReadableStreamDefaultReader(reader)) {
          const readRequests = reader._readRequests;
          reader._readRequests = new SimpleQueue();
          readRequests.forEach((readRequest) => {
            readRequest._closeSteps();
          });
        }
      }
      __name(ReadableStreamClose, "ReadableStreamClose");
      function ReadableStreamError(stream2, e4) {
        stream2._state = "errored";
        stream2._storedError = e4;
        const reader = stream2._reader;
        if (reader === void 0) {
          return;
        }
        defaultReaderClosedPromiseReject(reader, e4);
        if (IsReadableStreamDefaultReader(reader)) {
          ReadableStreamDefaultReaderErrorReadRequests(reader, e4);
        } else {
          ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e4);
        }
      }
      __name(ReadableStreamError, "ReadableStreamError");
      function streamBrandCheckException$1(name3) {
        return new TypeError(`ReadableStream.prototype.${name3} can only be used on a ReadableStream`);
      }
      __name(streamBrandCheckException$1, "streamBrandCheckException$1");
      function convertQueuingStrategyInit(init, context2) {
        assertDictionary(init, context2);
        const highWaterMark = init === null || init === void 0 ? void 0 : init.highWaterMark;
        assertRequiredField(highWaterMark, "highWaterMark", "QueuingStrategyInit");
        return {
          highWaterMark: convertUnrestrictedDouble(highWaterMark)
        };
      }
      __name(convertQueuingStrategyInit, "convertQueuingStrategyInit");
      const byteLengthSizeFunction = /* @__PURE__ */ __name((chunk) => {
        return chunk.byteLength;
      }, "byteLengthSizeFunction");
      setFunctionName(byteLengthSizeFunction, "size");
      class ByteLengthQueuingStrategy2 {
        static {
          __name(this, "ByteLengthQueuingStrategy");
        }
        constructor(options2) {
          assertRequiredArgument(options2, 1, "ByteLengthQueuingStrategy");
          options2 = convertQueuingStrategyInit(options2, "First parameter");
          this._byteLengthQueuingStrategyHighWaterMark = options2.highWaterMark;
        }
        /**
         * Returns the high water mark provided to the constructor.
         */
        get highWaterMark() {
          if (!IsByteLengthQueuingStrategy(this)) {
            throw byteLengthBrandCheckException("highWaterMark");
          }
          return this._byteLengthQueuingStrategyHighWaterMark;
        }
        /**
         * Measures the size of `chunk` by returning the value of its `byteLength` property.
         */
        get size() {
          if (!IsByteLengthQueuingStrategy(this)) {
            throw byteLengthBrandCheckException("size");
          }
          return byteLengthSizeFunction;
        }
      }
      Object.defineProperties(ByteLengthQueuingStrategy2.prototype, {
        highWaterMark: { enumerable: true },
        size: { enumerable: true }
      });
      if (typeof Symbol.toStringTag === "symbol") {
        Object.defineProperty(ByteLengthQueuingStrategy2.prototype, Symbol.toStringTag, {
          value: "ByteLengthQueuingStrategy",
          configurable: true
        });
      }
      function byteLengthBrandCheckException(name3) {
        return new TypeError(`ByteLengthQueuingStrategy.prototype.${name3} can only be used on a ByteLengthQueuingStrategy`);
      }
      __name(byteLengthBrandCheckException, "byteLengthBrandCheckException");
      function IsByteLengthQueuingStrategy(x3) {
        if (!typeIsObject(x3)) {
          return false;
        }
        if (!Object.prototype.hasOwnProperty.call(x3, "_byteLengthQueuingStrategyHighWaterMark")) {
          return false;
        }
        return x3 instanceof ByteLengthQueuingStrategy2;
      }
      __name(IsByteLengthQueuingStrategy, "IsByteLengthQueuingStrategy");
      const countSizeFunction = /* @__PURE__ */ __name(() => {
        return 1;
      }, "countSizeFunction");
      setFunctionName(countSizeFunction, "size");
      class CountQueuingStrategy2 {
        static {
          __name(this, "CountQueuingStrategy");
        }
        constructor(options2) {
          assertRequiredArgument(options2, 1, "CountQueuingStrategy");
          options2 = convertQueuingStrategyInit(options2, "First parameter");
          this._countQueuingStrategyHighWaterMark = options2.highWaterMark;
        }
        /**
         * Returns the high water mark provided to the constructor.
         */
        get highWaterMark() {
          if (!IsCountQueuingStrategy(this)) {
            throw countBrandCheckException("highWaterMark");
          }
          return this._countQueuingStrategyHighWaterMark;
        }
        /**
         * Measures the size of `chunk` by always returning 1.
         * This ensures that the total queue size is a count of the number of chunks in the queue.
         */
        get size() {
          if (!IsCountQueuingStrategy(this)) {
            throw countBrandCheckException("size");
          }
          return countSizeFunction;
        }
      }
      Object.defineProperties(CountQueuingStrategy2.prototype, {
        highWaterMark: { enumerable: true },
        size: { enumerable: true }
      });
      if (typeof Symbol.toStringTag === "symbol") {
        Object.defineProperty(CountQueuingStrategy2.prototype, Symbol.toStringTag, {
          value: "CountQueuingStrategy",
          configurable: true
        });
      }
      function countBrandCheckException(name3) {
        return new TypeError(`CountQueuingStrategy.prototype.${name3} can only be used on a CountQueuingStrategy`);
      }
      __name(countBrandCheckException, "countBrandCheckException");
      function IsCountQueuingStrategy(x3) {
        if (!typeIsObject(x3)) {
          return false;
        }
        if (!Object.prototype.hasOwnProperty.call(x3, "_countQueuingStrategyHighWaterMark")) {
          return false;
        }
        return x3 instanceof CountQueuingStrategy2;
      }
      __name(IsCountQueuingStrategy, "IsCountQueuingStrategy");
      function convertTransformer(original, context2) {
        assertDictionary(original, context2);
        const cancel = original === null || original === void 0 ? void 0 : original.cancel;
        const flush = original === null || original === void 0 ? void 0 : original.flush;
        const readableType = original === null || original === void 0 ? void 0 : original.readableType;
        const start = original === null || original === void 0 ? void 0 : original.start;
        const transform2 = original === null || original === void 0 ? void 0 : original.transform;
        const writableType = original === null || original === void 0 ? void 0 : original.writableType;
        return {
          cancel: cancel === void 0 ? void 0 : convertTransformerCancelCallback(cancel, original, `${context2} has member 'cancel' that`),
          flush: flush === void 0 ? void 0 : convertTransformerFlushCallback(flush, original, `${context2} has member 'flush' that`),
          readableType,
          start: start === void 0 ? void 0 : convertTransformerStartCallback(start, original, `${context2} has member 'start' that`),
          transform: transform2 === void 0 ? void 0 : convertTransformerTransformCallback(transform2, original, `${context2} has member 'transform' that`),
          writableType
        };
      }
      __name(convertTransformer, "convertTransformer");
      function convertTransformerFlushCallback(fn, original, context2) {
        assertFunction(fn, context2);
        return (controller) => promiseCall(fn, original, [controller]);
      }
      __name(convertTransformerFlushCallback, "convertTransformerFlushCallback");
      function convertTransformerStartCallback(fn, original, context2) {
        assertFunction(fn, context2);
        return (controller) => reflectCall(fn, original, [controller]);
      }
      __name(convertTransformerStartCallback, "convertTransformerStartCallback");
      function convertTransformerTransformCallback(fn, original, context2) {
        assertFunction(fn, context2);
        return (chunk, controller) => promiseCall(fn, original, [chunk, controller]);
      }
      __name(convertTransformerTransformCallback, "convertTransformerTransformCallback");
      function convertTransformerCancelCallback(fn, original, context2) {
        assertFunction(fn, context2);
        return (reason) => promiseCall(fn, original, [reason]);
      }
      __name(convertTransformerCancelCallback, "convertTransformerCancelCallback");
      class TransformStream3 {
        static {
          __name(this, "TransformStream");
        }
        constructor(rawTransformer = {}, rawWritableStrategy = {}, rawReadableStrategy = {}) {
          if (rawTransformer === void 0) {
            rawTransformer = null;
          }
          const writableStrategy = convertQueuingStrategy(rawWritableStrategy, "Second parameter");
          const readableStrategy = convertQueuingStrategy(rawReadableStrategy, "Third parameter");
          const transformer = convertTransformer(rawTransformer, "First parameter");
          if (transformer.readableType !== void 0) {
            throw new RangeError("Invalid readableType specified");
          }
          if (transformer.writableType !== void 0) {
            throw new RangeError("Invalid writableType specified");
          }
          const readableHighWaterMark = ExtractHighWaterMark(readableStrategy, 0);
          const readableSizeAlgorithm = ExtractSizeAlgorithm(readableStrategy);
          const writableHighWaterMark = ExtractHighWaterMark(writableStrategy, 1);
          const writableSizeAlgorithm = ExtractSizeAlgorithm(writableStrategy);
          let startPromise_resolve;
          const startPromise = newPromise((resolve30) => {
            startPromise_resolve = resolve30;
          });
          InitializeTransformStream(this, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark, readableSizeAlgorithm);
          SetUpTransformStreamDefaultControllerFromTransformer(this, transformer);
          if (transformer.start !== void 0) {
            startPromise_resolve(transformer.start(this._transformStreamController));
          } else {
            startPromise_resolve(void 0);
          }
        }
        /**
         * The readable side of the transform stream.
         */
        get readable() {
          if (!IsTransformStream(this)) {
            throw streamBrandCheckException("readable");
          }
          return this._readable;
        }
        /**
         * The writable side of the transform stream.
         */
        get writable() {
          if (!IsTransformStream(this)) {
            throw streamBrandCheckException("writable");
          }
          return this._writable;
        }
      }
      Object.defineProperties(TransformStream3.prototype, {
        readable: { enumerable: true },
        writable: { enumerable: true }
      });
      if (typeof Symbol.toStringTag === "symbol") {
        Object.defineProperty(TransformStream3.prototype, Symbol.toStringTag, {
          value: "TransformStream",
          configurable: true
        });
      }
      function InitializeTransformStream(stream2, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark, readableSizeAlgorithm) {
        function startAlgorithm() {
          return startPromise;
        }
        __name(startAlgorithm, "startAlgorithm");
        function writeAlgorithm(chunk) {
          return TransformStreamDefaultSinkWriteAlgorithm(stream2, chunk);
        }
        __name(writeAlgorithm, "writeAlgorithm");
        function abortAlgorithm(reason) {
          return TransformStreamDefaultSinkAbortAlgorithm(stream2, reason);
        }
        __name(abortAlgorithm, "abortAlgorithm");
        function closeAlgorithm() {
          return TransformStreamDefaultSinkCloseAlgorithm(stream2);
        }
        __name(closeAlgorithm, "closeAlgorithm");
        stream2._writable = CreateWritableStream(startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, writableHighWaterMark, writableSizeAlgorithm);
        function pullAlgorithm() {
          return TransformStreamDefaultSourcePullAlgorithm(stream2);
        }
        __name(pullAlgorithm, "pullAlgorithm");
        function cancelAlgorithm(reason) {
          return TransformStreamDefaultSourceCancelAlgorithm(stream2, reason);
        }
        __name(cancelAlgorithm, "cancelAlgorithm");
        stream2._readable = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, readableHighWaterMark, readableSizeAlgorithm);
        stream2._backpressure = void 0;
        stream2._backpressureChangePromise = void 0;
        stream2._backpressureChangePromise_resolve = void 0;
        TransformStreamSetBackpressure(stream2, true);
        stream2._transformStreamController = void 0;
      }
      __name(InitializeTransformStream, "InitializeTransformStream");
      function IsTransformStream(x3) {
        if (!typeIsObject(x3)) {
          return false;
        }
        if (!Object.prototype.hasOwnProperty.call(x3, "_transformStreamController")) {
          return false;
        }
        return x3 instanceof TransformStream3;
      }
      __name(IsTransformStream, "IsTransformStream");
      function TransformStreamError(stream2, e4) {
        ReadableStreamDefaultControllerError(stream2._readable._readableStreamController, e4);
        TransformStreamErrorWritableAndUnblockWrite(stream2, e4);
      }
      __name(TransformStreamError, "TransformStreamError");
      function TransformStreamErrorWritableAndUnblockWrite(stream2, e4) {
        TransformStreamDefaultControllerClearAlgorithms(stream2._transformStreamController);
        WritableStreamDefaultControllerErrorIfNeeded(stream2._writable._writableStreamController, e4);
        TransformStreamUnblockWrite(stream2);
      }
      __name(TransformStreamErrorWritableAndUnblockWrite, "TransformStreamErrorWritableAndUnblockWrite");
      function TransformStreamUnblockWrite(stream2) {
        if (stream2._backpressure) {
          TransformStreamSetBackpressure(stream2, false);
        }
      }
      __name(TransformStreamUnblockWrite, "TransformStreamUnblockWrite");
      function TransformStreamSetBackpressure(stream2, backpressure) {
        if (stream2._backpressureChangePromise !== void 0) {
          stream2._backpressureChangePromise_resolve();
        }
        stream2._backpressureChangePromise = newPromise((resolve30) => {
          stream2._backpressureChangePromise_resolve = resolve30;
        });
        stream2._backpressure = backpressure;
      }
      __name(TransformStreamSetBackpressure, "TransformStreamSetBackpressure");
      class TransformStreamDefaultController2 {
        static {
          __name(this, "TransformStreamDefaultController");
        }
        constructor() {
          throw new TypeError("Illegal constructor");
        }
        /**
         * Returns the desired size to fill the readable side’s internal queue. It can be negative, if the queue is over-full.
         */
        get desiredSize() {
          if (!IsTransformStreamDefaultController(this)) {
            throw defaultControllerBrandCheckException("desiredSize");
          }
          const readableController = this._controlledTransformStream._readable._readableStreamController;
          return ReadableStreamDefaultControllerGetDesiredSize(readableController);
        }
        enqueue(chunk = void 0) {
          if (!IsTransformStreamDefaultController(this)) {
            throw defaultControllerBrandCheckException("enqueue");
          }
          TransformStreamDefaultControllerEnqueue(this, chunk);
        }
        /**
         * Errors both the readable side and the writable side of the controlled transform stream, making all future
         * interactions with it fail with the given error `e`. Any chunks queued for transformation will be discarded.
         */
        error(reason = void 0) {
          if (!IsTransformStreamDefaultController(this)) {
            throw defaultControllerBrandCheckException("error");
          }
          TransformStreamDefaultControllerError(this, reason);
        }
        /**
         * Closes the readable side and errors the writable side of the controlled transform stream. This is useful when the
         * transformer only needs to consume a portion of the chunks written to the writable side.
         */
        terminate() {
          if (!IsTransformStreamDefaultController(this)) {
            throw defaultControllerBrandCheckException("terminate");
          }
          TransformStreamDefaultControllerTerminate(this);
        }
      }
      Object.defineProperties(TransformStreamDefaultController2.prototype, {
        enqueue: { enumerable: true },
        error: { enumerable: true },
        terminate: { enumerable: true },
        desiredSize: { enumerable: true }
      });
      setFunctionName(TransformStreamDefaultController2.prototype.enqueue, "enqueue");
      setFunctionName(TransformStreamDefaultController2.prototype.error, "error");
      setFunctionName(TransformStreamDefaultController2.prototype.terminate, "terminate");
      if (typeof Symbol.toStringTag === "symbol") {
        Object.defineProperty(TransformStreamDefaultController2.prototype, Symbol.toStringTag, {
          value: "TransformStreamDefaultController",
          configurable: true
        });
      }
      function IsTransformStreamDefaultController(x3) {
        if (!typeIsObject(x3)) {
          return false;
        }
        if (!Object.prototype.hasOwnProperty.call(x3, "_controlledTransformStream")) {
          return false;
        }
        return x3 instanceof TransformStreamDefaultController2;
      }
      __name(IsTransformStreamDefaultController, "IsTransformStreamDefaultController");
      function SetUpTransformStreamDefaultController(stream2, controller, transformAlgorithm, flushAlgorithm, cancelAlgorithm) {
        controller._controlledTransformStream = stream2;
        stream2._transformStreamController = controller;
        controller._transformAlgorithm = transformAlgorithm;
        controller._flushAlgorithm = flushAlgorithm;
        controller._cancelAlgorithm = cancelAlgorithm;
        controller._finishPromise = void 0;
        controller._finishPromise_resolve = void 0;
        controller._finishPromise_reject = void 0;
      }
      __name(SetUpTransformStreamDefaultController, "SetUpTransformStreamDefaultController");
      function SetUpTransformStreamDefaultControllerFromTransformer(stream2, transformer) {
        const controller = Object.create(TransformStreamDefaultController2.prototype);
        let transformAlgorithm;
        let flushAlgorithm;
        let cancelAlgorithm;
        if (transformer.transform !== void 0) {
          transformAlgorithm = /* @__PURE__ */ __name((chunk) => transformer.transform(chunk, controller), "transformAlgorithm");
        } else {
          transformAlgorithm = /* @__PURE__ */ __name((chunk) => {
            try {
              TransformStreamDefaultControllerEnqueue(controller, chunk);
              return promiseResolvedWith(void 0);
            } catch (transformResultE) {
              return promiseRejectedWith(transformResultE);
            }
          }, "transformAlgorithm");
        }
        if (transformer.flush !== void 0) {
          flushAlgorithm = /* @__PURE__ */ __name(() => transformer.flush(controller), "flushAlgorithm");
        } else {
          flushAlgorithm = /* @__PURE__ */ __name(() => promiseResolvedWith(void 0), "flushAlgorithm");
        }
        if (transformer.cancel !== void 0) {
          cancelAlgorithm = /* @__PURE__ */ __name((reason) => transformer.cancel(reason), "cancelAlgorithm");
        } else {
          cancelAlgorithm = /* @__PURE__ */ __name(() => promiseResolvedWith(void 0), "cancelAlgorithm");
        }
        SetUpTransformStreamDefaultController(stream2, controller, transformAlgorithm, flushAlgorithm, cancelAlgorithm);
      }
      __name(SetUpTransformStreamDefaultControllerFromTransformer, "SetUpTransformStreamDefaultControllerFromTransformer");
      function TransformStreamDefaultControllerClearAlgorithms(controller) {
        controller._transformAlgorithm = void 0;
        controller._flushAlgorithm = void 0;
        controller._cancelAlgorithm = void 0;
      }
      __name(TransformStreamDefaultControllerClearAlgorithms, "TransformStreamDefaultControllerClearAlgorithms");
      function TransformStreamDefaultControllerEnqueue(controller, chunk) {
        const stream2 = controller._controlledTransformStream;
        const readableController = stream2._readable._readableStreamController;
        if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(readableController)) {
          throw new TypeError("Readable side is not in a state that permits enqueue");
        }
        try {
          ReadableStreamDefaultControllerEnqueue(readableController, chunk);
        } catch (e4) {
          TransformStreamErrorWritableAndUnblockWrite(stream2, e4);
          throw stream2._readable._storedError;
        }
        const backpressure = ReadableStreamDefaultControllerHasBackpressure(readableController);
        if (backpressure !== stream2._backpressure) {
          TransformStreamSetBackpressure(stream2, true);
        }
      }
      __name(TransformStreamDefaultControllerEnqueue, "TransformStreamDefaultControllerEnqueue");
      function TransformStreamDefaultControllerError(controller, e4) {
        TransformStreamError(controller._controlledTransformStream, e4);
      }
      __name(TransformStreamDefaultControllerError, "TransformStreamDefaultControllerError");
      function TransformStreamDefaultControllerPerformTransform(controller, chunk) {
        const transformPromise = controller._transformAlgorithm(chunk);
        return transformPromiseWith(transformPromise, void 0, (r5) => {
          TransformStreamError(controller._controlledTransformStream, r5);
          throw r5;
        });
      }
      __name(TransformStreamDefaultControllerPerformTransform, "TransformStreamDefaultControllerPerformTransform");
      function TransformStreamDefaultControllerTerminate(controller) {
        const stream2 = controller._controlledTransformStream;
        const readableController = stream2._readable._readableStreamController;
        ReadableStreamDefaultControllerClose(readableController);
        const error2 = new TypeError("TransformStream terminated");
        TransformStreamErrorWritableAndUnblockWrite(stream2, error2);
      }
      __name(TransformStreamDefaultControllerTerminate, "TransformStreamDefaultControllerTerminate");
      function TransformStreamDefaultSinkWriteAlgorithm(stream2, chunk) {
        const controller = stream2._transformStreamController;
        if (stream2._backpressure) {
          const backpressureChangePromise = stream2._backpressureChangePromise;
          return transformPromiseWith(backpressureChangePromise, () => {
            const writable = stream2._writable;
            const state = writable._state;
            if (state === "erroring") {
              throw writable._storedError;
            }
            return TransformStreamDefaultControllerPerformTransform(controller, chunk);
          });
        }
        return TransformStreamDefaultControllerPerformTransform(controller, chunk);
      }
      __name(TransformStreamDefaultSinkWriteAlgorithm, "TransformStreamDefaultSinkWriteAlgorithm");
      function TransformStreamDefaultSinkAbortAlgorithm(stream2, reason) {
        const controller = stream2._transformStreamController;
        if (controller._finishPromise !== void 0) {
          return controller._finishPromise;
        }
        const readable = stream2._readable;
        controller._finishPromise = newPromise((resolve30, reject) => {
          controller._finishPromise_resolve = resolve30;
          controller._finishPromise_reject = reject;
        });
        const cancelPromise = controller._cancelAlgorithm(reason);
        TransformStreamDefaultControllerClearAlgorithms(controller);
        uponPromise(cancelPromise, () => {
          if (readable._state === "errored") {
            defaultControllerFinishPromiseReject(controller, readable._storedError);
          } else {
            ReadableStreamDefaultControllerError(readable._readableStreamController, reason);
            defaultControllerFinishPromiseResolve(controller);
          }
          return null;
        }, (r5) => {
          ReadableStreamDefaultControllerError(readable._readableStreamController, r5);
          defaultControllerFinishPromiseReject(controller, r5);
          return null;
        });
        return controller._finishPromise;
      }
      __name(TransformStreamDefaultSinkAbortAlgorithm, "TransformStreamDefaultSinkAbortAlgorithm");
      function TransformStreamDefaultSinkCloseAlgorithm(stream2) {
        const controller = stream2._transformStreamController;
        if (controller._finishPromise !== void 0) {
          return controller._finishPromise;
        }
        const readable = stream2._readable;
        controller._finishPromise = newPromise((resolve30, reject) => {
          controller._finishPromise_resolve = resolve30;
          controller._finishPromise_reject = reject;
        });
        const flushPromise = controller._flushAlgorithm();
        TransformStreamDefaultControllerClearAlgorithms(controller);
        uponPromise(flushPromise, () => {
          if (readable._state === "errored") {
            defaultControllerFinishPromiseReject(controller, readable._storedError);
          } else {
            ReadableStreamDefaultControllerClose(readable._readableStreamController);
            defaultControllerFinishPromiseResolve(controller);
          }
          return null;
        }, (r5) => {
          ReadableStreamDefaultControllerError(readable._readableStreamController, r5);
          defaultControllerFinishPromiseReject(controller, r5);
          return null;
        });
        return controller._finishPromise;
      }
      __name(TransformStreamDefaultSinkCloseAlgorithm, "TransformStreamDefaultSinkCloseAlgorithm");
      function TransformStreamDefaultSourcePullAlgorithm(stream2) {
        TransformStreamSetBackpressure(stream2, false);
        return stream2._backpressureChangePromise;
      }
      __name(TransformStreamDefaultSourcePullAlgorithm, "TransformStreamDefaultSourcePullAlgorithm");
      function TransformStreamDefaultSourceCancelAlgorithm(stream2, reason) {
        const controller = stream2._transformStreamController;
        if (controller._finishPromise !== void 0) {
          return controller._finishPromise;
        }
        const writable = stream2._writable;
        controller._finishPromise = newPromise((resolve30, reject) => {
          controller._finishPromise_resolve = resolve30;
          controller._finishPromise_reject = reject;
        });
        const cancelPromise = controller._cancelAlgorithm(reason);
        TransformStreamDefaultControllerClearAlgorithms(controller);
        uponPromise(cancelPromise, () => {
          if (writable._state === "errored") {
            defaultControllerFinishPromiseReject(controller, writable._storedError);
          } else {
            WritableStreamDefaultControllerErrorIfNeeded(writable._writableStreamController, reason);
            TransformStreamUnblockWrite(stream2);
            defaultControllerFinishPromiseResolve(controller);
          }
          return null;
        }, (r5) => {
          WritableStreamDefaultControllerErrorIfNeeded(writable._writableStreamController, r5);
          TransformStreamUnblockWrite(stream2);
          defaultControllerFinishPromiseReject(controller, r5);
          return null;
        });
        return controller._finishPromise;
      }
      __name(TransformStreamDefaultSourceCancelAlgorithm, "TransformStreamDefaultSourceCancelAlgorithm");
      function defaultControllerBrandCheckException(name3) {
        return new TypeError(`TransformStreamDefaultController.prototype.${name3} can only be used on a TransformStreamDefaultController`);
      }
      __name(defaultControllerBrandCheckException, "defaultControllerBrandCheckException");
      function defaultControllerFinishPromiseResolve(controller) {
        if (controller._finishPromise_resolve === void 0) {
          return;
        }
        controller._finishPromise_resolve();
        controller._finishPromise_resolve = void 0;
        controller._finishPromise_reject = void 0;
      }
      __name(defaultControllerFinishPromiseResolve, "defaultControllerFinishPromiseResolve");
      function defaultControllerFinishPromiseReject(controller, reason) {
        if (controller._finishPromise_reject === void 0) {
          return;
        }
        setPromiseIsHandledToTrue(controller._finishPromise);
        controller._finishPromise_reject(reason);
        controller._finishPromise_resolve = void 0;
        controller._finishPromise_reject = void 0;
      }
      __name(defaultControllerFinishPromiseReject, "defaultControllerFinishPromiseReject");
      function streamBrandCheckException(name3) {
        return new TypeError(`TransformStream.prototype.${name3} can only be used on a TransformStream`);
      }
      __name(streamBrandCheckException, "streamBrandCheckException");
      exports3.ByteLengthQueuingStrategy = ByteLengthQueuingStrategy2;
      exports3.CountQueuingStrategy = CountQueuingStrategy2;
      exports3.ReadableByteStreamController = ReadableByteStreamController2;
      exports3.ReadableStream = ReadableStream5;
      exports3.ReadableStreamBYOBReader = ReadableStreamBYOBReader2;
      exports3.ReadableStreamBYOBRequest = ReadableStreamBYOBRequest2;
      exports3.ReadableStreamDefaultController = ReadableStreamDefaultController2;
      exports3.ReadableStreamDefaultReader = ReadableStreamDefaultReader2;
      exports3.TransformStream = TransformStream3;
      exports3.TransformStreamDefaultController = TransformStreamDefaultController2;
      exports3.WritableStream = WritableStream2;
      exports3.WritableStreamDefaultController = WritableStreamDefaultController2;
      exports3.WritableStreamDefaultWriter = WritableStreamDefaultWriter2;
    });
  }
});

// node_modules/fetch-blob/streams.cjs
var require_streams = __commonJS({
  "node_modules/fetch-blob/streams.cjs"() {
    init_esbuild_shims();
    var POOL_SIZE2 = 65536;
    if (!globalThis.ReadableStream) {
      try {
        const process50 = __require("node:process");
        const { emitWarning: emitWarning2 } = process50;
        try {
          process50.emitWarning = () => {
          };
          Object.assign(globalThis, __require("node:stream/web"));
          process50.emitWarning = emitWarning2;
        } catch (error2) {
          process50.emitWarning = emitWarning2;
          throw error2;
        }
      } catch (error2) {
        Object.assign(globalThis, require_ponyfill_es2018());
      }
    }
    try {
      const { Blob: Blob6 } = __require("buffer");
      if (Blob6 && !Blob6.prototype.stream) {
        Blob6.prototype.stream = /* @__PURE__ */ __name(function name3(params) {
          let position = 0;
          const blob = this;
          return new ReadableStream({
            type: "bytes",
            async pull(ctrl) {
              const chunk = blob.slice(position, Math.min(blob.size, position + POOL_SIZE2));
              const buffer = await chunk.arrayBuffer();
              position += buffer.byteLength;
              ctrl.enqueue(new Uint8Array(buffer));
              if (position === blob.size) {
                ctrl.close();
              }
            }
          });
        }, "name");
      }
    } catch (error2) {
    }
  }
});

// node_modules/fetch-blob/index.js
async function* toIterator(parts, clone4 = true) {
  for (const part of parts) {
    if ("stream" in part) {
      yield* (
        /** @type {AsyncIterableIterator<Uint8Array>} */
        part.stream()
      );
    } else if (ArrayBuffer.isView(part)) {
      if (clone4) {
        let position = part.byteOffset;
        const end = part.byteOffset + part.byteLength;
        while (position !== end) {
          const size = Math.min(end - position, POOL_SIZE);
          const chunk = part.buffer.slice(position, position + size);
          position += chunk.byteLength;
          yield new Uint8Array(chunk);
        }
      } else {
        yield part;
      }
    } else {
      let position = 0, b2 = (
        /** @type {Blob} */
        part
      );
      while (position !== b2.size) {
        const chunk = b2.slice(position, Math.min(b2.size, position + POOL_SIZE));
        const buffer = await chunk.arrayBuffer();
        position += buffer.byteLength;
        yield new Uint8Array(buffer);
      }
    }
  }
}
var import_streams, POOL_SIZE, _Blob, Blob3, fetch_blob_default;
var init_fetch_blob = __esm({
  "node_modules/fetch-blob/index.js"() {
    init_esbuild_shims();
    import_streams = __toESM(require_streams(), 1);
    POOL_SIZE = 65536;
    __name(toIterator, "toIterator");
    _Blob = class Blob2 {
      static {
        __name(this, "Blob");
      }
      /** @type {Array.<(Blob|Uint8Array)>} */
      #parts = [];
      #type = "";
      #size = 0;
      #endings = "transparent";
      /**
       * The Blob() constructor returns a new Blob object. The content
       * of the blob consists of the concatenation of the values given
       * in the parameter array.
       *
       * @param {*} blobParts
       * @param {{ type?: string, endings?: string }} [options]
       */
      constructor(blobParts = [], options2 = {}) {
        if (typeof blobParts !== "object" || blobParts === null) {
          throw new TypeError("Failed to construct 'Blob': The provided value cannot be converted to a sequence.");
        }
        if (typeof blobParts[Symbol.iterator] !== "function") {
          throw new TypeError("Failed to construct 'Blob': The object must have a callable @@iterator property.");
        }
        if (typeof options2 !== "object" && typeof options2 !== "function") {
          throw new TypeError("Failed to construct 'Blob': parameter 2 cannot convert to dictionary.");
        }
        if (options2 === null) options2 = {};
        const encoder = new TextEncoder();
        for (const element of blobParts) {
          let part;
          if (ArrayBuffer.isView(element)) {
            part = new Uint8Array(element.buffer.slice(element.byteOffset, element.byteOffset + element.byteLength));
          } else if (element instanceof ArrayBuffer) {
            part = new Uint8Array(element.slice(0));
          } else if (element instanceof Blob2) {
            part = element;
          } else {
            part = encoder.encode(`${element}`);
          }
          this.#size += ArrayBuffer.isView(part) ? part.byteLength : part.size;
          this.#parts.push(part);
        }
        this.#endings = `${options2.endings === void 0 ? "transparent" : options2.endings}`;
        const type = options2.type === void 0 ? "" : String(options2.type);
        this.#type = /^[\x20-\x7E]*$/.test(type) ? type : "";
      }
      /**
       * The Blob interface's size property returns the
       * size of the Blob in bytes.
       */
      get size() {
        return this.#size;
      }
      /**
       * The type property of a Blob object returns the MIME type of the file.
       */
      get type() {
        return this.#type;
      }
      /**
       * The text() method in the Blob interface returns a Promise
       * that resolves with a string containing the contents of
       * the blob, interpreted as UTF-8.
       *
       * @return {Promise<string>}
       */
      async text() {
        const decoder = new TextDecoder();
        let str2 = "";
        for await (const part of toIterator(this.#parts, false)) {
          str2 += decoder.decode(part, { stream: true });
        }
        str2 += decoder.decode();
        return str2;
      }
      /**
       * The arrayBuffer() method in the Blob interface returns a
       * Promise that resolves with the contents of the blob as
       * binary data contained in an ArrayBuffer.
       *
       * @return {Promise<ArrayBuffer>}
       */
      async arrayBuffer() {
        const data = new Uint8Array(this.size);
        let offset = 0;
        for await (const chunk of toIterator(this.#parts, false)) {
          data.set(chunk, offset);
          offset += chunk.length;
        }
        return data.buffer;
      }
      stream() {
        const it2 = toIterator(this.#parts, true);
        return new globalThis.ReadableStream({
          // @ts-ignore
          type: "bytes",
          async pull(ctrl) {
            const chunk = await it2.next();
            chunk.done ? ctrl.close() : ctrl.enqueue(chunk.value);
          },
          async cancel() {
            await it2.return();
          }
        });
      }
      /**
       * The Blob interface's slice() method creates and returns a
       * new Blob object which contains data from a subset of the
       * blob on which it's called.
       *
       * @param {number} [start]
       * @param {number} [end]
       * @param {string} [type]
       */
      slice(start = 0, end = this.size, type = "") {
        const { size } = this;
        let relativeStart = start < 0 ? Math.max(size + start, 0) : Math.min(start, size);
        let relativeEnd = end < 0 ? Math.max(size + end, 0) : Math.min(end, size);
        const span = Math.max(relativeEnd - relativeStart, 0);
        const parts = this.#parts;
        const blobParts = [];
        let added = 0;
        for (const part of parts) {
          if (added >= span) {
            break;
          }
          const size2 = ArrayBuffer.isView(part) ? part.byteLength : part.size;
          if (relativeStart && size2 <= relativeStart) {
            relativeStart -= size2;
            relativeEnd -= size2;
          } else {
            let chunk;
            if (ArrayBuffer.isView(part)) {
              chunk = part.subarray(relativeStart, Math.min(size2, relativeEnd));
              added += chunk.byteLength;
            } else {
              chunk = part.slice(relativeStart, Math.min(size2, relativeEnd));
              added += chunk.size;
            }
            relativeEnd -= size2;
            blobParts.push(chunk);
            relativeStart = 0;
          }
        }
        const blob = new Blob2([], { type: String(type).toLowerCase() });
        blob.#size = span;
        blob.#parts = blobParts;
        return blob;
      }
      get [Symbol.toStringTag]() {
        return "Blob";
      }
      static [Symbol.hasInstance](object3) {
        return object3 && typeof object3 === "object" && typeof object3.constructor === "function" && (typeof object3.stream === "function" || typeof object3.arrayBuffer === "function") && /^(Blob|File)$/.test(object3[Symbol.toStringTag]);
      }
    };
    Object.defineProperties(_Blob.prototype, {
      size: { enumerable: true },
      type: { enumerable: true },
      slice: { enumerable: true }
    });
    Blob3 = _Blob;
    fetch_blob_default = Blob3;
  }
});

// node_modules/fetch-blob/file.js
var _File, File3, file_default;
var init_file = __esm({
  "node_modules/fetch-blob/file.js"() {
    init_esbuild_shims();
    init_fetch_blob();
    _File = class File2 extends fetch_blob_default {
      static {
        __name(this, "File");
      }
      #lastModified = 0;
      #name = "";
      /**
       * @param {*[]} fileBits
       * @param {string} fileName
       * @param {{lastModified?: number, type?: string}} options
       */
      // @ts-ignore
      constructor(fileBits, fileName, options2 = {}) {
        if (arguments.length < 2) {
          throw new TypeError(`Failed to construct 'File': 2 arguments required, but only ${arguments.length} present.`);
        }
        super(fileBits, options2);
        if (options2 === null) options2 = {};
        const lastModified = options2.lastModified === void 0 ? Date.now() : Number(options2.lastModified);
        if (!Number.isNaN(lastModified)) {
          this.#lastModified = lastModified;
        }
        this.#name = String(fileName);
      }
      get name() {
        return this.#name;
      }
      get lastModified() {
        return this.#lastModified;
      }
      get [Symbol.toStringTag]() {
        return "File";
      }
      static [Symbol.hasInstance](object3) {
        return !!object3 && object3 instanceof fetch_blob_default && /^(File)$/.test(object3[Symbol.toStringTag]);
      }
    };
    File3 = _File;
    file_default = File3;
  }
});

// node_modules/formdata-polyfill/esm.min.js
function formDataToBlob(F4, B2 = fetch_blob_default) {
  var b2 = `${r()}${r()}`.replace(/\./g, "").slice(-28).padStart(32, "-"), c4 = [], p2 = `--${b2}\r
Content-Disposition: form-data; name="`;
  F4.forEach((v2, n3) => typeof v2 == "string" ? c4.push(p2 + e(n3) + `"\r
\r
${v2.replace(/\r(?!\n)|(?<!\r)\n/g, "\r\n")}\r
`) : c4.push(p2 + e(n3) + `"; filename="${e(v2.name, 1)}"\r
Content-Type: ${v2.type || "application/octet-stream"}\r
\r
`, v2, "\r\n"));
  c4.push(`--${b2}--`);
  return new B2(c4, { type: "multipart/form-data; boundary=" + b2 });
}
var t, i, h, r, m, f, e, x, FormData2;
var init_esm_min = __esm({
  "node_modules/formdata-polyfill/esm.min.js"() {
    init_esbuild_shims();
    init_fetch_blob();
    init_file();
    ({ toStringTag: t, iterator: i, hasInstance: h } = Symbol);
    r = Math.random;
    m = "append,set,get,getAll,delete,keys,values,entries,forEach,constructor".split(",");
    f = /* @__PURE__ */ __name((a2, b2, c4) => (a2 += "", /^(Blob|File)$/.test(b2 && b2[t]) ? [(c4 = c4 !== void 0 ? c4 + "" : b2[t] == "File" ? b2.name : "blob", a2), b2.name !== c4 || b2[t] == "blob" ? new file_default([b2], c4, b2) : b2] : [a2, b2 + ""]), "f");
    e = /* @__PURE__ */ __name((c4, f5) => (f5 ? c4 : c4.replace(/\r?\n|\r/g, "\r\n")).replace(/\n/g, "%0A").replace(/\r/g, "%0D").replace(/"/g, "%22"), "e");
    x = /* @__PURE__ */ __name((n3, a2, e4) => {
      if (a2.length < e4) {
        throw new TypeError(`Failed to execute '${n3}' on 'FormData': ${e4} arguments required, but only ${a2.length} present.`);
      }
    }, "x");
    FormData2 = class FormData3 {
      static {
        __name(this, "FormData");
      }
      #d = [];
      constructor(...a2) {
        if (a2.length) throw new TypeError(`Failed to construct 'FormData': parameter 1 is not of type 'HTMLFormElement'.`);
      }
      get [t]() {
        return "FormData";
      }
      [i]() {
        return this.entries();
      }
      static [h](o3) {
        return o3 && typeof o3 === "object" && o3[t] === "FormData" && !m.some((m3) => typeof o3[m3] != "function");
      }
      append(...a2) {
        x("append", arguments, 2);
        this.#d.push(f(...a2));
      }
      delete(a2) {
        x("delete", arguments, 1);
        a2 += "";
        this.#d = this.#d.filter(([b2]) => b2 !== a2);
      }
      get(a2) {
        x("get", arguments, 1);
        a2 += "";
        for (var b2 = this.#d, l3 = b2.length, c4 = 0; c4 < l3; c4++) if (b2[c4][0] === a2) return b2[c4][1];
        return null;
      }
      getAll(a2, b2) {
        x("getAll", arguments, 1);
        b2 = [];
        a2 += "";
        this.#d.forEach((c4) => c4[0] === a2 && b2.push(c4[1]));
        return b2;
      }
      has(a2) {
        x("has", arguments, 1);
        a2 += "";
        return this.#d.some((b2) => b2[0] === a2);
      }
      forEach(a2, b2) {
        x("forEach", arguments, 1);
        for (var [c4, d2] of this) a2.call(b2, d2, c4, this);
      }
      set(...a2) {
        x("set", arguments, 2);
        var b2 = [], c4 = true;
        a2 = f(...a2);
        this.#d.forEach((d2) => {
          d2[0] === a2[0] ? c4 && (c4 = !b2.push(a2)) : b2.push(d2);
        });
        c4 && b2.push(a2);
        this.#d = b2;
      }
      *entries() {
        yield* this.#d;
      }
      *keys() {
        for (var [a2] of this) yield a2;
      }
      *values() {
        for (var [, a2] of this) yield a2;
      }
    };
    __name(formDataToBlob, "formDataToBlob");
  }
});

// packages/core/node_modules/node-fetch/src/errors/base.js
var FetchBaseError;
var init_base = __esm({
  "packages/core/node_modules/node-fetch/src/errors/base.js"() {
    init_esbuild_shims();
    FetchBaseError = class extends Error {
      static {
        __name(this, "FetchBaseError");
      }
      constructor(message, type) {
        super(message);
        Error.captureStackTrace(this, this.constructor);
        this.type = type;
      }
      get name() {
        return this.constructor.name;
      }
      get [Symbol.toStringTag]() {
        return this.constructor.name;
      }
    };
  }
});

// packages/core/node_modules/node-fetch/src/errors/fetch-error.js
var FetchError;
var init_fetch_error = __esm({
  "packages/core/node_modules/node-fetch/src/errors/fetch-error.js"() {
    init_esbuild_shims();
    init_base();
    FetchError = class extends FetchBaseError {
      static {
        __name(this, "FetchError");
      }
      /**
       * @param  {string} message -      Error message for human
       * @param  {string} [type] -        Error type for machine
       * @param  {SystemError} [systemError] - For Node.js system error
       */
      constructor(message, type, systemError) {
        super(message, type);
        if (systemError) {
          this.code = this.errno = systemError.code;
          this.erroredSysCall = systemError.syscall;
        }
      }
    };
  }
});

// packages/core/node_modules/node-fetch/src/utils/is.js
var NAME, isURLSearchParameters, isBlob, isAbortSignal, isDomainOrSubdomain, isSameProtocol;
var init_is = __esm({
  "packages/core/node_modules/node-fetch/src/utils/is.js"() {
    init_esbuild_shims();
    NAME = Symbol.toStringTag;
    isURLSearchParameters = /* @__PURE__ */ __name((object3) => {
      return typeof object3 === "object" && typeof object3.append === "function" && typeof object3.delete === "function" && typeof object3.get === "function" && typeof object3.getAll === "function" && typeof object3.has === "function" && typeof object3.set === "function" && typeof object3.sort === "function" && object3[NAME] === "URLSearchParams";
    }, "isURLSearchParameters");
    isBlob = /* @__PURE__ */ __name((object3) => {
      return object3 && typeof object3 === "object" && typeof object3.arrayBuffer === "function" && typeof object3.type === "string" && typeof object3.stream === "function" && typeof object3.constructor === "function" && /^(Blob|File)$/.test(object3[NAME]);
    }, "isBlob");
    isAbortSignal = /* @__PURE__ */ __name((object3) => {
      return typeof object3 === "object" && (object3[NAME] === "AbortSignal" || object3[NAME] === "EventTarget");
    }, "isAbortSignal");
    isDomainOrSubdomain = /* @__PURE__ */ __name((destination, original) => {
      const orig = new URL(original).hostname;
      const dest = new URL(destination).hostname;
      return orig === dest || orig.endsWith(`.${dest}`);
    }, "isDomainOrSubdomain");
    isSameProtocol = /* @__PURE__ */ __name((destination, original) => {
      const orig = new URL(original).protocol;
      const dest = new URL(destination).protocol;
      return orig === dest;
    }, "isSameProtocol");
  }
});

// node_modules/node-domexception/index.js
var require_node_domexception = __commonJS({
  "node_modules/node-domexception/index.js"(exports2, module2) {
    init_esbuild_shims();
    if (!globalThis.DOMException) {
      try {
        const { MessageChannel: MessageChannel2 } = __require("worker_threads"), port = new MessageChannel2().port1, ab2 = new ArrayBuffer();
        port.postMessage(ab2, [ab2, ab2]);
      } catch (err) {
        err.constructor.name === "DOMException" && (globalThis.DOMException = err.constructor);
      }
    }
    module2.exports = globalThis.DOMException;
  }
});

// node_modules/fetch-blob/from.js
import { statSync, createReadStream, promises as fs4 } from "node:fs";
import { basename } from "node:path";
var import_node_domexception, stat, blobFromSync, blobFrom, fileFrom, fileFromSync, fromBlob, fromFile, BlobDataItem;
var init_from = __esm({
  "node_modules/fetch-blob/from.js"() {
    init_esbuild_shims();
    import_node_domexception = __toESM(require_node_domexception(), 1);
    init_file();
    init_fetch_blob();
    ({ stat } = fs4);
    blobFromSync = /* @__PURE__ */ __name((path125, type) => fromBlob(statSync(path125), path125, type), "blobFromSync");
    blobFrom = /* @__PURE__ */ __name((path125, type) => stat(path125).then((stat10) => fromBlob(stat10, path125, type)), "blobFrom");
    fileFrom = /* @__PURE__ */ __name((path125, type) => stat(path125).then((stat10) => fromFile(stat10, path125, type)), "fileFrom");
    fileFromSync = /* @__PURE__ */ __name((path125, type) => fromFile(statSync(path125), path125, type), "fileFromSync");
    fromBlob = /* @__PURE__ */ __name((stat10, path125, type = "") => new fetch_blob_default([new BlobDataItem({
      path: path125,
      size: stat10.size,
      lastModified: stat10.mtimeMs,
      start: 0
    })], { type }), "fromBlob");
    fromFile = /* @__PURE__ */ __name((stat10, path125, type = "") => new file_default([new BlobDataItem({
      path: path125,
      size: stat10.size,
      lastModified: stat10.mtimeMs,
      start: 0
    })], basename(path125), { type, lastModified: stat10.mtimeMs }), "fromFile");
    BlobDataItem = class _BlobDataItem {
      static {
        __name(this, "BlobDataItem");
      }
      #path;
      #start;
      constructor(options2) {
        this.#path = options2.path;
        this.#start = options2.start;
        this.size = options2.size;
        this.lastModified = options2.lastModified;
      }
      /**
       * Slicing arguments is first validated and formatted
       * to not be out of range by Blob.prototype.slice
       */
      slice(start, end) {
        return new _BlobDataItem({
          path: this.#path,
          lastModified: this.lastModified,
          size: end - start,
          start: this.#start + start
        });
      }
      async *stream() {
        const { mtimeMs } = await stat(this.#path);
        if (mtimeMs > this.lastModified) {
          throw new import_node_domexception.default("The requested file could not be read, typically due to permission problems that have occurred after a reference to a file was acquired.", "NotReadableError");
        }
        yield* createReadStream(this.#path, {
          start: this.#start,
          end: this.#start + this.size - 1
        });
      }
      get [Symbol.toStringTag]() {
        return "Blob";
      }
    };
  }
});

// packages/core/node_modules/node-fetch/src/utils/multipart-parser.js
var multipart_parser_exports = {};
__export(multipart_parser_exports, {
  toFormData: () => toFormData
});
function _fileName(headerValue) {
  const m3 = headerValue.match(/\bfilename=("(.*?)"|([^()<>@,;:\\"/[\]?={}\s\t]+))($|;\s)/i);
  if (!m3) {
    return;
  }
  const match2 = m3[2] || m3[3] || "";
  let filename = match2.slice(match2.lastIndexOf("\\") + 1);
  filename = filename.replace(/%22/g, '"');
  filename = filename.replace(/&#(\d{4});/g, (m4, code2) => {
    return String.fromCharCode(code2);
  });
  return filename;
}
async function toFormData(Body3, ct2) {
  if (!/multipart/i.test(ct2)) {
    throw new TypeError("Failed to fetch");
  }
  const m3 = ct2.match(/boundary=(?:"([^"]+)"|([^;]+))/i);
  if (!m3) {
    throw new TypeError("no or bad content-type header, no multipart boundary");
  }
  const parser6 = new MultipartParser(m3[1] || m3[2]);
  let headerField;
  let headerValue;
  let entryValue;
  let entryName;
  let contentType;
  let filename;
  const entryChunks = [];
  const formData = new FormData2();
  const onPartData = /* @__PURE__ */ __name((ui8a) => {
    entryValue += decoder.decode(ui8a, { stream: true });
  }, "onPartData");
  const appendToFile = /* @__PURE__ */ __name((ui8a) => {
    entryChunks.push(ui8a);
  }, "appendToFile");
  const appendFileToFormData = /* @__PURE__ */ __name(() => {
    const file = new file_default(entryChunks, filename, { type: contentType });
    formData.append(entryName, file);
  }, "appendFileToFormData");
  const appendEntryToFormData = /* @__PURE__ */ __name(() => {
    formData.append(entryName, entryValue);
  }, "appendEntryToFormData");
  const decoder = new TextDecoder("utf-8");
  decoder.decode();
  parser6.onPartBegin = function() {
    parser6.onPartData = onPartData;
    parser6.onPartEnd = appendEntryToFormData;
    headerField = "";
    headerValue = "";
    entryValue = "";
    entryName = "";
    contentType = "";
    filename = null;
    entryChunks.length = 0;
  };
  parser6.onHeaderField = function(ui8a) {
    headerField += decoder.decode(ui8a, { stream: true });
  };
  parser6.onHeaderValue = function(ui8a) {
    headerValue += decoder.decode(ui8a, { stream: true });
  };
  parser6.onHeaderEnd = function() {
    headerValue += decoder.decode();
    headerField = headerField.toLowerCase();
    if (headerField === "content-disposition") {
      const m4 = headerValue.match(/\bname=("([^"]*)"|([^()<>@,;:\\"/[\]?={}\s\t]+))/i);
      if (m4) {
        entryName = m4[2] || m4[3] || "";
      }
      filename = _fileName(headerValue);
      if (filename) {
        parser6.onPartData = appendToFile;
        parser6.onPartEnd = appendFileToFormData;
      }
    } else if (headerField === "content-type") {
      contentType = headerValue;
    }
    headerValue = "";
    headerField = "";
  };
  for await (const chunk of Body3) {
    parser6.write(chunk);
  }
  parser6.end();
  return formData;
}
var s, S, f2, F, LF, CR, SPACE, HYPHEN, COLON, A, Z, lower, noop, MultipartParser;
var init_multipart_parser = __esm({
  "packages/core/node_modules/node-fetch/src/utils/multipart-parser.js"() {
    init_esbuild_shims();
    init_from();
    init_esm_min();
    s = 0;
    S = {
      START_BOUNDARY: s++,
      HEADER_FIELD_START: s++,
      HEADER_FIELD: s++,
      HEADER_VALUE_START: s++,
      HEADER_VALUE: s++,
      HEADER_VALUE_ALMOST_DONE: s++,
      HEADERS_ALMOST_DONE: s++,
      PART_DATA_START: s++,
      PART_DATA: s++,
      END: s++
    };
    f2 = 1;
    F = {
      PART_BOUNDARY: f2,
      LAST_BOUNDARY: f2 *= 2
    };
    LF = 10;
    CR = 13;
    SPACE = 32;
    HYPHEN = 45;
    COLON = 58;
    A = 97;
    Z = 122;
    lower = /* @__PURE__ */ __name((c4) => c4 | 32, "lower");
    noop = /* @__PURE__ */ __name(() => {
    }, "noop");
    MultipartParser = class {
      static {
        __name(this, "MultipartParser");
      }
      /**
       * @param {string} boundary
       */
      constructor(boundary) {
        this.index = 0;
        this.flags = 0;
        this.onHeaderEnd = noop;
        this.onHeaderField = noop;
        this.onHeadersEnd = noop;
        this.onHeaderValue = noop;
        this.onPartBegin = noop;
        this.onPartData = noop;
        this.onPartEnd = noop;
        this.boundaryChars = {};
        boundary = "\r\n--" + boundary;
        const ui8a = new Uint8Array(boundary.length);
        for (let i3 = 0; i3 < boundary.length; i3++) {
          ui8a[i3] = boundary.charCodeAt(i3);
          this.boundaryChars[ui8a[i3]] = true;
        }
        this.boundary = ui8a;
        this.lookbehind = new Uint8Array(this.boundary.length + 8);
        this.state = S.START_BOUNDARY;
      }
      /**
       * @param {Uint8Array} data
       */
      write(data) {
        let i3 = 0;
        const length_ = data.length;
        let previousIndex = this.index;
        let { lookbehind, boundary, boundaryChars, index, state, flags } = this;
        const boundaryLength = this.boundary.length;
        const boundaryEnd = boundaryLength - 1;
        const bufferLength = data.length;
        let c4;
        let cl;
        const mark = /* @__PURE__ */ __name((name3) => {
          this[name3 + "Mark"] = i3;
        }, "mark");
        const clear = /* @__PURE__ */ __name((name3) => {
          delete this[name3 + "Mark"];
        }, "clear");
        const callback = /* @__PURE__ */ __name((callbackSymbol, start, end, ui8a) => {
          if (start === void 0 || start !== end) {
            this[callbackSymbol](ui8a && ui8a.subarray(start, end));
          }
        }, "callback");
        const dataCallback = /* @__PURE__ */ __name((name3, clear2) => {
          const markSymbol = name3 + "Mark";
          if (!(markSymbol in this)) {
            return;
          }
          if (clear2) {
            callback(name3, this[markSymbol], i3, data);
            delete this[markSymbol];
          } else {
            callback(name3, this[markSymbol], data.length, data);
            this[markSymbol] = 0;
          }
        }, "dataCallback");
        for (i3 = 0; i3 < length_; i3++) {
          c4 = data[i3];
          switch (state) {
            case S.START_BOUNDARY:
              if (index === boundary.length - 2) {
                if (c4 === HYPHEN) {
                  flags |= F.LAST_BOUNDARY;
                } else if (c4 !== CR) {
                  return;
                }
                index++;
                break;
              } else if (index - 1 === boundary.length - 2) {
                if (flags & F.LAST_BOUNDARY && c4 === HYPHEN) {
                  state = S.END;
                  flags = 0;
                } else if (!(flags & F.LAST_BOUNDARY) && c4 === LF) {
                  index = 0;
                  callback("onPartBegin");
                  state = S.HEADER_FIELD_START;
                } else {
                  return;
                }
                break;
              }
              if (c4 !== boundary[index + 2]) {
                index = -2;
              }
              if (c4 === boundary[index + 2]) {
                index++;
              }
              break;
            case S.HEADER_FIELD_START:
              state = S.HEADER_FIELD;
              mark("onHeaderField");
              index = 0;
            // falls through
            case S.HEADER_FIELD:
              if (c4 === CR) {
                clear("onHeaderField");
                state = S.HEADERS_ALMOST_DONE;
                break;
              }
              index++;
              if (c4 === HYPHEN) {
                break;
              }
              if (c4 === COLON) {
                if (index === 1) {
                  return;
                }
                dataCallback("onHeaderField", true);
                state = S.HEADER_VALUE_START;
                break;
              }
              cl = lower(c4);
              if (cl < A || cl > Z) {
                return;
              }
              break;
            case S.HEADER_VALUE_START:
              if (c4 === SPACE) {
                break;
              }
              mark("onHeaderValue");
              state = S.HEADER_VALUE;
            // falls through
            case S.HEADER_VALUE:
              if (c4 === CR) {
                dataCallback("onHeaderValue", true);
                callback("onHeaderEnd");
                state = S.HEADER_VALUE_ALMOST_DONE;
              }
              break;
            case S.HEADER_VALUE_ALMOST_DONE:
              if (c4 !== LF) {
                return;
              }
              state = S.HEADER_FIELD_START;
              break;
            case S.HEADERS_ALMOST_DONE:
              if (c4 !== LF) {
                return;
              }
              callback("onHeadersEnd");
              state = S.PART_DATA_START;
              break;
            case S.PART_DATA_START:
              state = S.PART_DATA;
              mark("onPartData");
            // falls through
            case S.PART_DATA:
              previousIndex = index;
              if (index === 0) {
                i3 += boundaryEnd;
                while (i3 < bufferLength && !(data[i3] in boundaryChars)) {
                  i3 += boundaryLength;
                }
                i3 -= boundaryEnd;
                c4 = data[i3];
              }
              if (index < boundary.length) {
                if (boundary[index] === c4) {
                  if (index === 0) {
                    dataCallback("onPartData", true);
                  }
                  index++;
                } else {
                  index = 0;
                }
              } else if (index === boundary.length) {
                index++;
                if (c4 === CR) {
                  flags |= F.PART_BOUNDARY;
                } else if (c4 === HYPHEN) {
                  flags |= F.LAST_BOUNDARY;
                } else {
                  index = 0;
                }
              } else if (index - 1 === boundary.length) {
                if (flags & F.PART_BOUNDARY) {
                  index = 0;
                  if (c4 === LF) {
                    flags &= ~F.PART_BOUNDARY;
                    callback("onPartEnd");
                    callback("onPartBegin");
                    state = S.HEADER_FIELD_START;
                    break;
                  }
                } else if (flags & F.LAST_BOUNDARY) {
                  if (c4 === HYPHEN) {
                    callback("onPartEnd");
                    state = S.END;
                    flags = 0;
                  } else {
                    index = 0;
                  }
                } else {
                  index = 0;
                }
              }
              if (index > 0) {
                lookbehind[index - 1] = c4;
              } else if (previousIndex > 0) {
                const _lookbehind = new Uint8Array(lookbehind.buffer, lookbehind.byteOffset, lookbehind.byteLength);
                callback("onPartData", 0, previousIndex, _lookbehind);
                previousIndex = 0;
                mark("onPartData");
                i3--;
              }
              break;
            case S.END:
              break;
            default:
              throw new Error(`Unexpected state entered: ${state}`);
          }
        }
        dataCallback("onHeaderField");
        dataCallback("onHeaderValue");
        dataCallback("onPartData");
        this.index = index;
        this.state = state;
        this.flags = flags;
      }
      end() {
        if (this.state === S.HEADER_FIELD_START && this.index === 0 || this.state === S.PART_DATA && this.index === this.boundary.length) {
          this.onPartEnd();
        } else if (this.state !== S.END) {
          throw new Error("MultipartParser.end(): stream ended unexpectedly");
        }
      }
    };
    __name(_fileName, "_fileName");
    __name(toFormData, "toFormData");
  }
});

// packages/core/node_modules/node-fetch/src/body.js
import Stream, { PassThrough } from "node:stream";
import { types, deprecate, promisify } from "node:util";
import { Buffer as Buffer2 } from "node:buffer";
async function consumeBody(data) {
  if (data[INTERNALS].disturbed) {
    throw new TypeError(`body used already for: ${data.url}`);
  }
  data[INTERNALS].disturbed = true;
  if (data[INTERNALS].error) {
    throw data[INTERNALS].error;
  }
  const { body } = data;
  if (body === null) {
    return Buffer2.alloc(0);
  }
  if (!(body instanceof Stream)) {
    return Buffer2.alloc(0);
  }
  const accum = [];
  let accumBytes = 0;
  try {
    for await (const chunk of body) {
      if (data.size > 0 && accumBytes + chunk.length > data.size) {
        const error2 = new FetchError(`content size at ${data.url} over limit: ${data.size}`, "max-size");
        body.destroy(error2);
        throw error2;
      }
      accumBytes += chunk.length;
      accum.push(chunk);
    }
  } catch (error2) {
    const error_ = error2 instanceof FetchBaseError ? error2 : new FetchError(`Invalid response body while trying to fetch ${data.url}: ${error2.message}`, "system", error2);
    throw error_;
  }
  if (body.readableEnded === true || body._readableState.ended === true) {
    try {
      if (accum.every((c4) => typeof c4 === "string")) {
        return Buffer2.from(accum.join(""));
      }
      return Buffer2.concat(accum, accumBytes);
    } catch (error2) {
      throw new FetchError(`Could not create Buffer from response body for ${data.url}: ${error2.message}`, "system", error2);
    }
  } else {
    throw new FetchError(`Premature close of server response while trying to fetch ${data.url}`);
  }
}
var pipeline, INTERNALS, Body, clone, getNonSpecFormDataBoundary, extractContentType, getTotalBytes, writeToStream;
var init_body = __esm({
  "packages/core/node_modules/node-fetch/src/body.js"() {
    init_esbuild_shims();
    init_fetch_blob();
    init_esm_min();
    init_fetch_error();
    init_base();
    init_is();
    pipeline = promisify(Stream.pipeline);
    INTERNALS = Symbol("Body internals");
    Body = class {
      static {
        __name(this, "Body");
      }
      constructor(body, {
        size = 0
      } = {}) {
        let boundary = null;
        if (body === null) {
          body = null;
        } else if (isURLSearchParameters(body)) {
          body = Buffer2.from(body.toString());
        } else if (isBlob(body)) {
        } else if (Buffer2.isBuffer(body)) {
        } else if (types.isAnyArrayBuffer(body)) {
          body = Buffer2.from(body);
        } else if (ArrayBuffer.isView(body)) {
          body = Buffer2.from(body.buffer, body.byteOffset, body.byteLength);
        } else if (body instanceof Stream) {
        } else if (body instanceof FormData2) {
          body = formDataToBlob(body);
          boundary = body.type.split("=")[1];
        } else {
          body = Buffer2.from(String(body));
        }
        let stream2 = body;
        if (Buffer2.isBuffer(body)) {
          stream2 = Stream.Readable.from(body);
        } else if (isBlob(body)) {
          stream2 = Stream.Readable.from(body.stream());
        }
        this[INTERNALS] = {
          body,
          stream: stream2,
          boundary,
          disturbed: false,
          error: null
        };
        this.size = size;
        if (body instanceof Stream) {
          body.on("error", (error_) => {
            const error2 = error_ instanceof FetchBaseError ? error_ : new FetchError(`Invalid response body while trying to fetch ${this.url}: ${error_.message}`, "system", error_);
            this[INTERNALS].error = error2;
          });
        }
      }
      get body() {
        return this[INTERNALS].stream;
      }
      get bodyUsed() {
        return this[INTERNALS].disturbed;
      }
      /**
       * Decode response as ArrayBuffer
       *
       * @return  Promise
       */
      async arrayBuffer() {
        const { buffer, byteOffset, byteLength } = await consumeBody(this);
        return buffer.slice(byteOffset, byteOffset + byteLength);
      }
      async formData() {
        const ct2 = this.headers.get("content-type");
        if (ct2.startsWith("application/x-www-form-urlencoded")) {
          const formData = new FormData2();
          const parameters = new URLSearchParams(await this.text());
          for (const [name3, value] of parameters) {
            formData.append(name3, value);
          }
          return formData;
        }
        const { toFormData: toFormData3 } = await Promise.resolve().then(() => (init_multipart_parser(), multipart_parser_exports));
        return toFormData3(this.body, ct2);
      }
      /**
       * Return raw response as Blob
       *
       * @return Promise
       */
      async blob() {
        const ct2 = this.headers && this.headers.get("content-type") || this[INTERNALS].body && this[INTERNALS].body.type || "";
        const buf = await this.arrayBuffer();
        return new fetch_blob_default([buf], {
          type: ct2
        });
      }
      /**
       * Decode response as json
       *
       * @return  Promise
       */
      async json() {
        const text = await this.text();
        return JSON.parse(text);
      }
      /**
       * Decode response as text
       *
       * @return  Promise
       */
      async text() {
        const buffer = await consumeBody(this);
        return new TextDecoder().decode(buffer);
      }
      /**
       * Decode response as buffer (non-spec api)
       *
       * @return  Promise
       */
      buffer() {
        return consumeBody(this);
      }
    };
    Body.prototype.buffer = deprecate(Body.prototype.buffer, "Please use 'response.arrayBuffer()' instead of 'response.buffer()'", "node-fetch#buffer");
    Object.defineProperties(Body.prototype, {
      body: { enumerable: true },
      bodyUsed: { enumerable: true },
      arrayBuffer: { enumerable: true },
      blob: { enumerable: true },
      json: { enumerable: true },
      text: { enumerable: true },
      data: { get: deprecate(
        () => {
        },
        "data doesn't exist, use json(), text(), arrayBuffer(), or body instead",
        "https://github.com/node-fetch/node-fetch/issues/1000 (response)"
      ) }
    });
    __name(consumeBody, "consumeBody");
    clone = /* @__PURE__ */ __name((instance, highWaterMark) => {
      let p1;
      let p2;
      let { body } = instance[INTERNALS];
      if (instance.bodyUsed) {
        throw new Error("cannot clone body after it is used");
      }
      if (body instanceof Stream && typeof body.getBoundary !== "function") {
        p1 = new PassThrough({ highWaterMark });
        p2 = new PassThrough({ highWaterMark });
        body.pipe(p1);
        body.pipe(p2);
        instance[INTERNALS].stream = p1;
        body = p2;
      }
      return body;
    }, "clone");
    getNonSpecFormDataBoundary = deprecate(
      (body) => body.getBoundary(),
      "form-data doesn't follow the spec and requires special treatment. Use alternative package",
      "https://github.com/node-fetch/node-fetch/issues/1167"
    );
    extractContentType = /* @__PURE__ */ __name((body, request4) => {
      if (body === null) {
        return null;
      }
      if (typeof body === "string") {
        return "text/plain;charset=UTF-8";
      }
      if (isURLSearchParameters(body)) {
        return "application/x-www-form-urlencoded;charset=UTF-8";
      }
      if (isBlob(body)) {
        return body.type || null;
      }
      if (Buffer2.isBuffer(body) || types.isAnyArrayBuffer(body) || ArrayBuffer.isView(body)) {
        return null;
      }
      if (body instanceof FormData2) {
        return `multipart/form-data; boundary=${request4[INTERNALS].boundary}`;
      }
      if (body && typeof body.getBoundary === "function") {
        return `multipart/form-data;boundary=${getNonSpecFormDataBoundary(body)}`;
      }
      if (body instanceof Stream) {
        return null;
      }
      return "text/plain;charset=UTF-8";
    }, "extractContentType");
    getTotalBytes = /* @__PURE__ */ __name((request4) => {
      const { body } = request4[INTERNALS];
      if (body === null) {
        return 0;
      }
      if (isBlob(body)) {
        return body.size;
      }
      if (Buffer2.isBuffer(body)) {
        return body.length;
      }
      if (body && typeof body.getLengthSync === "function") {
        return body.hasKnownLength && body.hasKnownLength() ? body.getLengthSync() : null;
      }
      return null;
    }, "getTotalBytes");
    writeToStream = /* @__PURE__ */ __name(async (dest, { body }) => {
      if (body === null) {
        dest.end();
      } else {
        await pipeline(body, dest);
      }
    }, "writeToStream");
  }
});

// packages/core/node_modules/node-fetch/src/headers.js
import { types as types2 } from "node:util";
import http from "node:http";
function fromRawHeaders(headers = []) {
  return new Headers2(
    headers.reduce((result, value, index, array2) => {
      if (index % 2 === 0) {
        result.push(array2.slice(index, index + 2));
      }
      return result;
    }, []).filter(([name3, value]) => {
      try {
        validateHeaderName(name3);
        validateHeaderValue(name3, String(value));
        return true;
      } catch {
        return false;
      }
    })
  );
}
var validateHeaderName, validateHeaderValue, Headers2;
var init_headers = __esm({
  "packages/core/node_modules/node-fetch/src/headers.js"() {
    init_esbuild_shims();
    validateHeaderName = typeof http.validateHeaderName === "function" ? http.validateHeaderName : (name3) => {
      if (!/^[\^`\-\w!#$%&'*+.|~]+$/.test(name3)) {
        const error2 = new TypeError(`Header name must be a valid HTTP token [${name3}]`);
        Object.defineProperty(error2, "code", { value: "ERR_INVALID_HTTP_TOKEN" });
        throw error2;
      }
    };
    validateHeaderValue = typeof http.validateHeaderValue === "function" ? http.validateHeaderValue : (name3, value) => {
      if (/[^\t\u0020-\u007E\u0080-\u00FF]/.test(value)) {
        const error2 = new TypeError(`Invalid character in header content ["${name3}"]`);
        Object.defineProperty(error2, "code", { value: "ERR_INVALID_CHAR" });
        throw error2;
      }
    };
    Headers2 = class _Headers extends URLSearchParams {
      static {
        __name(this, "Headers");
      }
      /**
       * Headers class
       *
       * @constructor
       * @param {HeadersInit} [init] - Response headers
       */
      constructor(init) {
        let result = [];
        if (init instanceof _Headers) {
          const raw2 = init.raw();
          for (const [name3, values] of Object.entries(raw2)) {
            result.push(...values.map((value) => [name3, value]));
          }
        } else if (init == null) {
        } else if (typeof init === "object" && !types2.isBoxedPrimitive(init)) {
          const method = init[Symbol.iterator];
          if (method == null) {
            result.push(...Object.entries(init));
          } else {
            if (typeof method !== "function") {
              throw new TypeError("Header pairs must be iterable");
            }
            result = [...init].map((pair) => {
              if (typeof pair !== "object" || types2.isBoxedPrimitive(pair)) {
                throw new TypeError("Each header pair must be an iterable object");
              }
              return [...pair];
            }).map((pair) => {
              if (pair.length !== 2) {
                throw new TypeError("Each header pair must be a name/value tuple");
              }
              return [...pair];
            });
          }
        } else {
          throw new TypeError("Failed to construct 'Headers': The provided value is not of type '(sequence<sequence<ByteString>> or record<ByteString, ByteString>)");
        }
        result = result.length > 0 ? result.map(([name3, value]) => {
          validateHeaderName(name3);
          validateHeaderValue(name3, String(value));
          return [String(name3).toLowerCase(), String(value)];
        }) : void 0;
        super(result);
        return new Proxy(this, {
          get(target, p2, receiver) {
            switch (p2) {
              case "append":
              case "set":
                return (name3, value) => {
                  validateHeaderName(name3);
                  validateHeaderValue(name3, String(value));
                  return URLSearchParams.prototype[p2].call(
                    target,
                    String(name3).toLowerCase(),
                    String(value)
                  );
                };
              case "delete":
              case "has":
              case "getAll":
                return (name3) => {
                  validateHeaderName(name3);
                  return URLSearchParams.prototype[p2].call(
                    target,
                    String(name3).toLowerCase()
                  );
                };
              case "keys":
                return () => {
                  target.sort();
                  return new Set(URLSearchParams.prototype.keys.call(target)).keys();
                };
              default:
                return Reflect.get(target, p2, receiver);
            }
          }
        });
      }
      get [Symbol.toStringTag]() {
        return this.constructor.name;
      }
      toString() {
        return Object.prototype.toString.call(this);
      }
      get(name3) {
        const values = this.getAll(name3);
        if (values.length === 0) {
          return null;
        }
        let value = values.join(", ");
        if (/^content-encoding$/i.test(name3)) {
          value = value.toLowerCase();
        }
        return value;
      }
      forEach(callback, thisArg = void 0) {
        for (const name3 of this.keys()) {
          Reflect.apply(callback, thisArg, [this.get(name3), name3, this]);
        }
      }
      *values() {
        for (const name3 of this.keys()) {
          yield this.get(name3);
        }
      }
      /**
       * @type {() => IterableIterator<[string, string]>}
       */
      *entries() {
        for (const name3 of this.keys()) {
          yield [name3, this.get(name3)];
        }
      }
      [Symbol.iterator]() {
        return this.entries();
      }
      /**
       * Node-fetch non-spec method
       * returning all headers and their values as array
       * @returns {Record<string, string[]>}
       */
      raw() {
        return [...this.keys()].reduce((result, key) => {
          result[key] = this.getAll(key);
          return result;
        }, {});
      }
      /**
       * For better console.log(headers) and also to convert Headers into Node.js Request compatible format
       */
      [Symbol.for("nodejs.util.inspect.custom")]() {
        return [...this.keys()].reduce((result, key) => {
          const values = this.getAll(key);
          if (key === "host") {
            result[key] = values[0];
          } else {
            result[key] = values.length > 1 ? values : values[0];
          }
          return result;
        }, {});
      }
    };
    Object.defineProperties(
      Headers2.prototype,
      ["get", "entries", "forEach", "values"].reduce((result, property) => {
        result[property] = { enumerable: true };
        return result;
      }, {})
    );
    __name(fromRawHeaders, "fromRawHeaders");
  }
});

// packages/core/node_modules/node-fetch/src/utils/is-redirect.js
var redirectStatus, isRedirect;
var init_is_redirect = __esm({
  "packages/core/node_modules/node-fetch/src/utils/is-redirect.js"() {
    init_esbuild_shims();
    redirectStatus = /* @__PURE__ */ new Set([301, 302, 303, 307, 308]);
    isRedirect = /* @__PURE__ */ __name((code2) => {
      return redirectStatus.has(code2);
    }, "isRedirect");
  }
});

// packages/core/node_modules/node-fetch/src/response.js
var INTERNALS2, Response2;
var init_response = __esm({
  "packages/core/node_modules/node-fetch/src/response.js"() {
    init_esbuild_shims();
    init_headers();
    init_body();
    init_is_redirect();
    INTERNALS2 = Symbol("Response internals");
    Response2 = class _Response extends Body {
      static {
        __name(this, "Response");
      }
      constructor(body = null, options2 = {}) {
        super(body, options2);
        const status = options2.status != null ? options2.status : 200;
        const headers = new Headers2(options2.headers);
        if (body !== null && !headers.has("Content-Type")) {
          const contentType = extractContentType(body, this);
          if (contentType) {
            headers.append("Content-Type", contentType);
          }
        }
        this[INTERNALS2] = {
          type: "default",
          url: options2.url,
          status,
          statusText: options2.statusText || "",
          headers,
          counter: options2.counter,
          highWaterMark: options2.highWaterMark
        };
      }
      get type() {
        return this[INTERNALS2].type;
      }
      get url() {
        return this[INTERNALS2].url || "";
      }
      get status() {
        return this[INTERNALS2].status;
      }
      /**
       * Convenience property representing if the request ended normally
       */
      get ok() {
        return this[INTERNALS2].status >= 200 && this[INTERNALS2].status < 300;
      }
      get redirected() {
        return this[INTERNALS2].counter > 0;
      }
      get statusText() {
        return this[INTERNALS2].statusText;
      }
      get headers() {
        return this[INTERNALS2].headers;
      }
      get highWaterMark() {
        return this[INTERNALS2].highWaterMark;
      }
      /**
       * Clone this response
       *
       * @return  Response
       */
      clone() {
        return new _Response(clone(this, this.highWaterMark), {
          type: this.type,
          url: this.url,
          status: this.status,
          statusText: this.statusText,
          headers: this.headers,
          ok: this.ok,
          redirected: this.redirected,
          size: this.size,
          highWaterMark: this.highWaterMark
        });
      }
      /**
       * @param {string} url    The URL that the new response is to originate from.
       * @param {number} status An optional status code for the response (e.g., 302.)
       * @returns {Response}    A Response object.
       */
      static redirect(url2, status = 302) {
        if (!isRedirect(status)) {
          throw new RangeError('Failed to execute "redirect" on "response": Invalid status code');
        }
        return new _Response(null, {
          headers: {
            location: new URL(url2).toString()
          },
          status
        });
      }
      static error() {
        const response = new _Response(null, { status: 0, statusText: "" });
        response[INTERNALS2].type = "error";
        return response;
      }
      static json(data = void 0, init = {}) {
        const body = JSON.stringify(data);
        if (body === void 0) {
          throw new TypeError("data is not JSON serializable");
        }
        const headers = new Headers2(init && init.headers);
        if (!headers.has("content-type")) {
          headers.set("content-type", "application/json");
        }
        return new _Response(body, {
          ...init,
          headers
        });
      }
      get [Symbol.toStringTag]() {
        return "Response";
      }
    };
    Object.defineProperties(Response2.prototype, {
      type: { enumerable: true },
      url: { enumerable: true },
      status: { enumerable: true },
      ok: { enumerable: true },
      redirected: { enumerable: true },
      statusText: { enumerable: true },
      headers: { enumerable: true },
      clone: { enumerable: true }
    });
  }
});

// packages/core/node_modules/node-fetch/src/utils/get-search.js
var getSearch;
var init_get_search = __esm({
  "packages/core/node_modules/node-fetch/src/utils/get-search.js"() {
    init_esbuild_shims();
    getSearch = /* @__PURE__ */ __name((parsedURL) => {
      if (parsedURL.search) {
        return parsedURL.search;
      }
      const lastOffset = parsedURL.href.length - 1;
      const hash = parsedURL.hash || (parsedURL.href[lastOffset] === "#" ? "#" : "");
      return parsedURL.href[lastOffset - hash.length] === "?" ? "?" : "";
    }, "getSearch");
  }
});

// packages/core/node_modules/node-fetch/src/utils/referrer.js
import { isIP } from "node:net";
function stripURLForUseAsAReferrer(url2, originOnly = false) {
  if (url2 == null) {
    return "no-referrer";
  }
  url2 = new URL(url2);
  if (/^(about|blob|data):$/.test(url2.protocol)) {
    return "no-referrer";
  }
  url2.username = "";
  url2.password = "";
  url2.hash = "";
  if (originOnly) {
    url2.pathname = "";
    url2.search = "";
  }
  return url2;
}
function validateReferrerPolicy(referrerPolicy) {
  if (!ReferrerPolicy.has(referrerPolicy)) {
    throw new TypeError(`Invalid referrerPolicy: ${referrerPolicy}`);
  }
  return referrerPolicy;
}
function isOriginPotentiallyTrustworthy(url2) {
  if (/^(http|ws)s:$/.test(url2.protocol)) {
    return true;
  }
  const hostIp = url2.host.replace(/(^\[)|(]$)/g, "");
  const hostIPVersion = isIP(hostIp);
  if (hostIPVersion === 4 && /^127\./.test(hostIp)) {
    return true;
  }
  if (hostIPVersion === 6 && /^(((0+:){7})|(::(0+:){0,6}))0*1$/.test(hostIp)) {
    return true;
  }
  if (url2.host === "localhost" || url2.host.endsWith(".localhost")) {
    return false;
  }
  if (url2.protocol === "file:") {
    return true;
  }
  return false;
}
function isUrlPotentiallyTrustworthy(url2) {
  if (/^about:(blank|srcdoc)$/.test(url2)) {
    return true;
  }
  if (url2.protocol === "data:") {
    return true;
  }
  if (/^(blob|filesystem):$/.test(url2.protocol)) {
    return true;
  }
  return isOriginPotentiallyTrustworthy(url2);
}
function determineRequestsReferrer(request4, { referrerURLCallback, referrerOriginCallback } = {}) {
  if (request4.referrer === "no-referrer" || request4.referrerPolicy === "") {
    return null;
  }
  const policy = request4.referrerPolicy;
  if (request4.referrer === "about:client") {
    return "no-referrer";
  }
  const referrerSource = request4.referrer;
  let referrerURL = stripURLForUseAsAReferrer(referrerSource);
  let referrerOrigin = stripURLForUseAsAReferrer(referrerSource, true);
  if (referrerURL.toString().length > 4096) {
    referrerURL = referrerOrigin;
  }
  if (referrerURLCallback) {
    referrerURL = referrerURLCallback(referrerURL);
  }
  if (referrerOriginCallback) {
    referrerOrigin = referrerOriginCallback(referrerOrigin);
  }
  const currentURL = new URL(request4.url);
  switch (policy) {
    case "no-referrer":
      return "no-referrer";
    case "origin":
      return referrerOrigin;
    case "unsafe-url":
      return referrerURL;
    case "strict-origin":
      if (isUrlPotentiallyTrustworthy(referrerURL) && !isUrlPotentiallyTrustworthy(currentURL)) {
        return "no-referrer";
      }
      return referrerOrigin.toString();
    case "strict-origin-when-cross-origin":
      if (referrerURL.origin === currentURL.origin) {
        return referrerURL;
      }
      if (isUrlPotentiallyTrustworthy(referrerURL) && !isUrlPotentiallyTrustworthy(currentURL)) {
        return "no-referrer";
      }
      return referrerOrigin;
    case "same-origin":
      if (referrerURL.origin === currentURL.origin) {
        return referrerURL;
      }
      return "no-referrer";
    case "origin-when-cross-origin":
      if (referrerURL.origin === currentURL.origin) {
        return referrerURL;
      }
      return referrerOrigin;
    case "no-referrer-when-downgrade":
      if (isUrlPotentiallyTrustworthy(referrerURL) && !isUrlPotentiallyTrustworthy(currentURL)) {
        return "no-referrer";
      }
      return referrerURL;
    default:
      throw new TypeError(`Invalid referrerPolicy: ${policy}`);
  }
}
function parseReferrerPolicyFromHeader(headers) {
  const policyTokens = (headers.get("referrer-policy") || "").split(/[,\s]+/);
  let policy = "";
  for (const token2 of policyTokens) {
    if (token2 && ReferrerPolicy.has(token2)) {
      policy = token2;
    }
  }
  return policy;
}
var ReferrerPolicy, DEFAULT_REFERRER_POLICY;
var init_referrer = __esm({
  "packages/core/node_modules/node-fetch/src/utils/referrer.js"() {
    init_esbuild_shims();
    __name(stripURLForUseAsAReferrer, "stripURLForUseAsAReferrer");
    ReferrerPolicy = /* @__PURE__ */ new Set([
      "",
      "no-referrer",
      "no-referrer-when-downgrade",
      "same-origin",
      "origin",
      "strict-origin",
      "origin-when-cross-origin",
      "strict-origin-when-cross-origin",
      "unsafe-url"
    ]);
    DEFAULT_REFERRER_POLICY = "strict-origin-when-cross-origin";
    __name(validateReferrerPolicy, "validateReferrerPolicy");
    __name(isOriginPotentiallyTrustworthy, "isOriginPotentiallyTrustworthy");
    __name(isUrlPotentiallyTrustworthy, "isUrlPotentiallyTrustworthy");
    __name(determineRequestsReferrer, "determineRequestsReferrer");
    __name(parseReferrerPolicyFromHeader, "parseReferrerPolicyFromHeader");
  }
});

// packages/core/node_modules/node-fetch/src/request.js
import { format as formatUrl } from "node:url";
import { deprecate as deprecate2 } from "node:util";
var INTERNALS3, isRequest, doBadDataWarn, Request2, getNodeRequestOptions;
var init_request = __esm({
  "packages/core/node_modules/node-fetch/src/request.js"() {
    init_esbuild_shims();
    init_headers();
    init_body();
    init_is();
    init_get_search();
    init_referrer();
    INTERNALS3 = Symbol("Request internals");
    isRequest = /* @__PURE__ */ __name((object3) => {
      return typeof object3 === "object" && typeof object3[INTERNALS3] === "object";
    }, "isRequest");
    doBadDataWarn = deprecate2(
      () => {
      },
      ".data is not a valid RequestInit property, use .body instead",
      "https://github.com/node-fetch/node-fetch/issues/1000 (request)"
    );
    Request2 = class _Request extends Body {
      static {
        __name(this, "Request");
      }
      constructor(input, init = {}) {
        let parsedURL;
        if (isRequest(input)) {
          parsedURL = new URL(input.url);
        } else {
          parsedURL = new URL(input);
          input = {};
        }
        if (parsedURL.username !== "" || parsedURL.password !== "") {
          throw new TypeError(`${parsedURL} is an url with embedded credentials.`);
        }
        let method = init.method || input.method || "GET";
        if (/^(delete|get|head|options|post|put)$/i.test(method)) {
          method = method.toUpperCase();
        }
        if (!isRequest(init) && "data" in init) {
          doBadDataWarn();
        }
        if ((init.body != null || isRequest(input) && input.body !== null) && (method === "GET" || method === "HEAD")) {
          throw new TypeError("Request with GET/HEAD method cannot have body");
        }
        const inputBody = init.body ? init.body : isRequest(input) && input.body !== null ? clone(input) : null;
        super(inputBody, {
          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, this);
          if (contentType) {
            headers.set("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 or EventTarget");
        }
        let referrer = init.referrer == null ? input.referrer : init.referrer;
        if (referrer === "") {
          referrer = "no-referrer";
        } else if (referrer) {
          const parsedReferrer = new URL(referrer);
          referrer = /^about:(\/\/)?client$/.test(parsedReferrer) ? "client" : parsedReferrer;
        } else {
          referrer = void 0;
        }
        this[INTERNALS3] = {
          method,
          redirect: init.redirect || input.redirect || "follow",
          headers,
          parsedURL,
          signal,
          referrer
        };
        this.follow = init.follow === void 0 ? input.follow === void 0 ? 20 : input.follow : init.follow;
        this.compress = init.compress === void 0 ? input.compress === void 0 ? true : input.compress : init.compress;
        this.counter = init.counter || input.counter || 0;
        this.agent = init.agent || input.agent;
        this.highWaterMark = init.highWaterMark || input.highWaterMark || 16384;
        this.insecureHTTPParser = init.insecureHTTPParser || input.insecureHTTPParser || false;
        this.referrerPolicy = init.referrerPolicy || input.referrerPolicy || "";
      }
      /** @returns {string} */
      get method() {
        return this[INTERNALS3].method;
      }
      /** @returns {string} */
      get url() {
        return formatUrl(this[INTERNALS3].parsedURL);
      }
      /** @returns {Headers} */
      get headers() {
        return this[INTERNALS3].headers;
      }
      get redirect() {
        return this[INTERNALS3].redirect;
      }
      /** @returns {AbortSignal} */
      get signal() {
        return this[INTERNALS3].signal;
      }
      // https://fetch.spec.whatwg.org/#dom-request-referrer
      get referrer() {
        if (this[INTERNALS3].referrer === "no-referrer") {
          return "";
        }
        if (this[INTERNALS3].referrer === "client") {
          return "about:client";
        }
        if (this[INTERNALS3].referrer) {
          return this[INTERNALS3].referrer.toString();
        }
        return void 0;
      }
      get referrerPolicy() {
        return this[INTERNALS3].referrerPolicy;
      }
      set referrerPolicy(referrerPolicy) {
        this[INTERNALS3].referrerPolicy = validateReferrerPolicy(referrerPolicy);
      }
      /**
       * Clone this request
       *
       * @return  Request
       */
      clone() {
        return new _Request(this);
      }
      get [Symbol.toStringTag]() {
        return "Request";
      }
    };
    Object.defineProperties(Request2.prototype, {
      method: { enumerable: true },
      url: { enumerable: true },
      headers: { enumerable: true },
      redirect: { enumerable: true },
      clone: { enumerable: true },
      signal: { enumerable: true },
      referrer: { enumerable: true },
      referrerPolicy: { enumerable: true }
    });
    getNodeRequestOptions = /* @__PURE__ */ __name((request4) => {
      const { parsedURL } = request4[INTERNALS3];
      const headers = new Headers2(request4[INTERNALS3].headers);
      if (!headers.has("Accept")) {
        headers.set("Accept", "*/*");
      }
      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" && !Number.isNaN(totalBytes)) {
          contentLengthValue = String(totalBytes);
        }
      }
      if (contentLengthValue) {
        headers.set("Content-Length", contentLengthValue);
      }
      if (request4.referrerPolicy === "") {
        request4.referrerPolicy = DEFAULT_REFERRER_POLICY;
      }
      if (request4.referrer && request4.referrer !== "no-referrer") {
        request4[INTERNALS3].referrer = determineRequestsReferrer(request4);
      } else {
        request4[INTERNALS3].referrer = "no-referrer";
      }
      if (request4[INTERNALS3].referrer instanceof URL) {
        headers.set("Referer", request4.referrer);
      }
      if (!headers.has("User-Agent")) {
        headers.set("User-Agent", "node-fetch");
      }
      if (request4.compress && !headers.has("Accept-Encoding")) {
        headers.set("Accept-Encoding", "gzip, deflate, br");
      }
      let { agent } = request4;
      if (typeof agent === "function") {
        agent = agent(parsedURL);
      }
      const search = getSearch(parsedURL);
      const options2 = {
        // Overwrite search to retain trailing ? (issue #776)
        path: parsedURL.pathname + search,
        // The following options are not expressed in the URL
        method: request4.method,
        headers: headers[Symbol.for("nodejs.util.inspect.custom")](),
        insecureHTTPParser: request4.insecureHTTPParser,
        agent
      };
      return {
        /** @type {URL} */
        parsedURL,
        options: options2
      };
    }, "getNodeRequestOptions");
  }
});

// packages/core/node_modules/node-fetch/src/errors/abort-error.js
var AbortError;
var init_abort_error = __esm({
  "packages/core/node_modules/node-fetch/src/errors/abort-error.js"() {
    init_esbuild_shims();
    init_base();
    AbortError = class extends FetchBaseError {
      static {
        __name(this, "AbortError");
      }
      constructor(message, type = "aborted") {
        super(message, type);
      }
    };
  }
});

// packages/core/node_modules/node-fetch/src/index.js
var src_exports = {};
__export(src_exports, {
  AbortError: () => AbortError,
  Blob: () => fetch_blob_default,
  FetchError: () => FetchError,
  File: () => file_default,
  FormData: () => FormData2,
  Headers: () => Headers2,
  Request: () => Request2,
  Response: () => Response2,
  blobFrom: () => blobFrom,
  blobFromSync: () => blobFromSync,
  default: () => fetch2,
  fileFrom: () => fileFrom,
  fileFromSync: () => fileFromSync,
  isRedirect: () => isRedirect
});
import http2 from "node:http";
import https from "node:https";
import zlib from "node:zlib";
import Stream2, { PassThrough as PassThrough2, pipeline as pump } from "node:stream";
import { Buffer as Buffer3 } from "node:buffer";
async function fetch2(url2, options_) {
  return new Promise((resolve30, reject) => {
    const request4 = new Request2(url2, options_);
    const { parsedURL, options: options2 } = getNodeRequestOptions(request4);
    if (!supportedSchemas.has(parsedURL.protocol)) {
      throw new TypeError(`node-fetch cannot load ${url2}. URL scheme "${parsedURL.protocol.replace(/:$/, "")}" is not supported.`);
    }
    if (parsedURL.protocol === "data:") {
      const data = dist_default(request4.url);
      const response2 = new Response2(data, { headers: { "Content-Type": data.typeFull } });
      resolve30(response2);
      return;
    }
    const send = (parsedURL.protocol === "https:" ? https : http2).request;
    const { signal } = request4;
    let response = null;
    const abort = /* @__PURE__ */ __name(() => {
      const error2 = new AbortError("The operation was aborted.");
      reject(error2);
      if (request4.body && request4.body instanceof Stream2.Readable) {
        request4.body.destroy(error2);
      }
      if (!response || !response.body) {
        return;
      }
      response.body.emit("error", error2);
    }, "abort");
    if (signal && signal.aborted) {
      abort();
      return;
    }
    const abortAndFinalize = /* @__PURE__ */ __name(() => {
      abort();
      finalize();
    }, "abortAndFinalize");
    const request_ = send(parsedURL.toString(), options2);
    if (signal) {
      signal.addEventListener("abort", abortAndFinalize);
    }
    const finalize = /* @__PURE__ */ __name(() => {
      request_.abort();
      if (signal) {
        signal.removeEventListener("abort", abortAndFinalize);
      }
    }, "finalize");
    request_.on("error", (error2) => {
      reject(new FetchError(`request to ${request4.url} failed, reason: ${error2.message}`, "system", error2));
      finalize();
    });
    fixResponseChunkedTransferBadEnding(request_, (error2) => {
      if (response && response.body) {
        response.body.destroy(error2);
      }
    });
    if (process.version < "v14") {
      request_.on("socket", (s5) => {
        let endedWithEventsCount;
        s5.prependListener("end", () => {
          endedWithEventsCount = s5._eventsCount;
        });
        s5.prependListener("close", (hadError) => {
          if (response && endedWithEventsCount < s5._eventsCount && !hadError) {
            const error2 = new Error("Premature close");
            error2.code = "ERR_STREAM_PREMATURE_CLOSE";
            response.body.emit("error", error2);
          }
        });
      });
    }
    request_.on("response", (response_) => {
      request_.setTimeout(0);
      const headers = fromRawHeaders(response_.rawHeaders);
      if (isRedirect(response_.statusCode)) {
        const location = headers.get("Location");
        let locationURL = null;
        try {
          locationURL = location === null ? null : new URL(location, request4.url);
        } catch {
          if (request4.redirect !== "manual") {
            reject(new FetchError(`uri requested responds with an invalid redirect URL: ${location}`, "invalid-redirect"));
            finalize();
            return;
          }
        }
        switch (request4.redirect) {
          case "error":
            reject(new FetchError(`uri requested responds with a redirect, redirect mode is set to error: ${request4.url}`, "no-redirect"));
            finalize();
            return;
          case "manual":
            break;
          case "follow": {
            if (locationURL === null) {
              break;
            }
            if (request4.counter >= request4.follow) {
              reject(new FetchError(`maximum redirect reached at: ${request4.url}`, "max-redirect"));
              finalize();
              return;
            }
            const requestOptions = {
              headers: new Headers2(request4.headers),
              follow: request4.follow,
              counter: request4.counter + 1,
              agent: request4.agent,
              compress: request4.compress,
              method: request4.method,
              body: clone(request4),
              signal: request4.signal,
              size: request4.size,
              referrer: request4.referrer,
              referrerPolicy: request4.referrerPolicy
            };
            if (!isDomainOrSubdomain(request4.url, locationURL) || !isSameProtocol(request4.url, locationURL)) {
              for (const name3 of ["authorization", "www-authenticate", "cookie", "cookie2"]) {
                requestOptions.headers.delete(name3);
              }
            }
            if (response_.statusCode !== 303 && request4.body && options_.body instanceof Stream2.Readable) {
              reject(new FetchError("Cannot follow redirect with body being a readable stream", "unsupported-redirect"));
              finalize();
              return;
            }
            if (response_.statusCode === 303 || (response_.statusCode === 301 || response_.statusCode === 302) && request4.method === "POST") {
              requestOptions.method = "GET";
              requestOptions.body = void 0;
              requestOptions.headers.delete("content-length");
            }
            const responseReferrerPolicy = parseReferrerPolicyFromHeader(headers);
            if (responseReferrerPolicy) {
              requestOptions.referrerPolicy = responseReferrerPolicy;
            }
            resolve30(fetch2(new Request2(locationURL, requestOptions)));
            finalize();
            return;
          }
          default:
            return reject(new TypeError(`Redirect option '${request4.redirect}' is not a valid value of RequestRedirect`));
        }
      }
      if (signal) {
        response_.once("end", () => {
          signal.removeEventListener("abort", abortAndFinalize);
        });
      }
      let body = pump(response_, new PassThrough2(), (error2) => {
        if (error2) {
          reject(error2);
        }
      });
      if (process.version < "v12.10") {
        response_.on("aborted", abortAndFinalize);
      }
      const responseOptions = {
        url: request4.url,
        status: response_.statusCode,
        statusText: response_.statusMessage,
        headers,
        size: request4.size,
        counter: request4.counter,
        highWaterMark: request4.highWaterMark
      };
      const codings = headers.get("Content-Encoding");
      if (!request4.compress || request4.method === "HEAD" || codings === null || response_.statusCode === 204 || response_.statusCode === 304) {
        response = new Response2(body, responseOptions);
        resolve30(response);
        return;
      }
      const zlibOptions = {
        flush: zlib.Z_SYNC_FLUSH,
        finishFlush: zlib.Z_SYNC_FLUSH
      };
      if (codings === "gzip" || codings === "x-gzip") {
        body = pump(body, zlib.createGunzip(zlibOptions), (error2) => {
          if (error2) {
            reject(error2);
          }
        });
        response = new Response2(body, responseOptions);
        resolve30(response);
        return;
      }
      if (codings === "deflate" || codings === "x-deflate") {
        const raw2 = pump(response_, new PassThrough2(), (error2) => {
          if (error2) {
            reject(error2);
          }
        });
        raw2.once("data", (chunk) => {
          if ((chunk[0] & 15) === 8) {
            body = pump(body, zlib.createInflate(), (error2) => {
              if (error2) {
                reject(error2);
              }
            });
          } else {
            body = pump(body, zlib.createInflateRaw(), (error2) => {
              if (error2) {
                reject(error2);
              }
            });
          }
          response = new Response2(body, responseOptions);
          resolve30(response);
        });
        raw2.once("end", () => {
          if (!response) {
            response = new Response2(body, responseOptions);
            resolve30(response);
          }
        });
        return;
      }
      if (codings === "br") {
        body = pump(body, zlib.createBrotliDecompress(), (error2) => {
          if (error2) {
            reject(error2);
          }
        });
        response = new Response2(body, responseOptions);
        resolve30(response);
        return;
      }
      response = new Response2(body, responseOptions);
      resolve30(response);
    });
    writeToStream(request_, request4).catch(reject);
  });
}
function fixResponseChunkedTransferBadEnding(request4, errorCallback) {
  const LAST_CHUNK = Buffer3.from("0\r\n\r\n");
  let isChunkedTransfer = false;
  let properLastChunkReceived = false;
  let previousChunk;
  request4.on("response", (response) => {
    const { headers } = response;
    isChunkedTransfer = headers["transfer-encoding"] === "chunked" && !headers["content-length"];
  });
  request4.on("socket", (socket) => {
    const onSocketClose = /* @__PURE__ */ __name(() => {
      if (isChunkedTransfer && !properLastChunkReceived) {
        const error2 = new Error("Premature close");
        error2.code = "ERR_STREAM_PREMATURE_CLOSE";
        errorCallback(error2);
      }
    }, "onSocketClose");
    const onData = /* @__PURE__ */ __name((buf) => {
      properLastChunkReceived = Buffer3.compare(buf.slice(-5), LAST_CHUNK) === 0;
      if (!properLastChunkReceived && previousChunk) {
        properLastChunkReceived = Buffer3.compare(previousChunk.slice(-3), LAST_CHUNK.slice(0, 3)) === 0 && Buffer3.compare(buf.slice(-2), LAST_CHUNK.slice(3)) === 0;
      }
      previousChunk = buf;
    }, "onData");
    socket.prependListener("close", onSocketClose);
    socket.on("data", onData);
    request4.on("close", () => {
      socket.removeListener("close", onSocketClose);
      socket.removeListener("data", onData);
    });
  });
}
var supportedSchemas;
var init_src = __esm({
  "packages/core/node_modules/node-fetch/src/index.js"() {
    init_esbuild_shims();
    init_dist();
    init_body();
    init_response();
    init_headers();
    init_request();
    init_fetch_error();
    init_abort_error();
    init_is_redirect();
    init_esm_min();
    init_is();
    init_referrer();
    init_from();
    supportedSchemas = /* @__PURE__ */ new Set(["data:", "http:", "https:"]);
    __name(fetch2, "fetch");
    __name(fixResponseChunkedTransferBadEnding, "fixResponseChunkedTransferBadEnding");
  }
});

// packages/core/node_modules/gaxios/build/cjs/src/gaxios.js
var require_gaxios = __commonJS({
  "packages/core/node_modules/gaxios/build/cjs/src/gaxios.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    var __importDefault = exports2 && exports2.__importDefault || function(mod2) {
      return mod2 && mod2.__esModule ? mod2 : { "default": mod2 };
    };
    var _a7;
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.Gaxios = void 0;
    var extend_1 = __importDefault(require_extend());
    var https_1 = __require("https");
    var common_js_1 = require_common();
    var retry_js_1 = require_retry2();
    var stream_1 = __require("stream");
    var interceptor_js_1 = require_interceptor();
    var randomUUID10 = /* @__PURE__ */ __name(async () => globalThis.crypto?.randomUUID() || (await import("crypto")).randomUUID(), "randomUUID");
    var HTTP_STATUS_NO_CONTENT = 204;
    var Gaxios = class {
      static {
        __name(this, "Gaxios");
      }
      agentCache = /* @__PURE__ */ new Map();
      /**
       * Default HTTP options that will be used for every HTTP request.
       */
      defaults;
      /**
       * Interceptors
       */
      interceptors;
      /**
       * The Gaxios class is responsible for making HTTP requests.
       * @param defaults The default set of options to be used for this instance.
       */
      constructor(defaults3) {
        this.defaults = defaults3 || {};
        this.interceptors = {
          request: new interceptor_js_1.GaxiosInterceptorManager(),
          response: new interceptor_js_1.GaxiosInterceptorManager()
        };
      }
      /**
       * A {@link fetch `fetch`} compliant API for {@link Gaxios}.
       *
       * @remarks
       *
       * This is useful as a drop-in replacement for `fetch` API usage.
       *
       * @example
       *
       * ```ts
       * const gaxios = new Gaxios();
       * const myFetch: typeof fetch = (...args) => gaxios.fetch(...args);
       * await myFetch('https://example.com');
       * ```
       *
       * @param args `fetch` API or `Gaxios#request` parameters
       * @returns the {@link Response} with Gaxios-added properties
       */
      fetch(...args) {
        const input = args[0];
        const init = args[1];
        let url2 = void 0;
        const headers = new Headers();
        if (typeof input === "string") {
          url2 = new URL(input);
        } else if (input instanceof URL) {
          url2 = input;
        } else if (input && input.url) {
          url2 = new URL(input.url);
        }
        if (input && typeof input === "object" && "headers" in input) {
          _a7.mergeHeaders(headers, input.headers);
        }
        if (init) {
          _a7.mergeHeaders(headers, new Headers(init.headers));
        }
        if (typeof input === "object" && !(input instanceof URL)) {
          return this.request({ ...init, ...input, headers, url: url2 });
        } else {
          return this.request({ ...init, headers, url: url2 });
        }
      }
      /**
       * 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 = {}) {
        let prepared = await this.#prepareRequest(opts);
        prepared = await this.#applyRequestInterceptors(prepared);
        return this.#applyResponseInterceptors(this._request(prepared));
      }
      async _defaultAdapter(config2) {
        const fetchImpl = config2.fetchImplementation || this.defaults.fetchImplementation || await _a7.#getFetch();
        const preparedOpts = { ...config2 };
        delete preparedOpts.data;
        const res = await fetchImpl(config2.url, preparedOpts);
        const data = await this.getResponseData(config2, res);
        if (!Object.getOwnPropertyDescriptor(res, "data")?.configurable) {
          Object.defineProperties(res, {
            data: {
              configurable: true,
              writable: true,
              enumerable: true,
              value: data
            }
          });
        }
        return Object.assign(res, { config: config2, 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) {
        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") {
              const response = [];
              for await (const chunk of translatedResponse.data) {
                response.push(chunk);
              }
              translatedResponse.data = response.toString();
            }
            const errorInfo = common_js_1.GaxiosError.extractAPIErrorFromResponse(translatedResponse, `Request failed with status code ${translatedResponse.status}`);
            throw new common_js_1.GaxiosError(errorInfo?.message, opts, translatedResponse, errorInfo);
          }
          return translatedResponse;
        } catch (e4) {
          let err;
          if (e4 instanceof common_js_1.GaxiosError) {
            err = e4;
          } else if (e4 instanceof Error) {
            err = new common_js_1.GaxiosError(e4.message, opts, void 0, e4);
          } else {
            err = new common_js_1.GaxiosError("Unexpected Gaxios Error", opts, void 0, e4);
          }
          const { shouldRetry, config: config2 } = await (0, retry_js_1.getRetryConfig)(err);
          if (shouldRetry && config2) {
            err.config.retryConfig.currentRetryAttempt = config2.retryConfig.currentRetryAttempt;
            opts.retryConfig = err.config?.retryConfig;
            this.#appendTimeoutToSignal(opts);
            return this._request(opts);
          }
          if (opts.errorRedactor) {
            opts.errorRedactor(err);
          }
          throw err;
        }
      }
      async getResponseData(opts, res) {
        if (res.status === HTTP_STATUS_NO_CONTENT) {
          return "";
        }
        if (opts.maxContentLength && res.headers.has("content-length") && opts.maxContentLength < Number.parseInt(res.headers?.get("content-length") || "")) {
          throw new common_js_1.GaxiosError("Response's `Content-Length` is over the limit.", opts, Object.assign(res, { config: opts }));
        }
        switch (opts.responseType) {
          case "stream":
            return res.body;
          case "json": {
            const data = await res.text();
            try {
              return JSON.parse(data);
            } catch {
              return data;
            }
          }
          case "arraybuffer":
            return res.arrayBuffer();
          case "blob":
            return res.blob();
          case "text":
            return res.text();
          default:
            return this.getResponseDataFromContentType(res);
        }
      }
      #urlMayUseProxy(url2, noProxy = []) {
        const candidate = new URL(url2);
        const noProxyList = [...noProxy];
        const noProxyEnvList = (process.env.NO_PROXY ?? process.env.no_proxy)?.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) {
            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;
      }
      /**
       * Applies the request interceptors. The request interceptors are applied after the
       * call to prepareRequest is completed.
       *
       * @param {GaxiosOptionsPrepared} options The current set of options.
       *
       * @returns {Promise<GaxiosOptionsPrepared>} Promise that resolves to the set of options or response after interceptors are applied.
       */
      async #applyRequestInterceptors(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;
      }
      /**
       * Applies the response interceptors. The response interceptors are applied after the
       * call to request is made.
       *
       * @param {GaxiosOptionsPrepared} options The current set of options.
       *
       * @returns {Promise<GaxiosOptionsPrepared>} Promise that resolves to the set of options or response after interceptors are applied.
       */
      async #applyResponseInterceptors(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;
      }
      /**
       * 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
       */
      async #prepareRequest(options2) {
        const preparedHeaders = new Headers(this.defaults.headers);
        _a7.mergeHeaders(preparedHeaders, options2.headers);
        const opts = (0, extend_1.default)(true, {}, this.defaults, options2);
        if (!opts.url) {
          throw new Error("URL is required.");
        }
        if (opts.baseURL) {
          opts.url = new URL(opts.url, opts.baseURL);
        }
        opts.url = new URL(opts.url);
        if (opts.params) {
          if (opts.paramsSerializer) {
            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;
          } else {
            const url2 = opts.url instanceof URL ? opts.url : new URL(opts.url);
            for (const [key, value] of new URLSearchParams(opts.params)) {
              url2.searchParams.append(key, value);
            }
            opts.url = url2;
          }
        }
        if (typeof options2.maxContentLength === "number") {
          opts.size = options2.maxContentLength;
        }
        if (typeof options2.maxRedirects === "number") {
          opts.follow = options2.maxRedirects;
        }
        const shouldDirectlyPassData = typeof opts.data === "string" || opts.data instanceof ArrayBuffer || opts.data instanceof Blob || // Node 18 does not have a global `File` object
        globalThis.File && opts.data instanceof File || opts.data instanceof FormData || opts.data instanceof stream_1.Readable || opts.data instanceof ReadableStream || opts.data instanceof String || opts.data instanceof URLSearchParams || ArrayBuffer.isView(opts.data) || // `Buffer` (Node.js), `DataView`, `TypedArray`
        /**
         * @deprecated `node-fetch` or another third-party's request types
         */
        ["Blob", "File", "FormData"].includes(opts.data?.constructor?.name || "");
        if (opts.multipart?.length) {
          const boundary = await randomUUID10();
          preparedHeaders.set("content-type", `multipart/related; boundary=${boundary}`);
          opts.body = stream_1.Readable.from(this.getMultipartRequest(opts.multipart, boundary));
        } else if (shouldDirectlyPassData) {
          opts.body = opts.data;
        } else if (typeof opts.data === "object") {
          if (preparedHeaders.get("Content-Type") === "application/x-www-form-urlencoded") {
            opts.body = opts.paramsSerializer ? opts.paramsSerializer(opts.data) : new URLSearchParams(opts.data);
          } else {
            if (!preparedHeaders.has("content-type")) {
              preparedHeaders.set("content-type", "application/json");
            }
            opts.body = JSON.stringify(opts.data);
          }
        } else if (opts.data) {
          opts.body = opts.data;
        }
        opts.validateStatus = opts.validateStatus || this.validateStatus;
        opts.responseType = opts.responseType || "unknown";
        if (!preparedHeaders.has("accept") && opts.responseType === "json") {
          preparedHeaders.set("accept", "application/json");
        }
        const proxy = opts.proxy || process?.env?.HTTPS_PROXY || process?.env?.https_proxy || process?.env?.HTTP_PROXY || process?.env?.http_proxy;
        if (opts.agent) {
        } else if (proxy && this.#urlMayUseProxy(opts.url, opts.noProxy)) {
          const HttpsProxyAgent2 = await _a7.#getProxyAgent();
          if (this.agentCache.has(proxy)) {
            opts.agent = this.agentCache.get(proxy);
          } else {
            opts.agent = new HttpsProxyAgent2(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_js_1.defaultErrorRedactor;
        }
        if (opts.body && !("duplex" in opts)) {
          opts.duplex = "half";
        }
        this.#appendTimeoutToSignal(opts);
        return Object.assign(opts, {
          headers: preparedHeaders,
          url: opts.url instanceof URL ? opts.url : new URL(opts.url)
        });
      }
      #appendTimeoutToSignal(opts) {
        if (opts.timeout) {
          const timeoutSignal = AbortSignal.timeout(opts.timeout);
          if (opts.signal && !opts.signal.aborted) {
            opts.signal = AbortSignal.any([opts.signal, timeoutSignal]);
          } else {
            opts.signal = timeoutSignal;
          }
        }
      }
      /**
       * By default, throw for any non-2xx status code
       * @param status status code from the HTTP response
       */
      validateStatus(status) {
        return status >= 200 && status < 300;
      }
      /**
       * Attempts to parse a response by looking at the Content-Type header.
       * @param {Response} response the HTTP response.
       * @returns 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 {
          }
          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 {GaxiosMultipartOptions[]} 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.get("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;
      }
      /**
       * A cache for the lazily-loaded proxy agent.
       *
       * Should use {@link Gaxios[#getProxyAgent]} to retrieve.
       */
      // using `import` to dynamically import the types here
      static #proxyAgent;
      /**
       * A cache for the lazily-loaded fetch library.
       *
       * Should use {@link Gaxios[#getFetch]} to retrieve.
       */
      //
      static #fetch;
      /**
       * Imports, caches, and returns a proxy agent - if not already imported
       *
       * @returns A proxy agent
       */
      static async #getProxyAgent() {
        this.#proxyAgent ||= (await Promise.resolve().then(() => __toESM(require_dist2()))).HttpsProxyAgent;
        return this.#proxyAgent;
      }
      static async #getFetch() {
        const hasWindow = typeof window !== "undefined" && !!window;
        this.#fetch ||= hasWindow ? window.fetch : (await Promise.resolve().then(() => (init_src(), src_exports))).default;
        return this.#fetch;
      }
      /**
       * Merges headers.
       * If the base headers do not exist a new `Headers` object will be returned.
       *
       * @remarks
       *
       * Using this utility can be helpful when the headers are not known to exist:
       * - if they exist as `Headers`, that instance will be used
       *   - it improves performance and allows users to use their existing references to their `Headers`
       * - if they exist in another form (`HeadersInit`), they will be used to create a new `Headers` object
       * - if the base headers do not exist a new `Headers` object will be created
       *
       * @param base headers to append/overwrite to
       * @param append headers to append/overwrite with
       * @returns the base headers instance with merged `Headers`
       */
      static mergeHeaders(base, ...append2) {
        base = base instanceof Headers ? base : new Headers(base);
        for (const headers of append2) {
          const add = headers instanceof Headers ? headers : new Headers(headers);
          add.forEach((value, key) => {
            key === "set-cookie" ? base.append(key, value) : base.set(key, value);
          });
        }
        return base;
      }
    };
    exports2.Gaxios = Gaxios;
    _a7 = Gaxios;
  }
});

// packages/core/node_modules/gaxios/build/cjs/src/index.js
var require_src2 = __commonJS({
  "packages/core/node_modules/gaxios/build/cjs/src/index.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    var __createBinding = exports2 && exports2.__createBinding || (Object.create ? function(o3, m3, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc2 = Object.getOwnPropertyDescriptor(m3, k2);
      if (!desc2 || ("get" in desc2 ? !m3.__esModule : desc2.writable || desc2.configurable)) {
        desc2 = { enumerable: true, get: /* @__PURE__ */ __name(function() {
          return m3[k2];
        }, "get") };
      }
      Object.defineProperty(o3, k22, desc2);
    } : function(o3, m3, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o3[k22] = m3[k2];
    });
    var __exportStar = exports2 && exports2.__exportStar || function(m3, exports3) {
      for (var p2 in m3) if (p2 !== "default" && !Object.prototype.hasOwnProperty.call(exports3, p2)) __createBinding(exports3, m3, p2);
    };
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.instance = exports2.Gaxios = exports2.GaxiosError = void 0;
    exports2.request = request4;
    var gaxios_js_1 = require_gaxios();
    Object.defineProperty(exports2, "Gaxios", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return gaxios_js_1.Gaxios;
    }, "get") });
    var common_js_1 = require_common();
    Object.defineProperty(exports2, "GaxiosError", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return common_js_1.GaxiosError;
    }, "get") });
    __exportStar(require_interceptor(), exports2);
    exports2.instance = new gaxios_js_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 clone4(configObject) {
        var div, convertBase, parseNumeric, P2 = 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(v2, b2) {
          var alphabet2, c4, caseChanged, e4, i3, isNum, len, str2, x3 = this;
          if (!(x3 instanceof BigNumber2)) return new BigNumber2(v2, b2);
          if (b2 == null) {
            if (v2 && v2._isBigNumber === true) {
              x3.s = v2.s;
              if (!v2.c || v2.e > MAX_EXP) {
                x3.c = x3.e = null;
              } else if (v2.e < MIN_EXP) {
                x3.c = [x3.e = 0];
              } else {
                x3.e = v2.e;
                x3.c = v2.c.slice();
              }
              return;
            }
            if ((isNum = typeof v2 == "number") && v2 * 0 == 0) {
              x3.s = 1 / v2 < 0 ? (v2 = -v2, -1) : 1;
              if (v2 === ~~v2) {
                for (e4 = 0, i3 = v2; i3 >= 10; i3 /= 10, e4++) ;
                if (e4 > MAX_EXP) {
                  x3.c = x3.e = null;
                } else {
                  x3.e = e4;
                  x3.c = [v2];
                }
                return;
              }
              str2 = String(v2);
            } else {
              if (!isNumeric.test(str2 = String(v2))) return parseNumeric(x3, str2, isNum);
              x3.s = str2.charCodeAt(0) == 45 ? (str2 = str2.slice(1), -1) : 1;
            }
            if ((e4 = str2.indexOf(".")) > -1) str2 = str2.replace(".", "");
            if ((i3 = str2.search(/e/i)) > 0) {
              if (e4 < 0) e4 = i3;
              e4 += +str2.slice(i3 + 1);
              str2 = str2.substring(0, i3);
            } else if (e4 < 0) {
              e4 = str2.length;
            }
          } else {
            intCheck(b2, 2, ALPHABET.length, "Base");
            if (b2 == 10 && alphabetHasNormalDecimalDigits) {
              x3 = new BigNumber2(v2);
              return round(x3, DECIMAL_PLACES + x3.e + 1, ROUNDING_MODE);
            }
            str2 = String(v2);
            if (isNum = typeof v2 == "number") {
              if (v2 * 0 != 0) return parseNumeric(x3, str2, isNum, b2);
              x3.s = 1 / v2 < 0 ? (str2 = str2.slice(1), -1) : 1;
              if (BigNumber2.DEBUG && str2.replace(/^0\.0*|\./, "").length > 15) {
                throw Error(tooManyDigits + v2);
              }
            } else {
              x3.s = str2.charCodeAt(0) === 45 ? (str2 = str2.slice(1), -1) : 1;
            }
            alphabet2 = ALPHABET.slice(0, b2);
            e4 = i3 = 0;
            for (len = str2.length; i3 < len; i3++) {
              if (alphabet2.indexOf(c4 = str2.charAt(i3)) < 0) {
                if (c4 == ".") {
                  if (i3 > e4) {
                    e4 = len;
                    continue;
                  }
                } else if (!caseChanged) {
                  if (str2 == str2.toUpperCase() && (str2 = str2.toLowerCase()) || str2 == str2.toLowerCase() && (str2 = str2.toUpperCase())) {
                    caseChanged = true;
                    i3 = -1;
                    e4 = 0;
                    continue;
                  }
                }
                return parseNumeric(x3, String(v2), isNum, b2);
              }
            }
            isNum = false;
            str2 = convertBase(str2, b2, 10, x3.s);
            if ((e4 = str2.indexOf(".")) > -1) str2 = str2.replace(".", "");
            else e4 = str2.length;
          }
          for (i3 = 0; str2.charCodeAt(i3) === 48; i3++) ;
          for (len = str2.length; str2.charCodeAt(--len) === 48; ) ;
          if (str2 = str2.slice(i3, ++len)) {
            len -= i3;
            if (isNum && BigNumber2.DEBUG && len > 15 && (v2 > MAX_SAFE_INTEGER || v2 !== mathfloor(v2))) {
              throw Error(tooManyDigits + x3.s * v2);
            }
            if ((e4 = e4 - i3 - 1) > MAX_EXP) {
              x3.c = x3.e = null;
            } else if (e4 < MIN_EXP) {
              x3.c = [x3.e = 0];
            } else {
              x3.e = e4;
              x3.c = [];
              i3 = (e4 + 1) % LOG_BASE;
              if (e4 < 0) i3 += LOG_BASE;
              if (i3 < len) {
                if (i3) x3.c.push(+str2.slice(0, i3));
                for (len -= LOG_BASE; i3 < len; ) {
                  x3.c.push(+str2.slice(i3, i3 += LOG_BASE));
                }
                i3 = LOG_BASE - (str2 = str2.slice(i3)).length;
              } else {
                i3 -= len;
              }
              for (; i3--; str2 += "0") ;
              x3.c.push(+str2);
            }
          } else {
            x3.c = [x3.e = 0];
          }
        }
        __name(BigNumber2, "BigNumber");
        BigNumber2.clone = clone4;
        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 p2, v2;
          if (obj != null) {
            if (typeof obj == "object") {
              if (obj.hasOwnProperty(p2 = "DECIMAL_PLACES")) {
                v2 = obj[p2];
                intCheck(v2, 0, MAX2, p2);
                DECIMAL_PLACES = v2;
              }
              if (obj.hasOwnProperty(p2 = "ROUNDING_MODE")) {
                v2 = obj[p2];
                intCheck(v2, 0, 8, p2);
                ROUNDING_MODE = v2;
              }
              if (obj.hasOwnProperty(p2 = "EXPONENTIAL_AT")) {
                v2 = obj[p2];
                if (v2 && v2.pop) {
                  intCheck(v2[0], -MAX2, 0, p2);
                  intCheck(v2[1], 0, MAX2, p2);
                  TO_EXP_NEG = v2[0];
                  TO_EXP_POS = v2[1];
                } else {
                  intCheck(v2, -MAX2, MAX2, p2);
                  TO_EXP_NEG = -(TO_EXP_POS = v2 < 0 ? -v2 : v2);
                }
              }
              if (obj.hasOwnProperty(p2 = "RANGE")) {
                v2 = obj[p2];
                if (v2 && v2.pop) {
                  intCheck(v2[0], -MAX2, -1, p2);
                  intCheck(v2[1], 1, MAX2, p2);
                  MIN_EXP = v2[0];
                  MAX_EXP = v2[1];
                } else {
                  intCheck(v2, -MAX2, MAX2, p2);
                  if (v2) {
                    MIN_EXP = -(MAX_EXP = v2 < 0 ? -v2 : v2);
                  } else {
                    throw Error(bignumberError + p2 + " cannot be zero: " + v2);
                  }
                }
              }
              if (obj.hasOwnProperty(p2 = "CRYPTO")) {
                v2 = obj[p2];
                if (v2 === !!v2) {
                  if (v2) {
                    if (typeof crypto != "undefined" && crypto && (crypto.getRandomValues || crypto.randomBytes)) {
                      CRYPTO = v2;
                    } else {
                      CRYPTO = !v2;
                      throw Error(bignumberError + "crypto unavailable");
                    }
                  } else {
                    CRYPTO = v2;
                  }
                } else {
                  throw Error(bignumberError + p2 + " not true or false: " + v2);
                }
              }
              if (obj.hasOwnProperty(p2 = "MODULO_MODE")) {
                v2 = obj[p2];
                intCheck(v2, 0, 9, p2);
                MODULO_MODE = v2;
              }
              if (obj.hasOwnProperty(p2 = "POW_PRECISION")) {
                v2 = obj[p2];
                intCheck(v2, 0, MAX2, p2);
                POW_PRECISION = v2;
              }
              if (obj.hasOwnProperty(p2 = "FORMAT")) {
                v2 = obj[p2];
                if (typeof v2 == "object") FORMAT = v2;
                else throw Error(bignumberError + p2 + " not an object: " + v2);
              }
              if (obj.hasOwnProperty(p2 = "ALPHABET")) {
                v2 = obj[p2];
                if (typeof v2 == "string" && !/^.?$|[+\-.\s]|(.).*\1/.test(v2)) {
                  alphabetHasNormalDecimalDigits = v2.slice(0, 10) == "0123456789";
                  ALPHABET = v2;
                } else {
                  throw Error(bignumberError + p2 + " invalid: " + v2);
                }
              }
            } 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(v2) {
          if (!v2 || v2._isBigNumber !== true) return false;
          if (!BigNumber2.DEBUG) return true;
          var i3, n3, c4 = v2.c, e4 = v2.e, s5 = v2.s;
          out: if ({}.toString.call(c4) == "[object Array]") {
            if ((s5 === 1 || s5 === -1) && e4 >= -MAX2 && e4 <= MAX2 && e4 === mathfloor(e4)) {
              if (c4[0] === 0) {
                if (e4 === 0 && c4.length === 1) return true;
                break out;
              }
              i3 = (e4 + 1) % LOG_BASE;
              if (i3 < 1) i3 += LOG_BASE;
              if (String(c4[0]).length == i3) {
                for (i3 = 0; i3 < c4.length; i3++) {
                  n3 = c4[i3];
                  if (n3 < 0 || n3 >= BASE || n3 !== mathfloor(n3)) break out;
                }
                if (n3 !== 0) return true;
              }
            }
          } else if (c4 === null && e4 === null && (s5 === null || s5 === 1 || s5 === -1)) {
            return true;
          }
          throw Error(bignumberError + "Invalid BigNumber: " + v2);
        };
        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 a2, b2, e4, k2, v2, i3 = 0, c4 = [], rand = new BigNumber2(ONE);
            if (dp == null) dp = DECIMAL_PLACES;
            else intCheck(dp, 0, MAX2);
            k2 = mathceil(dp / LOG_BASE);
            if (CRYPTO) {
              if (crypto.getRandomValues) {
                a2 = crypto.getRandomValues(new Uint32Array(k2 *= 2));
                for (; i3 < k2; ) {
                  v2 = a2[i3] * 131072 + (a2[i3 + 1] >>> 11);
                  if (v2 >= 9e15) {
                    b2 = crypto.getRandomValues(new Uint32Array(2));
                    a2[i3] = b2[0];
                    a2[i3 + 1] = b2[1];
                  } else {
                    c4.push(v2 % 1e14);
                    i3 += 2;
                  }
                }
                i3 = k2 / 2;
              } else if (crypto.randomBytes) {
                a2 = crypto.randomBytes(k2 *= 7);
                for (; i3 < k2; ) {
                  v2 = (a2[i3] & 31) * 281474976710656 + a2[i3 + 1] * 1099511627776 + a2[i3 + 2] * 4294967296 + a2[i3 + 3] * 16777216 + (a2[i3 + 4] << 16) + (a2[i3 + 5] << 8) + a2[i3 + 6];
                  if (v2 >= 9e15) {
                    crypto.randomBytes(7).copy(a2, i3);
                  } else {
                    c4.push(v2 % 1e14);
                    i3 += 7;
                  }
                }
                i3 = k2 / 7;
              } else {
                CRYPTO = false;
                throw Error(bignumberError + "crypto unavailable");
              }
            }
            if (!CRYPTO) {
              for (; i3 < k2; ) {
                v2 = random53bitInt();
                if (v2 < 9e15) c4[i3++] = v2 % 1e14;
              }
            }
            k2 = c4[--i3];
            dp %= LOG_BASE;
            if (k2 && dp) {
              v2 = POWS_TEN[LOG_BASE - dp];
              c4[i3] = mathfloor(k2 / v2) * v2;
            }
            for (; c4[i3] === 0; c4.pop(), i3--) ;
            if (i3 < 0) {
              c4 = [e4 = 0];
            } else {
              for (e4 = -1; c4[0] === 0; c4.splice(0, 1), e4 -= LOG_BASE) ;
              for (i3 = 1, v2 = c4[0]; v2 >= 10; v2 /= 10, i3++) ;
              if (i3 < LOG_BASE) e4 -= LOG_BASE - i3;
            }
            rand.e = e4;
            rand.c = c4;
            return rand;
          };
        }();
        BigNumber2.sum = function() {
          var i3 = 1, args = arguments, sum = new BigNumber2(args[0]);
          for (; i3 < args.length; ) sum = sum.plus(args[i3++]);
          return sum;
        };
        convertBase = /* @__PURE__ */ function() {
          var decimal = "0123456789";
          function toBaseOut(str2, baseIn, baseOut, alphabet2) {
            var j2, arr = [0], arrL, i3 = 0, len = str2.length;
            for (; i3 < len; ) {
              for (arrL = arr.length; arrL--; arr[arrL] *= baseIn) ;
              arr[0] += alphabet2.indexOf(str2.charAt(i3++));
              for (j2 = 0; j2 < arr.length; j2++) {
                if (arr[j2] > baseOut - 1) {
                  if (arr[j2 + 1] == null) arr[j2 + 1] = 0;
                  arr[j2 + 1] += arr[j2] / baseOut | 0;
                  arr[j2] %= baseOut;
                }
              }
            }
            return arr.reverse();
          }
          __name(toBaseOut, "toBaseOut");
          return function(str2, baseIn, baseOut, sign, callerIsToString) {
            var alphabet2, d2, e4, k2, r5, x3, xc, y2, i3 = str2.indexOf("."), dp = DECIMAL_PLACES, rm = ROUNDING_MODE;
            if (i3 >= 0) {
              k2 = POW_PRECISION;
              POW_PRECISION = 0;
              str2 = str2.replace(".", "");
              y2 = new BigNumber2(baseIn);
              x3 = y2.pow(str2.length - i3);
              POW_PRECISION = k2;
              y2.c = toBaseOut(
                toFixedPoint(coeffToString(x3.c), x3.e, "0"),
                10,
                baseOut,
                decimal
              );
              y2.e = y2.c.length;
            }
            xc = toBaseOut(str2, baseIn, baseOut, callerIsToString ? (alphabet2 = ALPHABET, decimal) : (alphabet2 = decimal, ALPHABET));
            e4 = k2 = xc.length;
            for (; xc[--k2] == 0; xc.pop()) ;
            if (!xc[0]) return alphabet2.charAt(0);
            if (i3 < 0) {
              --e4;
            } else {
              x3.c = xc;
              x3.e = e4;
              x3.s = sign;
              x3 = div(x3, y2, dp, rm, baseOut);
              xc = x3.c;
              r5 = x3.r;
              e4 = x3.e;
            }
            d2 = e4 + dp + 1;
            i3 = xc[d2];
            k2 = baseOut / 2;
            r5 = r5 || d2 < 0 || xc[d2 + 1] != null;
            r5 = rm < 4 ? (i3 != null || r5) && (rm == 0 || rm == (x3.s < 0 ? 3 : 2)) : i3 > k2 || i3 == k2 && (rm == 4 || r5 || rm == 6 && xc[d2 - 1] & 1 || rm == (x3.s < 0 ? 8 : 7));
            if (d2 < 1 || !xc[0]) {
              str2 = r5 ? toFixedPoint(alphabet2.charAt(1), -dp, alphabet2.charAt(0)) : alphabet2.charAt(0);
            } else {
              xc.length = d2;
              if (r5) {
                for (--baseOut; ++xc[--d2] > baseOut; ) {
                  xc[d2] = 0;
                  if (!d2) {
                    ++e4;
                    xc = [1].concat(xc);
                  }
                }
              }
              for (k2 = xc.length; !xc[--k2]; ) ;
              for (i3 = 0, str2 = ""; i3 <= k2; str2 += alphabet2.charAt(xc[i3++])) ;
              str2 = toFixedPoint(str2, e4, alphabet2.charAt(0));
            }
            return str2;
          };
        }();
        div = /* @__PURE__ */ function() {
          function multiply(x3, k2, base) {
            var m3, temp, xlo, xhi, carry = 0, i3 = x3.length, klo = k2 % SQRT_BASE, khi = k2 / SQRT_BASE | 0;
            for (x3 = x3.slice(); i3--; ) {
              xlo = x3[i3] % SQRT_BASE;
              xhi = x3[i3] / SQRT_BASE | 0;
              m3 = khi * xlo + xhi * klo;
              temp = klo * xlo + m3 % SQRT_BASE * SQRT_BASE + carry;
              carry = (temp / base | 0) + (m3 / SQRT_BASE | 0) + khi * xhi;
              x3[i3] = temp % base;
            }
            if (carry) x3 = [carry].concat(x3);
            return x3;
          }
          __name(multiply, "multiply");
          function compare2(a2, b2, aL, bL) {
            var i3, cmp;
            if (aL != bL) {
              cmp = aL > bL ? 1 : -1;
            } else {
              for (i3 = cmp = 0; i3 < aL; i3++) {
                if (a2[i3] != b2[i3]) {
                  cmp = a2[i3] > b2[i3] ? 1 : -1;
                  break;
                }
              }
            }
            return cmp;
          }
          __name(compare2, "compare");
          function subtract(a2, b2, aL, base) {
            var i3 = 0;
            for (; aL--; ) {
              a2[aL] -= i3;
              i3 = a2[aL] < b2[aL] ? 1 : 0;
              a2[aL] = i3 * base + a2[aL] - b2[aL];
            }
            for (; !a2[0] && a2.length > 1; a2.splice(0, 1)) ;
          }
          __name(subtract, "subtract");
          return function(x3, y2, dp, rm, base) {
            var cmp, e4, i3, more, n3, prod, prodL, q2, qc, rem, remL, rem0, xi, xL, yc0, yL, yz, s5 = x3.s == y2.s ? 1 : -1, xc = x3.c, yc = y2.c;
            if (!xc || !xc[0] || !yc || !yc[0]) {
              return new BigNumber2(
                // Return NaN if either NaN, or both Infinity or 0.
                !x3.s || !y2.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 ? s5 * 0 : s5 / 0
                )
              );
            }
            q2 = new BigNumber2(s5);
            qc = q2.c = [];
            e4 = x3.e - y2.e;
            s5 = dp + e4 + 1;
            if (!base) {
              base = BASE;
              e4 = bitFloor(x3.e / LOG_BASE) - bitFloor(y2.e / LOG_BASE);
              s5 = s5 / LOG_BASE | 0;
            }
            for (i3 = 0; yc[i3] == (xc[i3] || 0); i3++) ;
            if (yc[i3] > (xc[i3] || 0)) e4--;
            if (s5 < 0) {
              qc.push(1);
              more = true;
            } else {
              xL = xc.length;
              yL = yc.length;
              i3 = 0;
              s5 += 2;
              n3 = mathfloor(base / (yc[0] + 1));
              if (n3 > 1) {
                yc = multiply(yc, n3, base);
                xc = multiply(xc, n3, 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 {
                n3 = 0;
                cmp = compare2(yc, rem, yL, remL);
                if (cmp < 0) {
                  rem0 = rem[0];
                  if (yL != remL) rem0 = rem0 * base + (rem[1] || 0);
                  n3 = mathfloor(rem0 / yc0);
                  if (n3 > 1) {
                    if (n3 >= base) n3 = base - 1;
                    prod = multiply(yc, n3, base);
                    prodL = prod.length;
                    remL = rem.length;
                    while (compare2(prod, rem, prodL, remL) == 1) {
                      n3--;
                      subtract(prod, yL < prodL ? yz : yc, prodL, base);
                      prodL = prod.length;
                      cmp = 1;
                    }
                  } else {
                    if (n3 == 0) {
                      cmp = n3 = 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) {
                      n3++;
                      subtract(rem, yL < remL ? yz : yc, remL, base);
                      remL = rem.length;
                    }
                  }
                } else if (cmp === 0) {
                  n3++;
                  rem = [0];
                }
                qc[i3++] = n3;
                if (rem[0]) {
                  rem[remL++] = xc[xi] || 0;
                } else {
                  rem = [xc[xi]];
                  remL = 1;
                }
              } while ((xi++ < xL || rem[0] != null) && s5--);
              more = rem[0] != null;
              if (!qc[0]) qc.splice(0, 1);
            }
            if (base == BASE) {
              for (i3 = 1, s5 = qc[0]; s5 >= 10; s5 /= 10, i3++) ;
              round(q2, dp + (q2.e = i3 + e4 * LOG_BASE - 1) + 1, rm, more);
            } else {
              q2.e = e4;
              q2.r = +more;
            }
            return q2;
          };
        }();
        function format4(n3, i3, rm, id) {
          var c0, e4, ne2, len, str2;
          if (rm == null) rm = ROUNDING_MODE;
          else intCheck(rm, 0, 8);
          if (!n3.c) return n3.toString();
          c0 = n3.c[0];
          ne2 = n3.e;
          if (i3 == null) {
            str2 = coeffToString(n3.c);
            str2 = id == 1 || id == 2 && (ne2 <= TO_EXP_NEG || ne2 >= TO_EXP_POS) ? toExponential(str2, ne2) : toFixedPoint(str2, ne2, "0");
          } else {
            n3 = round(new BigNumber2(n3), i3, rm);
            e4 = n3.e;
            str2 = coeffToString(n3.c);
            len = str2.length;
            if (id == 1 || id == 2 && (i3 <= e4 || e4 <= TO_EXP_NEG)) {
              for (; len < i3; str2 += "0", len++) ;
              str2 = toExponential(str2, e4);
            } else {
              i3 -= ne2;
              str2 = toFixedPoint(str2, e4, "0");
              if (e4 + 1 > len) {
                if (--i3 > 0) for (str2 += "."; i3--; str2 += "0") ;
              } else {
                i3 += e4 - len;
                if (i3 > 0) {
                  if (e4 + 1 == len) str2 += ".";
                  for (; i3--; str2 += "0") ;
                }
              }
            }
          }
          return n3.s < 0 && c0 ? "-" + str2 : str2;
        }
        __name(format4, "format");
        function maxOrMin(args, n3) {
          var k2, y2, i3 = 1, x3 = new BigNumber2(args[0]);
          for (; i3 < args.length; i3++) {
            y2 = new BigNumber2(args[i3]);
            if (!y2.s || (k2 = compare(x3, y2)) === n3 || k2 === 0 && x3.s === n3) {
              x3 = y2;
            }
          }
          return x3;
        }
        __name(maxOrMin, "maxOrMin");
        function normalise(n3, c4, e4) {
          var i3 = 1, j2 = c4.length;
          for (; !c4[--j2]; c4.pop()) ;
          for (j2 = c4[0]; j2 >= 10; j2 /= 10, i3++) ;
          if ((e4 = i3 + e4 * LOG_BASE - 1) > MAX_EXP) {
            n3.c = n3.e = null;
          } else if (e4 < MIN_EXP) {
            n3.c = [n3.e = 0];
          } else {
            n3.e = e4;
            n3.c = c4;
          }
          return n3;
        }
        __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(x3, str2, isNum, b2) {
            var base, s5 = isNum ? str2 : str2.replace(whitespaceOrPlus, "");
            if (isInfinityOrNaN.test(s5)) {
              x3.s = isNaN(s5) ? null : s5 < 0 ? -1 : 1;
            } else {
              if (!isNum) {
                s5 = s5.replace(basePrefix, function(m3, p1, p2) {
                  base = (p2 = p2.toLowerCase()) == "x" ? 16 : p2 == "b" ? 2 : 8;
                  return !b2 || b2 == base ? p1 : m3;
                });
                if (b2) {
                  base = b2;
                  s5 = s5.replace(dotAfter, "$1").replace(dotBefore, "0.$1");
                }
                if (str2 != s5) return new BigNumber2(s5, base);
              }
              if (BigNumber2.DEBUG) {
                throw Error(bignumberError + "Not a" + (b2 ? " base " + b2 : "") + " number: " + str2);
              }
              x3.s = null;
            }
            x3.c = x3.e = null;
          };
        }();
        function round(x3, sd, rm, r5) {
          var d2, i3, j2, k2, n3, ni, rd, xc = x3.c, pows10 = POWS_TEN;
          if (xc) {
            out: {
              for (d2 = 1, k2 = xc[0]; k2 >= 10; k2 /= 10, d2++) ;
              i3 = sd - d2;
              if (i3 < 0) {
                i3 += LOG_BASE;
                j2 = sd;
                n3 = xc[ni = 0];
                rd = mathfloor(n3 / pows10[d2 - j2 - 1] % 10);
              } else {
                ni = mathceil((i3 + 1) / LOG_BASE);
                if (ni >= xc.length) {
                  if (r5) {
                    for (; xc.length <= ni; xc.push(0)) ;
                    n3 = rd = 0;
                    d2 = 1;
                    i3 %= LOG_BASE;
                    j2 = i3 - LOG_BASE + 1;
                  } else {
                    break out;
                  }
                } else {
                  n3 = k2 = xc[ni];
                  for (d2 = 1; k2 >= 10; k2 /= 10, d2++) ;
                  i3 %= LOG_BASE;
                  j2 = i3 - LOG_BASE + d2;
                  rd = j2 < 0 ? 0 : mathfloor(n3 / pows10[d2 - j2 - 1] % 10);
                }
              }
              r5 = r5 || 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 || (j2 < 0 ? n3 : n3 % pows10[d2 - j2 - 1]);
              r5 = rm < 4 ? (rd || r5) && (rm == 0 || rm == (x3.s < 0 ? 3 : 2)) : rd > 5 || rd == 5 && (rm == 4 || r5 || rm == 6 && // Check whether the digit to the left of the rounding digit is odd.
              (i3 > 0 ? j2 > 0 ? n3 / pows10[d2 - j2] : 0 : xc[ni - 1]) % 10 & 1 || rm == (x3.s < 0 ? 8 : 7));
              if (sd < 1 || !xc[0]) {
                xc.length = 0;
                if (r5) {
                  sd -= x3.e + 1;
                  xc[0] = pows10[(LOG_BASE - sd % LOG_BASE) % LOG_BASE];
                  x3.e = -sd || 0;
                } else {
                  xc[0] = x3.e = 0;
                }
                return x3;
              }
              if (i3 == 0) {
                xc.length = ni;
                k2 = 1;
                ni--;
              } else {
                xc.length = ni + 1;
                k2 = pows10[LOG_BASE - i3];
                xc[ni] = j2 > 0 ? mathfloor(n3 / pows10[d2 - j2] % pows10[j2]) * k2 : 0;
              }
              if (r5) {
                for (; ; ) {
                  if (ni == 0) {
                    for (i3 = 1, j2 = xc[0]; j2 >= 10; j2 /= 10, i3++) ;
                    j2 = xc[0] += k2;
                    for (k2 = 1; j2 >= 10; j2 /= 10, k2++) ;
                    if (i3 != k2) {
                      x3.e++;
                      if (xc[0] == BASE) xc[0] = 1;
                    }
                    break;
                  } else {
                    xc[ni] += k2;
                    if (xc[ni] != BASE) break;
                    xc[ni--] = 0;
                    k2 = 1;
                  }
                }
              }
              for (i3 = xc.length; xc[--i3] === 0; xc.pop()) ;
            }
            if (x3.e > MAX_EXP) {
              x3.c = x3.e = null;
            } else if (x3.e < MIN_EXP) {
              x3.c = [x3.e = 0];
            }
          }
          return x3;
        }
        __name(round, "round");
        function valueOf(n3) {
          var str2, e4 = n3.e;
          if (e4 === null) return n3.toString();
          str2 = coeffToString(n3.c);
          str2 = e4 <= TO_EXP_NEG || e4 >= TO_EXP_POS ? toExponential(str2, e4) : toFixedPoint(str2, e4, "0");
          return n3.s < 0 ? "-" + str2 : str2;
        }
        __name(valueOf, "valueOf");
        P2.absoluteValue = P2.abs = function() {
          var x3 = new BigNumber2(this);
          if (x3.s < 0) x3.s = 1;
          return x3;
        };
        P2.comparedTo = function(y2, b2) {
          return compare(this, new BigNumber2(y2, b2));
        };
        P2.decimalPlaces = P2.dp = function(dp, rm) {
          var c4, n3, v2, x3 = this;
          if (dp != null) {
            intCheck(dp, 0, MAX2);
            if (rm == null) rm = ROUNDING_MODE;
            else intCheck(rm, 0, 8);
            return round(new BigNumber2(x3), dp + x3.e + 1, rm);
          }
          if (!(c4 = x3.c)) return null;
          n3 = ((v2 = c4.length - 1) - bitFloor(this.e / LOG_BASE)) * LOG_BASE;
          if (v2 = c4[v2]) for (; v2 % 10 == 0; v2 /= 10, n3--) ;
          if (n3 < 0) n3 = 0;
          return n3;
        };
        P2.dividedBy = P2.div = function(y2, b2) {
          return div(this, new BigNumber2(y2, b2), DECIMAL_PLACES, ROUNDING_MODE);
        };
        P2.dividedToIntegerBy = P2.idiv = function(y2, b2) {
          return div(this, new BigNumber2(y2, b2), 0, 1);
        };
        P2.exponentiatedBy = P2.pow = function(n3, m3) {
          var half, isModExp, i3, k2, more, nIsBig, nIsNeg, nIsOdd, y2, x3 = this;
          n3 = new BigNumber2(n3);
          if (n3.c && !n3.isInteger()) {
            throw Error(bignumberError + "Exponent not an integer: " + valueOf(n3));
          }
          if (m3 != null) m3 = new BigNumber2(m3);
          nIsBig = n3.e > 14;
          if (!x3.c || !x3.c[0] || x3.c[0] == 1 && !x3.e && x3.c.length == 1 || !n3.c || !n3.c[0]) {
            y2 = new BigNumber2(Math.pow(+valueOf(x3), nIsBig ? n3.s * (2 - isOdd(n3)) : +valueOf(n3)));
            return m3 ? y2.mod(m3) : y2;
          }
          nIsNeg = n3.s < 0;
          if (m3) {
            if (m3.c ? !m3.c[0] : !m3.s) return new BigNumber2(NaN);
            isModExp = !nIsNeg && x3.isInteger() && m3.isInteger();
            if (isModExp) x3 = x3.mod(m3);
          } else if (n3.e > 9 && (x3.e > 0 || x3.e < -1 || (x3.e == 0 ? x3.c[0] > 1 || nIsBig && x3.c[1] >= 24e7 : x3.c[0] < 8e13 || nIsBig && x3.c[0] <= 9999975e7))) {
            k2 = x3.s < 0 && isOdd(n3) ? -0 : 0;
            if (x3.e > -1) k2 = 1 / k2;
            return new BigNumber2(nIsNeg ? 1 / k2 : k2);
          } else if (POW_PRECISION) {
            k2 = mathceil(POW_PRECISION / LOG_BASE + 2);
          }
          if (nIsBig) {
            half = new BigNumber2(0.5);
            if (nIsNeg) n3.s = 1;
            nIsOdd = isOdd(n3);
          } else {
            i3 = Math.abs(+valueOf(n3));
            nIsOdd = i3 % 2;
          }
          y2 = new BigNumber2(ONE);
          for (; ; ) {
            if (nIsOdd) {
              y2 = y2.times(x3);
              if (!y2.c) break;
              if (k2) {
                if (y2.c.length > k2) y2.c.length = k2;
              } else if (isModExp) {
                y2 = y2.mod(m3);
              }
            }
            if (i3) {
              i3 = mathfloor(i3 / 2);
              if (i3 === 0) break;
              nIsOdd = i3 % 2;
            } else {
              n3 = n3.times(half);
              round(n3, n3.e + 1, 1);
              if (n3.e > 14) {
                nIsOdd = isOdd(n3);
              } else {
                i3 = +valueOf(n3);
                if (i3 === 0) break;
                nIsOdd = i3 % 2;
              }
            }
            x3 = x3.times(x3);
            if (k2) {
              if (x3.c && x3.c.length > k2) x3.c.length = k2;
            } else if (isModExp) {
              x3 = x3.mod(m3);
            }
          }
          if (isModExp) return y2;
          if (nIsNeg) y2 = ONE.div(y2);
          return m3 ? y2.mod(m3) : k2 ? round(y2, POW_PRECISION, ROUNDING_MODE, more) : y2;
        };
        P2.integerValue = function(rm) {
          var n3 = new BigNumber2(this);
          if (rm == null) rm = ROUNDING_MODE;
          else intCheck(rm, 0, 8);
          return round(n3, n3.e + 1, rm);
        };
        P2.isEqualTo = P2.eq = function(y2, b2) {
          return compare(this, new BigNumber2(y2, b2)) === 0;
        };
        P2.isFinite = function() {
          return !!this.c;
        };
        P2.isGreaterThan = P2.gt = function(y2, b2) {
          return compare(this, new BigNumber2(y2, b2)) > 0;
        };
        P2.isGreaterThanOrEqualTo = P2.gte = function(y2, b2) {
          return (b2 = compare(this, new BigNumber2(y2, b2))) === 1 || b2 === 0;
        };
        P2.isInteger = function() {
          return !!this.c && bitFloor(this.e / LOG_BASE) > this.c.length - 2;
        };
        P2.isLessThan = P2.lt = function(y2, b2) {
          return compare(this, new BigNumber2(y2, b2)) < 0;
        };
        P2.isLessThanOrEqualTo = P2.lte = function(y2, b2) {
          return (b2 = compare(this, new BigNumber2(y2, b2))) === -1 || b2 === 0;
        };
        P2.isNaN = function() {
          return !this.s;
        };
        P2.isNegative = function() {
          return this.s < 0;
        };
        P2.isPositive = function() {
          return this.s > 0;
        };
        P2.isZero = function() {
          return !!this.c && this.c[0] == 0;
        };
        P2.minus = function(y2, b2) {
          var i3, j2, t5, xLTy, x3 = this, a2 = x3.s;
          y2 = new BigNumber2(y2, b2);
          b2 = y2.s;
          if (!a2 || !b2) return new BigNumber2(NaN);
          if (a2 != b2) {
            y2.s = -b2;
            return x3.plus(y2);
          }
          var xe2 = x3.e / LOG_BASE, ye2 = y2.e / LOG_BASE, xc = x3.c, yc = y2.c;
          if (!xe2 || !ye2) {
            if (!xc || !yc) return xc ? (y2.s = -b2, y2) : new BigNumber2(yc ? x3 : NaN);
            if (!xc[0] || !yc[0]) {
              return yc[0] ? (y2.s = -b2, y2) : new BigNumber2(xc[0] ? x3 : (
                // IEEE 754 (2008) 6.3: n - n = -0 when rounding to -Infinity
                ROUNDING_MODE == 3 ? -0 : 0
              ));
            }
          }
          xe2 = bitFloor(xe2);
          ye2 = bitFloor(ye2);
          xc = xc.slice();
          if (a2 = xe2 - ye2) {
            if (xLTy = a2 < 0) {
              a2 = -a2;
              t5 = xc;
            } else {
              ye2 = xe2;
              t5 = yc;
            }
            t5.reverse();
            for (b2 = a2; b2--; t5.push(0)) ;
            t5.reverse();
          } else {
            j2 = (xLTy = (a2 = xc.length) < (b2 = yc.length)) ? a2 : b2;
            for (a2 = b2 = 0; b2 < j2; b2++) {
              if (xc[b2] != yc[b2]) {
                xLTy = xc[b2] < yc[b2];
                break;
              }
            }
          }
          if (xLTy) {
            t5 = xc;
            xc = yc;
            yc = t5;
            y2.s = -y2.s;
          }
          b2 = (j2 = yc.length) - (i3 = xc.length);
          if (b2 > 0) for (; b2--; xc[i3++] = 0) ;
          b2 = BASE - 1;
          for (; j2 > a2; ) {
            if (xc[--j2] < yc[j2]) {
              for (i3 = j2; i3 && !xc[--i3]; xc[i3] = b2) ;
              --xc[i3];
              xc[j2] += BASE;
            }
            xc[j2] -= yc[j2];
          }
          for (; xc[0] == 0; xc.splice(0, 1), --ye2) ;
          if (!xc[0]) {
            y2.s = ROUNDING_MODE == 3 ? -1 : 1;
            y2.c = [y2.e = 0];
            return y2;
          }
          return normalise(y2, xc, ye2);
        };
        P2.modulo = P2.mod = function(y2, b2) {
          var q2, s5, x3 = this;
          y2 = new BigNumber2(y2, b2);
          if (!x3.c || !y2.s || y2.c && !y2.c[0]) {
            return new BigNumber2(NaN);
          } else if (!y2.c || x3.c && !x3.c[0]) {
            return new BigNumber2(x3);
          }
          if (MODULO_MODE == 9) {
            s5 = y2.s;
            y2.s = 1;
            q2 = div(x3, y2, 0, 3);
            y2.s = s5;
            q2.s *= s5;
          } else {
            q2 = div(x3, y2, 0, MODULO_MODE);
          }
          y2 = x3.minus(q2.times(y2));
          if (!y2.c[0] && MODULO_MODE == 1) y2.s = x3.s;
          return y2;
        };
        P2.multipliedBy = P2.times = function(y2, b2) {
          var c4, e4, i3, j2, k2, m3, xcL, xlo, xhi, ycL, ylo, yhi, zc, base, sqrtBase, x3 = this, xc = x3.c, yc = (y2 = new BigNumber2(y2, b2)).c;
          if (!xc || !yc || !xc[0] || !yc[0]) {
            if (!x3.s || !y2.s || xc && !xc[0] && !yc || yc && !yc[0] && !xc) {
              y2.c = y2.e = y2.s = null;
            } else {
              y2.s *= x3.s;
              if (!xc || !yc) {
                y2.c = y2.e = null;
              } else {
                y2.c = [0];
                y2.e = 0;
              }
            }
            return y2;
          }
          e4 = bitFloor(x3.e / LOG_BASE) + bitFloor(y2.e / LOG_BASE);
          y2.s *= x3.s;
          xcL = xc.length;
          ycL = yc.length;
          if (xcL < ycL) {
            zc = xc;
            xc = yc;
            yc = zc;
            i3 = xcL;
            xcL = ycL;
            ycL = i3;
          }
          for (i3 = xcL + ycL, zc = []; i3--; zc.push(0)) ;
          base = BASE;
          sqrtBase = SQRT_BASE;
          for (i3 = ycL; --i3 >= 0; ) {
            c4 = 0;
            ylo = yc[i3] % sqrtBase;
            yhi = yc[i3] / sqrtBase | 0;
            for (k2 = xcL, j2 = i3 + k2; j2 > i3; ) {
              xlo = xc[--k2] % sqrtBase;
              xhi = xc[k2] / sqrtBase | 0;
              m3 = yhi * xlo + xhi * ylo;
              xlo = ylo * xlo + m3 % sqrtBase * sqrtBase + zc[j2] + c4;
              c4 = (xlo / base | 0) + (m3 / sqrtBase | 0) + yhi * xhi;
              zc[j2--] = xlo % base;
            }
            zc[j2] = c4;
          }
          if (c4) {
            ++e4;
          } else {
            zc.splice(0, 1);
          }
          return normalise(y2, zc, e4);
        };
        P2.negated = function() {
          var x3 = new BigNumber2(this);
          x3.s = -x3.s || null;
          return x3;
        };
        P2.plus = function(y2, b2) {
          var t5, x3 = this, a2 = x3.s;
          y2 = new BigNumber2(y2, b2);
          b2 = y2.s;
          if (!a2 || !b2) return new BigNumber2(NaN);
          if (a2 != b2) {
            y2.s = -b2;
            return x3.minus(y2);
          }
          var xe2 = x3.e / LOG_BASE, ye2 = y2.e / LOG_BASE, xc = x3.c, yc = y2.c;
          if (!xe2 || !ye2) {
            if (!xc || !yc) return new BigNumber2(a2 / 0);
            if (!xc[0] || !yc[0]) return yc[0] ? y2 : new BigNumber2(xc[0] ? x3 : a2 * 0);
          }
          xe2 = bitFloor(xe2);
          ye2 = bitFloor(ye2);
          xc = xc.slice();
          if (a2 = xe2 - ye2) {
            if (a2 > 0) {
              ye2 = xe2;
              t5 = yc;
            } else {
              a2 = -a2;
              t5 = xc;
            }
            t5.reverse();
            for (; a2--; t5.push(0)) ;
            t5.reverse();
          }
          a2 = xc.length;
          b2 = yc.length;
          if (a2 - b2 < 0) {
            t5 = yc;
            yc = xc;
            xc = t5;
            b2 = a2;
          }
          for (a2 = 0; b2; ) {
            a2 = (xc[--b2] = xc[b2] + yc[b2] + a2) / BASE | 0;
            xc[b2] = BASE === xc[b2] ? 0 : xc[b2] % BASE;
          }
          if (a2) {
            xc = [a2].concat(xc);
            ++ye2;
          }
          return normalise(y2, xc, ye2);
        };
        P2.precision = P2.sd = function(sd, rm) {
          var c4, n3, v2, x3 = 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(x3), sd, rm);
          }
          if (!(c4 = x3.c)) return null;
          v2 = c4.length - 1;
          n3 = v2 * LOG_BASE + 1;
          if (v2 = c4[v2]) {
            for (; v2 % 10 == 0; v2 /= 10, n3--) ;
            for (v2 = c4[0]; v2 >= 10; v2 /= 10, n3++) ;
          }
          if (sd && x3.e + 1 > n3) n3 = x3.e + 1;
          return n3;
        };
        P2.shiftedBy = function(k2) {
          intCheck(k2, -MAX_SAFE_INTEGER, MAX_SAFE_INTEGER);
          return this.times("1e" + k2);
        };
        P2.squareRoot = P2.sqrt = function() {
          var m3, n3, r5, rep, t5, x3 = this, c4 = x3.c, s5 = x3.s, e4 = x3.e, dp = DECIMAL_PLACES + 4, half = new BigNumber2("0.5");
          if (s5 !== 1 || !c4 || !c4[0]) {
            return new BigNumber2(!s5 || s5 < 0 && (!c4 || c4[0]) ? NaN : c4 ? x3 : 1 / 0);
          }
          s5 = Math.sqrt(+valueOf(x3));
          if (s5 == 0 || s5 == 1 / 0) {
            n3 = coeffToString(c4);
            if ((n3.length + e4) % 2 == 0) n3 += "0";
            s5 = Math.sqrt(+n3);
            e4 = bitFloor((e4 + 1) / 2) - (e4 < 0 || e4 % 2);
            if (s5 == 1 / 0) {
              n3 = "5e" + e4;
            } else {
              n3 = s5.toExponential();
              n3 = n3.slice(0, n3.indexOf("e") + 1) + e4;
            }
            r5 = new BigNumber2(n3);
          } else {
            r5 = new BigNumber2(s5 + "");
          }
          if (r5.c[0]) {
            e4 = r5.e;
            s5 = e4 + dp;
            if (s5 < 3) s5 = 0;
            for (; ; ) {
              t5 = r5;
              r5 = half.times(t5.plus(div(x3, t5, dp, 1)));
              if (coeffToString(t5.c).slice(0, s5) === (n3 = coeffToString(r5.c)).slice(0, s5)) {
                if (r5.e < e4) --s5;
                n3 = n3.slice(s5 - 3, s5 + 1);
                if (n3 == "9999" || !rep && n3 == "4999") {
                  if (!rep) {
                    round(t5, t5.e + DECIMAL_PLACES + 2, 0);
                    if (t5.times(t5).eq(x3)) {
                      r5 = t5;
                      break;
                    }
                  }
                  dp += 4;
                  s5 += 4;
                  rep = 1;
                } else {
                  if (!+n3 || !+n3.slice(1) && n3.charAt(0) == "5") {
                    round(r5, r5.e + DECIMAL_PLACES + 2, 1);
                    m3 = !r5.times(r5).eq(x3);
                  }
                  break;
                }
              }
            }
          }
          return round(r5, r5.e + DECIMAL_PLACES + 1, ROUNDING_MODE, m3);
        };
        P2.toExponential = function(dp, rm) {
          if (dp != null) {
            intCheck(dp, 0, MAX2);
            dp++;
          }
          return format4(this, dp, rm, 1);
        };
        P2.toFixed = function(dp, rm) {
          if (dp != null) {
            intCheck(dp, 0, MAX2);
            dp = dp + this.e + 1;
          }
          return format4(this, dp, rm);
        };
        P2.toFormat = function(dp, rm, format5) {
          var str2, x3 = 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 = x3.toFixed(dp, rm);
          if (x3.c) {
            var i3, arr = str2.split("."), g1 = +format5.groupSize, g2 = +format5.secondaryGroupSize, groupSeparator = format5.groupSeparator || "", intPart = arr[0], fractionPart = arr[1], isNeg = x3.s < 0, intDigits = isNeg ? intPart.slice(1) : intPart, len = intDigits.length;
            if (g2) {
              i3 = g1;
              g1 = g2;
              g2 = i3;
              len -= i3;
            }
            if (g1 > 0 && len > 0) {
              i3 = len % g1 || g1;
              intPart = intDigits.substr(0, i3);
              for (; i3 < len; i3 += g1) intPart += groupSeparator + intDigits.substr(i3, g1);
              if (g2 > 0) intPart += groupSeparator + intDigits.slice(i3);
              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 || "");
        };
        P2.toFraction = function(md) {
          var d2, d0, d1, d22, e4, exp, n3, n0, n1, q2, r5, s5, x3 = this, xc = x3.c;
          if (md != null) {
            n3 = new BigNumber2(md);
            if (!n3.isInteger() && (n3.c || n3.s !== 1) || n3.lt(ONE)) {
              throw Error(bignumberError + "Argument " + (n3.isInteger() ? "out of range: " : "not an integer: ") + valueOf(n3));
            }
          }
          if (!xc) return new BigNumber2(x3);
          d2 = new BigNumber2(ONE);
          n1 = d0 = new BigNumber2(ONE);
          d1 = n0 = new BigNumber2(ONE);
          s5 = coeffToString(xc);
          e4 = d2.e = s5.length - x3.e - 1;
          d2.c[0] = POWS_TEN[(exp = e4 % LOG_BASE) < 0 ? LOG_BASE + exp : exp];
          md = !md || n3.comparedTo(d2) > 0 ? e4 > 0 ? d2 : n1 : n3;
          exp = MAX_EXP;
          MAX_EXP = 1 / 0;
          n3 = new BigNumber2(s5);
          n0.c[0] = 0;
          for (; ; ) {
            q2 = div(n3, d2, 0, 1);
            d22 = d0.plus(q2.times(d1));
            if (d22.comparedTo(md) == 1) break;
            d0 = d1;
            d1 = d22;
            n1 = n0.plus(q2.times(d22 = n1));
            n0 = d22;
            d2 = n3.minus(q2.times(d22 = d2));
            n3 = d22;
          }
          d22 = div(md.minus(d0), d1, 0, 1);
          n0 = n0.plus(d22.times(n1));
          d0 = d0.plus(d22.times(d1));
          n0.s = n1.s = x3.s;
          e4 = e4 * 2;
          r5 = div(n1, d1, e4, ROUNDING_MODE).minus(x3).abs().comparedTo(
            div(n0, d0, e4, ROUNDING_MODE).minus(x3).abs()
          ) < 1 ? [n1, d1] : [n0, d0];
          MAX_EXP = exp;
          return r5;
        };
        P2.toNumber = function() {
          return +valueOf(this);
        };
        P2.toPrecision = function(sd, rm) {
          if (sd != null) intCheck(sd, 1, MAX2);
          return format4(this, sd, rm, 2);
        };
        P2.toString = function(b2) {
          var str2, n3 = this, s5 = n3.s, e4 = n3.e;
          if (e4 === null) {
            if (s5) {
              str2 = "Infinity";
              if (s5 < 0) str2 = "-" + str2;
            } else {
              str2 = "NaN";
            }
          } else {
            if (b2 == null) {
              str2 = e4 <= TO_EXP_NEG || e4 >= TO_EXP_POS ? toExponential(coeffToString(n3.c), e4) : toFixedPoint(coeffToString(n3.c), e4, "0");
            } else if (b2 === 10 && alphabetHasNormalDecimalDigits) {
              n3 = round(new BigNumber2(n3), DECIMAL_PLACES + e4 + 1, ROUNDING_MODE);
              str2 = toFixedPoint(coeffToString(n3.c), n3.e, "0");
            } else {
              intCheck(b2, 2, ALPHABET.length, "Base");
              str2 = convertBase(toFixedPoint(coeffToString(n3.c), e4, "0"), 10, b2, s5, true);
            }
            if (s5 < 0 && n3.c[0]) str2 = "-" + str2;
          }
          return str2;
        };
        P2.valueOf = P2.toJSON = function() {
          return valueOf(this);
        };
        P2._isBigNumber = true;
        if (configObject != null) BigNumber2.set(configObject);
        return BigNumber2;
      }
      __name(clone4, "clone");
      function bitFloor(n3) {
        var i3 = n3 | 0;
        return n3 > 0 || n3 === i3 ? i3 : i3 - 1;
      }
      __name(bitFloor, "bitFloor");
      function coeffToString(a2) {
        var s5, z2, i3 = 1, j2 = a2.length, r5 = a2[0] + "";
        for (; i3 < j2; ) {
          s5 = a2[i3++] + "";
          z2 = LOG_BASE - s5.length;
          for (; z2--; s5 = "0" + s5) ;
          r5 += s5;
        }
        for (j2 = r5.length; r5.charCodeAt(--j2) === 48; ) ;
        return r5.slice(0, j2 + 1 || 1);
      }
      __name(coeffToString, "coeffToString");
      function compare(x3, y2) {
        var a2, b2, xc = x3.c, yc = y2.c, i3 = x3.s, j2 = y2.s, k2 = x3.e, l3 = y2.e;
        if (!i3 || !j2) return null;
        a2 = xc && !xc[0];
        b2 = yc && !yc[0];
        if (a2 || b2) return a2 ? b2 ? 0 : -j2 : i3;
        if (i3 != j2) return i3;
        a2 = i3 < 0;
        b2 = k2 == l3;
        if (!xc || !yc) return b2 ? 0 : !xc ^ a2 ? 1 : -1;
        if (!b2) return k2 > l3 ^ a2 ? 1 : -1;
        j2 = (k2 = xc.length) < (l3 = yc.length) ? k2 : l3;
        for (i3 = 0; i3 < j2; i3++) if (xc[i3] != yc[i3]) return xc[i3] > yc[i3] ^ a2 ? 1 : -1;
        return k2 == l3 ? 0 : k2 > l3 ^ a2 ? 1 : -1;
      }
      __name(compare, "compare");
      function intCheck(n3, min, max, name3) {
        if (n3 < min || n3 > max || n3 !== mathfloor(n3)) {
          throw Error(bignumberError + (name3 || "Argument") + (typeof n3 == "number" ? n3 < min || n3 > max ? " out of range: " : " not an integer: " : " not a primitive number: ") + String(n3));
        }
      }
      __name(intCheck, "intCheck");
      function isOdd(n3) {
        var k2 = n3.c.length - 1;
        return bitFloor(n3.e / LOG_BASE) == k2 && n3.c[k2] % 2 != 0;
      }
      __name(isOdd, "isOdd");
      function toExponential(str2, e4) {
        return (str2.length > 1 ? str2.charAt(0) + "." + str2.slice(1) : str2) + (e4 < 0 ? "e" : "e+") + e4;
      }
      __name(toExponential, "toExponential");
      function toFixedPoint(str2, e4, z2) {
        var len, zs;
        if (e4 < 0) {
          for (zs = z2 + "."; ++e4; zs += z2) ;
          str2 = zs + str2;
        } else {
          len = str2.length;
          if (++e4 > len) {
            for (zs = z2, e4 -= len; --e4; zs += z2) ;
            str2 += zs;
          } else if (e4 < len) {
            str2 = str2.slice(0, e4) + "." + str2.slice(e4);
          }
        }
        return str2;
      }
      __name(toFixedPoint, "toFixedPoint");
      BigNumber = clone4();
      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 f5(n3) {
        return n3 < 10 ? "0" + n3 : n3;
      }
      __name(f5, "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(string4) {
        escapable.lastIndex = 0;
        return escapable.test(string4) ? '"' + string4.replace(escapable, function(a2) {
          var c4 = meta[a2];
          return typeof c4 === "string" ? c4 : "\\u" + ("0000" + a2.charCodeAt(0).toString(16)).slice(-4);
        }) + '"' : '"' + string4 + '"';
      }
      __name(quote3, "quote");
      function str2(key, holder) {
        var i3, k2, v2, length, mind = gap, partial2, 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;
            partial2 = [];
            if (Object.prototype.toString.apply(value) === "[object Array]") {
              length = value.length;
              for (i3 = 0; i3 < length; i3 += 1) {
                partial2[i3] = str2(i3, value) || "null";
              }
              v2 = partial2.length === 0 ? "[]" : gap ? "[\n" + gap + partial2.join(",\n" + gap) + "\n" + mind + "]" : "[" + partial2.join(",") + "]";
              gap = mind;
              return v2;
            }
            if (rep && typeof rep === "object") {
              length = rep.length;
              for (i3 = 0; i3 < length; i3 += 1) {
                if (typeof rep[i3] === "string") {
                  k2 = rep[i3];
                  v2 = str2(k2, value);
                  if (v2) {
                    partial2.push(quote3(k2) + (gap ? ": " : ":") + v2);
                  }
                }
              }
            } else {
              Object.keys(value).forEach(function(k3) {
                var v3 = str2(k3, value);
                if (v3) {
                  partial2.push(quote3(k3) + (gap ? ": " : ":") + v3);
                }
              });
            }
            v2 = partial2.length === 0 ? "{}" : gap ? "{\n" + gap + partial2.join(",\n" + gap) + "\n" + mind + "}" : "{" + partial2.join(",") + "}";
            gap = mind;
            return v2;
        }
      }
      __name(str2, "str");
      if (typeof JSON2.stringify !== "function") {
        JSON2.stringify = function(value, replacer, space) {
          var i3;
          gap = "";
          indent = "";
          if (typeof space === "number") {
            for (i3 = 0; i3 < space; i3 += 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 at2, ch, escapee = {
        '"': '"',
        "\\": "\\",
        "/": "/",
        b: "\b",
        f: "\f",
        n: "\n",
        r: "\r",
        t: "	"
      }, text, error2 = /* @__PURE__ */ __name(function(m3) {
        throw {
          name: "SyntaxError",
          message: m3,
          at: at2,
          text
        };
      }, "error"), next = /* @__PURE__ */ __name(function(c4) {
        if (c4 && c4 !== ch) {
          error2("Expected '" + c4 + "' instead of '" + ch + "'");
        }
        ch = text.charAt(at2);
        at2 += 1;
        return ch;
      }, "next"), number4 = /* @__PURE__ */ __name(function() {
        var number5, string5 = "";
        if (ch === "-") {
          string5 = "-";
          next("-");
        }
        while (ch >= "0" && ch <= "9") {
          string5 += ch;
          next();
        }
        if (ch === ".") {
          string5 += ".";
          while (next() && ch >= "0" && ch <= "9") {
            string5 += ch;
          }
        }
        if (ch === "e" || ch === "E") {
          string5 += ch;
          next();
          if (ch === "-" || ch === "+") {
            string5 += ch;
            next();
          }
          while (ch >= "0" && ch <= "9") {
            string5 += ch;
            next();
          }
        }
        number5 = +string5;
        if (!isFinite(number5)) {
          error2("Bad number");
        } else {
          if (BigNumber == null) BigNumber = require_bignumber();
          if (string5.length > 15)
            return _options.storeAsString ? string5 : _options.useNativeBigInt ? BigInt(string5) : new BigNumber(string5);
          else
            return !_options.alwaysParseAsBig ? number5 : _options.useNativeBigInt ? BigInt(number5) : new BigNumber(number5);
        }
      }, "number"), string4 = /* @__PURE__ */ __name(function() {
        var hex, i3, string5 = "", uffff;
        if (ch === '"') {
          var startAt = at2;
          while (next()) {
            if (ch === '"') {
              if (at2 - 1 > startAt) string5 += text.substring(startAt, at2 - 1);
              next();
              return string5;
            }
            if (ch === "\\") {
              if (at2 - 1 > startAt) string5 += text.substring(startAt, at2 - 1);
              next();
              if (ch === "u") {
                uffff = 0;
                for (i3 = 0; i3 < 4; i3 += 1) {
                  hex = parseInt(next(), 16);
                  if (!isFinite(hex)) {
                    break;
                  }
                  uffff = uffff * 16 + hex;
                }
                string5 += String.fromCharCode(uffff);
              } else if (typeof escapee[ch] === "string") {
                string5 += escapee[ch];
              } else {
                break;
              }
              startAt = at2;
            }
          }
        }
        error2("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;
        }
        error2("Unexpected '" + ch + "'");
      }, "word"), value, array2 = /* @__PURE__ */ __name(function() {
        var array3 = [];
        if (ch === "[") {
          next("[");
          white();
          if (ch === "]") {
            next("]");
            return array3;
          }
          while (ch) {
            array3.push(value());
            white();
            if (ch === "]") {
              next("]");
              return array3;
            }
            next(",");
            white();
          }
        }
        error2("Bad array");
      }, "array"), object3 = /* @__PURE__ */ __name(function() {
        var key, object4 = /* @__PURE__ */ Object.create(null);
        if (ch === "{") {
          next("{");
          white();
          if (ch === "}") {
            next("}");
            return object4;
          }
          while (ch) {
            key = string4();
            white();
            next(":");
            if (_options.strict === true && Object.hasOwnProperty.call(object4, key)) {
              error2('Duplicate key "' + key + '"');
            }
            if (suspectProtoRx.test(key) === true) {
              if (_options.protoAction === "error") {
                error2("Object contains forbidden prototype property");
              } else if (_options.protoAction === "ignore") {
                value();
              } else {
                object4[key] = value();
              }
            } else if (suspectConstructorRx.test(key) === true) {
              if (_options.constructorAction === "error") {
                error2("Object contains forbidden constructor property");
              } else if (_options.constructorAction === "ignore") {
                value();
              } else {
                object4[key] = value();
              }
            } else {
              object4[key] = value();
            }
            white();
            if (ch === "}") {
              next("}");
              return object4;
            }
            next(",");
            white();
          }
        }
        error2("Bad object");
      }, "object");
      value = /* @__PURE__ */ __name(function() {
        white();
        switch (ch) {
          case "{":
            return object3();
          case "[":
            return array2();
          case '"':
            return string4();
          case "-":
            return number4();
          default:
            return ch >= "0" && ch <= "9" ? number4() : word();
        }
      }, "value");
      return function(source2, reviver) {
        var result;
        text = source2 + "";
        at2 = 0;
        ch = " ";
        result = value();
        white();
        if (ch) {
          error2("Syntax error");
        }
        return typeof reviver === "function" ? (/* @__PURE__ */ __name(function walk(holder, key) {
          var k2, v2, value2 = holder[key];
          if (value2 && typeof value2 === "object") {
            Object.keys(value2).forEach(function(k3) {
              v2 = walk(value2, k3);
              if (v2 !== void 0) {
                value2[k3] = v2;
              } else {
                delete value2[k3];
              }
            });
          }
          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;
  }
});

// packages/core/node_modules/gcp-metadata/build/src/gcp-residency.js
var require_gcp_residency = __commonJS({
  "packages/core/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 {
        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");
  }
});

// packages/core/node_modules/google-logging-utils/build/src/colours.js
var require_colours = __commonJS({
  "packages/core/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 && // May happen in browsers.
        stream2.isTTY && (typeof stream2.getColorDepth === "function" ? stream2.getColorDepth() > 2 : true);
      }
      static refresh() {
        _Colours.enabled = _Colours.isEnabled(process === null || process === void 0 ? void 0 : 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();
  }
});

// packages/core/node_modules/google-logging-utils/build/src/logging-utils.js
var require_logging_utils = __commonJS({
  "packages/core/node_modules/google-logging-utils/build/src/logging-utils.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    var __createBinding = exports2 && exports2.__createBinding || (Object.create ? function(o3, m3, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc2 = Object.getOwnPropertyDescriptor(m3, k2);
      if (!desc2 || ("get" in desc2 ? !m3.__esModule : desc2.writable || desc2.configurable)) {
        desc2 = { enumerable: true, get: /* @__PURE__ */ __name(function() {
          return m3[k2];
        }, "get") };
      }
      Object.defineProperty(o3, k22, desc2);
    } : function(o3, m3, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o3[k22] = m3[k2];
    });
    var __setModuleDefault = exports2 && exports2.__setModuleDefault || (Object.create ? function(o3, v2) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v2 });
    } : function(o3, v2) {
      o3["default"] = v2;
    });
    var __importStar = exports2 && exports2.__importStar || /* @__PURE__ */ function() {
      var ownKeys2 = /* @__PURE__ */ __name(function(o3) {
        ownKeys2 = Object.getOwnPropertyNames || function(o4) {
          var ar2 = [];
          for (var k2 in o4) if (Object.prototype.hasOwnProperty.call(o4, k2)) ar2[ar2.length] = k2;
          return ar2;
        };
        return ownKeys2(o3);
      }, "ownKeys");
      return function(mod2) {
        if (mod2 && mod2.__esModule) return mod2;
        var result = {};
        if (mod2 != null) {
          for (var k2 = ownKeys2(mod2), i3 = 0; i3 < k2.length; i3++) if (k2[i3] !== "default") __createBinding(result, mod2, k2[i3]);
        }
        __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 events_1 = __require("events");
    var process50 = __importStar(__require("process"));
    var util3 = __importStar(__require("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 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) {
          try {
            this.upstream(fields, ...args);
          } catch (e4) {
          }
        }
        try {
          this.emit("log", fields, args);
        } catch (e4) {
        }
      }
      invokeSeverity(severity, ...args) {
        this.invoke({ severity }, ...args);
      }
    };
    exports2.AdhocDebugLogger = AdhocDebugLogger;
    exports2.placeholder = new AdhocDebugLogger("", () => {
    }).func;
    var DebugLogBackendBase = class {
      static {
        __name(this, "DebugLogBackendBase");
      }
      constructor() {
        var _a7;
        this.cached = /* @__PURE__ */ new Map();
        this.filters = [];
        this.filtersSet = false;
        let nodeFlag = (_a7 = process50.env[exports2.env.nodeEnables]) !== null && _a7 !== void 0 ? _a7 : "*";
        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 (e4) {
          console.error(e4);
        }
      }
    };
    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 _a7;
          const nscolour = `${colours_1.Colours.green}${namespace}${colours_1.Colours.reset}`;
          const pid = `${colours_1.Colours.yellow}${process50.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 = (_a7 = fields.severity) !== null && _a7 !== void 0 ? _a7 : LogSeverity.DEFAULT;
              break;
          }
          const msg = util3.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 debugLogger124 = this.debugPkg(namespace);
        return (fields, ...args) => {
          debugLogger124(args[0], ...args.slice(1));
        };
      }
      setFilters() {
        var _a7;
        const existingFilters = (_a7 = process50.env["NODE_DEBUG"]) !== null && _a7 !== void 0 ? _a7 : "";
        process50.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 _a7;
        super();
        this.upstream = (_a7 = upstream) !== null && _a7 !== void 0 ? _a7 : void 0;
      }
      makeLogger(namespace) {
        var _a7;
        const debugLogger124 = (_a7 = this.upstream) === null || _a7 === void 0 ? void 0 : _a7.makeLogger(namespace);
        return (fields, ...args) => {
          var _a8;
          const severity = (_a8 = fields.severity) !== null && _a8 !== void 0 ? _a8 : LogSeverity.INFO;
          const json2 = Object.assign({
            severity,
            message: util3.format(...args)
          }, fields);
          const jsonString = JSON.stringify(json2);
          if (debugLogger124) {
            debugLogger124(fields, jsonString);
          } else {
            console.log("%s", jsonString);
          }
        };
      }
      setFilters() {
        var _a7;
        (_a7 = this.upstream) === null || _a7 === void 0 ? void 0 : _a7.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) {
      if (!cachedBackend) {
        const enablesFlag = process50.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");
  }
});

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

// packages/core/node_modules/gcp-metadata/build/src/index.js
var require_src4 = __commonJS({
  "packages/core/node_modules/gcp-metadata/build/src/index.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    var __createBinding = exports2 && exports2.__createBinding || (Object.create ? function(o3, m3, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc2 = Object.getOwnPropertyDescriptor(m3, k2);
      if (!desc2 || ("get" in desc2 ? !m3.__esModule : desc2.writable || desc2.configurable)) {
        desc2 = { enumerable: true, get: /* @__PURE__ */ __name(function() {
          return m3[k2];
        }, "get") };
      }
      Object.defineProperty(o3, k22, desc2);
    } : function(o3, m3, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o3[k22] = m3[k2];
    });
    var __setModuleDefault = exports2 && exports2.__setModuleDefault || (Object.create ? function(o3, v2) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v2 });
    } : function(o3, v2) {
      o3["default"] = v2;
    });
    var __importStar = exports2 && exports2.__importStar || /* @__PURE__ */ function() {
      var ownKeys2 = /* @__PURE__ */ __name(function(o3) {
        ownKeys2 = Object.getOwnPropertyNames || function(o4) {
          var ar2 = [];
          for (var k2 in o4) if (Object.prototype.hasOwnProperty.call(o4, k2)) ar2[ar2.length] = k2;
          return ar2;
        };
        return ownKeys2(o3);
      }, "ownKeys");
      return function(mod2) {
        if (mod2 && mod2.__esModule) return mod2;
        var result = {};
        if (mod2 != null) {
          for (var k2 = ownKeys2(mod2), i3 = 0; i3 < k2.length; i3++) if (k2[i3] !== "default") __createBinding(result, mod2, k2[i3]);
        }
        __setModuleDefault(result, mod2);
        return result;
      };
    }();
    var __exportStar = exports2 && exports2.__exportStar || function(m3, exports3) {
      for (var p2 in m3) if (p2 !== "default" && !Object.prototype.hasOwnProperty.call(exports3, p2)) __createBinding(exports3, m3, p2);
    };
    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 = __importStar(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 validate3(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(validate3, "validate");
    async function metadataAccessor(type, options2 = {}, noResponseRetries = 3, fastFail = false) {
      const headers = new Headers(exports2.HEADERS);
      let metadataKey = "";
      let params = {};
      if (typeof type === "object") {
        const metadataAccessor2 = type;
        new Headers(metadataAccessor2.headers).forEach((value, key) => headers.set(key, value));
        metadataKey = metadataAccessor2.metadataKey;
        params = metadataAccessor2.params || params;
        noResponseRetries = metadataAccessor2.noResponseRetries || noResponseRetries;
        fastFail = metadataAccessor2.fastFail || fastFail;
      } else {
        metadataKey = type;
      }
      if (typeof options2 === "string") {
        metadataKey += `/${options2}`;
      } else {
        validate3(options2);
        if (options2.property) {
          metadataKey += `/${options2.property}`;
        }
        new Headers(options2.headers).forEach((value, key) => headers.set(key, value));
        params = options2.params || params;
      }
      const requestMethod = fastFail ? fastFailMetadataRequest : gaxios_1.request;
      const req = {
        url: `${getBaseUrl2()}/${metadataKey}`,
        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);
      const metadataFlavor = res.headers.get(exports2.HEADER_NAME);
      if (metadataFlavor !== exports2.HEADER_VALUE) {
        throw new RangeError(`Invalid response from metadata service: incorrect ${exports2.HEADER_NAME} header. Expected '${exports2.HEADER_VALUE}', got ${metadataFlavor ? `'${metadataFlavor}'` : "no header"}`);
      }
      if (typeof res.data === "string") {
        try {
          return jsonBigint.parse(res.data);
        } catch {
        }
      }
      return res.data;
    }
    __name(metadataAccessor, "metadataAccessor");
    async function fastFailMetadataRequest(options2) {
      const secondaryOptions = {
        ...options2,
        url: options2.url?.toString().replace(getBaseUrl2(), getBaseUrl2(exports2.SECONDARY_HOST_ADDRESS))
      };
      const r1 = (0, gaxios_1.request)(options2);
      const r22 = (0, gaxios_1.request)(secondaryOptions);
      return Promise.any([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 r5 = {};
      await Promise.all(properties.map((item) => {
        return (async () => {
          const res = await metadataAccessor(item);
          const key = item.metadataKey;
          r5[key] = res;
        })();
      }));
      return r5;
    }
    __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 (e4) {
        const err = e4;
        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.toString()))) {
            let code2 = "UNKNOWN";
            if (err.code)
              code2 = err.code.toString();
            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 (i3 = 0, len = code2.length; i3 < len; ++i3) {
      lookup[i3] = code2[i3];
      revLookup[code2.charCodeAt(i3)] = i3;
    }
    var i3;
    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 i4;
      for (i4 = 0; i4 < len2; i4 += 4) {
        tmp = revLookup[b64.charCodeAt(i4)] << 18 | revLookup[b64.charCodeAt(i4 + 1)] << 12 | revLookup[b64.charCodeAt(i4 + 2)] << 6 | revLookup[b64.charCodeAt(i4 + 3)];
        arr[curByte++] = tmp >> 16 & 255;
        arr[curByte++] = tmp >> 8 & 255;
        arr[curByte++] = tmp & 255;
      }
      if (placeHoldersLen === 2) {
        tmp = revLookup[b64.charCodeAt(i4)] << 2 | revLookup[b64.charCodeAt(i4 + 1)] >> 4;
        arr[curByte++] = tmp & 255;
      }
      if (placeHoldersLen === 1) {
        tmp = revLookup[b64.charCodeAt(i4)] << 10 | revLookup[b64.charCodeAt(i4 + 1)] << 4 | revLookup[b64.charCodeAt(i4 + 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 i4 = start; i4 < end; i4 += 3) {
        tmp = (uint8[i4] << 16 & 16711680) + (uint8[i4 + 1] << 8 & 65280) + (uint8[i4 + 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 i4 = 0, len22 = len2 - extraBytes; i4 < len22; i4 += maxChunkLength) {
        parts.push(encodeChunk(uint8, i4, i4 + maxChunkLength > len22 ? len22 : i4 + 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");
  }
});

// packages/core/node_modules/google-auth-library/build/src/crypto/shared.js
var require_shared = __commonJS({
  "packages/core/node_modules/google-auth-library/build/src/crypto/shared.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.fromArrayBufferToHex = fromArrayBufferToHex;
    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");
  }
});

// packages/core/node_modules/google-auth-library/build/src/crypto/browser/crypto.js
var require_crypto = __commonJS({
  "packages/core/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 shared_1 = require_shared();
    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 array2 = new Uint8Array(count);
        window.crypto.getRandomValues(array2);
        return base64js.fromByteArray(array2);
      }
      static padBase64(base642) {
        while (base642.length % 4 !== 0) {
          base642 += "=";
        }
        return base642;
      }
      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(base642) {
        const uint8array = base64js.toByteArray(_BrowserCrypto.padBase64(base642));
        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, shared_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;
  }
});

// packages/core/node_modules/google-auth-library/build/src/crypto/node/crypto.js
var require_crypto2 = __commonJS({
  "packages/core/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 crypto14 = __require("crypto");
    var NodeCrypto = class {
      static {
        __name(this, "NodeCrypto");
      }
      async sha256DigestBase64(str2) {
        return crypto14.createHash("sha256").update(str2).digest("base64");
      }
      randomBytesBase64(count) {
        return crypto14.randomBytes(count).toString("base64");
      }
      async verify(pubkey, data, signature) {
        const verifier = crypto14.createVerify("RSA-SHA256");
        verifier.update(data);
        verifier.end();
        return verifier.verify(pubkey, signature, "base64");
      }
      async sign(privateKey, data) {
        const signer = crypto14.createSign("RSA-SHA256");
        signer.update(data);
        signer.end();
        return signer.sign(privateKey, "base64");
      }
      decodeBase64StringUtf8(base642) {
        return Buffer.from(base642, "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 crypto14.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(crypto14.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");
  }
});

// packages/core/node_modules/google-auth-library/build/src/crypto/crypto.js
var require_crypto3 = __commonJS({
  "packages/core/node_modules/google-auth-library/build/src/crypto/crypto.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    var __createBinding = exports2 && exports2.__createBinding || (Object.create ? function(o3, m3, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc2 = Object.getOwnPropertyDescriptor(m3, k2);
      if (!desc2 || ("get" in desc2 ? !m3.__esModule : desc2.writable || desc2.configurable)) {
        desc2 = { enumerable: true, get: /* @__PURE__ */ __name(function() {
          return m3[k2];
        }, "get") };
      }
      Object.defineProperty(o3, k22, desc2);
    } : function(o3, m3, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o3[k22] = m3[k2];
    });
    var __exportStar = exports2 && exports2.__exportStar || function(m3, exports3) {
      for (var p2 in m3) if (p2 !== "default" && !Object.prototype.hasOwnProperty.call(exports3, p2)) __createBinding(exports3, m3, p2);
    };
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.createCrypto = createCrypto;
    exports2.hasBrowserCrypto = hasBrowserCrypto;
    var crypto_1 = require_crypto();
    var crypto_2 = require_crypto2();
    __exportStar(require_shared(), exports2);
    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");
  }
});

// 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 Buffer9 = buffer.Buffer;
    function copyProps(src, dst) {
      for (var key in src) {
        dst[key] = src[key];
      }
    }
    __name(copyProps, "copyProps");
    if (Buffer9.from && Buffer9.alloc && Buffer9.allocUnsafe && Buffer9.allocUnsafeSlow) {
      module2.exports = buffer;
    } else {
      copyProps(buffer, exports2);
      exports2.Buffer = SafeBuffer;
    }
    function SafeBuffer(arg, encodingOrOffset, length) {
      return Buffer9(arg, encodingOrOffset, length);
    }
    __name(SafeBuffer, "SafeBuffer");
    SafeBuffer.prototype = Object.create(Buffer9.prototype);
    copyProps(Buffer9, SafeBuffer);
    SafeBuffer.from = function(arg, encodingOrOffset, length) {
      if (typeof arg === "number") {
        throw new TypeError("Argument must not be a number");
      }
      return Buffer9(arg, encodingOrOffset, length);
    };
    SafeBuffer.alloc = function(size, fill, encoding) {
      if (typeof size !== "number") {
        throw new TypeError("Argument must be a number");
      }
      var buf = Buffer9(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 Buffer9(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 Buffer9 = 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(base642) {
      return base642.replace(/=/g, "").replace(/\+/g, "-").replace(/\//g, "_");
    }
    __name(base64Url, "base64Url");
    function signatureAsBuffer(signature) {
      if (Buffer9.isBuffer(signature)) {
        return signature;
      } else if ("string" === typeof signature) {
        return Buffer9.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 = Buffer9.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 o3 = offset; offset < o3 + 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 = Buffer9.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
    };
  }
});

// packages/core/node_modules/google-auth-library/build/src/util.js
var require_util10 = __commonJS({
  "packages/core/node_modules/google-auth-library/build/src/util.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.LRUCache = void 0;
    exports2.snakeToCamel = snakeToCamel;
    exports2.originalOrCamelOptions = originalOrCamelOptions;
    exports2.removeUndefinedValuesInObject = removeUndefinedValuesInObject;
    exports2.isValidFile = isValidFile;
    exports2.getWellKnownCertificateConfigFileLocation = getWellKnownCertificateConfigFileLocation;
    var fs113 = __require("fs");
    var os47 = __require("os");
    var path125 = __require("path");
    var WELL_KNOWN_CERTIFICATE_CONFIG_FILE = "certificate_config.json";
    var CLOUDSDK_CONFIG_DIRECTORY = "gcloud";
    function snakeToCamel(str2) {
      return str2.replace(/([_][^_])/g, (match2) => match2.slice(1).toUpperCase());
    }
    __name(snakeToCamel, "snakeToCamel");
    function originalOrCamelOptions(obj) {
      function get4(key) {
        const o3 = obj || {};
        return o3[key] ?? o3[snakeToCamel(key)];
      }
      __name(get4, "get");
      return { get: get4 };
    }
    __name(originalOrCamelOptions, "originalOrCamelOptions");
    var LRUCache2 = class {
      static {
        __name(this, "LRUCache");
      }
      capacity;
      /**
       * Maps are in order. Thus, the older item is the first item.
       *
       * {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map}
       */
      #cache = /* @__PURE__ */ new Map();
      maxAge;
      constructor(options2) {
        this.capacity = options2.capacity;
        this.maxAge = options2.maxAge;
      }
      /**
       * Moves the key to the end of the cache.
       *
       * @param key the key to move
       * @param value the value of the key
       */
      #moveToEnd(key, value) {
        this.#cache.delete(key);
        this.#cache.set(key, {
          value,
          lastAccessed: Date.now()
        });
      }
      /**
       * Add an item to the cache.
       *
       * @param key the key to upsert
       * @param value the value of the key
       */
      set(key, value) {
        this.#moveToEnd(key, value);
        this.#evict();
      }
      /**
       * Get an item from the cache.
       *
       * @param key the key to retrieve
       */
      get(key) {
        const item = this.#cache.get(key);
        if (!item)
          return;
        this.#moveToEnd(key, item.value);
        this.#evict();
        return item.value;
      }
      /**
       * Maintain the cache based on capacity and TTL.
       */
      #evict() {
        const cutoffDate = this.maxAge ? Date.now() - this.maxAge : 0;
        let oldestItem = this.#cache.entries().next();
        while (!oldestItem.done && (this.#cache.size > this.capacity || // too many
        oldestItem.value[1].lastAccessed < cutoffDate)) {
          this.#cache.delete(oldestItem.value[0]);
          oldestItem = this.#cache.entries().next();
        }
      }
    };
    exports2.LRUCache = LRUCache2;
    function removeUndefinedValuesInObject(object3) {
      Object.entries(object3).forEach(([key, value]) => {
        if (value === void 0 || value === "undefined") {
          delete object3[key];
        }
      });
      return object3;
    }
    __name(removeUndefinedValuesInObject, "removeUndefinedValuesInObject");
    async function isValidFile(filePath) {
      try {
        const stats = await fs113.promises.lstat(filePath);
        return stats.isFile();
      } catch (e4) {
        return false;
      }
    }
    __name(isValidFile, "isValidFile");
    function getWellKnownCertificateConfigFileLocation() {
      const configDir = process.env.CLOUDSDK_CONFIG || (_isWindows() ? path125.join(process.env.APPDATA || "", CLOUDSDK_CONFIG_DIRECTORY) : path125.join(process.env.HOME || "", ".config", CLOUDSDK_CONFIG_DIRECTORY));
      return path125.join(configDir, WELL_KNOWN_CERTIFICATE_CONFIG_FILE);
    }
    __name(getWellKnownCertificateConfigFileLocation, "getWellKnownCertificateConfigFileLocation");
    function _isWindows() {
      return os47.platform().startsWith("win");
    }
    __name(_isWindows, "_isWindows");
  }
});

// packages/core/node_modules/google-auth-library/package.json
var require_package2 = __commonJS({
  "packages/core/node_modules/google-auth-library/package.json"(exports2, module2) {
    module2.exports = {
      name: "google-auth-library",
      version: "10.5.0",
      author: "Google Inc.",
      description: "Google APIs Authentication Client Library for Node.js",
      engines: {
        node: ">=18"
      },
      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: "^7.0.0",
        "gcp-metadata": "^8.0.0",
        "google-logging-utils": "^1.0.0",
        gtoken: "^8.0.0",
        jws: "^4.0.0"
      },
      devDependencies: {
        "@types/base64-js": "^1.2.5",
        "@types/jws": "^3.1.0",
        "@types/mocha": "^10.0.10",
        "@types/mv": "^2.1.0",
        "@types/ncp": "^2.0.1",
        "@types/node": "^22.0.0",
        "@types/sinon": "^17.0.0",
        "assert-rejects": "^1.0.0",
        c8: "^10.0.0",
        codecov: "^3.0.2",
        gts: "^6.0.0",
        "is-docker": "^3.0.0",
        jsdoc: "^4.0.0",
        "jsdoc-fresh": "^5.0.0",
        "jsdoc-region-tag": "^4.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.1",
        keypair: "^1.0.4",
        mocha: "^11.1.0",
        mv: "^2.1.1",
        ncp: "^2.0.0",
        nock: "^14.0.5",
        "null-loader": "^4.0.0",
        puppeteer: "^24.0.0",
        sinon: "^21.0.0",
        "ts-loader": "^8.0.0",
        typescript: "5.8.2",
        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 --no-inline-config",
        compile: "tsc -p .",
        fix: "gts fix",
        pretest: "npm run compile -- --sourceMap",
        docs: "jsdoc -c .jsdoc.js",
        "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": "echo 'disabled until linkinator is fixed'",
        "predocs-test": "npm run docs",
        prelint: "cd samples; npm link ../; npm install"
      },
      license: "Apache-2.0"
    };
  }
});

// packages/core/node_modules/google-auth-library/build/src/shared.cjs
var require_shared2 = __commonJS({
  "packages/core/node_modules/google-auth-library/build/src/shared.cjs"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.USER_AGENT = exports2.PRODUCT_NAME = exports2.pkg = void 0;
    var pkg2 = require_package2();
    exports2.pkg = pkg2;
    var PRODUCT_NAME = "google-api-nodejs-client";
    exports2.PRODUCT_NAME = PRODUCT_NAME;
    var USER_AGENT = `${PRODUCT_NAME}/${pkg2.version}`;
    exports2.USER_AGENT = USER_AGENT;
  }
});

// packages/core/node_modules/google-auth-library/build/src/auth/authclient.js
var require_authclient = __commonJS({
  "packages/core/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 util_1 = require_util10();
    var google_logging_utils_1 = require_src3();
    var shared_cjs_1 = require_shared2();
    exports2.DEFAULT_UNIVERSE = "googleapis.com";
    exports2.DEFAULT_EAGER_REFRESH_THRESHOLD_MILLIS = 5 * 60 * 1e3;
    var AuthClient = class _AuthClient extends events_1.EventEmitter {
      static {
        __name(this, "AuthClient");
      }
      apiKey;
      projectId;
      /**
       * The quota project ID. The quota project can be used by client libraries for the billing purpose.
       * See {@link https://cloud.google.com/docs/quota Working with quotas}
       */
      quotaProjectId;
      /**
       * The {@link Gaxios `Gaxios`} instance used for making requests.
       */
      transporter;
      credentials = {};
      eagerRefreshThresholdMillis = exports2.DEFAULT_EAGER_REFRESH_THRESHOLD_MILLIS;
      forceRefreshOnFailure = false;
      universeDomain = exports2.DEFAULT_UNIVERSE;
      /**
       * Symbols that can be added to GaxiosOptions to specify the method name that is
       * making an RPC call, for logging purposes, as well as a string ID that can be
       * used to correlate calls and responses.
       */
      static RequestMethodNameSymbol = Symbol("request method name");
      static RequestLogIdSymbol = Symbol("request log id");
      constructor(opts = {}) {
        super();
        const options2 = (0, util_1.originalOrCamelOptions)(opts);
        this.apiKey = opts.apiKey;
        this.projectId = options2.get("project_id") ?? null;
        this.quotaProjectId = options2.get("quota_project_id");
        this.credentials = options2.get("credentials") ?? {};
        this.universeDomain = options2.get("universe_domain") ?? exports2.DEFAULT_UNIVERSE;
        this.transporter = opts.transporter ?? new gaxios_1.Gaxios(opts.transporterOptions);
        if (options2.get("useAuthRequestParameters") !== false) {
          this.transporter.interceptors.request.add(_AuthClient.DEFAULT_REQUEST_INTERCEPTOR);
          this.transporter.interceptors.response.add(_AuthClient.DEFAULT_RESPONSE_INTERCEPTOR);
        }
        if (opts.eagerRefreshThresholdMillis) {
          this.eagerRefreshThresholdMillis = opts.eagerRefreshThresholdMillis;
        }
        this.forceRefreshOnFailure = opts.forceRefreshOnFailure ?? false;
      }
      /**
       * A {@link fetch `fetch`} compliant API for {@link AuthClient}.
       *
       * @see {@link AuthClient.request} for the classic method.
       *
       * @remarks
       *
       * This is useful as a drop-in replacement for `fetch` API usage.
       *
       * @example
       *
       * ```ts
       * const authClient = new AuthClient();
       * const fetchWithAuthClient: typeof fetch = (...args) => authClient.fetch(...args);
       * await fetchWithAuthClient('https://example.com');
       * ```
       *
       * @param args `fetch` API or {@link Gaxios.fetch `Gaxios#fetch`} parameters
       * @returns the {@link GaxiosResponse} with Gaxios-added properties
       */
      fetch(...args) {
        const input = args[0];
        const init = args[1];
        let url2 = void 0;
        const headers = new Headers();
        if (typeof input === "string") {
          url2 = new URL(input);
        } else if (input instanceof URL) {
          url2 = input;
        } else if (input && input.url) {
          url2 = new URL(input.url);
        }
        if (input && typeof input === "object" && "headers" in input) {
          gaxios_1.Gaxios.mergeHeaders(headers, input.headers);
        }
        if (init) {
          gaxios_1.Gaxios.mergeHeaders(headers, new Headers(init.headers));
        }
        if (typeof input === "object" && !(input instanceof URL)) {
          return this.request({ ...init, ...input, headers, url: url2 });
        } else {
          return this.request({ ...init, headers, url: url2 });
        }
      }
      /**
       * 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.has("x-goog-user-project") && // don't override a value the user sets.
        this.quotaProjectId) {
          headers.set("x-goog-user-project", this.quotaProjectId);
        }
        return headers;
      }
      /**
       * Adds the `x-goog-user-project` and `authorization` headers to the target Headers
       * object, if they exist on the source.
       *
       * @param target the headers to target
       * @param source the headers to source from
       * @returns the target headers
       */
      addUserProjectAndAuthHeaders(target, source2) {
        const xGoogUserProject = source2.get("x-goog-user-project");
        const authorizationHeader = source2.get("authorization");
        if (xGoogUserProject) {
          target.set("x-goog-user-project", xGoogUserProject);
        }
        if (authorizationHeader) {
          target.set("authorization", authorizationHeader);
        }
        return target;
      }
      static log = (0, google_logging_utils_1.log)("auth");
      static DEFAULT_REQUEST_INTERCEPTOR = {
        resolved: /* @__PURE__ */ __name(async (config2) => {
          if (!config2.headers.has("x-goog-api-client")) {
            const nodeVersion2 = process.version.replace(/^v/, "");
            config2.headers.set("x-goog-api-client", `gl-node/${nodeVersion2}`);
          }
          const userAgent2 = config2.headers.get("User-Agent");
          if (!userAgent2) {
            config2.headers.set("User-Agent", shared_cjs_1.USER_AGENT);
          } else if (!userAgent2.includes(`${shared_cjs_1.PRODUCT_NAME}/`)) {
            config2.headers.set("User-Agent", `${userAgent2} ${shared_cjs_1.USER_AGENT}`);
          }
          try {
            const symbols = config2;
            const methodName = symbols[_AuthClient.RequestMethodNameSymbol];
            const logId = `${Math.floor(Math.random() * 1e3)}`;
            symbols[_AuthClient.RequestLogIdSymbol] = logId;
            const logObject = {
              url: config2.url,
              headers: config2.headers
            };
            if (methodName) {
              _AuthClient.log.info("%s [%s] request %j", methodName, logId, logObject);
            } else {
              _AuthClient.log.info("[%s] request %j", logId, logObject);
            }
          } catch (e4) {
          }
          return config2;
        }, "resolved")
      };
      static DEFAULT_RESPONSE_INTERCEPTOR = {
        resolved: /* @__PURE__ */ __name(async (response) => {
          try {
            const symbols = response.config;
            const methodName = symbols[_AuthClient.RequestMethodNameSymbol];
            const logId = symbols[_AuthClient.RequestLogIdSymbol];
            if (methodName) {
              _AuthClient.log.info("%s [%s] response %j", methodName, logId, response.data);
            } else {
              _AuthClient.log.info("[%s] response %j", logId, response.data);
            }
          } catch (e4) {
          }
          return response;
        }, "resolved"),
        rejected: /* @__PURE__ */ __name(async (error2) => {
          try {
            const symbols = error2.config;
            const methodName = symbols[_AuthClient.RequestMethodNameSymbol];
            const logId = symbols[_AuthClient.RequestLogIdSymbol];
            if (methodName) {
              _AuthClient.log.info("%s [%s] error %j", methodName, logId, error2.response?.data);
            } else {
              _AuthClient.log.error("[%s] error %j", logId, error2.response?.data);
            }
          } catch (e4) {
          }
          throw error2;
        }, "rejected")
      };
      /**
       * Sets the method name that is making a Gaxios request, so that logging may tag
       * log lines with the operation.
       * @param config A Gaxios request config
       * @param methodName The method name making the call
       */
      static setMethodName(config2, methodName) {
        try {
          const symbols = config2;
          symbols[_AuthClient.RequestMethodNameSymbol] = methodName;
        } catch (e4) {
        }
      }
      /**
       * 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;
  }
});

// packages/core/node_modules/google-auth-library/build/src/auth/loginticket.js
var require_loginticket = __commonJS({
  "packages/core/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");
      }
      envelope;
      payload;
      /**
       * 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;
  }
});

// packages/core/node_modules/google-auth-library/build/src/auth/oauth2client.js
var require_oauth2client = __commonJS({
  "packages/core/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 util_1 = require_util10();
    var crypto_1 = require_crypto3();
    var authclient_1 = require_authclient();
    var loginticket_1 = require_loginticket();
    var CodeChallengeMethod;
    (function(CodeChallengeMethod2) {
      CodeChallengeMethod2["Plain"] = "plain";
      CodeChallengeMethod2["S256"] = "S256";
    })(CodeChallengeMethod || (exports2.CodeChallengeMethod = CodeChallengeMethod = {}));
    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 OAuth2Client = class _OAuth2Client extends authclient_1.AuthClient {
      static {
        __name(this, "OAuth2Client");
      }
      redirectUri;
      certificateCache = {};
      certificateExpiry = null;
      certificateCacheFormat = CertificateFormat.PEM;
      refreshTokenPromises = /* @__PURE__ */ new Map();
      endpoints;
      issuers;
      clientAuthentication;
      // TODO: refactor tests to make this private
      _clientId;
      // TODO: refactor tests to make this private
      _clientSecret;
      refreshHandler;
      /**
       * An OAuth2 Client for Google APIs.
       *
       * @param options The OAuth2 Client Options. Passing an `clientId` directly is **@DEPRECATED**.
       * @param clientSecret **@DEPRECATED**. Provide a {@link OAuth2ClientOptions `OAuth2ClientOptions`} object in the first parameter instead.
       * @param redirectUri **@DEPRECATED**. Provide a {@link OAuth2ClientOptions `OAuth2ClientOptions`} object in the first parameter instead.
       */
      constructor(options2 = {}, clientSecret, redirectUri) {
        super(typeof options2 === "object" ? options2 : {});
        if (typeof options2 !== "object") {
          options2 = {
            clientId: options2,
            clientSecret,
            redirectUri
          };
        }
        this._clientId = options2.clientId || options2.client_id;
        this._clientSecret = options2.clientSecret || options2.client_secret;
        this.redirectUri = options2.redirectUri || options2.redirect_uris?.[0];
        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",
          ...options2.endpoints
        };
        this.clientAuthentication = options2.clientAuthentication || ClientAuthentication.ClientSecretPost;
        this.issuers = options2.issuers || [
          "accounts.google.com",
          "https://accounts.google.com",
          this.universeDomain
        ];
      }
      /**
       * @deprecated use instance's {@link OAuth2Client.endpoints}
       */
      static GOOGLE_TOKEN_INFO_URL = "https://oauth2.googleapis.com/tokeninfo";
      /**
       * Clock skew - five minutes in seconds
       */
      static CLOCK_SKEW_SECS_ = 300;
      /**
       * The default max Token Lifetime is one day in seconds
       */
      static DEFAULT_MAX_TOKEN_LIFETIME_SECS_ = 86400;
      /**
       * 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 crypto14 = (0, crypto_1.createCrypto)();
        const randomString2 = crypto14.randomBytesBase64(96);
        const codeVerifier = randomString2.replace(/\+/g, "~").replace(/=/g, "_").replace(/\//g, "-");
        const unencodedCodeChallenge = await crypto14.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((r5) => callback(null, r5.tokens, r5.res), (e4) => callback(e4, null, e4.response));
        } else {
          return this.getTokenAsync(options2);
        }
      }
      async getTokenAsync(options2) {
        const url2 = this.endpoints.oauth2TokenUrl.toString();
        const headers = new Headers();
        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.set("authorization", `Basic ${basic.toString("base64")}`);
        }
        if (this.clientAuthentication === ClientAuthentication.ClientSecretPost) {
          values.client_secret = this._clientSecret;
        }
        const opts = {
          ..._OAuth2Client.RETRY_CONFIG,
          method: "POST",
          url: url2,
          data: new URLSearchParams((0, util_1.removeUndefinedValuesInObject)(values)),
          headers
        };
        authclient_1.AuthClient.setMethodName(opts, "getTokenAsync");
        const res = await this.transporter.request(opts);
        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 p2 = this.refreshTokenNoCache(refreshToken).then((r5) => {
          this.refreshTokenPromises.delete(refreshToken);
          return r5;
        }, (e4) => {
          this.refreshTokenPromises.delete(refreshToken);
          throw e4;
        });
        this.refreshTokenPromises.set(refreshToken, p2);
        return p2;
      }
      async refreshTokenNoCache(refreshToken) {
        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 {
          const opts = {
            ..._OAuth2Client.RETRY_CONFIG,
            method: "POST",
            url: url2,
            data: new URLSearchParams((0, util_1.removeUndefinedValuesInObject)(data))
          };
          authclient_1.AuthClient.setMethodName(opts, "refreshTokenNoCache");
          res = await this.transporter.request(opts);
        } catch (e4) {
          if (e4 instanceof gaxios_1.GaxiosError && e4.message === "invalid_grant" && e4.response?.data && /ReAuth/i.test(e4.response.data.error_description)) {
            e4.message = JSON.stringify(e4.response.data);
          }
          throw e4;
        }
        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((r5) => callback(null, r5.credentials, r5.res), callback);
        } else {
          return this.refreshAccessTokenAsync();
        }
      }
      async refreshAccessTokenAsync() {
        const r5 = await this.refreshToken(this.credentials.refresh_token);
        const tokens = r5.tokens;
        tokens.refresh_token = this.credentials.refresh_token;
        this.credentials = tokens;
        return { credentials: this.credentials, res: r5.res };
      }
      getAccessToken(callback) {
        if (callback) {
          this.getAccessTokenAsync().then((r5) => callback(null, r5.token, r5.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?.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 r5 = await this.refreshAccessTokenAsync();
          if (!r5.credentials || r5.credentials && !r5.credentials.access_token) {
            throw new Error("Could not refresh access token.");
          }
          return { token: r5.credentials.access_token, res: r5.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>' }
       */
      async getRequestHeaders(url2) {
        const headers = (await this.getRequestMetadataAsync(url2)).headers;
        return headers;
      }
      async getRequestMetadataAsync(url2) {
        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 = new Headers({
            authorization: thisCreds.token_type + " " + thisCreds.access_token
          });
          return { headers: this.addSharedMetadataHeaders(headers2) };
        }
        if (this.refreshHandler) {
          const refreshedAccessToken = await this.processAndValidateRefreshHandler();
          if (refreshedAccessToken?.access_token) {
            this.setCredentials(refreshedAccessToken);
            const headers2 = new Headers({
              authorization: "Bearer " + this.credentials.access_token
            });
            return { headers: this.addSharedMetadataHeaders(headers2) };
          }
        }
        if (this.apiKey) {
          return { headers: new Headers({ "X-Goog-Api-Key": this.apiKey }) };
        }
        let r5 = null;
        let tokens = null;
        try {
          r5 = await this.refreshToken(thisCreds.refresh_token);
          tokens = r5.tokens;
        } catch (err) {
          const e4 = err;
          if (e4.response && (e4.response.status === 403 || e4.response.status === 404)) {
            e4.message = `Could not refresh access token: ${e4.message}`;
          }
          throw e4;
        }
        const credentials = this.credentials;
        credentials.token_type = credentials.token_type || "Bearer";
        tokens.refresh_token = credentials.refresh_token;
        this.credentials = tokens;
        const headers = new Headers({
          authorization: credentials.token_type + " " + tokens.access_token
        });
        return { headers: this.addSharedMetadataHeaders(headers), res: r5.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"
        };
        authclient_1.AuthClient.setMethodName(opts, "revokeToken");
        if (callback) {
          this.transporter.request(opts).then((r5) => callback(null, r5), 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((r5) => callback(null, r5), (e4) => {
            return callback(e4, e4.response);
          });
        } else {
          return this.requestAsync(opts);
        }
      }
      async requestAsync(opts, reAuthRetried = false) {
        try {
          const r5 = await this.getRequestMetadataAsync();
          opts.headers = gaxios_1.Gaxios.mergeHeaders(opts.headers);
          this.addUserProjectAndAuthHeaders(opts.headers, r5.headers);
          if (this.apiKey) {
            opts.headers.set("X-Goog-Api-Key", this.apiKey);
          }
          return await this.transporter.request(opts);
        } catch (e4) {
          const res = e4.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?.access_token) {
                this.setCredentials(refreshedAccessToken);
              }
              return this.requestAsync(opts, true);
            }
          }
          throw e4;
        }
      }
      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((r5) => callback(null, r5), 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;charset=UTF-8",
            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((r5) => callback(null, r5.certs, r5.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 {
          const opts = {
            ..._OAuth2Client.RETRY_CONFIG,
            url: url2
          };
          authclient_1.AuthClient.setMethodName(opts, "getFederatedSignonCertsAsync");
          res = await this.transporter.request(opts);
        } catch (e4) {
          if (e4 instanceof Error) {
            e4.message = `Failed to retrieve verification certificates: ${e4.message}`;
          }
          throw e4;
        }
        const cacheControl = res?.headers.get("cache-control");
        let cacheAge = -1;
        if (cacheControl) {
          const maxAge = /max-age=(?<maxAge>[0-9]+)/.exec(cacheControl)?.groups?.maxAge;
          if (maxAge) {
            cacheAge = Number(maxAge) * 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((r5) => callback(null, r5.pubkeys, r5.res), callback);
        } else {
          return this.getIapPublicKeysAsync();
        }
      }
      async getIapPublicKeysAsync() {
        let res;
        const url2 = this.endpoints.oauth2IapPublicKeyUrl.toString();
        try {
          const opts = {
            ..._OAuth2Client.RETRY_CONFIG,
            url: url2
          };
          authclient_1.AuthClient.setMethodName(opts, "getIapPublicKeysAsync");
          res = await this.transporter.request(opts);
        } catch (e4) {
          if (e4 instanceof Error) {
            e4.message = `Failed to retrieve verification certificates: ${e4.message}`;
          }
          throw e4;
        }
        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 crypto14 = (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(crypto14.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(crypto14.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 crypto14.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 = OAuth2Client;
  }
});

// packages/core/node_modules/google-auth-library/build/src/auth/computeclient.js
var require_computeclient = __commonJS({
  "packages/core/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 Compute = class extends oauth2client_1.OAuth2Client {
      static {
        __name(this, "Compute");
      }
      serviceAccountEmail;
      scopes;
      /**
       * 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() {
        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 (e4) {
          if (e4 instanceof gaxios_1.GaxiosError) {
            e4.message = `Could not refresh access token: ${e4.message}`;
            this.wrapError(e4);
          }
          throw e4;
        }
        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 (e4) {
          if (e4 instanceof Error) {
            e4.message = `Could not fetch ID token: ${e4.message}`;
          }
          throw e4;
        }
        return idToken;
      }
      wrapError(e4) {
        const res = e4.response;
        if (res && res.status) {
          e4.status = res.status;
          if (res.status === 403) {
            e4.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: " + e4.message;
          } else if (res.status === 404) {
            e4.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: " + e4.message;
          }
        }
      }
    };
    exports2.Compute = Compute;
  }
});

// packages/core/node_modules/google-auth-library/build/src/auth/idtokenclient.js
var require_idtokenclient = __commonJS({
  "packages/core/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");
      }
      targetAudience;
      idTokenProvider;
      /**
       * 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() {
        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 = new 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;
  }
});

// packages/core/node_modules/google-auth-library/build/src/auth/envDetect.js
var require_envDetect = __commonJS({
  "packages/core/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["CLOUD_RUN_JOBS"] = "CLOUD_RUN_JOBS";
      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 if (isCloudRunJob()) {
          env7 = GCPEnv.CLOUD_RUN_JOBS;
        } 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");
    function isCloudRunJob() {
      return !!process.env.CLOUD_RUN_JOB;
    }
    __name(isCloudRunJob, "isCloudRunJob");
    async function isKubernetesEngine() {
      try {
        await gcpMetadata.instance("attributes/cluster-name");
        return true;
      } catch (e4) {
        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 Buffer9 = require_safe_buffer().Buffer;
    var Stream9 = __require("stream");
    var util3 = __require("util");
    function DataStream(data) {
      this.buffer = null;
      this.writable = true;
      this.readable = true;
      if (!data) {
        this.buffer = Buffer9.alloc(0);
        return this;
      }
      if (typeof data.pipe === "function") {
        this.buffer = Buffer9.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");
    util3.inherits(DataStream, Stream9);
    DataStream.prototype.write = /* @__PURE__ */ __name(function write2(data) {
      this.buffer = Buffer9.concat([this.buffer, Buffer9.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 Buffer9 = __require("buffer").Buffer;
    var SlowBuffer = __require("buffer").SlowBuffer;
    module2.exports = bufferEq;
    function bufferEq(a2, b2) {
      if (!Buffer9.isBuffer(a2) || !Buffer9.isBuffer(b2)) {
        return false;
      }
      if (a2.length !== b2.length) {
        return false;
      }
      var c4 = 0;
      for (var i3 = 0; i3 < a2.length; i3++) {
        c4 |= a2[i3] ^ b2[i3];
      }
      return c4 === 0;
    }
    __name(bufferEq, "bufferEq");
    bufferEq.install = function() {
      Buffer9.prototype.equal = SlowBuffer.prototype.equal = /* @__PURE__ */ __name(function equal(that) {
        return bufferEq(this, that);
      }, "equal");
    };
    var origBufEqual = Buffer9.prototype.equal;
    var origSlowBufEqual = SlowBuffer.prototype.equal;
    bufferEq.restore = function() {
      Buffer9.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 Buffer9 = require_safe_buffer().Buffer;
    var crypto14 = __require("crypto");
    var formatEcdsa = require_ecdsa_sig_formatter();
    var util3 = __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 crypto14.createPublicKey === "function";
    if (supportsKeyObjects) {
      MSG_INVALID_VERIFIER_KEY += " or a KeyObject";
      MSG_INVALID_SECRET += "or a KeyObject";
    }
    function checkIsPublicKey(key) {
      if (Buffer9.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 (Buffer9.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 (Buffer9.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(base642) {
      return base642.replace(/=/g, "").replace(/\+/g, "-").replace(/\//g, "_");
    }
    __name(fromBase64, "fromBase64");
    function toBase64(base64url2) {
      base64url2 = base64url2.toString();
      var padding = 4 - base64url2.length % 4;
      if (padding !== 4) {
        for (var i3 = 0; i3 < padding; ++i3) {
          base64url2 += "=";
        }
      }
      return base64url2.replace(/\-/g, "+").replace(/_/g, "/");
    }
    __name(toBase64, "toBase64");
    function typeError(template) {
      var args = [].slice.call(arguments, 1);
      var errMsg = util3.format.bind(util3, template).apply(null, args);
      return new TypeError(errMsg);
    }
    __name(typeError, "typeError");
    function bufferOrString(obj) {
      return Buffer9.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 = crypto14.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 crypto14 ? /* @__PURE__ */ __name(function timingSafeEqual2(a2, b2) {
      if (a2.byteLength !== b2.byteLength) {
        return false;
      }
      return crypto14.timingSafeEqual(a2, b2);
    }, "timingSafeEqual") : /* @__PURE__ */ __name(function timingSafeEqual2(a2, b2) {
      if (!bufferEqual) {
        bufferEqual = require_buffer_equal_constant_time();
      }
      return bufferEqual(a2, b2);
    }, "timingSafeEqual");
    function createHmacVerifier(bits) {
      return /* @__PURE__ */ __name(function verify(thing, signature, secret) {
        var computedSig = createHmacSigner(bits)(thing, secret);
        return timingSafeEqual(Buffer9.from(signature), Buffer9.from(computedSig));
      }, "verify");
    }
    __name(createHmacVerifier, "createHmacVerifier");
    function createKeySigner(bits) {
      return /* @__PURE__ */ __name(function sign(thing, privateKey) {
        checkIsPrivateKey(privateKey);
        thing = normalizeInput(thing);
        var signer = crypto14.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 = crypto14.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 = crypto14.createSign("RSA-SHA" + bits);
        var sig = (signer.update(thing), signer.sign({
          key: privateKey,
          padding: crypto14.constants.RSA_PKCS1_PSS_PADDING,
          saltLength: crypto14.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 = crypto14.createVerify("RSA-SHA" + bits);
        verifier.update(thing);
        return verifier.verify({
          key: publicKey,
          padding: crypto14.constants.RSA_PKCS1_PSS_PADDING,
          saltLength: crypto14.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 Buffer9 = __require("buffer").Buffer;
    module2.exports = /* @__PURE__ */ __name(function toString(obj) {
      if (typeof obj === "string")
        return obj;
      if (typeof obj === "number" || Buffer9.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 Buffer9 = require_safe_buffer().Buffer;
    var DataStream = require_data_stream();
    var jwa = require_jwa();
    var Stream9 = __require("stream");
    var toString = require_tostring();
    var util3 = __require("util");
    function base64url2(string4, encoding) {
      return Buffer9.from(string4, encoding).toString("base64").replace(/=/g, "").replace(/\+/g, "-").replace(/\//g, "_");
    }
    __name(base64url2, "base64url");
    function jwsSecuredInput(header, payload, encoding) {
      encoding = encoding || "utf8";
      var encodedHeader = base64url2(toString(header), "binary");
      var encodedPayload = base64url2(toString(payload), encoding);
      return util3.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 util3.format("%s.%s", securedInput, signature);
    }
    __name(jwsSign, "jwsSign");
    function SignStream(opts) {
      var secret = opts.secret;
      secret = secret == null ? opts.privateKey : secret;
      secret = secret == null ? opts.key : secret;
      if (/^hs/i.test(opts.header.alg) === true && secret == null) {
        throw new TypeError("secret must be a string or buffer or a KeyObject");
      }
      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");
    util3.inherits(SignStream, Stream9);
    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 (e4) {
        this.readable = false;
        this.emit("error", e4);
        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 Buffer9 = require_safe_buffer().Buffer;
    var DataStream = require_data_stream();
    var jwa = require_jwa();
    var Stream9 = __require("stream");
    var toString = require_tostring();
    var util3 = __require("util");
    var JWS_REGEX = /^[a-zA-Z0-9\-_]+?\.[a-zA-Z0-9\-_]+?\.([a-zA-Z0-9\-_]+)?$/;
    function isObject4(thing) {
      return Object.prototype.toString.call(thing) === "[object Object]";
    }
    __name(isObject4, "isObject");
    function safeJsonParse2(thing) {
      if (isObject4(thing))
        return thing;
      try {
        return JSON.parse(thing);
      } catch (e4) {
        return void 0;
      }
    }
    __name(safeJsonParse2, "safeJsonParse");
    function headerFromJWS(jwsSig) {
      var encodedHeader = jwsSig.split(".", 1)[0];
      return safeJsonParse2(Buffer9.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 Buffer9.from(payload, "base64").toString(encoding);
    }
    __name(payloadFromJWS, "payloadFromJWS");
    function isValidJws(string4) {
      return JWS_REGEX.test(string4) && !!headerFromJWS(string4);
    }
    __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;
      secretOrKey = secretOrKey == null ? opts.publicKey : secretOrKey;
      secretOrKey = secretOrKey == null ? opts.key : secretOrKey;
      if (/^hs/i.test(opts.algorithm) === true && secretOrKey == null) {
        throw new TypeError("secret must be a string or buffer or a KeyObject");
      }
      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");
    util3.inherits(VerifyStream, Stream9);
    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 (e4) {
        this.readable = false;
        this.emit("error", e4);
        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");
  }
});

// packages/core/node_modules/gtoken/build/cjs/src/index.cjs
var require_src5 = __commonJS({
  "packages/core/node_modules/gtoken/build/cjs/src/index.cjs"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", {
      value: true
    });
    exports2.GoogleToken = void 0;
    var fs113 = _interopRequireWildcard(__require("fs"));
    var _gaxios = require_src2();
    var jws = _interopRequireWildcard(require_jws());
    var path125 = _interopRequireWildcard(__require("path"));
    var _util = __require("util");
    function _interopRequireWildcard(e4, t5) {
      if ("function" == typeof WeakMap) var r5 = /* @__PURE__ */ new WeakMap(), n3 = /* @__PURE__ */ new WeakMap();
      return (_interopRequireWildcard = /* @__PURE__ */ __name(function _interopRequireWildcard2(e5, t6) {
        if (!t6 && e5 && e5.__esModule) return e5;
        var o3, i3, f5 = { __proto__: null, "default": e5 };
        if (null === e5 || "object" != _typeof2(e5) && "function" != typeof e5) return f5;
        if (o3 = t6 ? n3 : r5) {
          if (o3.has(e5)) return o3.get(e5);
          o3.set(e5, f5);
        }
        for (var _t3 in e5) "default" !== _t3 && {}.hasOwnProperty.call(e5, _t3) && ((i3 = (o3 = Object.defineProperty) && Object.getOwnPropertyDescriptor(e5, _t3)) && (i3.get || i3.set) ? o3(f5, _t3, i3) : f5[_t3] = e5[_t3]);
        return f5;
      }, "_interopRequireWildcard"))(e4, t5);
    }
    __name(_interopRequireWildcard, "_interopRequireWildcard");
    function _typeof2(o3) {
      "@babel/helpers - typeof";
      return _typeof2 = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(o4) {
        return typeof o4;
      } : function(o4) {
        return o4 && "function" == typeof Symbol && o4.constructor === Symbol && o4 !== Symbol.prototype ? "symbol" : typeof o4;
      }, _typeof2(o3);
    }
    __name(_typeof2, "_typeof");
    function _classPrivateMethodInitSpec(e4, a2) {
      _checkPrivateRedeclaration(e4, a2), a2.add(e4);
    }
    __name(_classPrivateMethodInitSpec, "_classPrivateMethodInitSpec");
    function _classPrivateFieldInitSpec(e4, t5, a2) {
      _checkPrivateRedeclaration(e4, t5), t5.set(e4, a2);
    }
    __name(_classPrivateFieldInitSpec, "_classPrivateFieldInitSpec");
    function _checkPrivateRedeclaration(e4, t5) {
      if (t5.has(e4)) throw new TypeError("Cannot initialize the same private elements twice on an object");
    }
    __name(_checkPrivateRedeclaration, "_checkPrivateRedeclaration");
    function _classPrivateFieldSet(s5, a2, r5) {
      return s5.set(_assertClassBrand(s5, a2), r5), r5;
    }
    __name(_classPrivateFieldSet, "_classPrivateFieldSet");
    function _classPrivateFieldGet(s5, a2) {
      return s5.get(_assertClassBrand(s5, a2));
    }
    __name(_classPrivateFieldGet, "_classPrivateFieldGet");
    function _assertClassBrand(e4, t5, n3) {
      if ("function" == typeof e4 ? e4 === t5 : e4.has(t5)) return arguments.length < 3 ? t5 : n3;
      throw new TypeError("Private element is not present on this object");
    }
    __name(_assertClassBrand, "_assertClassBrand");
    function _defineProperties(e4, r5) {
      for (var t5 = 0; t5 < r5.length; t5++) {
        var o3 = r5[t5];
        o3.enumerable = o3.enumerable || false, o3.configurable = true, "value" in o3 && (o3.writable = true), Object.defineProperty(e4, _toPropertyKey2(o3.key), o3);
      }
    }
    __name(_defineProperties, "_defineProperties");
    function _createClass(e4, r5, t5) {
      return r5 && _defineProperties(e4.prototype, r5), t5 && _defineProperties(e4, t5), Object.defineProperty(e4, "prototype", { writable: false }), e4;
    }
    __name(_createClass, "_createClass");
    function _classCallCheck(a2, n3) {
      if (!(a2 instanceof n3)) throw new TypeError("Cannot call a class as a function");
    }
    __name(_classCallCheck, "_classCallCheck");
    function _callSuper(t5, o3, e4) {
      return o3 = _getPrototypeOf(o3), _possibleConstructorReturn(t5, _isNativeReflectConstruct() ? Reflect.construct(o3, e4 || [], _getPrototypeOf(t5).constructor) : o3.apply(t5, e4));
    }
    __name(_callSuper, "_callSuper");
    function _possibleConstructorReturn(t5, e4) {
      if (e4 && ("object" == _typeof2(e4) || "function" == typeof e4)) return e4;
      if (void 0 !== e4) throw new TypeError("Derived constructors may only return object or undefined");
      return _assertThisInitialized(t5);
    }
    __name(_possibleConstructorReturn, "_possibleConstructorReturn");
    function _assertThisInitialized(e4) {
      if (void 0 === e4) throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
      return e4;
    }
    __name(_assertThisInitialized, "_assertThisInitialized");
    function _inherits(t5, e4) {
      if ("function" != typeof e4 && null !== e4) throw new TypeError("Super expression must either be null or a function");
      t5.prototype = Object.create(e4 && e4.prototype, { constructor: { value: t5, writable: true, configurable: true } }), Object.defineProperty(t5, "prototype", { writable: false }), e4 && _setPrototypeOf(t5, e4);
    }
    __name(_inherits, "_inherits");
    function _wrapNativeSuper(t5) {
      var r5 = "function" == typeof Map ? /* @__PURE__ */ new Map() : void 0;
      return _wrapNativeSuper = /* @__PURE__ */ __name(function _wrapNativeSuper2(t6) {
        if (null === t6 || !_isNativeFunction(t6)) return t6;
        if ("function" != typeof t6) throw new TypeError("Super expression must either be null or a function");
        if (void 0 !== r5) {
          if (r5.has(t6)) return r5.get(t6);
          r5.set(t6, Wrapper);
        }
        function Wrapper() {
          return _construct(t6, arguments, _getPrototypeOf(this).constructor);
        }
        __name(Wrapper, "Wrapper");
        return Wrapper.prototype = Object.create(t6.prototype, { constructor: { value: Wrapper, enumerable: false, writable: true, configurable: true } }), _setPrototypeOf(Wrapper, t6);
      }, "_wrapNativeSuper"), _wrapNativeSuper(t5);
    }
    __name(_wrapNativeSuper, "_wrapNativeSuper");
    function _construct(t5, e4, r5) {
      if (_isNativeReflectConstruct()) return Reflect.construct.apply(null, arguments);
      var o3 = [null];
      o3.push.apply(o3, e4);
      var p2 = new (t5.bind.apply(t5, o3))();
      return r5 && _setPrototypeOf(p2, r5.prototype), p2;
    }
    __name(_construct, "_construct");
    function _isNativeReflectConstruct() {
      try {
        var t5 = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function() {
        }));
      } catch (t6) {
      }
      return (_isNativeReflectConstruct = /* @__PURE__ */ __name(function _isNativeReflectConstruct2() {
        return !!t5;
      }, "_isNativeReflectConstruct"))();
    }
    __name(_isNativeReflectConstruct, "_isNativeReflectConstruct");
    function _isNativeFunction(t5) {
      try {
        return -1 !== Function.toString.call(t5).indexOf("[native code]");
      } catch (n3) {
        return "function" == typeof t5;
      }
    }
    __name(_isNativeFunction, "_isNativeFunction");
    function _setPrototypeOf(t5, e4) {
      return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function(t6, e5) {
        return t6.__proto__ = e5, t6;
      }, _setPrototypeOf(t5, e4);
    }
    __name(_setPrototypeOf, "_setPrototypeOf");
    function _getPrototypeOf(t5) {
      return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function(t6) {
        return t6.__proto__ || Object.getPrototypeOf(t6);
      }, _getPrototypeOf(t5);
    }
    __name(_getPrototypeOf, "_getPrototypeOf");
    function _defineProperty2(e4, r5, t5) {
      return (r5 = _toPropertyKey2(r5)) in e4 ? Object.defineProperty(e4, r5, { value: t5, enumerable: true, configurable: true, writable: true }) : e4[r5] = t5, e4;
    }
    __name(_defineProperty2, "_defineProperty");
    function _toPropertyKey2(t5) {
      var i3 = _toPrimitive2(t5, "string");
      return "symbol" == _typeof2(i3) ? i3 : i3 + "";
    }
    __name(_toPropertyKey2, "_toPropertyKey");
    function _toPrimitive2(t5, r5) {
      if ("object" != _typeof2(t5) || !t5) return t5;
      var e4 = t5[Symbol.toPrimitive];
      if (void 0 !== e4) {
        var i3 = e4.call(t5, r5 || "default");
        if ("object" != _typeof2(i3)) return i3;
        throw new TypeError("@@toPrimitive must return a primitive value.");
      }
      return ("string" === r5 ? String : Number)(t5);
    }
    __name(_toPrimitive2, "_toPrimitive");
    function _regenerator() {
      var e4, t5, r5 = "function" == typeof Symbol ? Symbol : {}, n3 = r5.iterator || "@@iterator", o3 = r5.toStringTag || "@@toStringTag";
      function i3(r6, n4, o4, i4) {
        var c5 = n4 && n4.prototype instanceof Generator ? n4 : Generator, u3 = Object.create(c5.prototype);
        return _regeneratorDefine2(u3, "_invoke", function(r7, n5, o5) {
          var i5, c6, u4, f6 = 0, p2 = o5 || [], y2 = false, G2 = { p: 0, n: 0, v: e4, a: d2, f: d2.bind(e4, 4), d: /* @__PURE__ */ __name(function d3(t6, r8) {
            return i5 = t6, c6 = 0, u4 = e4, G2.n = r8, a2;
          }, "d") };
          function d2(r8, n6) {
            for (c6 = r8, u4 = n6, t5 = 0; !y2 && f6 && !o6 && t5 < p2.length; t5++) {
              var o6, i6 = p2[t5], d3 = G2.p, l3 = i6[2];
              r8 > 3 ? (o6 = l3 === n6) && (u4 = i6[(c6 = i6[4]) ? 5 : (c6 = 3, 3)], i6[4] = i6[5] = e4) : i6[0] <= d3 && ((o6 = r8 < 2 && d3 < i6[1]) ? (c6 = 0, G2.v = n6, G2.n = i6[1]) : d3 < l3 && (o6 = r8 < 3 || i6[0] > n6 || n6 > l3) && (i6[4] = r8, i6[5] = n6, G2.n = l3, c6 = 0));
            }
            if (o6 || r8 > 1) return a2;
            throw y2 = true, n6;
          }
          __name(d2, "d");
          return function(o6, p3, l3) {
            if (f6 > 1) throw TypeError("Generator is already running");
            for (y2 && 1 === p3 && d2(p3, l3), c6 = p3, u4 = l3; (t5 = c6 < 2 ? e4 : u4) || !y2; ) {
              i5 || (c6 ? c6 < 3 ? (c6 > 1 && (G2.n = -1), d2(c6, u4)) : G2.n = u4 : G2.v = u4);
              try {
                if (f6 = 2, i5) {
                  if (c6 || (o6 = "next"), t5 = i5[o6]) {
                    if (!(t5 = t5.call(i5, u4))) throw TypeError("iterator result is not an object");
                    if (!t5.done) return t5;
                    u4 = t5.value, c6 < 2 && (c6 = 0);
                  } else 1 === c6 && (t5 = i5["return"]) && t5.call(i5), c6 < 2 && (u4 = TypeError("The iterator does not provide a '" + o6 + "' method"), c6 = 1);
                  i5 = e4;
                } else if ((t5 = (y2 = G2.n < 0) ? u4 : r7.call(n5, G2)) !== a2) break;
              } catch (t6) {
                i5 = e4, c6 = 1, u4 = t6;
              } finally {
                f6 = 1;
              }
            }
            return { value: t5, done: y2 };
          };
        }(r6, o4, i4), true), u3;
      }
      __name(i3, "i");
      var a2 = {};
      function Generator() {
      }
      __name(Generator, "Generator");
      function GeneratorFunction() {
      }
      __name(GeneratorFunction, "GeneratorFunction");
      function GeneratorFunctionPrototype() {
      }
      __name(GeneratorFunctionPrototype, "GeneratorFunctionPrototype");
      t5 = Object.getPrototypeOf;
      var c4 = [][n3] ? t5(t5([][n3]())) : (_regeneratorDefine2(t5 = {}, n3, function() {
        return this;
      }), t5), u2 = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(c4);
      function f5(e5) {
        return Object.setPrototypeOf ? Object.setPrototypeOf(e5, GeneratorFunctionPrototype) : (e5.__proto__ = GeneratorFunctionPrototype, _regeneratorDefine2(e5, o3, "GeneratorFunction")), e5.prototype = Object.create(u2), e5;
      }
      __name(f5, "f");
      return GeneratorFunction.prototype = GeneratorFunctionPrototype, _regeneratorDefine2(u2, "constructor", GeneratorFunctionPrototype), _regeneratorDefine2(GeneratorFunctionPrototype, "constructor", GeneratorFunction), GeneratorFunction.displayName = "GeneratorFunction", _regeneratorDefine2(GeneratorFunctionPrototype, o3, "GeneratorFunction"), _regeneratorDefine2(u2), _regeneratorDefine2(u2, o3, "Generator"), _regeneratorDefine2(u2, n3, function() {
        return this;
      }), _regeneratorDefine2(u2, "toString", function() {
        return "[object Generator]";
      }), (_regenerator = /* @__PURE__ */ __name(function _regenerator2() {
        return { w: i3, m: f5 };
      }, "_regenerator"))();
    }
    __name(_regenerator, "_regenerator");
    function _regeneratorDefine2(e4, r5, n3, t5) {
      var i3 = Object.defineProperty;
      try {
        i3({}, "", {});
      } catch (e5) {
        i3 = 0;
      }
      _regeneratorDefine2 = /* @__PURE__ */ __name(function _regeneratorDefine(e5, r6, n4, t6) {
        if (r6) i3 ? i3(e5, r6, { value: n4, enumerable: !t6, configurable: !t6, writable: !t6 }) : e5[r6] = n4;
        else {
          var o3 = /* @__PURE__ */ __name(function o4(r7, n5) {
            _regeneratorDefine2(e5, r7, function(e6) {
              return this._invoke(r7, n5, e6);
            });
          }, "o");
          o3("next", 0), o3("throw", 1), o3("return", 2);
        }
      }, "_regeneratorDefine"), _regeneratorDefine2(e4, r5, n3, t5);
    }
    __name(_regeneratorDefine2, "_regeneratorDefine2");
    function asyncGeneratorStep(n3, t5, e4, r5, o3, a2, c4) {
      try {
        var i3 = n3[a2](c4), u2 = i3.value;
      } catch (n4) {
        return void e4(n4);
      }
      i3.done ? t5(u2) : Promise.resolve(u2).then(r5, o3);
    }
    __name(asyncGeneratorStep, "asyncGeneratorStep");
    function _asyncToGenerator(n3) {
      return function() {
        var t5 = this, e4 = arguments;
        return new Promise(function(r5, o3) {
          var a2 = n3.apply(t5, e4);
          function _next(n4) {
            asyncGeneratorStep(a2, r5, o3, _next, _throw, "next", n4);
          }
          __name(_next, "_next");
          function _throw(n4) {
            asyncGeneratorStep(a2, r5, o3, _next, _throw, "throw", n4);
          }
          __name(_throw, "_throw");
          _next(void 0);
        });
      };
    }
    __name(_asyncToGenerator, "_asyncToGenerator");
    var readFile13 = fs113.readFile ? (0, _util.promisify)(fs113.readFile) : /* @__PURE__ */ _asyncToGenerator(/* @__PURE__ */ _regenerator().m(/* @__PURE__ */ __name(function _callee() {
      return _regenerator().w(function(_context) {
        while (1) switch (_context.n) {
          case 0:
            throw new ErrorWithCode("use key rather than keyFile.", "MISSING_CREDENTIALS");
          case 1:
            return _context.a(2);
        }
      }, _callee);
    }, "_callee")));
    var GOOGLE_TOKEN_URL = "https://oauth2.googleapis.com/token";
    var GOOGLE_REVOKE_TOKEN_URL = "https://oauth2.googleapis.com/revoke?token=";
    var ErrorWithCode = /* @__PURE__ */ function(_Error) {
      function ErrorWithCode2(message, code2) {
        var _this;
        _classCallCheck(this, ErrorWithCode2);
        _this = _callSuper(this, ErrorWithCode2, [message]);
        _defineProperty2(_this, "code", void 0);
        _this.code = code2;
        return _this;
      }
      __name(ErrorWithCode2, "ErrorWithCode");
      _inherits(ErrorWithCode2, _Error);
      return _createClass(ErrorWithCode2);
    }(/* @__PURE__ */ _wrapNativeSuper(Error));
    var _inFlightRequest = /* @__PURE__ */ new WeakMap();
    var _GoogleToken_brand = /* @__PURE__ */ new WeakSet();
    var GoogleToken = exports2.GoogleToken = /* @__PURE__ */ function() {
      function GoogleToken2(_options) {
        _classCallCheck(this, GoogleToken2);
        _classPrivateMethodInitSpec(this, _GoogleToken_brand);
        _defineProperty2(this, "expiresAt", void 0);
        _defineProperty2(this, "key", void 0);
        _defineProperty2(this, "keyFile", void 0);
        _defineProperty2(this, "iss", void 0);
        _defineProperty2(this, "sub", void 0);
        _defineProperty2(this, "scope", void 0);
        _defineProperty2(this, "rawToken", void 0);
        _defineProperty2(this, "tokenExpires", void 0);
        _defineProperty2(this, "email", void 0);
        _defineProperty2(this, "additionalClaims", void 0);
        _defineProperty2(this, "eagerRefreshThresholdMillis", void 0);
        _defineProperty2(this, "transporter", {
          request: /* @__PURE__ */ __name(function request4(opts) {
            return (0, _gaxios.request)(opts);
          }, "request")
        });
        _classPrivateFieldInitSpec(this, _inFlightRequest, void 0);
        _assertClassBrand(_GoogleToken_brand, this, _configure).call(this, _options);
      }
      __name(GoogleToken2, "GoogleToken");
      return _createClass(GoogleToken2, [{
        key: "accessToken",
        get: /* @__PURE__ */ __name(function get4() {
          return this.rawToken ? this.rawToken.access_token : void 0;
        }, "get")
      }, {
        key: "idToken",
        get: /* @__PURE__ */ __name(function get4() {
          return this.rawToken ? this.rawToken.id_token : void 0;
        }, "get")
      }, {
        key: "tokenType",
        get: /* @__PURE__ */ __name(function get4() {
          return this.rawToken ? this.rawToken.token_type : void 0;
        }, "get")
      }, {
        key: "refreshToken",
        get: /* @__PURE__ */ __name(function get4() {
          return this.rawToken ? this.rawToken.refresh_token : void 0;
        }, "get")
      }, {
        key: "hasExpired",
        value: /* @__PURE__ */ __name(function hasExpired() {
          var now = (/* @__PURE__ */ new Date()).getTime();
          if (this.rawToken && this.expiresAt) {
            return now >= this.expiresAt;
          } else {
            return true;
          }
        }, "hasExpired")
        /**
         * Returns whether the token will expire within eagerRefreshThresholdMillis
         *
         * @return true if the token will be expired within eagerRefreshThresholdMillis, false otherwise.
         */
      }, {
        key: "isTokenExpiring",
        value: /* @__PURE__ */ __name(function isTokenExpiring() {
          var _this$eagerRefreshThr;
          var now = (/* @__PURE__ */ new Date()).getTime();
          var eagerRefreshThresholdMillis = (_this$eagerRefreshThr = this.eagerRefreshThresholdMillis) !== null && _this$eagerRefreshThr !== void 0 ? _this$eagerRefreshThr : 0;
          if (this.rawToken && this.expiresAt) {
            return this.expiresAt <= now + eagerRefreshThresholdMillis;
          } else {
            return true;
          }
        }, "isTokenExpiring")
        /**
         * Returns a cached token or retrieves a new one from Google.
         *
         * @param callback The callback function.
         */
      }, {
        key: "getToken",
        value: /* @__PURE__ */ __name(function getToken(callback) {
          var opts = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {};
          if (_typeof2(callback) === "object") {
            opts = callback;
            callback = void 0;
          }
          opts = Object.assign({
            forceRefresh: false
          }, opts);
          if (callback) {
            var cb = callback;
            _assertClassBrand(_GoogleToken_brand, this, _getTokenAsync).call(this, opts).then(function(t5) {
              return cb(null, t5);
            }, callback);
            return;
          }
          return _assertClassBrand(_GoogleToken_brand, this, _getTokenAsync).call(this, opts);
        }, "getToken")
        /**
         * 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
         */
      }, {
        key: "getCredentials",
        value: function() {
          var _getCredentials = _asyncToGenerator(/* @__PURE__ */ _regenerator().m(/* @__PURE__ */ __name(function _callee2(keyFile) {
            var ext2, key, body, privateKey, clientEmail, _privateKey, _t2;
            return _regenerator().w(function(_context2) {
              while (1) switch (_context2.n) {
                case 0:
                  ext2 = path125.extname(keyFile);
                  _t2 = ext2;
                  _context2.n = _t2 === ".json" ? 1 : _t2 === ".der" ? 4 : _t2 === ".crt" ? 4 : _t2 === ".pem" ? 4 : _t2 === ".p12" ? 6 : _t2 === ".pfx" ? 6 : 7;
                  break;
                case 1:
                  _context2.n = 2;
                  return readFile13(keyFile, "utf8");
                case 2:
                  key = _context2.v;
                  body = JSON.parse(key);
                  privateKey = body.private_key;
                  clientEmail = body.client_email;
                  if (!(!privateKey || !clientEmail)) {
                    _context2.n = 3;
                    break;
                  }
                  throw new ErrorWithCode("private_key and client_email are required.", "MISSING_CREDENTIALS");
                case 3:
                  return _context2.a(2, {
                    privateKey,
                    clientEmail
                  });
                case 4:
                  _context2.n = 5;
                  return readFile13(keyFile, "utf8");
                case 5:
                  _privateKey = _context2.v;
                  return _context2.a(2, {
                    privateKey: _privateKey
                  });
                case 6:
                  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");
                case 7:
                  throw new ErrorWithCode("Unknown certificate type. Type is determined based on file extension. Current supported extensions are *.json, and *.pem.", "UNKNOWN_CERTIFICATE_TYPE");
                case 8:
                  return _context2.a(2);
              }
            }, _callee2);
          }, "_callee2")));
          function getCredentials(_x) {
            return _getCredentials.apply(this, arguments);
          }
          __name(getCredentials, "getCredentials");
          return getCredentials;
        }()
      }, {
        key: "revokeToken",
        value: /* @__PURE__ */ __name(function revokeToken(callback) {
          if (callback) {
            _assertClassBrand(_GoogleToken_brand, this, _revokeTokenAsync).call(this).then(function() {
              return callback();
            }, callback);
            return;
          }
          return _assertClassBrand(_GoogleToken_brand, this, _revokeTokenAsync).call(this);
        }, "revokeToken")
      }]);
    }();
    function _getTokenAsync(_x2) {
      return _getTokenAsync2.apply(this, arguments);
    }
    __name(_getTokenAsync, "_getTokenAsync");
    function _getTokenAsync2() {
      _getTokenAsync2 = _asyncToGenerator(/* @__PURE__ */ _regenerator().m(/* @__PURE__ */ __name(function _callee3(opts) {
        return _regenerator().w(function(_context3) {
          while (1) switch (_context3.n) {
            case 0:
              if (!(_classPrivateFieldGet(_inFlightRequest, this) && !opts.forceRefresh)) {
                _context3.n = 1;
                break;
              }
              return _context3.a(2, _classPrivateFieldGet(_inFlightRequest, this));
            case 1:
              _context3.p = 1;
              _context3.n = 2;
              return _classPrivateFieldSet(_inFlightRequest, this, _assertClassBrand(_GoogleToken_brand, this, _getTokenAsyncInner).call(this, opts));
            case 2:
              return _context3.a(2, _context3.v);
            case 3:
              _context3.p = 3;
              _classPrivateFieldSet(_inFlightRequest, this, void 0);
              return _context3.f(3);
            case 4:
              return _context3.a(2);
          }
        }, _callee3, this, [[1, , 3, 4]]);
      }, "_callee3")));
      return _getTokenAsync2.apply(this, arguments);
    }
    __name(_getTokenAsync2, "_getTokenAsync2");
    function _getTokenAsyncInner(_x3) {
      return _getTokenAsyncInner2.apply(this, arguments);
    }
    __name(_getTokenAsyncInner, "_getTokenAsyncInner");
    function _getTokenAsyncInner2() {
      _getTokenAsyncInner2 = _asyncToGenerator(/* @__PURE__ */ _regenerator().m(/* @__PURE__ */ __name(function _callee4(opts) {
        var creds;
        return _regenerator().w(function(_context4) {
          while (1) switch (_context4.n) {
            case 0:
              if (!(this.isTokenExpiring() === false && opts.forceRefresh === false)) {
                _context4.n = 1;
                break;
              }
              return _context4.a(2, Promise.resolve(this.rawToken));
            case 1:
              if (!(!this.key && !this.keyFile)) {
                _context4.n = 2;
                break;
              }
              throw new Error("No key or keyFile set.");
            case 2:
              if (!(!this.key && this.keyFile)) {
                _context4.n = 4;
                break;
              }
              _context4.n = 3;
              return this.getCredentials(this.keyFile);
            case 3:
              creds = _context4.v;
              this.key = creds.privateKey;
              this.iss = creds.clientEmail || this.iss;
              if (!creds.clientEmail) {
                _assertClassBrand(_GoogleToken_brand, this, _ensureEmail).call(this);
              }
            case 4:
              return _context4.a(2, _assertClassBrand(_GoogleToken_brand, this, _requestToken).call(this));
          }
        }, _callee4, this);
      }, "_callee4")));
      return _getTokenAsyncInner2.apply(this, arguments);
    }
    __name(_getTokenAsyncInner2, "_getTokenAsyncInner2");
    function _ensureEmail() {
      if (!this.iss) {
        throw new ErrorWithCode("email is required.", "MISSING_CREDENTIALS");
      }
    }
    __name(_ensureEmail, "_ensureEmail");
    function _revokeTokenAsync() {
      return _revokeTokenAsync2.apply(this, arguments);
    }
    __name(_revokeTokenAsync, "_revokeTokenAsync");
    function _revokeTokenAsync2() {
      _revokeTokenAsync2 = _asyncToGenerator(/* @__PURE__ */ _regenerator().m(/* @__PURE__ */ __name(function _callee5() {
        var url2;
        return _regenerator().w(function(_context5) {
          while (1) switch (_context5.n) {
            case 0:
              if (this.accessToken) {
                _context5.n = 1;
                break;
              }
              throw new Error("No token to revoke.");
            case 1:
              url2 = GOOGLE_REVOKE_TOKEN_URL + this.accessToken;
              _context5.n = 2;
              return this.transporter.request({
                url: url2,
                retry: true
              });
            case 2:
              _assertClassBrand(_GoogleToken_brand, this, _configure).call(this, {
                email: this.iss,
                sub: this.sub,
                key: this.key,
                keyFile: this.keyFile,
                scope: this.scope,
                additionalClaims: this.additionalClaims
              });
            case 3:
              return _context5.a(2);
          }
        }, _callee5, this);
      }, "_callee5")));
      return _revokeTokenAsync2.apply(this, arguments);
    }
    __name(_revokeTokenAsync2, "_revokeTokenAsync2");
    function _configure() {
      var options2 = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {};
      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 (_typeof2(options2.scope) === "object") {
        this.scope = options2.scope.join(" ");
      } else {
        this.scope = options2.scope;
      }
      this.eagerRefreshThresholdMillis = options2.eagerRefreshThresholdMillis;
      if (options2.transporter) {
        this.transporter = options2.transporter;
      }
    }
    __name(_configure, "_configure");
    function _requestToken() {
      return _requestToken2.apply(this, arguments);
    }
    __name(_requestToken, "_requestToken");
    function _requestToken2() {
      _requestToken2 = _asyncToGenerator(/* @__PURE__ */ _regenerator().m(/* @__PURE__ */ __name(function _callee6() {
        var iat, additionalClaims, payload, signedJWT, r5, _response, _response2, body, desc2, _t2;
        return _regenerator().w(function(_context6) {
          while (1) switch (_context6.n) {
            case 0:
              iat = Math.floor((/* @__PURE__ */ new Date()).getTime() / 1e3);
              additionalClaims = this.additionalClaims || {};
              payload = Object.assign({
                iss: this.iss,
                scope: this.scope,
                aud: GOOGLE_TOKEN_URL,
                exp: iat + 3600,
                iat,
                sub: this.sub
              }, additionalClaims);
              signedJWT = jws.sign({
                header: {
                  alg: "RS256"
                },
                payload,
                secret: this.key
              });
              _context6.p = 1;
              _context6.n = 2;
              return this.transporter.request({
                method: "POST",
                url: GOOGLE_TOKEN_URL,
                data: new URLSearchParams({
                  grant_type: "urn:ietf:params:oauth:grant-type:jwt-bearer",
                  assertion: signedJWT
                }),
                responseType: "json",
                retryConfig: {
                  httpMethodsToRetry: ["POST"]
                }
              });
            case 2:
              r5 = _context6.v;
              this.rawToken = r5.data;
              this.expiresAt = r5.data.expires_in === null || r5.data.expires_in === void 0 ? void 0 : (iat + r5.data.expires_in) * 1e3;
              return _context6.a(2, this.rawToken);
            case 3:
              _context6.p = 3;
              _t2 = _context6.v;
              this.rawToken = void 0;
              this.tokenExpires = void 0;
              body = _t2.response && (_response = _t2.response) !== null && _response !== void 0 && _response.data ? (_response2 = _t2.response) === null || _response2 === void 0 ? void 0 : _response2.data : {};
              if (body.error) {
                desc2 = body.error_description ? ": ".concat(body.error_description) : "";
                _t2.message = "".concat(body.error).concat(desc2);
              }
              throw _t2;
            case 4:
              return _context6.a(2);
          }
        }, _callee6, this, [[1, 3]]);
      }, "_callee6")));
      return _requestToken2.apply(this, arguments);
    }
    __name(_requestToken2, "_requestToken2");
  }
});

// packages/core/node_modules/google-auth-library/build/src/auth/jwtaccess.js
var require_jwtaccess = __commonJS({
  "packages/core/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_util10();
    var DEFAULT_HEADER = {
      alg: "RS256",
      typ: "JWT"
    };
    var JWTAccess = class _JWTAccess {
      static {
        __name(this, "JWTAccess");
      }
      email;
      key;
      keyId;
      projectId;
      eagerRefreshThresholdMillis;
      cache = new util_1.LRUCache({
        capacity: 500,
        maxAge: 60 * 60 * 1e3
      });
      /**
       * 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(email2, key, keyId, eagerRefreshThresholdMillis) {
        this.email = email2;
        this.key = key;
        this.keyId = keyId;
        this.eagerRefreshThresholdMillis = 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 new Headers(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 = new 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((resolve30, reject) => {
          if (!inputStream) {
            reject(new Error("Must pass in a stream containing the service account auth settings."));
          }
          let s5 = "";
          inputStream.setEncoding("utf8").on("data", (chunk) => s5 += chunk).on("error", reject).on("end", () => {
            try {
              const data = JSON.parse(s5);
              this.fromJSON(data);
              resolve30();
            } catch (err) {
              reject(err);
            }
          });
        });
      }
    };
    exports2.JWTAccess = JWTAccess;
  }
});

// packages/core/node_modules/google-auth-library/build/src/auth/jwtclient.js
var require_jwtclient = __commonJS({
  "packages/core/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");
      }
      email;
      keyFile;
      key;
      keyId;
      defaultScopes;
      scopes;
      scope;
      subject;
      gtoken;
      additionalClaims;
      useJWTAccessWithScope;
      defaultServicePath;
      access;
      /**
       * JWT service account credentials.
       *
       * Retrieve access token using gtoken.
       *
       * @param options the
       */
      constructor(options2 = {}) {
        super(options2);
        this.email = options2.email;
        this.keyFile = options2.keyFile;
        this.key = options2.key;
        this.keyId = options2.keyId;
        this.scopes = options2.scopes;
        this.subject = options2.subject;
        this.additionalClaims = options2.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(new Headers({
                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 ?? 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: new 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((r5) => callback(null, r5), 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() {
        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((resolve30, reject) => {
          if (!inputStream) {
            throw new Error("Must pass in a stream containing the service account auth settings.");
          }
          let s5 = "";
          inputStream.setEncoding("utf8").on("error", reject).on("data", (chunk) => s5 += chunk).on("end", () => {
            try {
              const data = JSON.parse(s5);
              this.fromJSON(data);
              resolve30();
            } catch (e4) {
              reject(e4);
            }
          });
        });
      }
      /**
       * 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;
  }
});

// packages/core/node_modules/google-auth-library/build/src/auth/refreshclient.js
var require_refreshclient = __commonJS({
  "packages/core/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 authclient_1 = require_authclient();
    exports2.USER_REFRESH_ACCOUNT_TYPE = "authorized_user";
    var UserRefreshClient = class _UserRefreshClient extends oauth2client_1.OAuth2Client {
      static {
        __name(this, "UserRefreshClient");
      }
      // TODO: refactor tests to make this private
      // In a future gts release, the _propertyName rule will be lifted.
      // This is also a hard one because `this.refreshToken` is a function.
      _refreshToken;
      /**
       * The User Refresh Token client.
       *
       * @param optionsOrClientId The User Refresh Token client options. Passing an `clientId` directly is **@DEPRECATED**.
       * @param clientSecret **@DEPRECATED**. Provide a {@link UserRefreshClientOptions `UserRefreshClientOptions`} object in the first parameter instead.
       * @param refreshToken **@DEPRECATED**. Provide a {@link UserRefreshClientOptions `UserRefreshClientOptions`} object in the first parameter instead.
       * @param eagerRefreshThresholdMillis **@DEPRECATED**. Provide a {@link UserRefreshClientOptions `UserRefreshClientOptions`} object in the first parameter instead.
       * @param forceRefreshOnFailure **@DEPRECATED**. Provide a {@link UserRefreshClientOptions `UserRefreshClientOptions`} object in the first parameter instead.
       */
      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() {
        return super.refreshTokenNoCache(this._refreshToken);
      }
      async fetchIdToken(targetAudience) {
        const opts = {
          ..._UserRefreshClient.RETRY_CONFIG,
          url: this.endpoints.oauth2TokenUrl,
          method: "POST",
          data: new URLSearchParams({
            client_id: this._clientId,
            client_secret: this._clientSecret,
            grant_type: "refresh_token",
            refresh_token: this._refreshToken,
            target_audience: targetAudience
          })
        };
        authclient_1.AuthClient.setMethodName(opts, "fetchIdToken");
        const res = await this.transporter.request(opts);
        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((resolve30, reject) => {
          if (!inputStream) {
            return reject(new Error("Must pass in a stream containing the user refresh token."));
          }
          let s5 = "";
          inputStream.setEncoding("utf8").on("error", reject).on("data", (chunk) => s5 += chunk).on("end", () => {
            try {
              const data = JSON.parse(s5);
              this.fromJSON(data);
              return resolve30();
            } 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;
  }
});

// packages/core/node_modules/google-auth-library/build/src/auth/impersonated.js
var require_impersonated = __commonJS({
  "packages/core/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_util10();
    exports2.IMPERSONATED_ACCOUNT_TYPE = "impersonated_service_account";
    var Impersonated = class _Impersonated extends oauth2client_1.OAuth2Client {
      static {
        __name(this, "Impersonated");
      }
      sourceClient;
      targetPrincipal;
      targetScopes;
      delegates;
      lifetime;
      endpoint;
      /**
       * 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.
       *
       * **IMPORTANT**: This method does not validate the credential configuration.
       * A security risk occurs when a credential configuration configured with
       * malicious URLs is used. When the credential configuration is accepted from
       * an untrusted source, you should validate it before using it with this
       * method. For more details, see
       * https://cloud.google.com/docs/authentication/external/externally-sourced-credentials.
       *
       * @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 = {}) {
        super(options2);
        this.credentials = {
          expiry_date: 1,
          refresh_token: "impersonated-placeholder"
        };
        this.sourceClient = options2.sourceClient ?? new oauth2client_1.OAuth2Client();
        this.targetPrincipal = options2.targetPrincipal ?? "";
        this.delegates = options2.delegates ?? [];
        this.targetScopes = options2.targetScopes ?? [];
        this.lifetime = options2.lifetime ?? 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 = options2.endpoint ?? `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 u2 = `${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: u2,
          data: body,
          method: "POST"
        });
        return res.data;
      }
      /** The service account email to be impersonated. */
      getTargetPrincipal() {
        return this.targetPrincipal;
      }
      /**
       * Refreshes the access token.
       */
      async refreshToken() {
        try {
          await this.sourceClient.getAccessToken();
          const name3 = "projects/-/serviceAccounts/" + this.targetPrincipal;
          const u2 = `${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: u2,
            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 (error2) {
          if (!(error2 instanceof Error))
            throw error2;
          let status = 0;
          let message = "";
          if (error2 instanceof gaxios_1.GaxiosError) {
            status = error2?.response?.data?.error?.status;
            message = error2?.response?.data?.error?.message;
          }
          if (status && message) {
            error2.message = `${status}: unable to impersonate: ${message}`;
            throw error2;
          } else {
            error2.message = `unable to impersonate: ${error2}`;
            throw error2;
          }
        }
      }
      /**
       * 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) {
        await this.sourceClient.getAccessToken();
        const name3 = `projects/-/serviceAccounts/${this.targetPrincipal}`;
        const u2 = `${this.endpoint}/v1/${name3}:generateIdToken`;
        const body = {
          delegates: this.delegates,
          audience: targetAudience,
          includeEmail: options2?.includeEmail ?? true,
          useEmailAzp: options2?.includeEmail ?? true
        };
        const res = await this.sourceClient.request({
          ..._Impersonated.RETRY_CONFIG,
          url: u2,
          data: body,
          method: "POST"
        });
        return res.data.token;
      }
    };
    exports2.Impersonated = Impersonated;
  }
});

// packages/core/node_modules/google-auth-library/build/src/auth/oauth2common.js
var require_oauth2common = __commonJS({
  "packages/core/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 gaxios_1 = require_src2();
    var crypto_1 = require_crypto3();
    var METHODS_SUPPORTING_REQUEST_BODY = ["PUT", "POST", "PATCH"];
    var OAuthClientAuthHandler = class {
      static {
        __name(this, "OAuthClientAuthHandler");
      }
      #crypto = (0, crypto_1.createCrypto)();
      #clientAuthentication;
      transporter;
      /**
       * Instantiates an OAuth client authentication handler.
       * @param options The OAuth Client Auth Handler instance options. Passing an `ClientAuthentication` directly is **@DEPRECATED**.
       */
      constructor(options2) {
        if (options2 && "clientId" in options2) {
          this.#clientAuthentication = options2;
          this.transporter = new gaxios_1.Gaxios();
        } else {
          this.#clientAuthentication = options2?.clientAuthentication;
          this.transporter = options2?.transporter || new gaxios_1.Gaxios();
        }
      }
      /**
       * 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) {
        opts.headers = gaxios_1.Gaxios.mergeHeaders(opts.headers);
        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) {
        if (bearerToken) {
          opts.headers = gaxios_1.Gaxios.mergeHeaders(opts.headers, {
            authorization: `Bearer ${bearerToken}`
          });
        } else if (this.#clientAuthentication?.confidentialClientType === "basic") {
          opts.headers = gaxios_1.Gaxios.mergeHeaders(opts.headers);
          const clientId = this.#clientAuthentication.clientId;
          const clientSecret = this.#clientAuthentication.clientSecret || "";
          const base64EncodedCreds = this.#crypto.encodeBase64StringUtf8(`${clientId}:${clientSecret}`);
          gaxios_1.Gaxios.mergeHeaders(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) {
        if (this.#clientAuthentication?.confidentialClientType === "request-body") {
          const method = (opts.method || "GET").toUpperCase();
          if (!METHODS_SUPPORTING_REQUEST_BODY.includes(method)) {
            throw new Error(`${method} HTTP method does not support ${this.#clientAuthentication.confidentialClientType} client authentication`);
          }
          const headers = new Headers(opts.headers);
          const contentType = headers.get("content-type");
          if (contentType?.startsWith("application/x-www-form-urlencoded") || opts.data instanceof URLSearchParams) {
            const data = new URLSearchParams(opts.data ?? "");
            data.append("client_id", this.#clientAuthentication.clientId);
            data.append("client_secret", this.#clientAuthentication.clientSecret || "");
            opts.data = data;
          } else if (contentType?.startsWith("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`);
          }
        }
      }
      /**
       * 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, {
              value: err[key],
              writable: false,
              enumerable: true
            });
          }
        });
      }
      return newError;
    }
    __name(getErrorFromOAuthErrorResponse, "getErrorFromOAuthErrorResponse");
  }
});

// packages/core/node_modules/google-auth-library/build/src/auth/stscredentials.js
var require_stscredentials = __commonJS({
  "packages/core/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 authclient_1 = require_authclient();
    var oauth2common_1 = require_oauth2common();
    var util_1 = require_util10();
    var StsCredentials = class _StsCredentials extends oauth2common_1.OAuthClientAuthHandler {
      static {
        __name(this, "StsCredentials");
      }
      #tokenExchangeEndpoint;
      /**
       * Initializes an STS credentials instance.
       *
       * @param options The STS credentials instance options. Passing an `tokenExchangeEndpoint` directly is **@DEPRECATED**.
       * @param clientAuthentication **@DEPRECATED**. Provide a {@link StsCredentialsConstructionOptions `StsCredentialsConstructionOptions`} object in the first parameter instead.
       */
      constructor(options2 = {
        tokenExchangeEndpoint: ""
      }, clientAuthentication) {
        if (typeof options2 !== "object" || options2 instanceof URL) {
          options2 = {
            tokenExchangeEndpoint: options2,
            clientAuthentication
          };
        }
        super(options2);
        this.#tokenExchangeEndpoint = options2.tokenExchangeEndpoint;
      }
      /**
       * 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, headers, options2) {
        const values = {
          grant_type: stsCredentialsOptions.grantType,
          resource: stsCredentialsOptions.resource,
          audience: stsCredentialsOptions.audience,
          scope: stsCredentialsOptions.scope?.join(" "),
          requested_token_type: stsCredentialsOptions.requestedTokenType,
          subject_token: stsCredentialsOptions.subjectToken,
          subject_token_type: stsCredentialsOptions.subjectTokenType,
          actor_token: stsCredentialsOptions.actingParty?.actorToken,
          actor_token_type: stsCredentialsOptions.actingParty?.actorTokenType,
          // Non-standard GCP-specific options.
          options: options2 && JSON.stringify(options2)
        };
        const opts = {
          ..._StsCredentials.RETRY_CONFIG,
          url: this.#tokenExchangeEndpoint.toString(),
          method: "POST",
          headers,
          data: new URLSearchParams((0, util_1.removeUndefinedValuesInObject)(values))
        };
        authclient_1.AuthClient.setMethodName(opts, "exchangeToken");
        this.applyClientAuthenticationOptions(opts);
        try {
          const response = await this.transporter.request(opts);
          const stsSuccessfulResponse = response.data;
          stsSuccessfulResponse.res = response;
          return stsSuccessfulResponse;
        } catch (error2) {
          if (error2 instanceof gaxios_1.GaxiosError && error2.response) {
            throw (0, oauth2common_1.getErrorFromOAuthErrorResponse)(
              error2.response.data,
              // Preserve other fields from the original error.
              error2
            );
          }
          throw error2;
        }
      }
    };
    exports2.StsCredentials = StsCredentials;
  }
});

// packages/core/node_modules/google-auth-library/build/src/auth/baseexternalclient.js
var require_baseexternalclient = __commonJS({
  "packages/core/node_modules/google-auth-library/build/src/auth/baseexternalclient.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.BaseExternalAccountClient = exports2.CLOUD_RESOURCE_MANAGER = exports2.EXTERNAL_ACCOUNT_TYPE = exports2.EXPIRATION_TIME_OFFSET = void 0;
    var gaxios_1 = require_src2();
    var stream2 = __require("stream");
    var authclient_1 = require_authclient();
    var sts = require_stscredentials();
    var util_1 = require_util10();
    var shared_cjs_1 = require_shared2();
    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 BaseExternalAccountClient = class _BaseExternalAccountClient extends authclient_1.AuthClient {
      static {
        __name(this, "BaseExternalAccountClient");
      }
      /**
       * OAuth scopes for the GCP access token to use. When not provided,
       * the default https://www.googleapis.com/auth/cloud-platform is
       * used.
       */
      scopes;
      projectNumber;
      audience;
      subjectTokenType;
      stsCredential;
      clientAuth;
      credentialSourceType;
      cachedAccessToken;
      serviceAccountImpersonationUrl;
      serviceAccountImpersonationLifetime;
      workforcePoolUserProject;
      configLifetimeRequested;
      tokenUrl;
      /**
       * @example
       * ```ts
       * new URL('https://cloudresourcemanager.googleapis.com/v1/projects/');
       * ```
       */
      cloudResourceManagerURL;
      supplierContext;
      /**
       * A pending access token request. Used for concurrent calls.
       */
      #pendingAccessToken = null;
      /**
       * 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.
       */
      constructor(options2) {
        super(options2);
        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");
        this.tokenUrl = opts.get("token_url") ?? 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({
          tokenExchangeEndpoint: this.tokenUrl,
          clientAuthentication: 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() {
        if (this.serviceAccountImpersonationUrl) {
          if (this.serviceAccountImpersonationUrl.length > 256) {
            throw new RangeError(`URL is too long: ${this.serviceAccountImpersonationUrl}`);
          }
          const re3 = /serviceAccounts\/(?<email>[^:]+):generateAccessToken$/;
          const result = re3.exec(this.serviceAccountImpersonationUrl);
          return result?.groups?.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 = new Headers({
          authorization: `Bearer ${accessTokenResponse.token}`
        });
        return this.addSharedMetadataHeaders(headers);
      }
      request(opts, callback) {
        if (callback) {
          this.requestAsync(opts).then((r5) => callback(null, r5), (e4) => {
            return callback(e4, e4.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 opts = {
            ..._BaseExternalAccountClient.RETRY_CONFIG,
            headers,
            url: `${this.cloudResourceManagerURL.toString()}${projectNumber}`
          };
          authclient_1.AuthClient.setMethodName(opts, "getProjectId");
          const response = await this.transporter.request(opts);
          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 = gaxios_1.Gaxios.mergeHeaders(opts.headers);
          this.addUserProjectAndAuthHeaders(opts.headers, requestHeaders);
          response = await this.transporter.request(opts);
        } catch (e4) {
          const res = e4.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 e4;
        }
        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() {
        this.#pendingAccessToken = this.#pendingAccessToken || this.#internalRefreshAccessTokenAsync();
        try {
          return await this.#pendingAccessToken;
        } finally {
          this.#pendingAccessToken = null;
        }
      }
      async #internalRefreshAccessTokenAsync() {
        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 = new Headers({
          "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;
      }
      /**
       * 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"
          }
        };
        authclient_1.AuthClient.setMethodName(opts, "getImpersonatedAccessToken");
        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/${shared_cjs_1.pkg.version} google-byoid-sdk source/${credentialSourceType} sa-impersonation/${saImpersonation} config-lifetime/${this.configLifetimeRequested}`;
      }
      getTokenUrl() {
        return this.tokenUrl;
      }
    };
    exports2.BaseExternalAccountClient = BaseExternalAccountClient;
  }
});

// packages/core/node_modules/google-auth-library/build/src/auth/filesubjecttokensupplier.js
var require_filesubjecttokensupplier = __commonJS({
  "packages/core/node_modules/google-auth-library/build/src/auth/filesubjecttokensupplier.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.FileSubjectTokenSupplier = void 0;
    var util_1 = __require("util");
    var fs113 = __require("fs");
    var readFile13 = (0, util_1.promisify)(fs113.readFile ?? (() => {
    }));
    var realpath3 = (0, util_1.promisify)(fs113.realpath ?? (() => {
    }));
    var lstat6 = (0, util_1.promisify)(fs113.lstat ?? (() => {
    }));
    var FileSubjectTokenSupplier = class {
      static {
        __name(this, "FileSubjectTokenSupplier");
      }
      filePath;
      formatType;
      subjectTokenFieldName;
      /**
       * 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() {
        let parsedFilePath = this.filePath;
        try {
          parsedFilePath = await realpath3(parsedFilePath);
          if (!(await lstat6(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 readFile13(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;
  }
});

// packages/core/node_modules/google-auth-library/build/src/auth/urlsubjecttokensupplier.js
var require_urlsubjecttokensupplier = __commonJS({
  "packages/core/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 authclient_1 = require_authclient();
    var UrlSubjectTokenSupplier = class {
      static {
        __name(this, "UrlSubjectTokenSupplier");
      }
      url;
      headers;
      formatType;
      subjectTokenFieldName;
      additionalGaxiosOptions;
      /**
       * 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
        };
        authclient_1.AuthClient.setMethodName(opts, "getSubjectToken");
        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;
  }
});

// packages/core/node_modules/google-auth-library/build/src/auth/certificatesubjecttokensupplier.js
var require_certificatesubjecttokensupplier = __commonJS({
  "packages/core/node_modules/google-auth-library/build/src/auth/certificatesubjecttokensupplier.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.CertificateSubjectTokenSupplier = exports2.InvalidConfigurationError = exports2.CertificateSourceUnavailableError = exports2.CERTIFICATE_CONFIGURATION_ENV_VARIABLE = void 0;
    var util_1 = require_util10();
    var fs113 = __require("fs");
    var crypto_1 = __require("crypto");
    var https7 = __require("https");
    exports2.CERTIFICATE_CONFIGURATION_ENV_VARIABLE = "GOOGLE_API_CERTIFICATE_CONFIG";
    var CertificateSourceUnavailableError = class extends Error {
      static {
        __name(this, "CertificateSourceUnavailableError");
      }
      constructor(message) {
        super(message);
        this.name = "CertificateSourceUnavailableError";
      }
    };
    exports2.CertificateSourceUnavailableError = CertificateSourceUnavailableError;
    var InvalidConfigurationError = class extends Error {
      static {
        __name(this, "InvalidConfigurationError");
      }
      constructor(message) {
        super(message);
        this.name = "InvalidConfigurationError";
      }
    };
    exports2.InvalidConfigurationError = InvalidConfigurationError;
    var CertificateSubjectTokenSupplier = class {
      static {
        __name(this, "CertificateSubjectTokenSupplier");
      }
      certificateConfigPath;
      trustChainPath;
      cert;
      key;
      /**
       * Initializes a new instance of the CertificateSubjectTokenSupplier.
       * @param opts The configuration options for the supplier.
       */
      constructor(opts) {
        if (!opts.useDefaultCertificateConfig && !opts.certificateConfigLocation) {
          throw new InvalidConfigurationError("Either `useDefaultCertificateConfig` must be true or a `certificateConfigLocation` must be provided.");
        }
        if (opts.useDefaultCertificateConfig && opts.certificateConfigLocation) {
          throw new InvalidConfigurationError("Both `useDefaultCertificateConfig` and `certificateConfigLocation` cannot be provided.");
        }
        this.trustChainPath = opts.trustChainPath;
        this.certificateConfigPath = opts.certificateConfigLocation ?? "";
      }
      /**
       * Creates an HTTPS agent configured with the client certificate and private key for mTLS.
       * @returns An mTLS-configured https.Agent.
       */
      async createMtlsHttpsAgent() {
        if (!this.key || !this.cert) {
          throw new InvalidConfigurationError("Cannot create mTLS Agent with missing certificate or key");
        }
        return new https7.Agent({ key: this.key, cert: this.cert });
      }
      /**
       * Constructs the subject token, which is the base64-encoded certificate chain.
       * @returns A promise that resolves with the subject token.
       */
      async getSubjectToken() {
        this.certificateConfigPath = await this.#resolveCertificateConfigFilePath();
        const { certPath, keyPath } = await this.#getCertAndKeyPaths();
        ({ cert: this.cert, key: this.key } = await this.#getKeyAndCert(certPath, keyPath));
        return await this.#processChainFromPaths(this.cert);
      }
      /**
       * Resolves the absolute path to the certificate configuration file
       * by checking the "certificate_config_location" provided in the ADC file,
       * or the "GOOGLE_API_CERTIFICATE_CONFIG" environment variable
       * or in the default gcloud path.
       * @param overridePath An optional path to check first.
       * @returns The resolved file path.
       */
      async #resolveCertificateConfigFilePath() {
        const overridePath = this.certificateConfigPath;
        if (overridePath) {
          if (await (0, util_1.isValidFile)(overridePath)) {
            return overridePath;
          }
          throw new CertificateSourceUnavailableError(`Provided certificate config path is invalid: ${overridePath}`);
        }
        const envPath = process.env[exports2.CERTIFICATE_CONFIGURATION_ENV_VARIABLE];
        if (envPath) {
          if (await (0, util_1.isValidFile)(envPath)) {
            return envPath;
          }
          throw new CertificateSourceUnavailableError(`Path from environment variable "${exports2.CERTIFICATE_CONFIGURATION_ENV_VARIABLE}" is invalid: ${envPath}`);
        }
        const wellKnownPath = (0, util_1.getWellKnownCertificateConfigFileLocation)();
        if (await (0, util_1.isValidFile)(wellKnownPath)) {
          return wellKnownPath;
        }
        throw new CertificateSourceUnavailableError(`Could not find certificate configuration file. Searched override path, the "${exports2.CERTIFICATE_CONFIGURATION_ENV_VARIABLE}" env var, and the gcloud path (${wellKnownPath}).`);
      }
      /**
       * Reads and parses the certificate config JSON file to extract the certificate and key paths.
       * @returns An object containing the certificate and key paths.
       */
      async #getCertAndKeyPaths() {
        const configPath = this.certificateConfigPath;
        let fileContents;
        try {
          fileContents = await fs113.promises.readFile(configPath, "utf8");
        } catch (err) {
          throw new CertificateSourceUnavailableError(`Failed to read certificate config file at: ${configPath}`);
        }
        try {
          const config2 = JSON.parse(fileContents);
          const certPath = config2?.cert_configs?.workload?.cert_path;
          const keyPath = config2?.cert_configs?.workload?.key_path;
          if (!certPath || !keyPath) {
            throw new InvalidConfigurationError(`Certificate config file (${configPath}) is missing required "cert_path" or "key_path" in the workload config.`);
          }
          return { certPath, keyPath };
        } catch (e4) {
          if (e4 instanceof InvalidConfigurationError)
            throw e4;
          throw new InvalidConfigurationError(`Failed to parse certificate config from ${configPath}: ${e4.message}`);
        }
      }
      /**
       * Reads and parses the cert and key files get their content and check valid format.
       * @returns An object containing the cert content and key content in buffer format.
       */
      async #getKeyAndCert(certPath, keyPath) {
        let cert, key;
        try {
          cert = await fs113.promises.readFile(certPath);
          new crypto_1.X509Certificate(cert);
        } catch (err) {
          const message = err instanceof Error ? err.message : String(err);
          throw new CertificateSourceUnavailableError(`Failed to read certificate file at ${certPath}: ${message}`);
        }
        try {
          key = await fs113.promises.readFile(keyPath);
          (0, crypto_1.createPrivateKey)(key);
        } catch (err) {
          const message = err instanceof Error ? err.message : String(err);
          throw new CertificateSourceUnavailableError(`Failed to read private key file at ${keyPath}: ${message}`);
        }
        return { cert, key };
      }
      /**
       * Reads the leaf certificate and trust chain, combines them,
       * and returns a JSON array of base64-encoded certificates.
       * @returns A stringified JSON array of the certificate chain.
       */
      async #processChainFromPaths(leafCertBuffer) {
        const leafCert = new crypto_1.X509Certificate(leafCertBuffer);
        if (!this.trustChainPath) {
          return JSON.stringify([leafCert.raw.toString("base64")]);
        }
        try {
          const chainPems = await fs113.promises.readFile(this.trustChainPath, "utf8");
          const pemBlocks = chainPems.match(/-----BEGIN CERTIFICATE-----[^-]+-----END CERTIFICATE-----/g) ?? [];
          const chainCerts = pemBlocks.map((pem, index) => {
            try {
              return new crypto_1.X509Certificate(pem);
            } catch (err) {
              const message = err instanceof Error ? err.message : String(err);
              throw new InvalidConfigurationError(`Failed to parse certificate at index ${index} in trust chain file ${this.trustChainPath}: ${message}`);
            }
          });
          const leafIndex = chainCerts.findIndex((chainCert) => leafCert.raw.equals(chainCert.raw));
          let finalChain;
          if (leafIndex === -1) {
            finalChain = [leafCert, ...chainCerts];
          } else if (leafIndex === 0) {
            finalChain = chainCerts;
          } else {
            throw new InvalidConfigurationError(`Leaf certificate exists in the trust chain but is not the first entry (found at index ${leafIndex}).`);
          }
          return JSON.stringify(finalChain.map((cert) => cert.raw.toString("base64")));
        } catch (err) {
          if (err instanceof InvalidConfigurationError)
            throw err;
          const message = err instanceof Error ? err.message : String(err);
          throw new CertificateSourceUnavailableError(`Failed to process certificate chain from ${this.trustChainPath}: ${message}`);
        }
      }
    };
    exports2.CertificateSubjectTokenSupplier = CertificateSubjectTokenSupplier;
  }
});

// packages/core/node_modules/google-auth-library/build/src/auth/identitypoolclient.js
var require_identitypoolclient = __commonJS({
  "packages/core/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_util10();
    var filesubjecttokensupplier_1 = require_filesubjecttokensupplier();
    var urlsubjecttokensupplier_1 = require_urlsubjecttokensupplier();
    var certificatesubjecttokensupplier_1 = require_certificatesubjecttokensupplier();
    var stscredentials_1 = require_stscredentials();
    var gaxios_1 = require_src2();
    var IdentityPoolClient = class _IdentityPoolClient extends baseexternalclient_1.BaseExternalAccountClient {
      static {
        __name(this, "IdentityPoolClient");
      }
      subjectTokenSupplier;
      /**
       * 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.
       */
      constructor(options2) {
        super(options2);
        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 certificate = credentialSourceOpts.get("certificate");
          const headers = credentialSourceOpts.get("headers");
          if (file && url2 || url2 && certificate || file && certificate) {
            throw new Error('No valid Identity Pool "credential_source" provided, must be either file, url, or certificate.');
          } else if (file) {
            this.credentialSourceType = "file";
            this.subjectTokenSupplier = new filesubjecttokensupplier_1.FileSubjectTokenSupplier({
              filePath: file,
              formatType,
              subjectTokenFieldName: formatSubjectTokenFieldName
            });
          } else if (url2) {
            this.credentialSourceType = "url";
            this.subjectTokenSupplier = new urlsubjecttokensupplier_1.UrlSubjectTokenSupplier({
              url: url2,
              formatType,
              subjectTokenFieldName: formatSubjectTokenFieldName,
              headers,
              additionalGaxiosOptions: _IdentityPoolClient.RETRY_CONFIG
            });
          } else if (certificate) {
            this.credentialSourceType = "certificate";
            const certificateSubjecttokensupplier = new certificatesubjecttokensupplier_1.CertificateSubjectTokenSupplier({
              useDefaultCertificateConfig: certificate.use_default_certificate_config,
              certificateConfigLocation: certificate.certificate_config_location,
              trustChainPath: certificate.trust_chain_path
            });
            this.subjectTokenSupplier = certificateSubjecttokensupplier;
          } else {
            throw new Error('No valid Identity Pool "credential_source" provided, must be either file, url, or certificate.');
          }
        }
      }
      /**
       * 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() {
        const subjectToken = await this.subjectTokenSupplier.getSubjectToken(this.supplierContext);
        if (this.subjectTokenSupplier instanceof certificatesubjecttokensupplier_1.CertificateSubjectTokenSupplier) {
          const mtlsAgent = await this.subjectTokenSupplier.createMtlsHttpsAgent();
          this.stsCredential = new stscredentials_1.StsCredentials({
            tokenExchangeEndpoint: this.getTokenUrl(),
            clientAuthentication: this.clientAuth,
            transporter: new gaxios_1.Gaxios({ agent: mtlsAgent })
          });
          this.transporter = new gaxios_1.Gaxios({
            ...this.transporter.defaults || {},
            agent: mtlsAgent
          });
        }
        return subjectToken;
      }
    };
    exports2.IdentityPoolClient = IdentityPoolClient;
  }
});

// packages/core/node_modules/google-auth-library/build/src/auth/awsrequestsigner.js
var require_awsrequestsigner = __commonJS({
  "packages/core/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 gaxios_1 = require_src2();
    var crypto_1 = require_crypto3();
    var AWS_ALGORITHM = "AWS4-HMAC-SHA256";
    var AWS_REQUEST_TYPE = "aws4_request";
    var AwsRequestSigner = class {
      static {
        __name(this, "AwsRequestSigner");
      }
      getCredentials;
      region;
      crypto;
      /**
       * 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 RangeError('"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);
        if (typeof requestPayload !== "string" && requestPayload !== void 0) {
          throw new TypeError(`'requestPayload' is expected to be a string if provided. Got: ${requestPayload}`);
        }
        const headerMap = await generateAuthenticationHeaderMap({
          crypto: this.crypto,
          host: uri.host,
          canonicalUri: uri.pathname,
          canonicalQuerystring: uri.search.slice(1),
          method,
          region: this.region,
          securityCredentials: awsSecurityCredentials,
          requestPayload,
          additionalAmzHeaders
        });
        const headers = gaxios_1.Gaxios.mergeHeaders(
          // Add x-amz-date if available.
          headerMap.amzDate ? { "x-amz-date": headerMap.amzDate } : {},
          {
            authorization: headerMap.authorizationHeader,
            host: uri.host
          },
          additionalAmzHeaders || {}
        );
        if (awsSecurityCredentials.token) {
          gaxios_1.Gaxios.mergeHeaders(headers, {
            "x-amz-security-token": awsSecurityCredentials.token
          });
        }
        const awsSignedReq = {
          url: url2,
          method,
          headers
        };
        if (requestPayload !== void 0) {
          awsSignedReq.body = requestPayload;
        }
        return awsSignedReq;
      }
    };
    exports2.AwsRequestSigner = AwsRequestSigner;
    async function sign(crypto14, key, msg) {
      return await crypto14.signWithHmacSha256(key, msg);
    }
    __name(sign, "sign");
    async function getSigningKey(crypto14, key, dateStamp, region, serviceName) {
      const kDate = await sign(crypto14, `AWS4${key}`, dateStamp);
      const kRegion = await sign(crypto14, kDate, region);
      const kService = await sign(crypto14, kRegion, serviceName);
      const kSigning = await sign(crypto14, kService, "aws4_request");
      return kSigning;
    }
    __name(getSigningKey, "getSigningKey");
    async function generateAuthenticationHeaderMap(options2) {
      const additionalAmzHeaders = gaxios_1.Gaxios.mergeHeaders(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.*/, "");
      if (options2.securityCredentials.token) {
        additionalAmzHeaders.set("x-amz-security-token", options2.securityCredentials.token);
      }
      const amzHeaders = gaxios_1.Gaxios.mergeHeaders(
        {
          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
        additionalAmzHeaders.has("date") ? {} : { "x-amz-date": amzDate },
        additionalAmzHeaders
      );
      let canonicalHeaders = "";
      const signedHeadersList = [
        ...amzHeaders.keys()
      ].sort();
      signedHeadersList.forEach((key) => {
        canonicalHeaders += `${key}:${amzHeaders.get(key)}
`;
      });
      const signedHeaders = signedHeadersList.join(";");
      const payloadHash = await options2.crypto.sha256DigestHex(requestPayload);
      const canonicalRequest = `${options2.method.toUpperCase()}
${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: additionalAmzHeaders.has("date") ? void 0 : amzDate,
        authorizationHeader,
        canonicalQuerystring: options2.canonicalQuerystring
      };
    }
    __name(generateAuthenticationHeaderMap, "generateAuthenticationHeaderMap");
  }
});

// packages/core/node_modules/google-auth-library/build/src/auth/defaultawssecuritycredentialssupplier.js
var require_defaultawssecuritycredentialssupplier = __commonJS({
  "packages/core/node_modules/google-auth-library/build/src/auth/defaultawssecuritycredentialssupplier.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.DefaultAwsSecurityCredentialsSupplier = void 0;
    var authclient_1 = require_authclient();
    var DefaultAwsSecurityCredentialsSupplier = class {
      static {
        __name(this, "DefaultAwsSecurityCredentialsSupplier");
      }
      regionUrl;
      securityCredentialsUrl;
      imdsV2SessionTokenUrl;
      additionalGaxiosOptions;
      /**
       * 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) {
        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 (this.#regionFromEnv) {
          return this.#regionFromEnv;
        }
        const metadataHeaders = new Headers();
        if (!this.#regionFromEnv && this.imdsV2SessionTokenUrl) {
          metadataHeaders.set("x-aws-ec2-metadata-token", await this.#getImdsV2SessionToken(context2.transporter));
        }
        if (!this.regionUrl) {
          throw new RangeError('Unable to determine AWS region due to missing "options.credential_source.region_url"');
        }
        const opts = {
          ...this.additionalGaxiosOptions,
          url: this.regionUrl,
          method: "GET",
          headers: metadataHeaders
        };
        authclient_1.AuthClient.setMethodName(opts, "getAwsRegion");
        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 (this.#securityCredentialsFromEnv) {
          return this.#securityCredentialsFromEnv;
        }
        const metadataHeaders = new Headers();
        if (this.imdsV2SessionTokenUrl) {
          metadataHeaders.set("x-aws-ec2-metadata-token", await this.#getImdsV2SessionToken(context2.transporter));
        }
        const roleName = await this.#getAwsRoleName(metadataHeaders, context2.transporter);
        const awsCreds = await this.#retrieveAwsSecurityCredentials(roleName, metadataHeaders, context2.transporter);
        return {
          accessKeyId: awsCreds.AccessKeyId,
          secretAccessKey: awsCreds.SecretAccessKey,
          token: awsCreds.Token
        };
      }
      /**
       * @param transporter The transporter to use for requests.
       * @return A promise that resolves with the IMDSv2 Session Token.
       */
      async #getImdsV2SessionToken(transporter) {
        const opts = {
          ...this.additionalGaxiosOptions,
          url: this.imdsV2SessionTokenUrl,
          method: "PUT",
          headers: { "x-aws-ec2-metadata-token-ttl-seconds": "300" }
        };
        authclient_1.AuthClient.setMethodName(opts, "#getImdsV2SessionToken");
        const response = await transporter.request(opts);
        return response.data;
      }
      /**
       * @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.
       */
      async #getAwsRoleName(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",
          headers
        };
        authclient_1.AuthClient.setMethodName(opts, "#getAwsRoleName");
        const response = await transporter.request(opts);
        return response.data;
      }
      /**
       * 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.
       */
      async #retrieveAwsSecurityCredentials(roleName, headers, transporter) {
        const opts = {
          ...this.additionalGaxiosOptions,
          url: `${this.securityCredentialsUrl}/${roleName}`,
          headers
        };
        authclient_1.AuthClient.setMethodName(opts, "#retrieveAwsSecurityCredentials");
        const response = await transporter.request(opts);
        return response.data;
      }
      get #regionFromEnv() {
        return process.env["AWS_REGION"] || process.env["AWS_DEFAULT_REGION"] || null;
      }
      get #securityCredentialsFromEnv() {
        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;
      }
    };
    exports2.DefaultAwsSecurityCredentialsSupplier = DefaultAwsSecurityCredentialsSupplier;
  }
});

// packages/core/node_modules/google-auth-library/build/src/auth/awsclient.js
var require_awsclient = __commonJS({
  "packages/core/node_modules/google-auth-library/build/src/auth/awsclient.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    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_util10();
    var gaxios_1 = require_src2();
    var AwsClient = class _AwsClient extends baseexternalclient_1.BaseExternalAccountClient {
      static {
        __name(this, "AwsClient");
      }
      environmentId;
      awsSecurityCredentialsSupplier;
      regionalCredVerificationUrl;
      awsRequestSigner;
      region;
      static #DEFAULT_AWS_REGIONAL_CREDENTIAL_VERIFICATION_URL = "https://sts.{region}.amazonaws.com?Action=GetCallerIdentity&Version=2011-06-15";
      /**
       * @deprecated AWS client no validates the EC2 metadata address.
       **/
      static AWS_EC2_METADATA_IPV4_ADDRESS = "169.254.169.254";
      /**
       * @deprecated AWS client no validates the EC2 metadata address.
       **/
      static AWS_EC2_METADATA_IPV6_ADDRESS = "fd00:ec2::254";
      /**
       * 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.
       */
      constructor(options2) {
        super(options2);
        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 = _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() {
        const match2 = this.environmentId?.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({
          ..._AwsClient.RETRY_CONFIG,
          url: this.regionalCredVerificationUrl.replace("{region}", this.region),
          method: "POST"
        });
        const reformattedHeader = [];
        const extendedHeaders = gaxios_1.Gaxios.mergeHeaders({
          // 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);
        extendedHeaders.forEach((value, key) => reformattedHeader.push({ key, value }));
        return encodeURIComponent(JSON.stringify({
          url: options2.url,
          method: options2.method,
          headers: reformattedHeader
        }));
      }
    };
    exports2.AwsClient = AwsClient;
  }
});

// packages/core/node_modules/google-auth-library/build/src/auth/executable-response.js
var require_executable_response = __commonJS({
  "packages/core/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");
      }
      /**
       * The version of the Executable response. Only version 1 is currently supported.
       */
      version;
      /**
       * Whether the executable ran successfully.
       */
      success;
      /**
       * The epoch time for expiration of the token in seconds.
       */
      expirationTime;
      /**
       * The type of subject token in the response, currently supported values are:
       * urn:ietf:params:oauth:token-type:saml2
       * urn:ietf:params:oauth:token-type:id_token
       * urn:ietf:params:oauth:token-type:jwt
       */
      tokenType;
      /**
       * The error code from the executable.
       */
      errorCode;
      /**
       * The error message from the executable.
       */
      errorMessage;
      /**
       * The subject token from the executable, format depends on tokenType.
       */
      subjectToken;
      /**
       * 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;
  }
});

// packages/core/node_modules/google-auth-library/build/src/auth/pluggable-auth-handler.js
var require_pluggable_auth_handler = __commonJS({
  "packages/core/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 = exports2.ExecutableError = void 0;
    var executable_response_1 = require_executable_response();
    var childProcess3 = __require("child_process");
    var fs113 = __require("fs");
    var ExecutableError = class extends Error {
      static {
        __name(this, "ExecutableError");
      }
      /**
       * The exit code returned by the executable.
       */
      code;
      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 PluggableAuthHandler = class _PluggableAuthHandler {
      static {
        __name(this, "PluggableAuthHandler");
      }
      commandComponents;
      timeoutMillis;
      outputFile;
      /**
       * 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((resolve30, 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 resolve30(response);
              } catch (error2) {
                if (error2 instanceof executable_response_1.ExecutableResponseError) {
                  return reject(error2);
                }
                return reject(new executable_response_1.ExecutableResponseError(`The executable returned an invalid response: ${output}`));
              }
            } else {
              return reject(new 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 fs113.promises.realpath(this.outputFile);
        } catch {
          return void 0;
        }
        if (!(await fs113.promises.lstat(filePath)).isFile()) {
          return void 0;
        }
        const responseString = await fs113.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 (error2) {
          if (error2 instanceof executable_response_1.ExecutableResponseError) {
            throw error2;
          }
          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 i3 = 0; i3 < components.length; i3++) {
          if (components[i3][0] === '"' && components[i3].slice(-1) === '"') {
            components[i3] = components[i3].slice(1, -1);
          }
        }
        return components;
      }
    };
    exports2.PluggableAuthHandler = PluggableAuthHandler;
  }
});

// packages/core/node_modules/google-auth-library/build/src/auth/pluggable-auth-client.js
var require_pluggable_auth_client = __commonJS({
  "packages/core/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 pluggable_auth_handler_2 = require_pluggable_auth_handler();
    Object.defineProperty(exports2, "ExecutableError", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return pluggable_auth_handler_2.ExecutableError;
    }, "get") });
    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");
      }
      /**
       * The command used to retrieve the third party token.
       */
      command;
      /**
       * The timeout in milliseconds for running executable,
       * set to default if none provided.
       */
      timeoutMillis;
      /**
       * The path to file to check for cached executable response.
       */
      outputFile;
      /**
       * Executable and output file handler.
       */
      handler;
      /**
       * 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.
       */
      constructor(options2) {
        super(options2);
        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 pluggable_auth_handler_1.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;
  }
});

// packages/core/node_modules/google-auth-library/build/src/auth/externalclient.js
var require_externalclient = __commonJS({
  "packages/core/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.
       *
       * **IMPORTANT**: This method does not validate the credential configuration.
       * A security risk occurs when a credential configuration configured with
       * malicious URLs is used. When the credential configuration is accepted from
       * an untrusted source, you should validate it before using it with this
       * method. For more details, see
       * https://cloud.google.com/docs/authentication/external/externally-sourced-credentials.
       *
       * @param options The external account options object typically loaded
       *   from the external account JSON credential file.
       * @return A BaseExternalAccountClient instance or null if the options
       *   provided do not correspond to an external account credential.
       */
      static fromJSON(options2) {
        if (options2 && options2.type === baseexternalclient_1.EXTERNAL_ACCOUNT_TYPE) {
          if (options2.credential_source?.environment_id) {
            return new awsclient_1.AwsClient(options2);
          } else if (options2.credential_source?.executable) {
            return new pluggable_auth_client_1.PluggableAuthClient(options2);
          } else {
            return new identitypoolclient_1.IdentityPoolClient(options2);
          }
        } else {
          return null;
        }
      }
    };
    exports2.ExternalAccountClient = ExternalAccountClient;
  }
});

// packages/core/node_modules/google-auth-library/build/src/auth/externalAccountAuthorizedUserClient.js
var require_externalAccountAuthorizedUserClient = __commonJS({
  "packages/core/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");
      }
      #tokenRefreshEndpoint;
      /**
       * 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(options2) {
        super(options2);
        this.#tokenRefreshEndpoint = options2.tokenRefreshEndpoint;
      }
      /**
       * 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, headers) {
        const opts = {
          ..._ExternalAccountAuthorizedUserHandler.RETRY_CONFIG,
          url: this.#tokenRefreshEndpoint,
          method: "POST",
          headers,
          data: new URLSearchParams({
            grant_type: "refresh_token",
            refresh_token: refreshToken
          })
        };
        authclient_1.AuthClient.setMethodName(opts, "refreshToken");
        this.applyClientAuthenticationOptions(opts);
        try {
          const response = await this.transporter.request(opts);
          const tokenRefreshResponse = response.data;
          tokenRefreshResponse.res = response;
          return tokenRefreshResponse;
        } catch (error2) {
          if (error2 instanceof gaxios_1.GaxiosError && error2.response) {
            throw (0, oauth2common_1.getErrorFromOAuthErrorResponse)(
              error2.response.data,
              // Preserve other fields from the original error.
              error2
            );
          }
          throw error2;
        }
      }
    };
    var ExternalAccountAuthorizedUserClient = class extends authclient_1.AuthClient {
      static {
        __name(this, "ExternalAccountAuthorizedUserClient");
      }
      cachedAccessToken;
      externalAccountAuthorizedUserHandler;
      refreshToken;
      /**
       * 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.
       */
      constructor(options2) {
        super(options2);
        if (options2.universe_domain) {
          this.universeDomain = options2.universe_domain;
        }
        this.refreshToken = options2.refresh_token;
        const clientAuthentication = {
          confidentialClientType: "basic",
          clientId: options2.client_id,
          clientSecret: options2.client_secret
        };
        this.externalAccountAuthorizedUserHandler = new ExternalAccountAuthorizedUserHandler({
          tokenRefreshEndpoint: options2.token_url ?? DEFAULT_TOKEN_URL.replace("{universeDomain}", this.universeDomain),
          transporter: this.transporter,
          clientAuthentication
        });
        this.cachedAccessToken = null;
        this.quotaProjectId = options2.quota_project_id;
        if (typeof options2?.eagerRefreshThresholdMillis !== "number") {
          this.eagerRefreshThresholdMillis = baseexternalclient_1.EXPIRATION_TIME_OFFSET;
        } else {
          this.eagerRefreshThresholdMillis = options2.eagerRefreshThresholdMillis;
        }
        this.forceRefreshOnFailure = !!options2?.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 = new Headers({
          authorization: `Bearer ${accessTokenResponse.token}`
        });
        return this.addSharedMetadataHeaders(headers);
      }
      request(opts, callback) {
        if (callback) {
          this.requestAsync(opts).then((r5) => callback(null, r5), (e4) => {
            return callback(e4, e4.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 = gaxios_1.Gaxios.mergeHeaders(opts.headers);
          this.addUserProjectAndAuthHeaders(opts.headers, requestHeaders);
          response = await this.transporter.request(opts);
        } catch (e4) {
          const res = e4.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 e4;
        }
        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;
  }
});

// packages/core/node_modules/google-auth-library/build/src/auth/googleauth.js
var require_googleauth = __commonJS({
  "packages/core/node_modules/google-auth-library/build/src/auth/googleauth.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.GoogleAuth = exports2.GoogleAuthExceptionMessages = void 0;
    var child_process_1 = __require("child_process");
    var fs113 = __require("fs");
    var gaxios_1 = require_src2();
    var gcpMetadata = require_src4();
    var os47 = __require("os");
    var path125 = __require("path");
    var crypto_1 = require_crypto3();
    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_util10();
    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 GoogleAuth5 = class {
      static {
        __name(this, "GoogleAuth");
      }
      /**
       * Caches a value indicating whether the auth layer is running on Google
       * Compute Engine.
       * @private
       */
      checkIsGCE = void 0;
      useJWTAccessWithScope;
      defaultServicePath;
      // Note:  this properly is only public to satisfy unit tests.
      // https://github.com/Microsoft/TypeScript/issues/5228
      get isGCE() {
        return this.checkIsGCE;
      }
      _findProjectIdPromise;
      _cachedProjectId;
      // To save the contents of the JSON credential file
      jsonContent = null;
      apiKey;
      cachedCredential = null;
      /**
       * A pending {@link AuthClient}. Used for concurrent {@link GoogleAuth.getClient} calls.
       */
      #pendingAuthClient = null;
      /**
       * Scopes populated by the client library by default. We differentiate between
       * these and user defined scopes when deciding whether to use a self-signed JWT.
       */
      defaultScopes;
      keyFilename;
      scopes;
      clientOptions = {};
      /**
       * 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 = {}) {
        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((r5) => callback(null, r5), 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 (e4) {
          if (e4 instanceof Error && e4.message === exports2.GoogleAuthExceptionMessages.NO_PROJECT_ID_FOUND) {
            return null;
          } else {
            throw e4;
          }
        }
      }
      /**
       * 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 ||= await this.getProductionProjectId();
        projectId ||= await this.getFileProjectId();
        projectId ||= await this.getDefaultServiceProjectId();
        projectId ||= await this.getGCEProjectId();
        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() {
        let universeDomain;
        try {
          universeDomain = await gcpMetadata.universe("universe-domain");
          universeDomain ||= authclient_1.DEFAULT_UNIVERSE;
        } catch (e4) {
          if (e4 && e4?.response?.status === 404) {
            universeDomain = authclient_1.DEFAULT_UNIVERSE;
          } else {
            throw e4;
          }
        }
        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 ??= (await this.getClient()).universeDomain;
        } catch {
          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((r5) => callback(null, r5.credential, r5.projectId), callback);
        } else {
          return this.getApplicationDefaultAsync(options2);
        }
      }
      async getApplicationDefaultAsync(options2 = {}) {
        if (this.cachedCredential) {
          return await this.#prepareAndCacheClient(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 this.#prepareAndCacheClient(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 this.#prepareAndCacheClient(credential);
        }
        if (await this._checkIsGCE()) {
          options2.scopes = this.getAnyScopes();
          return await this.#prepareAndCacheClient(new computeclient_1.Compute(options2));
        }
        throw new Error(exports2.GoogleAuthExceptionMessages.NO_ADC_FOUND);
      }
      async #prepareAndCacheClient(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 };
      }
      /**
       * 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 (e4) {
          if (e4 instanceof Error) {
            e4.message = `Unable to read the credential file specified by the GOOGLE_APPLICATION_CREDENTIALS environment variable: ${e4.message}`;
          }
          throw e4;
        }
      }
      /**
       * 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 = path125.join(home, ".config");
          }
        }
        if (location) {
          location = path125.join(location, "gcloud", "application_default_credentials.json");
          if (!fs113.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 = fs113.realpathSync(filePath);
          if (!fs113.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 = fs113.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) {
        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 (json2.service_account_impersonation_url?.length > 256) {
          throw new RangeError(`Target principal is too long: ${json2.service_account_impersonation_url}`);
        }
        const targetPrincipal = /(?<target>[^/]+):(generateAccessToken|generateIdToken)$/.exec(json2.service_account_impersonation_url)?.groups?.target;
        if (!targetPrincipal) {
          throw new RangeError(`Cannot extract target principal from ${json2.service_account_impersonation_url}`);
        }
        const targetScopes = (this.scopes || json2.scopes || this.defaultScopes) ?? [];
        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}.
       *
       * @deprecated This method is being deprecated because of a potential security risk.
       *
       * This method does not validate the credential configuration. The security
       * risk occurs when a credential configuration is accepted from a source that
       * is not under your control and used without validation on your side.
       *
       * If you know that you will be loading credential configurations of a
       * specific type, it is recommended to use a credential-type-specific
       * constructor. This will ensure that an unexpected credential type with
       * potential for malicious intent is not loaded unintentionally. You might
       * still have to do validation for certain credential types. Please follow
       * the recommendation for that method. For example, if you want to load only
       * service accounts, you can use the `JWT` constructor:
       * ```
       * const {JWT} = require('google-auth-library');
       * const keys = require('/path/to/key.json');
       * const client = new JWT({
       *   email: keys.client_email,
       *   key: keys.private_key,
       *   scopes: ['https://www.googleapis.com/auth/cloud-platform'],
       * });
       * ```
       *
       * If you are loading your credential configuration from an untrusted source and have
       * not mitigated the risks (e.g. by validating the configuration yourself), make
       * these changes as soon as possible to prevent security risks to your environment.
       *
       * Regardless of the method used, it is always your responsibility to validate
       * configurations received from external sources.
       *
       * For more details, see https://cloud.google.com/docs/authentication/external/externally-sourced-credentials.
       *
       * @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((r5) => callback(null, r5), callback);
        } else {
          return this.fromStreamAsync(inputStream, options2);
        }
      }
      fromStreamAsync(inputStream, options2) {
        return new Promise((resolve30, 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 r5 = this._cacheClientFromJSON(data, options2);
                return resolve30(r5);
              } 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 resolve30(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 = os47.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((resolve30) => {
          (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;
                resolve30(projectId);
                return;
              } catch (e4) {
              }
            }
            resolve30(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 r5 = await this._tryGetApplicationCredentialsFromEnvironmentVariable();
        if (r5) {
          return r5.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 r5 = await gcpMetadata.project("project-id");
          return r5;
        } catch (e4) {
          return null;
        }
      }
      getCredentials(callback) {
        if (callback) {
          this.getCredentialsAsync().then((r5) => callback(null, r5), 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;
        }
        this.#pendingAuthClient = this.#pendingAuthClient || this.#determineClient();
        try {
          return await this.#pendingAuthClient;
        } finally {
          this.#pendingAuthClient = null;
        }
      }
      async #determineClient() {
        if (this.jsonContent) {
          return this._cacheClientFromJSON(this.jsonContent, this.clientOptions);
        } else if (this.keyFilename) {
          const filePath = path125.resolve(this.keyFilename);
          const stream2 = fs113.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 this.#prepareAndCacheClient(client);
          return credential;
        } else {
          const { credential } = await this.getApplicationDefaultAsync(this.clientOptions);
          return credential;
        }
      }
      /**
       * 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 = {}) {
        const url2 = opts.url;
        const client = await this.getClient();
        const headers = await client.getRequestHeaders(url2);
        opts.headers = gaxios_1.Gaxios.mergeHeaders(opts.headers, headers);
        return opts;
      }
      /**
       * A {@link fetch `fetch`} compliant API for {@link GoogleAuth}.
       *
       * @see {@link GoogleAuth.request} for the classic method.
       *
       * @remarks
       *
       * This is useful as a drop-in replacement for `fetch` API usage.
       *
       * @example
       *
       * ```ts
       * const auth = new GoogleAuth();
       * const fetchWithAuth: typeof fetch = (...args) => auth.fetch(...args);
       * await fetchWithAuth('https://example.com');
       * ```
       *
       * @param args `fetch` API or {@link Gaxios.fetch `Gaxios#fetch`} parameters
       * @returns the {@link GaxiosResponse} with Gaxios-added properties
       */
      async fetch(...args) {
        const client = await this.getClient();
        return client.fetch(...args);
      }
      /**
       * Automatically obtain application default credentials, and make an
       * HTTP request using the given options.
       *
       * @see {@link GoogleAuth.fetch} for the modern method.
       *
       * @param opts Axios request options for the HTTP request.
       */
      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 crypto14 = (0, crypto_1.createCrypto)();
        if (client instanceof jwtclient_1.JWT && client.key) {
          const sign = await crypto14.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(crypto14, creds.client_email, data, endpoint);
      }
      async signBlob(crypto14, emailOrUniqueId, data, endpoint) {
        const url2 = new URL(endpoint + `${emailOrUniqueId}:signBlob`);
        const res = await this.request({
          method: "POST",
          url: url2.href,
          data: {
            payload: crypto14.encodeBase64StringUtf8(data)
          },
          retry: true,
          retryConfig: {
            httpMethodsToRetry: ["POST"]
          }
        });
        return res.data.signedBlob;
      }
    };
    exports2.GoogleAuth = GoogleAuth5;
  }
});

// packages/core/node_modules/google-auth-library/build/src/auth/iam.js
var require_iam = __commonJS({
  "packages/core/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");
      }
      selector;
      token;
      /**
       * 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;
  }
});

// packages/core/node_modules/google-auth-library/build/src/auth/downscopedclient.js
var require_downscopedclient = __commonJS({
  "packages/core/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 gaxios_1 = require_src2();
    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");
      }
      authClient;
      credentialAccessBoundary;
      cachedDownscopedAccessToken;
      stsCredential;
      /**
       * 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 options the {@link DownscopedClientOptions `DownscopedClientOptions`} to use. Passing an `AuthClient` directly is **@DEPRECATED**.
       * @param credentialAccessBoundary **@DEPRECATED**. Provide a {@link DownscopedClientOptions `DownscopedClientOptions`} object in the first parameter instead.
       */
      constructor(options2, credentialAccessBoundary = {
        accessBoundary: {
          accessBoundaryRules: []
        }
      }) {
        super(options2 instanceof authclient_1.AuthClient ? {} : options2);
        if (options2 instanceof authclient_1.AuthClient) {
          this.authClient = options2;
          this.credentialAccessBoundary = credentialAccessBoundary;
        } else {
          this.authClient = options2.authClient;
          this.credentialAccessBoundary = options2.credentialAccessBoundary;
        }
        if (this.credentialAccessBoundary.accessBoundary.accessBoundaryRules.length === 0) {
          throw new Error("At least one access boundary rule needs to be defined.");
        } else if (this.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 this.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({
          tokenExchangeEndpoint: `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 = new Headers({
          authorization: `Bearer ${accessTokenResponse.token}`
        });
        return this.addSharedMetadataHeaders(headers);
      }
      request(opts, callback) {
        if (callback) {
          this.requestAsync(opts).then((r5) => callback(null, r5), (e4) => {
            return callback(e4, e4.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 = gaxios_1.Gaxios.mergeHeaders(opts.headers);
          this.addUserProjectAndAuthHeaders(opts.headers, requestHeaders);
          response = await this.transporter.request(opts);
        } catch (e4) {
          const res = e4.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 e4;
        }
        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() {
        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 = this.authClient.credentials?.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;
  }
});

// packages/core/node_modules/google-auth-library/build/src/auth/passthrough.js
var require_passthrough = __commonJS({
  "packages/core/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 new Headers();
      }
    };
    exports2.PassThroughClient = PassThroughClient;
  }
});

// packages/core/node_modules/google-auth-library/build/src/index.js
var require_src6 = __commonJS({
  "packages/core/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.PassThroughClient = exports2.ExternalAccountAuthorizedUserClient = exports2.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE = 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 externalAccountAuthorizedUserClient_1 = require_externalAccountAuthorizedUserClient();
    Object.defineProperty(exports2, "EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return externalAccountAuthorizedUserClient_1.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE;
    }, "get") });
    Object.defineProperty(exports2, "ExternalAccountAuthorizedUserClient", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return externalAccountAuthorizedUserClient_1.ExternalAccountAuthorizedUserClient;
    }, "get") });
    var passthrough_1 = require_passthrough();
    Object.defineProperty(exports2, "PassThroughClient", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return passthrough_1.PassThroughClient;
    }, "get") });
    var auth2 = new googleauth_1.GoogleAuth();
    exports2.auth = auth2;
  }
});

// node_modules/ws/lib/constants.js
var require_constants6 = __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_constants6();
    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 i3 = 0; i3 < list3.length; i3++) {
        const buf = list3[i3];
        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 i3 = 0; i3 < length; i3++) {
        output[offset + i3] = source2[i3] ^ mask[i3 & 3];
      }
    }
    __name(_mask, "_mask");
    function _unmask(buffer, mask) {
      for (let i3 = 0; i3 < buffer.length; i3++) {
        buffer[i3] ^= mask[i3 & 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 (e4) {
      }
    }
  }
});

// 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_deflate2 = __commonJS({
  "node_modules/ws/lib/permessage-deflate.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var zlib4 = __require("zlib");
    var bufferUtil = require_buffer_util();
    var Limiter = require_limiter();
    var { kStatusCode } = require_constants6();
    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" ? zlib4.Z_DEFAULT_WINDOWBITS : this.params[key];
          this._inflate = zlib4.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" ? zlib4.Z_DEFAULT_WINDOWBITS : this.params[key];
          this._deflate = zlib4.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(zlib4.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_constants6();
    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 i3 = 0;
      while (i3 < len) {
        if ((buf[i3] & 128) === 0) {
          i3++;
        } else if ((buf[i3] & 224) === 192) {
          if (i3 + 1 === len || (buf[i3 + 1] & 192) !== 128 || (buf[i3] & 254) === 192) {
            return false;
          }
          i3 += 2;
        } else if ((buf[i3] & 240) === 224) {
          if (i3 + 2 >= len || (buf[i3 + 1] & 192) !== 128 || (buf[i3 + 2] & 192) !== 128 || buf[i3] === 224 && (buf[i3 + 1] & 224) === 128 || // Overlong
          buf[i3] === 237 && (buf[i3 + 1] & 224) === 160) {
            return false;
          }
          i3 += 3;
        } else if ((buf[i3] & 248) === 240) {
          if (i3 + 3 >= len || (buf[i3 + 1] & 192) !== 128 || (buf[i3 + 2] & 192) !== 128 || (buf[i3 + 3] & 192) !== 128 || buf[i3] === 240 && (buf[i3 + 1] & 240) === 128 || // Overlong
          buf[i3] === 244 && buf[i3 + 1] > 143 || buf[i3] > 244) {
            return false;
          }
          i3 += 4;
        } else {
          return false;
        }
      }
      return true;
    }
    __name(_isValidUTF8, "_isValidUTF8");
    function isBlob4(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(isBlob4, "isBlob");
    module2.exports = {
      isBlob: isBlob4,
      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 (e4) {
      }
    }
  }
});

// node_modules/ws/lib/receiver.js
var require_receiver2 = __commonJS({
  "node_modules/ws/lib/receiver.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var { Writable: Writable3 } = __require("stream");
    var PerMessageDeflate = require_permessage_deflate2();
    var {
      BINARY_TYPES,
      EMPTY_BUFFER,
      kStatusCode,
      kWebSocket
    } = require_constants6();
    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(n3) {
        this._bufferedBytes -= n3;
        if (n3 === this._buffers[0].length) return this._buffers.shift();
        if (n3 < this._buffers[0].length) {
          const buf = this._buffers[0];
          this._buffers[0] = new FastBuffer(
            buf.buffer,
            buf.byteOffset + n3,
            buf.length - n3
          );
          return new FastBuffer(buf.buffer, buf.byteOffset, n3);
        }
        const dst = Buffer.allocUnsafe(n3);
        do {
          const buf = this._buffers[0];
          const offset = dst.length - n3;
          if (n3 >= buf.length) {
            dst.set(this._buffers.shift(), offset);
          } else {
            dst.set(new Uint8Array(buf.buffer, buf.byteOffset, n3), offset);
            this._buffers[0] = new FastBuffer(
              buf.buffer,
              buf.byteOffset + n3,
              buf.length - n3
            );
          }
          n3 -= buf.length;
        } while (n3 > 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 error2 = this.createError(
            RangeError,
            "RSV2 and RSV3 must be clear",
            true,
            1002,
            "WS_ERR_UNEXPECTED_RSV_2_3"
          );
          cb(error2);
          return;
        }
        const compressed = (buf[0] & 64) === 64;
        if (compressed && !this._extensions[PerMessageDeflate.extensionName]) {
          const error2 = this.createError(
            RangeError,
            "RSV1 must be clear",
            true,
            1002,
            "WS_ERR_UNEXPECTED_RSV_1"
          );
          cb(error2);
          return;
        }
        this._fin = (buf[0] & 128) === 128;
        this._opcode = buf[0] & 15;
        this._payloadLength = buf[1] & 127;
        if (this._opcode === 0) {
          if (compressed) {
            const error2 = this.createError(
              RangeError,
              "RSV1 must be clear",
              true,
              1002,
              "WS_ERR_UNEXPECTED_RSV_1"
            );
            cb(error2);
            return;
          }
          if (!this._fragmented) {
            const error2 = this.createError(
              RangeError,
              "invalid opcode 0",
              true,
              1002,
              "WS_ERR_INVALID_OPCODE"
            );
            cb(error2);
            return;
          }
          this._opcode = this._fragmented;
        } else if (this._opcode === 1 || this._opcode === 2) {
          if (this._fragmented) {
            const error2 = this.createError(
              RangeError,
              `invalid opcode ${this._opcode}`,
              true,
              1002,
              "WS_ERR_INVALID_OPCODE"
            );
            cb(error2);
            return;
          }
          this._compressed = compressed;
        } else if (this._opcode > 7 && this._opcode < 11) {
          if (!this._fin) {
            const error2 = this.createError(
              RangeError,
              "FIN must be set",
              true,
              1002,
              "WS_ERR_EXPECTED_FIN"
            );
            cb(error2);
            return;
          }
          if (compressed) {
            const error2 = this.createError(
              RangeError,
              "RSV1 must be clear",
              true,
              1002,
              "WS_ERR_UNEXPECTED_RSV_1"
            );
            cb(error2);
            return;
          }
          if (this._payloadLength > 125 || this._opcode === 8 && this._payloadLength === 1) {
            const error2 = this.createError(
              RangeError,
              `invalid payload length ${this._payloadLength}`,
              true,
              1002,
              "WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH"
            );
            cb(error2);
            return;
          }
        } else {
          const error2 = this.createError(
            RangeError,
            `invalid opcode ${this._opcode}`,
            true,
            1002,
            "WS_ERR_INVALID_OPCODE"
          );
          cb(error2);
          return;
        }
        if (!this._fin && !this._fragmented) this._fragmented = this._opcode;
        this._masked = (buf[1] & 128) === 128;
        if (this._isServer) {
          if (!this._masked) {
            const error2 = this.createError(
              RangeError,
              "MASK must be set",
              true,
              1002,
              "WS_ERR_EXPECTED_MASK"
            );
            cb(error2);
            return;
          }
        } else if (this._masked) {
          const error2 = this.createError(
            RangeError,
            "MASK must be clear",
            true,
            1002,
            "WS_ERR_UNEXPECTED_MASK"
          );
          cb(error2);
          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 error2 = this.createError(
            RangeError,
            "Unsupported WebSocket frame: payload length > 2^53 - 1",
            false,
            1009,
            "WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH"
          );
          cb(error2);
          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 error2 = this.createError(
              RangeError,
              "Max payload size exceeded",
              false,
              1009,
              "WS_ERR_UNSUPPORTED_MESSAGE_LENGTH"
            );
            cb(error2);
            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 error2 = this.createError(
                RangeError,
                "Max payload size exceeded",
                false,
                1009,
                "WS_ERR_UNSUPPORTED_MESSAGE_LENGTH"
              );
              cb(error2);
              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 error2 = this.createError(
              Error,
              "invalid UTF-8 sequence",
              true,
              1007,
              "WS_ERR_INVALID_UTF8"
            );
            cb(error2);
            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 error2 = this.createError(
                RangeError,
                `invalid status code ${code2}`,
                true,
                1002,
                "WS_ERR_INVALID_CLOSE_CODE"
              );
              cb(error2);
              return;
            }
            const buf = new FastBuffer(
              data.buffer,
              data.byteOffset + 2,
              data.length - 2
            );
            if (!this._skipUTF8Validation && !isValidUTF8(buf)) {
              const error2 = this.createError(
                Error,
                "invalid UTF-8 sequence",
                true,
                1007,
                "WS_ERR_INVALID_UTF8"
              );
              cb(error2);
              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_sender2 = __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_deflate2();
    var { EMPTY_BUFFER, kWebSocket, NOOP: NOOP3 } = require_constants6();
    var { isBlob: isBlob4, 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 merge4 = 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;
          merge4 = 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(merge4 ? 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 (merge4) {
          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 (isBlob4(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 (isBlob4(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 (isBlob4(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 (isBlob4(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 (isBlob4(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 (isBlob4(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, (_2, 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 i3 = 0; i3 < sender._queue.length; i3++) {
        const params = sender._queue[i3];
        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_constants6();
    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(error2) {
            const event = new ErrorEvent2("error", {
              error: error2,
              message: error2.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 parse14(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 i3 = 0;
      for (; i3 < header.length; i3++) {
        code2 = header.charCodeAt(i3);
        if (extensionName === void 0) {
          if (end === -1 && tokenChars[code2] === 1) {
            if (start === -1) start = i3;
          } else if (i3 !== 0 && (code2 === 32 || code2 === 9)) {
            if (end === -1 && start !== -1) end = i3;
          } else if (code2 === 59 || code2 === 44) {
            if (start === -1) {
              throw new SyntaxError(`Unexpected character at index ${i3}`);
            }
            if (end === -1) end = i3;
            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 ${i3}`);
          }
        } else if (paramName === void 0) {
          if (end === -1 && tokenChars[code2] === 1) {
            if (start === -1) start = i3;
          } else if (code2 === 32 || code2 === 9) {
            if (end === -1 && start !== -1) end = i3;
          } else if (code2 === 59 || code2 === 44) {
            if (start === -1) {
              throw new SyntaxError(`Unexpected character at index ${i3}`);
            }
            if (end === -1) end = i3;
            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, i3);
            start = end = -1;
          } else {
            throw new SyntaxError(`Unexpected character at index ${i3}`);
          }
        } else {
          if (isEscaping) {
            if (tokenChars[code2] !== 1) {
              throw new SyntaxError(`Unexpected character at index ${i3}`);
            }
            if (start === -1) start = i3;
            else if (!mustUnescape) mustUnescape = true;
            isEscaping = false;
          } else if (inQuotes) {
            if (tokenChars[code2] === 1) {
              if (start === -1) start = i3;
            } else if (code2 === 34 && start !== -1) {
              inQuotes = false;
              end = i3;
            } else if (code2 === 92) {
              isEscaping = true;
            } else {
              throw new SyntaxError(`Unexpected character at index ${i3}`);
            }
          } else if (code2 === 34 && header.charCodeAt(i3 - 1) === 61) {
            inQuotes = true;
          } else if (end === -1 && tokenChars[code2] === 1) {
            if (start === -1) start = i3;
          } else if (start !== -1 && (code2 === 32 || code2 === 9)) {
            if (end === -1) end = i3;
          } else if (code2 === 59 || code2 === 44) {
            if (start === -1) {
              throw new SyntaxError(`Unexpected character at index ${i3}`);
            }
            if (end === -1) end = i3;
            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 ${i3}`);
          }
        }
      }
      if (start === -1 || inQuotes || code2 === 32 || code2 === 9) {
        throw new SyntaxError("Unexpected end of input");
      }
      if (end === -1) end = i3;
      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(parse14, "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((k2) => {
              let values = params[k2];
              if (!Array.isArray(values)) values = [values];
              return values.map((v2) => v2 === true ? k2 : `${k2}=${v2}`).join("; ");
            })
          ).join("; ");
        }).join(", ");
      }).join(", ");
    }
    __name(format4, "format");
    module2.exports = { format: format4, parse: parse14 };
  }
});

// node_modules/ws/lib/websocket.js
var require_websocket2 = __commonJS({
  "node_modules/ws/lib/websocket.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var EventEmitter11 = __require("events");
    var https7 = __require("https");
    var http7 = __require("http");
    var net2 = __require("net");
    var tls = __require("tls");
    var { randomBytes: randomBytes6, createHash: createHash7 } = __require("crypto");
    var { Duplex, Readable: Readable6 } = __require("stream");
    var { URL: URL5 } = __require("url");
    var PerMessageDeflate = require_permessage_deflate2();
    var Receiver2 = require_receiver2();
    var Sender2 = require_sender2();
    var { isBlob: isBlob4 } = require_validation();
    var {
      BINARY_TYPES,
      EMPTY_BUFFER,
      GUID,
      kForOnEventAttribute,
      kListener,
      kStatusCode,
      kWebSocket,
      NOOP: NOOP3
    } = require_constants6();
    var {
      EventTarget: { addEventListener, removeEventListener }
    } = require_event_target();
    var { format: format4, parse: parse14 } = 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 EventEmitter11 {
      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 URL5) {
        parsedUrl = address;
      } else {
        try {
          parsedUrl = new URL5(address);
        } catch (e4) {
          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 ? https7.request : http7.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 URL5(location, address);
          } catch (e4) {
            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 = createHash7("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 = parse14(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 = isBlob4(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_websocket2();
    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 error2(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 error2(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 open4() {
            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 open4() {
            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 parse14(header) {
      const protocols = /* @__PURE__ */ new Set();
      let start = -1;
      let end = -1;
      let i3 = 0;
      for (i3; i3 < header.length; i3++) {
        const code2 = header.charCodeAt(i3);
        if (end === -1 && tokenChars[code2] === 1) {
          if (start === -1) start = i3;
        } else if (i3 !== 0 && (code2 === 32 || code2 === 9)) {
          if (end === -1 && start !== -1) end = i3;
        } else if (code2 === 44) {
          if (start === -1) {
            throw new SyntaxError(`Unexpected character at index ${i3}`);
          }
          if (end === -1) end = i3;
          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 ${i3}`);
        }
      }
      if (start === -1 || end !== -1) {
        throw new SyntaxError("Unexpected end of input");
      }
      const protocol = header.slice(start, i3);
      if (protocols.has(protocol)) {
        throw new SyntaxError(`The "${protocol}" subprotocol is duplicated`);
      }
      protocols.add(protocol);
      return protocols;
    }
    __name(parse14, "parse");
    module2.exports = { parse: parse14 };
  }
});

// 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 EventEmitter11 = __require("events");
    var http7 = __require("http");
    var { Duplex } = __require("stream");
    var { createHash: createHash7 } = __require("crypto");
    var extension = require_extension();
    var PerMessageDeflate = require_permessage_deflate2();
    var subprotocol = require_subprotocol();
    var WebSocket2 = require_websocket2();
    var { GUID, kWebSocket } = require_constants6();
    var keyRegex = /^[+/0-9A-Za-z]{22}==$/;
    var RUNNING = 0;
    var CLOSING = 1;
    var CLOSED2 = 2;
    var WebSocketServer2 = class extends EventEmitter11 {
      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 = http7.createServer((req, res) => {
            const body = http7.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 = createHash7("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 || http7.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} ${http7.STATUS_CODES[code2]}\r
` + Object.keys(headers).map((h3) => `${h3}: ${headers[h3]}`).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_receiver2(), 1);
    import_sender = __toESM(require_sender2(), 1);
    import_websocket = __toESM(require_websocket2(), 1);
    import_websocket_server = __toESM(require_websocket_server(), 1);
    wrapper_default = import_websocket.default;
  }
});

// packages/core/node_modules/@google/genai/dist/node/index.mjs
import { createWriteStream } from "fs";
import * as fs5 from "fs/promises";
import { writeFile } from "fs/promises";
import { Readable } from "node:stream";
import { finished } from "node:stream/promises";
import * as path3 from "path";
function getDefaultBaseUrls() {
  return {
    geminiUrl: _defaultBaseGeminiUrl,
    vertexUrl: _defaultBaseVertexUrl
  };
}
function getBaseUrl(httpOptions, vertexai, vertexBaseUrlFromEnv, geminiBaseUrlFromEnv) {
  var _a7, _b2;
  if (!(httpOptions === null || httpOptions === void 0 ? void 0 : httpOptions.baseUrl)) {
    const defaultBaseUrls = getDefaultBaseUrls();
    if (vertexai) {
      return (_a7 = defaultBaseUrls.vertexUrl) !== null && _a7 !== void 0 ? _a7 : 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 i3 = 0; i3 < keys.length - 1; i3++) {
    const key = keys[i3];
    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 j2 = 0; j2 < arrayData.length; j2++) {
            const entry = arrayData[j2];
            setValueByPath(entry, keys.slice(i3 + 1), value[j2]);
          }
        } else {
          for (const d2 of arrayData) {
            setValueByPath(d2, keys.slice(i3 + 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(i3 + 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 {
    if (keyToSet === "_self" && typeof value === "object" && value !== null && !Array.isArray(value)) {
      const valueAsRecord = value;
      Object.assign(data, valueAsRecord);
    } else {
      data[keyToSet] = value;
    }
  }
}
function getValueByPath(data, keys, defaultValue = void 0) {
  try {
    if (keys.length === 1 && keys[0] === "_self") {
      return data;
    }
    for (let i3 = 0; i3 < keys.length; i3++) {
      if (typeof data !== "object" || data === null) {
        return defaultValue;
      }
      const key = keys[i3];
      if (key.endsWith("[]")) {
        const keyName2 = key.slice(0, -2);
        if (keyName2 in data) {
          const arrayData = data[keyName2];
          if (!Array.isArray(arrayData)) {
            return defaultValue;
          }
          return arrayData.map((d2) => getValueByPath(d2, keys.slice(i3 + 1), defaultValue));
        } else {
          return defaultValue;
        }
      } else {
        data = data[key];
      }
    }
    return data;
  } catch (error2) {
    if (error2 instanceof TypeError) {
      return defaultValue;
    }
    throw error2;
  }
}
function moveValueByPath(data, paths) {
  for (const [sourcePath, destPath] of Object.entries(paths)) {
    const sourceKeys = sourcePath.split(".");
    const destKeys = destPath.split(".");
    const excludeKeys = /* @__PURE__ */ new Set();
    let wildcardIdx = -1;
    for (let i3 = 0; i3 < sourceKeys.length; i3++) {
      if (sourceKeys[i3] === "*") {
        wildcardIdx = i3;
        break;
      }
    }
    if (wildcardIdx !== -1 && destKeys.length > wildcardIdx) {
      for (let i3 = wildcardIdx; i3 < destKeys.length; i3++) {
        const key = destKeys[i3];
        if (key !== "*" && !key.endsWith("[]") && !key.endsWith("[0]")) {
          excludeKeys.add(key);
        }
      }
    }
    _moveValueRecursive(data, sourceKeys, destKeys, 0, excludeKeys);
  }
}
function _moveValueRecursive(data, sourceKeys, destKeys, keyIdx, excludeKeys) {
  if (keyIdx >= sourceKeys.length) {
    return;
  }
  if (typeof data !== "object" || data === null) {
    return;
  }
  const key = sourceKeys[keyIdx];
  if (key.endsWith("[]")) {
    const keyName2 = key.slice(0, -2);
    const dataRecord = data;
    if (keyName2 in dataRecord && Array.isArray(dataRecord[keyName2])) {
      for (const item of dataRecord[keyName2]) {
        _moveValueRecursive(item, sourceKeys, destKeys, keyIdx + 1, excludeKeys);
      }
    }
  } else if (key === "*") {
    if (typeof data === "object" && data !== null && !Array.isArray(data)) {
      const dataRecord = data;
      const keysToMove = Object.keys(dataRecord).filter((k2) => !k2.startsWith("_") && !excludeKeys.has(k2));
      const valuesToMove = {};
      for (const k2 of keysToMove) {
        valuesToMove[k2] = dataRecord[k2];
      }
      for (const [k2, v2] of Object.entries(valuesToMove)) {
        const newDestKeys = [];
        for (const dk of destKeys.slice(keyIdx)) {
          if (dk === "*") {
            newDestKeys.push(k2);
          } else {
            newDestKeys.push(dk);
          }
        }
        setValueByPath(dataRecord, newDestKeys, v2);
      }
      for (const k2 of keysToMove) {
        delete dataRecord[k2];
      }
    }
  } else {
    const dataRecord = data;
    if (key in dataRecord) {
      _moveValueRecursive(dataRecord[key], sourceKeys, destKeys, keyIdx + 1, excludeKeys);
    }
  }
}
function tBytes$1(fromBytes) {
  if (typeof fromBytes !== "string") {
    throw new Error("fromImageBytes must be a string");
  }
  return fromBytes;
}
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);
  }
  return toObject;
}
function generateVideosOperationFromMldev$1(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$1(fromResponse));
  }
  return toObject;
}
function generateVideosOperationFromVertex$1(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$1(fromResponse));
  }
  return toObject;
}
function generateVideosResponseFromMldev$1(fromObject) {
  const toObject = {};
  const fromGeneratedVideos = getValueByPath(fromObject, [
    "generatedSamples"
  ]);
  if (fromGeneratedVideos != null) {
    let transformedList = fromGeneratedVideos;
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return generatedVideoFromMldev$1(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 generateVideosResponseFromVertex$1(fromObject) {
  const toObject = {};
  const fromGeneratedVideos = getValueByPath(fromObject, ["videos"]);
  if (fromGeneratedVideos != null) {
    let transformedList = fromGeneratedVideos;
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return generatedVideoFromVertex$1(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 generatedVideoFromMldev$1(fromObject) {
  const toObject = {};
  const fromVideo = getValueByPath(fromObject, ["video"]);
  if (fromVideo != null) {
    setValueByPath(toObject, ["video"], videoFromMldev$1(fromVideo));
  }
  return toObject;
}
function generatedVideoFromVertex$1(fromObject) {
  const toObject = {};
  const fromVideo = getValueByPath(fromObject, ["_self"]);
  if (fromVideo != null) {
    setValueByPath(toObject, ["video"], videoFromVertex$1(fromVideo));
  }
  return toObject;
}
function getOperationParametersToMldev(fromObject) {
  const toObject = {};
  const fromOperationName = getValueByPath(fromObject, [
    "operationName"
  ]);
  if (fromOperationName != null) {
    setValueByPath(toObject, ["_url", "operationName"], fromOperationName);
  }
  return toObject;
}
function getOperationParametersToVertex(fromObject) {
  const toObject = {};
  const fromOperationName = getValueByPath(fromObject, [
    "operationName"
  ]);
  if (fromOperationName != null) {
    setValueByPath(toObject, ["_url", "operationName"], fromOperationName);
  }
  return toObject;
}
function importFileOperationFromMldev$1(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"], importFileResponseFromMldev$1(fromResponse));
  }
  return toObject;
}
function importFileResponseFromMldev$1(fromObject) {
  const toObject = {};
  const fromSdkHttpResponse = getValueByPath(fromObject, [
    "sdkHttpResponse"
  ]);
  if (fromSdkHttpResponse != null) {
    setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse);
  }
  const fromParent = getValueByPath(fromObject, ["parent"]);
  if (fromParent != null) {
    setValueByPath(toObject, ["parent"], fromParent);
  }
  const fromDocumentName = getValueByPath(fromObject, ["documentName"]);
  if (fromDocumentName != null) {
    setValueByPath(toObject, ["documentName"], fromDocumentName);
  }
  return toObject;
}
function uploadToFileSearchStoreOperationFromMldev(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"], uploadToFileSearchStoreResponseFromMldev(fromResponse));
  }
  return toObject;
}
function uploadToFileSearchStoreResponseFromMldev(fromObject) {
  const toObject = {};
  const fromSdkHttpResponse = getValueByPath(fromObject, [
    "sdkHttpResponse"
  ]);
  if (fromSdkHttpResponse != null) {
    setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse);
  }
  const fromParent = getValueByPath(fromObject, ["parent"]);
  if (fromParent != null) {
    setValueByPath(toObject, ["parent"], fromParent);
  }
  const fromDocumentName = getValueByPath(fromObject, ["documentName"]);
  if (fromDocumentName != null) {
    setValueByPath(toObject, ["documentName"], fromDocumentName);
  }
  return toObject;
}
function videoFromMldev$1(fromObject) {
  const toObject = {};
  const fromUri = getValueByPath(fromObject, ["uri"]);
  if (fromUri != null) {
    setValueByPath(toObject, ["uri"], fromUri);
  }
  const fromVideoBytes = getValueByPath(fromObject, ["encodedVideo"]);
  if (fromVideoBytes != null) {
    setValueByPath(toObject, ["videoBytes"], tBytes$1(fromVideoBytes));
  }
  const fromMimeType = getValueByPath(fromObject, ["encoding"]);
  if (fromMimeType != null) {
    setValueByPath(toObject, ["mimeType"], fromMimeType);
  }
  return toObject;
}
function videoFromVertex$1(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$1(fromVideoBytes));
  }
  const fromMimeType = getValueByPath(fromObject, ["mimeType"]);
  if (fromMimeType != null) {
    setValueByPath(toObject, ["mimeType"], fromMimeType);
  }
  return toObject;
}
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 createModelContent(partOrString) {
  return {
    role: "model",
    parts: _toParts(partOrString)
  };
}
function tModel(apiClient, model) {
  if (!model || typeof model !== "string") {
    throw new Error("model is required and must be a string");
  }
  if (model.includes("..") || model.includes("?") || model.includes("&")) {
    throw new Error("invalid model parameter");
  }
  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 i3 of listWithoutNull) {
      resultingSchema["anyOf"].push({
        "type": Object.values(Type).includes(i3.toUpperCase()) ? i3.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 _a7;
  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 = (_a7 = fromName.video) === null || _a7 === void 0 ? void 0 : _a7.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, config2 = {}) {
  const mcpToolSchema = mcpTool;
  const functionDeclaration = {
    name: mcpToolSchema["name"],
    description: mcpToolSchema["description"],
    parametersJsonSchema: mcpToolSchema["inputSchema"]
  };
  if (mcpToolSchema["outputSchema"]) {
    functionDeclaration["responseJsonSchema"] = mcpToolSchema["outputSchema"];
  }
  if (config2.behavior) {
    functionDeclaration["behavior"] = config2.behavior;
  }
  const geminiTool = {
    functionDeclarations: [
      functionDeclaration
    ]
  };
  return geminiTool;
}
function mcpToolsToGeminiTool(mcpTools, config2 = {}) {
  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, config2);
    if (geminiTool.functionDeclarations) {
      functionDeclarations.push(...geminiTool.functionDeclarations);
    }
  }
  return { functionDeclarations };
}
function tBatchJobSource(client, src) {
  let sourceObj;
  if (typeof src === "string") {
    if (client.isVertexAI()) {
      if (src.startsWith("gs://")) {
        sourceObj = { format: "jsonl", gcsUri: [src] };
      } else if (src.startsWith("bq://")) {
        sourceObj = { format: "bigquery", bigqueryUri: src };
      } else {
        throw new Error(`Unsupported string source for Vertex AI: ${src}`);
      }
    } else {
      if (src.startsWith("files/")) {
        sourceObj = { fileName: src };
      } else {
        throw new Error(`Unsupported string source for Gemini API: ${src}`);
      }
    }
  } else if (Array.isArray(src)) {
    if (client.isVertexAI()) {
      throw new Error("InlinedRequest[] is not supported in Vertex AI.");
    }
    sourceObj = { inlinedRequests: src };
  } else {
    sourceObj = src;
  }
  const vertexSourcesCount = [sourceObj.gcsUri, sourceObj.bigqueryUri].filter(Boolean).length;
  const mldevSourcesCount = [
    sourceObj.inlinedRequests,
    sourceObj.fileName
  ].filter(Boolean).length;
  if (client.isVertexAI()) {
    if (mldevSourcesCount > 0 || vertexSourcesCount !== 1) {
      throw new Error("Exactly one of `gcsUri` or `bigqueryUri` must be set for Vertex AI.");
    }
  } else {
    if (vertexSourcesCount > 0 || mldevSourcesCount !== 1) {
      throw new Error("Exactly one of `inlinedRequests`, `fileName`, must be set for Gemini API.");
    }
  }
  return sourceObj;
}
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 tRecvBatchJobDestination(dest) {
  if (typeof dest !== "object" || dest === null) {
    return {};
  }
  const obj = dest;
  const inlineResponsesVal = obj["inlinedResponses"];
  if (typeof inlineResponsesVal !== "object" || inlineResponsesVal === null) {
    return dest;
  }
  const inlineResponsesObj = inlineResponsesVal;
  const responsesArray = inlineResponsesObj["inlinedResponses"];
  if (!Array.isArray(responsesArray) || responsesArray.length === 0) {
    return dest;
  }
  let hasEmbedding = false;
  for (const responseItem of responsesArray) {
    if (typeof responseItem !== "object" || responseItem === null) {
      continue;
    }
    const responseItemObj = responseItem;
    const responseVal = responseItemObj["response"];
    if (typeof responseVal !== "object" || responseVal === null) {
      continue;
    }
    const responseObj = responseVal;
    if (responseObj["embedding"] !== void 0) {
      hasEmbedding = true;
      break;
    }
  }
  if (hasEmbedding) {
    obj["inlinedEmbedContentResponses"] = obj["inlinedResponses"];
    delete obj["inlinedResponses"];
  }
  return dest;
}
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_RUNNING") {
    return "JOB_STATE_RUNNING";
  } 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 if (stateString === "BATCH_STATE_EXPIRED") {
    return "JOB_STATE_EXPIRED";
  } else {
    return stateString;
  }
}
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);
  }
  const fromInlinedEmbedContentResponses = getValueByPath(fromObject, [
    "inlinedEmbedContentResponses",
    "inlinedResponses"
  ]);
  if (fromInlinedEmbedContentResponses != null) {
    let transformedList = fromInlinedEmbedContentResponses;
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return item;
      });
    }
    setValueByPath(toObject, ["inlinedEmbedContentResponses"], transformedList);
  }
  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 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.");
  }
  if (getValueByPath(fromObject, ["inlinedEmbedContentResponses"]) !== void 0) {
    throw new Error("inlinedEmbedContentResponses parameter is not supported in Vertex AI.");
  }
  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(tRecvBatchJobDestination(fromDest)));
  }
  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"], 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(tRecvBatchJobDestination(fromDest)));
  }
  const fromCompletionStats = getValueByPath(fromObject, [
    "completionStats"
  ]);
  if (fromCompletionStats != null) {
    setValueByPath(toObject, ["completionStats"], fromCompletionStats);
  }
  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 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 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 blobToMldev$4(fromObject) {
  const toObject = {};
  const fromData = getValueByPath(fromObject, ["data"]);
  if (fromData != null) {
    setValueByPath(toObject, ["data"], fromData);
  }
  if (getValueByPath(fromObject, ["displayName"]) !== void 0) {
    throw new Error("displayName parameter is not supported in Gemini API.");
  }
  const fromMimeType = getValueByPath(fromObject, ["mimeType"]);
  if (fromMimeType != null) {
    setValueByPath(toObject, ["mimeType"], fromMimeType);
  }
  return toObject;
}
function cancelBatchJobParametersToMldev(apiClient, fromObject) {
  const toObject = {};
  const fromName = getValueByPath(fromObject, ["name"]);
  if (fromName != null) {
    setValueByPath(toObject, ["_url", "name"], tBatchJobName(apiClient, fromName));
  }
  return toObject;
}
function cancelBatchJobParametersToVertex(apiClient, fromObject) {
  const toObject = {};
  const fromName = getValueByPath(fromObject, ["name"]);
  if (fromName != null) {
    setValueByPath(toObject, ["_url", "name"], tBatchJobName(apiClient, fromName));
  }
  return toObject;
}
function candidateFromMldev$1(fromObject) {
  const toObject = {};
  const fromContent = getValueByPath(fromObject, ["content"]);
  if (fromContent != null) {
    setValueByPath(toObject, ["content"], 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 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) {
    let transformedList = fromSafetyRatings;
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return item;
      });
    }
    setValueByPath(toObject, ["safetyRatings"], transformedList);
  }
  const fromUrlContextMetadata = getValueByPath(fromObject, [
    "urlContextMetadata"
  ]);
  if (fromUrlContextMetadata != null) {
    setValueByPath(toObject, ["urlContextMetadata"], fromUrlContextMetadata);
  }
  return toObject;
}
function citationMetadataFromMldev$1(fromObject) {
  const toObject = {};
  const fromCitations = getValueByPath(fromObject, ["citationSources"]);
  if (fromCitations != null) {
    let transformedList = fromCitations;
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return item;
      });
    }
    setValueByPath(toObject, ["citations"], transformedList);
  }
  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 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 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 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) {
    createBatchJobConfigToMldev(fromConfig, toObject);
  }
  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) {
    createBatchJobConfigToVertex(fromConfig, toObject);
  }
  return toObject;
}
function createEmbeddingsBatchJobConfigToMldev(fromObject, parentObject) {
  const toObject = {};
  const fromDisplayName = getValueByPath(fromObject, ["displayName"]);
  if (parentObject !== void 0 && fromDisplayName != null) {
    setValueByPath(parentObject, ["batch", "displayName"], fromDisplayName);
  }
  return toObject;
}
function createEmbeddingsBatchJobParametersToMldev(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"], embeddingsBatchJobSourceToMldev(apiClient, fromSrc));
  }
  const fromConfig = getValueByPath(fromObject, ["config"]);
  if (fromConfig != null) {
    createEmbeddingsBatchJobConfigToMldev(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));
  }
  return toObject;
}
function deleteBatchJobParametersToVertex(apiClient, fromObject) {
  const toObject = {};
  const fromName = getValueByPath(fromObject, ["name"]);
  if (fromName != null) {
    setValueByPath(toObject, ["_url", "name"], tBatchJobName(apiClient, fromName));
  }
  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"], fromError);
  }
  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"], fromError);
  }
  return toObject;
}
function embedContentBatchToMldev(apiClient, fromObject) {
  const toObject = {};
  const fromContents = getValueByPath(fromObject, ["contents"]);
  if (fromContents != null) {
    let transformedList = tContentsForEmbed(apiClient, fromContents);
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return item;
      });
    }
    setValueByPath(toObject, ["requests[]", "request", "content"], transformedList);
  }
  const fromConfig = getValueByPath(fromObject, ["config"]);
  if (fromConfig != null) {
    setValueByPath(toObject, ["_self"], embedContentConfigToMldev$1(fromConfig, toObject));
    moveValueByPath(toObject, { "requests[].*": "requests[].request.*" });
  }
  return toObject;
}
function embedContentConfigToMldev$1(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 embeddingsBatchJobSourceToMldev(apiClient, fromObject) {
  const toObject = {};
  const fromFileName = getValueByPath(fromObject, ["fileName"]);
  if (fromFileName != null) {
    setValueByPath(toObject, ["file_name"], fromFileName);
  }
  const fromInlinedRequests = getValueByPath(fromObject, [
    "inlinedRequests"
  ]);
  if (fromInlinedRequests != null) {
    setValueByPath(toObject, ["requests"], embedContentBatchToMldev(apiClient, fromInlinedRequests));
  }
  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 functionCallToMldev$4(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);
  }
  if (getValueByPath(fromObject, ["partialArgs"]) !== void 0) {
    throw new Error("partialArgs parameter is not supported in Gemini API.");
  }
  if (getValueByPath(fromObject, ["willContinue"]) !== void 0) {
    throw new Error("willContinue parameter is not supported in Gemini API.");
  }
  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);
  }
  if (getValueByPath(fromObject, ["streamFunctionCallArguments"]) !== void 0) {
    throw new Error("streamFunctionCallArguments parameter is not supported in Gemini API.");
  }
  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"], 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"], 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"], fromThinkingConfig);
  }
  const fromImageConfig = getValueByPath(fromObject, ["imageConfig"]);
  if (fromImageConfig != null) {
    setValueByPath(toObject, ["imageConfig"], imageConfigToMldev$1(fromImageConfig));
  }
  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 getBatchJobParametersToMldev(apiClient, fromObject) {
  const toObject = {};
  const fromName = getValueByPath(fromObject, ["name"]);
  if (fromName != null) {
    setValueByPath(toObject, ["_url", "name"], tBatchJobName(apiClient, fromName));
  }
  return toObject;
}
function getBatchJobParametersToVertex(apiClient, fromObject) {
  const toObject = {};
  const fromName = getValueByPath(fromObject, ["name"]);
  if (fromName != null) {
    setValueByPath(toObject, ["_url", "name"], tBatchJobName(apiClient, fromName));
  }
  return toObject;
}
function googleMapsToMldev$4(fromObject) {
  const toObject = {};
  if (getValueByPath(fromObject, ["authConfig"]) !== void 0) {
    throw new Error("authConfig parameter is not supported in Gemini API.");
  }
  const fromEnableWidget = getValueByPath(fromObject, ["enableWidget"]);
  if (fromEnableWidget != null) {
    setValueByPath(toObject, ["enableWidget"], fromEnableWidget);
  }
  return toObject;
}
function googleSearchToMldev$4(fromObject) {
  const toObject = {};
  if (getValueByPath(fromObject, ["excludeDomains"]) !== void 0) {
    throw new Error("excludeDomains parameter is not supported in Gemini API.");
  }
  if (getValueByPath(fromObject, ["blockingConfidence"]) !== void 0) {
    throw new Error("blockingConfidence parameter is not supported in Gemini API.");
  }
  const fromTimeRangeFilter = getValueByPath(fromObject, [
    "timeRangeFilter"
  ]);
  if (fromTimeRangeFilter != null) {
    setValueByPath(toObject, ["timeRangeFilter"], fromTimeRangeFilter);
  }
  return toObject;
}
function imageConfigToMldev$1(fromObject) {
  const toObject = {};
  const fromAspectRatio = getValueByPath(fromObject, ["aspectRatio"]);
  if (fromAspectRatio != null) {
    setValueByPath(toObject, ["aspectRatio"], fromAspectRatio);
  }
  const fromImageSize = getValueByPath(fromObject, ["imageSize"]);
  if (fromImageSize != null) {
    setValueByPath(toObject, ["imageSize"], fromImageSize);
  }
  if (getValueByPath(fromObject, ["outputMimeType"]) !== void 0) {
    throw new Error("outputMimeType parameter is not supported in Gemini API.");
  }
  if (getValueByPath(fromObject, ["outputCompressionQuality"]) !== void 0) {
    throw new Error("outputCompressionQuality parameter is not supported in Gemini API.");
  }
  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 fromMetadata = getValueByPath(fromObject, ["metadata"]);
  if (fromMetadata != null) {
    setValueByPath(toObject, ["metadata"], fromMetadata);
  }
  const fromConfig = getValueByPath(fromObject, ["config"]);
  if (fromConfig != null) {
    setValueByPath(toObject, ["request", "generationConfig"], generateContentConfigToMldev$1(apiClient, fromConfig, getValueByPath(toObject, ["request"], {})));
  }
  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"], fromError);
  }
  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 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 listBatchJobsParametersToMldev(fromObject) {
  const toObject = {};
  const fromConfig = getValueByPath(fromObject, ["config"]);
  if (fromConfig != null) {
    listBatchJobsConfigToMldev(fromConfig, toObject);
  }
  return toObject;
}
function listBatchJobsParametersToVertex(fromObject) {
  const toObject = {};
  const fromConfig = getValueByPath(fromObject, ["config"]);
  if (fromConfig != null) {
    listBatchJobsConfigToVertex(fromConfig, toObject);
  }
  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 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 partToMldev$4(fromObject) {
  const toObject = {};
  const fromMediaResolution = getValueByPath(fromObject, [
    "mediaResolution"
  ]);
  if (fromMediaResolution != null) {
    setValueByPath(toObject, ["mediaResolution"], fromMediaResolution);
  }
  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 fromFileData = getValueByPath(fromObject, ["fileData"]);
  if (fromFileData != null) {
    setValueByPath(toObject, ["fileData"], fileDataToMldev$4(fromFileData));
  }
  const fromFunctionCall = getValueByPath(fromObject, ["functionCall"]);
  if (fromFunctionCall != null) {
    setValueByPath(toObject, ["functionCall"], functionCallToMldev$4(fromFunctionCall));
  }
  const fromFunctionResponse = getValueByPath(fromObject, [
    "functionResponse"
  ]);
  if (fromFunctionResponse != null) {
    setValueByPath(toObject, ["functionResponse"], fromFunctionResponse);
  }
  const fromInlineData = getValueByPath(fromObject, ["inlineData"]);
  if (fromInlineData != null) {
    setValueByPath(toObject, ["inlineData"], blobToMldev$4(fromInlineData));
  }
  const fromText = getValueByPath(fromObject, ["text"]);
  if (fromText != null) {
    setValueByPath(toObject, ["text"], fromText);
  }
  const fromThought = getValueByPath(fromObject, ["thought"]);
  if (fromThought != null) {
    setValueByPath(toObject, ["thought"], fromThought);
  }
  const fromThoughtSignature = getValueByPath(fromObject, [
    "thoughtSignature"
  ]);
  if (fromThoughtSignature != null) {
    setValueByPath(toObject, ["thoughtSignature"], fromThoughtSignature);
  }
  const fromVideoMetadata = getValueByPath(fromObject, [
    "videoMetadata"
  ]);
  if (fromVideoMetadata != null) {
    setValueByPath(toObject, ["videoMetadata"], fromVideoMetadata);
  }
  return toObject;
}
function safetySettingToMldev$1(fromObject) {
  const toObject = {};
  const fromCategory = getValueByPath(fromObject, ["category"]);
  if (fromCategory != null) {
    setValueByPath(toObject, ["category"], fromCategory);
  }
  if (getValueByPath(fromObject, ["method"]) !== void 0) {
    throw new Error("method parameter is not supported in Gemini API.");
  }
  const fromThreshold = getValueByPath(fromObject, ["threshold"]);
  if (fromThreshold != null) {
    setValueByPath(toObject, ["threshold"], fromThreshold);
  }
  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"], fromRetrievalConfig);
  }
  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 item;
      });
    }
    setValueByPath(toObject, ["functionDeclarations"], transformedList);
  }
  if (getValueByPath(fromObject, ["retrieval"]) !== void 0) {
    throw new Error("retrieval parameter is not supported in Gemini API.");
  }
  const fromGoogleSearchRetrieval = getValueByPath(fromObject, [
    "googleSearchRetrieval"
  ]);
  if (fromGoogleSearchRetrieval != null) {
    setValueByPath(toObject, ["googleSearchRetrieval"], fromGoogleSearchRetrieval);
  }
  const fromComputerUse = getValueByPath(fromObject, ["computerUse"]);
  if (fromComputerUse != null) {
    setValueByPath(toObject, ["computerUse"], fromComputerUse);
  }
  const fromFileSearch = getValueByPath(fromObject, ["fileSearch"]);
  if (fromFileSearch != null) {
    setValueByPath(toObject, ["fileSearch"], fromFileSearch);
  }
  const fromCodeExecution = getValueByPath(fromObject, [
    "codeExecution"
  ]);
  if (fromCodeExecution != null) {
    setValueByPath(toObject, ["codeExecution"], fromCodeExecution);
  }
  if (getValueByPath(fromObject, ["enterpriseWebSearch"]) !== void 0) {
    throw new Error("enterpriseWebSearch parameter is not supported in Gemini API.");
  }
  const fromGoogleMaps = getValueByPath(fromObject, ["googleMaps"]);
  if (fromGoogleMaps != null) {
    setValueByPath(toObject, ["googleMaps"], googleMapsToMldev$4(fromGoogleMaps));
  }
  const fromGoogleSearch = getValueByPath(fromObject, ["googleSearch"]);
  if (fromGoogleSearch != null) {
    setValueByPath(toObject, ["googleSearch"], googleSearchToMldev$4(fromGoogleSearch));
  }
  const fromUrlContext = getValueByPath(fromObject, ["urlContext"]);
  if (fromUrlContext != null) {
    setValueByPath(toObject, ["urlContext"], fromUrlContext);
  }
  return toObject;
}
function blobToMldev$3(fromObject) {
  const toObject = {};
  const fromData = getValueByPath(fromObject, ["data"]);
  if (fromData != null) {
    setValueByPath(toObject, ["data"], fromData);
  }
  if (getValueByPath(fromObject, ["displayName"]) !== void 0) {
    throw new Error("displayName parameter is not supported in Gemini API.");
  }
  const fromMimeType = getValueByPath(fromObject, ["mimeType"]);
  if (fromMimeType != null) {
    setValueByPath(toObject, ["mimeType"], fromMimeType);
  }
  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 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 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 item;
      });
    }
    setValueByPath(parentObject, ["contents"], transformedList);
  }
  const fromSystemInstruction = getValueByPath(fromObject, [
    "systemInstruction"
  ]);
  if (parentObject !== void 0 && fromSystemInstruction != null) {
    setValueByPath(parentObject, ["systemInstruction"], 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"], fromToolConfig);
  }
  const fromKmsKeyName = getValueByPath(fromObject, ["kmsKeyName"]);
  if (parentObject !== void 0 && fromKmsKeyName != null) {
    setValueByPath(parentObject, ["encryption_spec", "kmsKeyName"], fromKmsKeyName);
  }
  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) {
    createCachedContentConfigToMldev(fromConfig, toObject);
  }
  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) {
    createCachedContentConfigToVertex(fromConfig, toObject);
  }
  return toObject;
}
function deleteCachedContentParametersToMldev(apiClient, fromObject) {
  const toObject = {};
  const fromName = getValueByPath(fromObject, ["name"]);
  if (fromName != null) {
    setValueByPath(toObject, ["_url", "name"], tCachedContentName(apiClient, fromName));
  }
  return toObject;
}
function deleteCachedContentParametersToVertex(apiClient, fromObject) {
  const toObject = {};
  const fromName = getValueByPath(fromObject, ["name"]);
  if (fromName != null) {
    setValueByPath(toObject, ["_url", "name"], tCachedContentName(apiClient, fromName));
  }
  return toObject;
}
function deleteCachedContentResponseFromMldev(fromObject) {
  const toObject = {};
  const fromSdkHttpResponse = getValueByPath(fromObject, [
    "sdkHttpResponse"
  ]);
  if (fromSdkHttpResponse != null) {
    setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse);
  }
  return toObject;
}
function deleteCachedContentResponseFromVertex(fromObject) {
  const toObject = {};
  const fromSdkHttpResponse = getValueByPath(fromObject, [
    "sdkHttpResponse"
  ]);
  if (fromSdkHttpResponse != null) {
    setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse);
  }
  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 functionCallToMldev$3(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);
  }
  if (getValueByPath(fromObject, ["partialArgs"]) !== void 0) {
    throw new Error("partialArgs parameter is not supported in Gemini API.");
  }
  if (getValueByPath(fromObject, ["willContinue"]) !== void 0) {
    throw new Error("willContinue parameter is not supported in Gemini API.");
  }
  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);
  }
  if (getValueByPath(fromObject, ["streamFunctionCallArguments"]) !== void 0) {
    throw new Error("streamFunctionCallArguments parameter is not supported in Gemini API.");
  }
  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 getCachedContentParametersToMldev(apiClient, fromObject) {
  const toObject = {};
  const fromName = getValueByPath(fromObject, ["name"]);
  if (fromName != null) {
    setValueByPath(toObject, ["_url", "name"], tCachedContentName(apiClient, fromName));
  }
  return toObject;
}
function getCachedContentParametersToVertex(apiClient, fromObject) {
  const toObject = {};
  const fromName = getValueByPath(fromObject, ["name"]);
  if (fromName != null) {
    setValueByPath(toObject, ["_url", "name"], tCachedContentName(apiClient, fromName));
  }
  return toObject;
}
function googleMapsToMldev$3(fromObject) {
  const toObject = {};
  if (getValueByPath(fromObject, ["authConfig"]) !== void 0) {
    throw new Error("authConfig parameter is not supported in Gemini API.");
  }
  const fromEnableWidget = getValueByPath(fromObject, ["enableWidget"]);
  if (fromEnableWidget != null) {
    setValueByPath(toObject, ["enableWidget"], fromEnableWidget);
  }
  return toObject;
}
function googleSearchToMldev$3(fromObject) {
  const toObject = {};
  if (getValueByPath(fromObject, ["excludeDomains"]) !== void 0) {
    throw new Error("excludeDomains parameter is not supported in Gemini API.");
  }
  if (getValueByPath(fromObject, ["blockingConfidence"]) !== void 0) {
    throw new Error("blockingConfidence parameter is not supported in Gemini API.");
  }
  const fromTimeRangeFilter = getValueByPath(fromObject, [
    "timeRangeFilter"
  ]);
  if (fromTimeRangeFilter != null) {
    setValueByPath(toObject, ["timeRangeFilter"], fromTimeRangeFilter);
  }
  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 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 listCachedContentsParametersToMldev(fromObject) {
  const toObject = {};
  const fromConfig = getValueByPath(fromObject, ["config"]);
  if (fromConfig != null) {
    listCachedContentsConfigToMldev(fromConfig, toObject);
  }
  return toObject;
}
function listCachedContentsParametersToVertex(fromObject) {
  const toObject = {};
  const fromConfig = getValueByPath(fromObject, ["config"]);
  if (fromConfig != null) {
    listCachedContentsConfigToVertex(fromConfig, toObject);
  }
  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 item;
      });
    }
    setValueByPath(toObject, ["cachedContents"], transformedList);
  }
  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 item;
      });
    }
    setValueByPath(toObject, ["cachedContents"], transformedList);
  }
  return toObject;
}
function partToMldev$3(fromObject) {
  const toObject = {};
  const fromMediaResolution = getValueByPath(fromObject, [
    "mediaResolution"
  ]);
  if (fromMediaResolution != null) {
    setValueByPath(toObject, ["mediaResolution"], fromMediaResolution);
  }
  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 fromFileData = getValueByPath(fromObject, ["fileData"]);
  if (fromFileData != null) {
    setValueByPath(toObject, ["fileData"], fileDataToMldev$3(fromFileData));
  }
  const fromFunctionCall = getValueByPath(fromObject, ["functionCall"]);
  if (fromFunctionCall != null) {
    setValueByPath(toObject, ["functionCall"], functionCallToMldev$3(fromFunctionCall));
  }
  const fromFunctionResponse = getValueByPath(fromObject, [
    "functionResponse"
  ]);
  if (fromFunctionResponse != null) {
    setValueByPath(toObject, ["functionResponse"], fromFunctionResponse);
  }
  const fromInlineData = getValueByPath(fromObject, ["inlineData"]);
  if (fromInlineData != null) {
    setValueByPath(toObject, ["inlineData"], blobToMldev$3(fromInlineData));
  }
  const fromText = getValueByPath(fromObject, ["text"]);
  if (fromText != null) {
    setValueByPath(toObject, ["text"], fromText);
  }
  const fromThought = getValueByPath(fromObject, ["thought"]);
  if (fromThought != null) {
    setValueByPath(toObject, ["thought"], fromThought);
  }
  const fromThoughtSignature = getValueByPath(fromObject, [
    "thoughtSignature"
  ]);
  if (fromThoughtSignature != null) {
    setValueByPath(toObject, ["thoughtSignature"], fromThoughtSignature);
  }
  const fromVideoMetadata = getValueByPath(fromObject, [
    "videoMetadata"
  ]);
  if (fromVideoMetadata != null) {
    setValueByPath(toObject, ["videoMetadata"], fromVideoMetadata);
  }
  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"], fromRetrievalConfig);
  }
  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 item;
      });
    }
    setValueByPath(toObject, ["functionDeclarations"], transformedList);
  }
  if (getValueByPath(fromObject, ["retrieval"]) !== void 0) {
    throw new Error("retrieval parameter is not supported in Gemini API.");
  }
  const fromGoogleSearchRetrieval = getValueByPath(fromObject, [
    "googleSearchRetrieval"
  ]);
  if (fromGoogleSearchRetrieval != null) {
    setValueByPath(toObject, ["googleSearchRetrieval"], fromGoogleSearchRetrieval);
  }
  const fromComputerUse = getValueByPath(fromObject, ["computerUse"]);
  if (fromComputerUse != null) {
    setValueByPath(toObject, ["computerUse"], fromComputerUse);
  }
  const fromFileSearch = getValueByPath(fromObject, ["fileSearch"]);
  if (fromFileSearch != null) {
    setValueByPath(toObject, ["fileSearch"], fromFileSearch);
  }
  const fromCodeExecution = getValueByPath(fromObject, [
    "codeExecution"
  ]);
  if (fromCodeExecution != null) {
    setValueByPath(toObject, ["codeExecution"], fromCodeExecution);
  }
  if (getValueByPath(fromObject, ["enterpriseWebSearch"]) !== void 0) {
    throw new Error("enterpriseWebSearch parameter is not supported in Gemini API.");
  }
  const fromGoogleMaps = getValueByPath(fromObject, ["googleMaps"]);
  if (fromGoogleMaps != null) {
    setValueByPath(toObject, ["googleMaps"], googleMapsToMldev$3(fromGoogleMaps));
  }
  const fromGoogleSearch = getValueByPath(fromObject, ["googleSearch"]);
  if (fromGoogleSearch != null) {
    setValueByPath(toObject, ["googleSearch"], googleSearchToMldev$3(fromGoogleSearch));
  }
  const fromUrlContext = getValueByPath(fromObject, ["urlContext"]);
  if (fromUrlContext != null) {
    setValueByPath(toObject, ["urlContext"], fromUrlContext);
  }
  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 fromGoogleSearchRetrieval = getValueByPath(fromObject, [
    "googleSearchRetrieval"
  ]);
  if (fromGoogleSearchRetrieval != null) {
    setValueByPath(toObject, ["googleSearchRetrieval"], fromGoogleSearchRetrieval);
  }
  const fromComputerUse = getValueByPath(fromObject, ["computerUse"]);
  if (fromComputerUse != null) {
    setValueByPath(toObject, ["computerUse"], fromComputerUse);
  }
  if (getValueByPath(fromObject, ["fileSearch"]) !== void 0) {
    throw new Error("fileSearch parameter is not supported in Vertex AI.");
  }
  const fromCodeExecution = getValueByPath(fromObject, [
    "codeExecution"
  ]);
  if (fromCodeExecution != null) {
    setValueByPath(toObject, ["codeExecution"], fromCodeExecution);
  }
  const fromEnterpriseWebSearch = getValueByPath(fromObject, [
    "enterpriseWebSearch"
  ]);
  if (fromEnterpriseWebSearch != null) {
    setValueByPath(toObject, ["enterpriseWebSearch"], fromEnterpriseWebSearch);
  }
  const fromGoogleMaps = getValueByPath(fromObject, ["googleMaps"]);
  if (fromGoogleMaps != null) {
    setValueByPath(toObject, ["googleMaps"], fromGoogleMaps);
  }
  const fromGoogleSearch = getValueByPath(fromObject, ["googleSearch"]);
  if (fromGoogleSearch != null) {
    setValueByPath(toObject, ["googleSearch"], fromGoogleSearch);
  }
  const fromUrlContext = getValueByPath(fromObject, ["urlContext"]);
  if (fromUrlContext != null) {
    setValueByPath(toObject, ["urlContext"], fromUrlContext);
  }
  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 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 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) {
    updateCachedContentConfigToMldev(fromConfig, toObject);
  }
  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) {
    updateCachedContentConfigToVertex(fromConfig, toObject);
  }
  return toObject;
}
function __values(o3) {
  var s5 = typeof Symbol === "function" && Symbol.iterator, m3 = s5 && o3[s5], i3 = 0;
  if (m3) return m3.call(o3);
  if (o3 && typeof o3.length === "number") return {
    next: /* @__PURE__ */ __name(function() {
      if (o3 && i3 >= o3.length) o3 = void 0;
      return { value: o3 && o3[i3++], done: !o3 };
    }, "next")
  };
  throw new TypeError(s5 ? "Object is not iterable." : "Symbol.iterator is not defined.");
}
function __await(v2) {
  return this instanceof __await ? (this.v = v2, this) : new __await(v2);
}
function __asyncGenerator(thisArg, _arguments, generator) {
  if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
  var g2 = generator.apply(thisArg, _arguments || []), i3, q2 = [];
  return i3 = Object.create((typeof AsyncIterator === "function" ? AsyncIterator : Object).prototype), verb("next"), verb("throw"), verb("return", awaitReturn), i3[Symbol.asyncIterator] = function() {
    return this;
  }, i3;
  function awaitReturn(f5) {
    return function(v2) {
      return Promise.resolve(v2).then(f5, reject);
    };
  }
  __name(awaitReturn, "awaitReturn");
  function verb(n3, f5) {
    if (g2[n3]) {
      i3[n3] = function(v2) {
        return new Promise(function(a2, b2) {
          q2.push([n3, v2, a2, b2]) > 1 || resume(n3, v2);
        });
      };
      if (f5) i3[n3] = f5(i3[n3]);
    }
  }
  __name(verb, "verb");
  function resume(n3, v2) {
    try {
      step(g2[n3](v2));
    } catch (e4) {
      settle(q2[0][3], e4);
    }
  }
  __name(resume, "resume");
  function step(r5) {
    r5.value instanceof __await ? Promise.resolve(r5.value.v).then(fulfill, reject) : settle(q2[0][2], r5);
  }
  __name(step, "step");
  function fulfill(value) {
    resume("next", value);
  }
  __name(fulfill, "fulfill");
  function reject(value) {
    resume("throw", value);
  }
  __name(reject, "reject");
  function settle(f5, v2) {
    if (f5(v2), q2.shift(), q2.length) resume(q2[0][0], q2[0][1]);
  }
  __name(settle, "settle");
}
function __asyncValues(o3) {
  if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
  var m3 = o3[Symbol.asyncIterator], i3;
  return m3 ? m3.call(o3) : (o3 = typeof __values === "function" ? __values(o3) : o3[Symbol.iterator](), i3 = {}, verb("next"), verb("throw"), verb("return"), i3[Symbol.asyncIterator] = function() {
    return this;
  }, i3);
  function verb(n3) {
    i3[n3] = o3[n3] && function(v2) {
      return new Promise(function(resolve30, reject) {
        v2 = o3[n3](v2), settle(resolve30, reject, v2.done, v2.value);
      });
    };
  }
  __name(verb, "verb");
  function settle(resolve30, reject, d2, v2) {
    Promise.resolve(v2).then(function(v3) {
      resolve30({ value: v3, done: d2 });
    }, reject);
  }
  __name(settle, "settle");
}
function isValidResponse(response) {
  var _a7;
  if (response.candidates == void 0 || response.candidates.length === 0) {
    return false;
  }
  const content = (_a7 = response.candidates[0]) === null || _a7 === void 0 ? void 0 : _a7.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 i3 = 0;
  while (i3 < length) {
    if (comprehensiveHistory[i3].role === "user") {
      curatedHistory.push(comprehensiveHistory[i3]);
      i3++;
    } else {
      const modelOutput = [];
      let isValid2 = true;
      while (i3 < length && comprehensiveHistory[i3].role === "model") {
        modelOutput.push(comprehensiveHistory[i3]);
        if (isValid2 && !isValidContent(comprehensiveHistory[i3])) {
          isValid2 = false;
        }
        i3++;
      }
      if (isValid2) {
        curatedHistory.push(...modelOutput);
      } else {
        curatedHistory.pop();
      }
    }
  }
  return curatedHistory;
}
function createFileParametersToMldev(fromObject) {
  const toObject = {};
  const fromFile2 = getValueByPath(fromObject, ["file"]);
  if (fromFile2 != null) {
    setValueByPath(toObject, ["file"], fromFile2);
  }
  return toObject;
}
function createFileResponseFromMldev(fromObject) {
  const toObject = {};
  const fromSdkHttpResponse = getValueByPath(fromObject, [
    "sdkHttpResponse"
  ]);
  if (fromSdkHttpResponse != null) {
    setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse);
  }
  return toObject;
}
function deleteFileParametersToMldev(fromObject) {
  const toObject = {};
  const fromName = getValueByPath(fromObject, ["name"]);
  if (fromName != null) {
    setValueByPath(toObject, ["_url", "file"], tFileName(fromName));
  }
  return toObject;
}
function deleteFileResponseFromMldev(fromObject) {
  const toObject = {};
  const fromSdkHttpResponse = getValueByPath(fromObject, [
    "sdkHttpResponse"
  ]);
  if (fromSdkHttpResponse != null) {
    setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse);
  }
  return toObject;
}
function getFileParametersToMldev(fromObject) {
  const toObject = {};
  const fromName = getValueByPath(fromObject, ["name"]);
  if (fromName != null) {
    setValueByPath(toObject, ["_url", "file"], tFileName(fromName));
  }
  return toObject;
}
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) {
    listFilesConfigToMldev(fromConfig, toObject);
  }
  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 item;
      });
    }
    setValueByPath(toObject, ["files"], transformedList);
  }
  return toObject;
}
function blobToMldev$2(fromObject) {
  const toObject = {};
  const fromData = getValueByPath(fromObject, ["data"]);
  if (fromData != null) {
    setValueByPath(toObject, ["data"], fromData);
  }
  if (getValueByPath(fromObject, ["displayName"]) !== void 0) {
    throw new Error("displayName parameter is not supported in Gemini API.");
  }
  const fromMimeType = getValueByPath(fromObject, ["mimeType"]);
  if (fromMimeType != null) {
    setValueByPath(toObject, ["mimeType"], fromMimeType);
  }
  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 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 functionCallToMldev$2(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);
  }
  if (getValueByPath(fromObject, ["partialArgs"]) !== void 0) {
    throw new Error("partialArgs parameter is not supported in Gemini API.");
  }
  if (getValueByPath(fromObject, ["willContinue"]) !== void 0) {
    throw new Error("willContinue parameter is not supported in Gemini API.");
  }
  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 generationConfigToVertex$1(fromObject) {
  const toObject = {};
  const fromModelSelectionConfig = getValueByPath(fromObject, [
    "modelSelectionConfig"
  ]);
  if (fromModelSelectionConfig != null) {
    setValueByPath(toObject, ["modelConfig"], fromModelSelectionConfig);
  }
  const fromResponseJsonSchema = getValueByPath(fromObject, [
    "responseJsonSchema"
  ]);
  if (fromResponseJsonSchema != null) {
    setValueByPath(toObject, ["responseJsonSchema"], fromResponseJsonSchema);
  }
  const fromAudioTimestamp = getValueByPath(fromObject, [
    "audioTimestamp"
  ]);
  if (fromAudioTimestamp != null) {
    setValueByPath(toObject, ["audioTimestamp"], fromAudioTimestamp);
  }
  const fromCandidateCount = getValueByPath(fromObject, [
    "candidateCount"
  ]);
  if (fromCandidateCount != null) {
    setValueByPath(toObject, ["candidateCount"], fromCandidateCount);
  }
  const fromEnableAffectiveDialog = getValueByPath(fromObject, [
    "enableAffectiveDialog"
  ]);
  if (fromEnableAffectiveDialog != null) {
    setValueByPath(toObject, ["enableAffectiveDialog"], fromEnableAffectiveDialog);
  }
  const fromFrequencyPenalty = getValueByPath(fromObject, [
    "frequencyPenalty"
  ]);
  if (fromFrequencyPenalty != null) {
    setValueByPath(toObject, ["frequencyPenalty"], fromFrequencyPenalty);
  }
  const fromLogprobs = getValueByPath(fromObject, ["logprobs"]);
  if (fromLogprobs != null) {
    setValueByPath(toObject, ["logprobs"], fromLogprobs);
  }
  const fromMaxOutputTokens = getValueByPath(fromObject, [
    "maxOutputTokens"
  ]);
  if (fromMaxOutputTokens != null) {
    setValueByPath(toObject, ["maxOutputTokens"], fromMaxOutputTokens);
  }
  const fromMediaResolution = getValueByPath(fromObject, [
    "mediaResolution"
  ]);
  if (fromMediaResolution != null) {
    setValueByPath(toObject, ["mediaResolution"], fromMediaResolution);
  }
  const fromPresencePenalty = getValueByPath(fromObject, [
    "presencePenalty"
  ]);
  if (fromPresencePenalty != null) {
    setValueByPath(toObject, ["presencePenalty"], fromPresencePenalty);
  }
  const fromResponseLogprobs = getValueByPath(fromObject, [
    "responseLogprobs"
  ]);
  if (fromResponseLogprobs != null) {
    setValueByPath(toObject, ["responseLogprobs"], fromResponseLogprobs);
  }
  const fromResponseMimeType = getValueByPath(fromObject, [
    "responseMimeType"
  ]);
  if (fromResponseMimeType != null) {
    setValueByPath(toObject, ["responseMimeType"], fromResponseMimeType);
  }
  const fromResponseModalities = getValueByPath(fromObject, [
    "responseModalities"
  ]);
  if (fromResponseModalities != null) {
    setValueByPath(toObject, ["responseModalities"], fromResponseModalities);
  }
  const fromResponseSchema = getValueByPath(fromObject, [
    "responseSchema"
  ]);
  if (fromResponseSchema != null) {
    setValueByPath(toObject, ["responseSchema"], fromResponseSchema);
  }
  const fromRoutingConfig = getValueByPath(fromObject, [
    "routingConfig"
  ]);
  if (fromRoutingConfig != null) {
    setValueByPath(toObject, ["routingConfig"], fromRoutingConfig);
  }
  const fromSeed = getValueByPath(fromObject, ["seed"]);
  if (fromSeed != null) {
    setValueByPath(toObject, ["seed"], fromSeed);
  }
  const fromSpeechConfig = getValueByPath(fromObject, ["speechConfig"]);
  if (fromSpeechConfig != null) {
    setValueByPath(toObject, ["speechConfig"], speechConfigToVertex$1(fromSpeechConfig));
  }
  const fromStopSequences = getValueByPath(fromObject, [
    "stopSequences"
  ]);
  if (fromStopSequences != null) {
    setValueByPath(toObject, ["stopSequences"], fromStopSequences);
  }
  const fromTemperature = getValueByPath(fromObject, ["temperature"]);
  if (fromTemperature != null) {
    setValueByPath(toObject, ["temperature"], fromTemperature);
  }
  const fromThinkingConfig = getValueByPath(fromObject, [
    "thinkingConfig"
  ]);
  if (fromThinkingConfig != null) {
    setValueByPath(toObject, ["thinkingConfig"], fromThinkingConfig);
  }
  const fromTopK = getValueByPath(fromObject, ["topK"]);
  if (fromTopK != null) {
    setValueByPath(toObject, ["topK"], fromTopK);
  }
  const fromTopP = getValueByPath(fromObject, ["topP"]);
  if (fromTopP != null) {
    setValueByPath(toObject, ["topP"], fromTopP);
  }
  if (getValueByPath(fromObject, ["enableEnhancedCivicAnswers"]) !== void 0) {
    throw new Error("enableEnhancedCivicAnswers parameter is not supported in Vertex AI.");
  }
  return toObject;
}
function googleMapsToMldev$2(fromObject) {
  const toObject = {};
  if (getValueByPath(fromObject, ["authConfig"]) !== void 0) {
    throw new Error("authConfig parameter is not supported in Gemini API.");
  }
  const fromEnableWidget = getValueByPath(fromObject, ["enableWidget"]);
  if (fromEnableWidget != null) {
    setValueByPath(toObject, ["enableWidget"], fromEnableWidget);
  }
  return toObject;
}
function googleSearchToMldev$2(fromObject) {
  const toObject = {};
  if (getValueByPath(fromObject, ["excludeDomains"]) !== void 0) {
    throw new Error("excludeDomains parameter is not supported in Gemini API.");
  }
  if (getValueByPath(fromObject, ["blockingConfidence"]) !== void 0) {
    throw new Error("blockingConfidence parameter is not supported in Gemini API.");
  }
  const fromTimeRangeFilter = getValueByPath(fromObject, [
    "timeRangeFilter"
  ]);
  if (fromTimeRangeFilter != null) {
    setValueByPath(toObject, ["timeRangeFilter"], fromTimeRangeFilter);
  }
  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"], tLiveSpeechConfig(fromSpeechConfig));
  }
  const fromThinkingConfig = getValueByPath(fromObject, [
    "thinkingConfig"
  ]);
  if (parentObject !== void 0 && fromThinkingConfig != null) {
    setValueByPath(parentObject, ["setup", "generationConfig", "thinkingConfig"], fromThinkingConfig);
  }
  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"], fromInputAudioTranscription);
  }
  const fromOutputAudioTranscription = getValueByPath(fromObject, [
    "outputAudioTranscription"
  ]);
  if (parentObject !== void 0 && fromOutputAudioTranscription != null) {
    setValueByPath(parentObject, ["setup", "outputAudioTranscription"], fromOutputAudioTranscription);
  }
  const fromRealtimeInputConfig = getValueByPath(fromObject, [
    "realtimeInputConfig"
  ]);
  if (parentObject !== void 0 && fromRealtimeInputConfig != null) {
    setValueByPath(parentObject, ["setup", "realtimeInputConfig"], fromRealtimeInputConfig);
  }
  const fromContextWindowCompression = getValueByPath(fromObject, [
    "contextWindowCompression"
  ]);
  if (parentObject !== void 0 && fromContextWindowCompression != null) {
    setValueByPath(parentObject, ["setup", "contextWindowCompression"], fromContextWindowCompression);
  }
  const fromProactivity = getValueByPath(fromObject, ["proactivity"]);
  if (parentObject !== void 0 && fromProactivity != null) {
    setValueByPath(parentObject, ["setup", "proactivity"], fromProactivity);
  }
  return toObject;
}
function liveConnectConfigToVertex(fromObject, parentObject) {
  const toObject = {};
  const fromGenerationConfig = getValueByPath(fromObject, [
    "generationConfig"
  ]);
  if (parentObject !== void 0 && fromGenerationConfig != null) {
    setValueByPath(parentObject, ["setup", "generationConfig"], generationConfigToVertex$1(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 fromThinkingConfig = getValueByPath(fromObject, [
    "thinkingConfig"
  ]);
  if (parentObject !== void 0 && fromThinkingConfig != null) {
    setValueByPath(parentObject, ["setup", "generationConfig", "thinkingConfig"], fromThinkingConfig);
  }
  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"], 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"], fromSessionResumption);
  }
  const fromInputAudioTranscription = getValueByPath(fromObject, [
    "inputAudioTranscription"
  ]);
  if (parentObject !== void 0 && fromInputAudioTranscription != null) {
    setValueByPath(parentObject, ["setup", "inputAudioTranscription"], fromInputAudioTranscription);
  }
  const fromOutputAudioTranscription = getValueByPath(fromObject, [
    "outputAudioTranscription"
  ]);
  if (parentObject !== void 0 && fromOutputAudioTranscription != null) {
    setValueByPath(parentObject, ["setup", "outputAudioTranscription"], fromOutputAudioTranscription);
  }
  const fromRealtimeInputConfig = getValueByPath(fromObject, [
    "realtimeInputConfig"
  ]);
  if (parentObject !== void 0 && fromRealtimeInputConfig != null) {
    setValueByPath(parentObject, ["setup", "realtimeInputConfig"], fromRealtimeInputConfig);
  }
  const fromContextWindowCompression = getValueByPath(fromObject, [
    "contextWindowCompression"
  ]);
  if (parentObject !== void 0 && fromContextWindowCompression != null) {
    setValueByPath(parentObject, ["setup", "contextWindowCompression"], fromContextWindowCompression);
  }
  const fromProactivity = getValueByPath(fromObject, ["proactivity"]);
  if (parentObject !== void 0 && fromProactivity != null) {
    setValueByPath(parentObject, ["setup", "proactivity"], 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 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 liveMusicSetConfigParametersToMldev(fromObject) {
  const toObject = {};
  const fromMusicGenerationConfig = getValueByPath(fromObject, [
    "musicGenerationConfig"
  ]);
  if (fromMusicGenerationConfig != null) {
    setValueByPath(toObject, ["musicGenerationConfig"], fromMusicGenerationConfig);
  }
  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 item;
      });
    }
    setValueByPath(toObject, ["weightedPrompts"], transformedList);
  }
  return toObject;
}
function liveSendRealtimeInputParametersToMldev(fromObject) {
  const toObject = {};
  const fromMedia = getValueByPath(fromObject, ["media"]);
  if (fromMedia != null) {
    let transformedList = tBlobs(fromMedia);
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return blobToMldev$2(item);
      });
    }
    setValueByPath(toObject, ["mediaChunks"], transformedList);
  }
  const fromAudio = getValueByPath(fromObject, ["audio"]);
  if (fromAudio != null) {
    setValueByPath(toObject, ["audio"], blobToMldev$2(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"], blobToMldev$2(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"], fromActivityStart);
  }
  const fromActivityEnd = getValueByPath(fromObject, ["activityEnd"]);
  if (fromActivityEnd != null) {
    setValueByPath(toObject, ["activityEnd"], fromActivityEnd);
  }
  return toObject;
}
function liveSendRealtimeInputParametersToVertex(fromObject) {
  const toObject = {};
  const fromMedia = getValueByPath(fromObject, ["media"]);
  if (fromMedia != null) {
    let transformedList = tBlobs(fromMedia);
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return item;
      });
    }
    setValueByPath(toObject, ["mediaChunks"], transformedList);
  }
  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"], fromActivityStart);
  }
  const fromActivityEnd = getValueByPath(fromObject, ["activityEnd"]);
  if (fromActivityEnd != null) {
    setValueByPath(toObject, ["activityEnd"], fromActivityEnd);
  }
  return toObject;
}
function liveServerMessageFromVertex(fromObject) {
  const toObject = {};
  const fromSetupComplete = getValueByPath(fromObject, [
    "setupComplete"
  ]);
  if (fromSetupComplete != null) {
    setValueByPath(toObject, ["setupComplete"], fromSetupComplete);
  }
  const fromServerContent = getValueByPath(fromObject, [
    "serverContent"
  ]);
  if (fromServerContent != null) {
    setValueByPath(toObject, ["serverContent"], fromServerContent);
  }
  const fromToolCall = getValueByPath(fromObject, ["toolCall"]);
  if (fromToolCall != null) {
    setValueByPath(toObject, ["toolCall"], fromToolCall);
  }
  const fromToolCallCancellation = getValueByPath(fromObject, [
    "toolCallCancellation"
  ]);
  if (fromToolCallCancellation != null) {
    setValueByPath(toObject, ["toolCallCancellation"], 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"], fromGoAway);
  }
  const fromSessionResumptionUpdate = getValueByPath(fromObject, [
    "sessionResumptionUpdate"
  ]);
  if (fromSessionResumptionUpdate != null) {
    setValueByPath(toObject, ["sessionResumptionUpdate"], fromSessionResumptionUpdate);
  }
  return toObject;
}
function partToMldev$2(fromObject) {
  const toObject = {};
  const fromMediaResolution = getValueByPath(fromObject, [
    "mediaResolution"
  ]);
  if (fromMediaResolution != null) {
    setValueByPath(toObject, ["mediaResolution"], fromMediaResolution);
  }
  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 fromFileData = getValueByPath(fromObject, ["fileData"]);
  if (fromFileData != null) {
    setValueByPath(toObject, ["fileData"], fileDataToMldev$2(fromFileData));
  }
  const fromFunctionCall = getValueByPath(fromObject, ["functionCall"]);
  if (fromFunctionCall != null) {
    setValueByPath(toObject, ["functionCall"], functionCallToMldev$2(fromFunctionCall));
  }
  const fromFunctionResponse = getValueByPath(fromObject, [
    "functionResponse"
  ]);
  if (fromFunctionResponse != null) {
    setValueByPath(toObject, ["functionResponse"], fromFunctionResponse);
  }
  const fromInlineData = getValueByPath(fromObject, ["inlineData"]);
  if (fromInlineData != null) {
    setValueByPath(toObject, ["inlineData"], blobToMldev$2(fromInlineData));
  }
  const fromText = getValueByPath(fromObject, ["text"]);
  if (fromText != null) {
    setValueByPath(toObject, ["text"], fromText);
  }
  const fromThought = getValueByPath(fromObject, ["thought"]);
  if (fromThought != null) {
    setValueByPath(toObject, ["thought"], fromThought);
  }
  const fromThoughtSignature = getValueByPath(fromObject, [
    "thoughtSignature"
  ]);
  if (fromThoughtSignature != null) {
    setValueByPath(toObject, ["thoughtSignature"], fromThoughtSignature);
  }
  const fromVideoMetadata = getValueByPath(fromObject, [
    "videoMetadata"
  ]);
  if (fromVideoMetadata != null) {
    setValueByPath(toObject, ["videoMetadata"], fromVideoMetadata);
  }
  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 speechConfigToVertex$1(fromObject) {
  const toObject = {};
  const fromLanguageCode = getValueByPath(fromObject, ["languageCode"]);
  if (fromLanguageCode != null) {
    setValueByPath(toObject, ["languageCode"], fromLanguageCode);
  }
  const fromVoiceConfig = getValueByPath(fromObject, ["voiceConfig"]);
  if (fromVoiceConfig != null) {
    setValueByPath(toObject, ["voiceConfig"], fromVoiceConfig);
  }
  if (getValueByPath(fromObject, ["multiSpeakerVoiceConfig"]) !== void 0) {
    throw new Error("multiSpeakerVoiceConfig parameter is not supported in Vertex AI.");
  }
  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 item;
      });
    }
    setValueByPath(toObject, ["functionDeclarations"], transformedList);
  }
  if (getValueByPath(fromObject, ["retrieval"]) !== void 0) {
    throw new Error("retrieval parameter is not supported in Gemini API.");
  }
  const fromGoogleSearchRetrieval = getValueByPath(fromObject, [
    "googleSearchRetrieval"
  ]);
  if (fromGoogleSearchRetrieval != null) {
    setValueByPath(toObject, ["googleSearchRetrieval"], fromGoogleSearchRetrieval);
  }
  const fromComputerUse = getValueByPath(fromObject, ["computerUse"]);
  if (fromComputerUse != null) {
    setValueByPath(toObject, ["computerUse"], fromComputerUse);
  }
  const fromFileSearch = getValueByPath(fromObject, ["fileSearch"]);
  if (fromFileSearch != null) {
    setValueByPath(toObject, ["fileSearch"], fromFileSearch);
  }
  const fromCodeExecution = getValueByPath(fromObject, [
    "codeExecution"
  ]);
  if (fromCodeExecution != null) {
    setValueByPath(toObject, ["codeExecution"], fromCodeExecution);
  }
  if (getValueByPath(fromObject, ["enterpriseWebSearch"]) !== void 0) {
    throw new Error("enterpriseWebSearch parameter is not supported in Gemini API.");
  }
  const fromGoogleMaps = getValueByPath(fromObject, ["googleMaps"]);
  if (fromGoogleMaps != null) {
    setValueByPath(toObject, ["googleMaps"], googleMapsToMldev$2(fromGoogleMaps));
  }
  const fromGoogleSearch = getValueByPath(fromObject, ["googleSearch"]);
  if (fromGoogleSearch != null) {
    setValueByPath(toObject, ["googleSearch"], googleSearchToMldev$2(fromGoogleSearch));
  }
  const fromUrlContext = getValueByPath(fromObject, ["urlContext"]);
  if (fromUrlContext != null) {
    setValueByPath(toObject, ["urlContext"], fromUrlContext);
  }
  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 fromGoogleSearchRetrieval = getValueByPath(fromObject, [
    "googleSearchRetrieval"
  ]);
  if (fromGoogleSearchRetrieval != null) {
    setValueByPath(toObject, ["googleSearchRetrieval"], fromGoogleSearchRetrieval);
  }
  const fromComputerUse = getValueByPath(fromObject, ["computerUse"]);
  if (fromComputerUse != null) {
    setValueByPath(toObject, ["computerUse"], fromComputerUse);
  }
  if (getValueByPath(fromObject, ["fileSearch"]) !== void 0) {
    throw new Error("fileSearch parameter is not supported in Vertex AI.");
  }
  const fromCodeExecution = getValueByPath(fromObject, [
    "codeExecution"
  ]);
  if (fromCodeExecution != null) {
    setValueByPath(toObject, ["codeExecution"], fromCodeExecution);
  }
  const fromEnterpriseWebSearch = getValueByPath(fromObject, [
    "enterpriseWebSearch"
  ]);
  if (fromEnterpriseWebSearch != null) {
    setValueByPath(toObject, ["enterpriseWebSearch"], fromEnterpriseWebSearch);
  }
  const fromGoogleMaps = getValueByPath(fromObject, ["googleMaps"]);
  if (fromGoogleMaps != null) {
    setValueByPath(toObject, ["googleMaps"], fromGoogleMaps);
  }
  const fromGoogleSearch = getValueByPath(fromObject, ["googleSearch"]);
  if (fromGoogleSearch != null) {
    setValueByPath(toObject, ["googleSearch"], fromGoogleSearch);
  }
  const fromUrlContext = getValueByPath(fromObject, ["urlContext"]);
  if (fromUrlContext != null) {
    setValueByPath(toObject, ["urlContext"], fromUrlContext);
  }
  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 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 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 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 item;
      });
    }
    setValueByPath(toObject, ["toolUsePromptTokensDetails"], transformedList);
  }
  const fromTrafficType = getValueByPath(fromObject, ["trafficType"]);
  if (fromTrafficType != null) {
    setValueByPath(toObject, ["trafficType"], fromTrafficType);
  }
  return toObject;
}
function blobToMldev$1(fromObject) {
  const toObject = {};
  const fromData = getValueByPath(fromObject, ["data"]);
  if (fromData != null) {
    setValueByPath(toObject, ["data"], fromData);
  }
  if (getValueByPath(fromObject, ["displayName"]) !== void 0) {
    throw new Error("displayName parameter is not supported in Gemini API.");
  }
  const fromMimeType = getValueByPath(fromObject, ["mimeType"]);
  if (fromMimeType != null) {
    setValueByPath(toObject, ["mimeType"], fromMimeType);
  }
  return toObject;
}
function candidateFromMldev(fromObject) {
  const toObject = {};
  const fromContent = getValueByPath(fromObject, ["content"]);
  if (fromContent != null) {
    setValueByPath(toObject, ["content"], 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 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) {
    let transformedList = fromSafetyRatings;
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return item;
      });
    }
    setValueByPath(toObject, ["safetyRatings"], transformedList);
  }
  const fromUrlContextMetadata = getValueByPath(fromObject, [
    "urlContextMetadata"
  ]);
  if (fromUrlContextMetadata != null) {
    setValueByPath(toObject, ["urlContextMetadata"], fromUrlContextMetadata);
  }
  return toObject;
}
function citationMetadataFromMldev(fromObject) {
  const toObject = {};
  const fromCitations = getValueByPath(fromObject, ["citationSources"]);
  if (fromCitations != null) {
    let transformedList = fromCitations;
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return item;
      });
    }
    setValueByPath(toObject, ["citations"], transformedList);
  }
  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 item;
      });
    }
    setValueByPath(toObject, ["contents"], transformedList);
  }
  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) {
    let transformedList = fromTokensInfo;
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return item;
      });
    }
    setValueByPath(toObject, ["tokensInfo"], transformedList);
  }
  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 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 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 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 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 countTokensConfigToVertex(fromObject, parentObject) {
  const toObject = {};
  const fromSystemInstruction = getValueByPath(fromObject, [
    "systemInstruction"
  ]);
  if (parentObject !== void 0 && fromSystemInstruction != null) {
    setValueByPath(parentObject, ["systemInstruction"], 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"], generationConfigToVertex(fromGenerationConfig));
  }
  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) {
    countTokensConfigToMldev(fromConfig);
  }
  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 item;
      });
    }
    setValueByPath(toObject, ["contents"], transformedList);
  }
  const fromConfig = getValueByPath(fromObject, ["config"]);
  if (fromConfig != null) {
    countTokensConfigToVertex(fromConfig, toObject);
  }
  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 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 deleteModelParametersToMldev(apiClient, fromObject) {
  const toObject = {};
  const fromModel = getValueByPath(fromObject, ["model"]);
  if (fromModel != null) {
    setValueByPath(toObject, ["_url", "name"], tModel(apiClient, fromModel));
  }
  return toObject;
}
function deleteModelParametersToVertex(apiClient, fromObject) {
  const toObject = {};
  const fromModel = getValueByPath(fromObject, ["model"]);
  if (fromModel != null) {
    setValueByPath(toObject, ["_url", "name"], tModel(apiClient, fromModel));
  }
  return toObject;
}
function deleteModelResponseFromMldev(fromObject) {
  const toObject = {};
  const fromSdkHttpResponse = getValueByPath(fromObject, [
    "sdkHttpResponse"
  ]);
  if (fromSdkHttpResponse != null) {
    setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse);
  }
  return toObject;
}
function deleteModelResponseFromVertex(fromObject) {
  const toObject = {};
  const fromSdkHttpResponse = getValueByPath(fromObject, [
    "sdkHttpResponse"
  ]);
  if (fromSdkHttpResponse != null) {
    setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse);
  }
  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 fromLabels = getValueByPath(fromObject, ["labels"]);
  if (parentObject !== void 0 && fromLabels != null) {
    setValueByPath(parentObject, ["labels"], fromLabels);
  }
  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) {
    editImageConfigToVertex(fromConfig, toObject);
  }
  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 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 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 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) {
    let transformedList = tContentsForEmbed(apiClient, fromContents);
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return item;
      });
    }
    setValueByPath(toObject, ["requests[]", "content"], transformedList);
  }
  const fromConfig = getValueByPath(fromObject, ["config"]);
  if (fromConfig != null) {
    embedContentConfigToMldev(fromConfig, toObject);
  }
  const fromModelForEmbedContent = getValueByPath(fromObject, ["model"]);
  if (fromModelForEmbedContent !== void 0) {
    setValueByPath(toObject, ["requests[]", "model"], tModel(apiClient, fromModelForEmbedContent));
  }
  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) {
    let transformedList = tContentsForEmbed(apiClient, fromContents);
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return item;
      });
    }
    setValueByPath(toObject, ["instances[]", "content"], transformedList);
  }
  const fromConfig = getValueByPath(fromObject, ["config"]);
  if (fromConfig != null) {
    embedContentConfigToVertex(fromConfig, 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 item;
      });
    }
    setValueByPath(toObject, ["embeddings"], transformedList);
  }
  const fromMetadata = getValueByPath(fromObject, ["metadata"]);
  if (fromMetadata != null) {
    setValueByPath(toObject, ["metadata"], fromMetadata);
  }
  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"], fromMetadata);
  }
  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 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 functionCallToMldev$1(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);
  }
  if (getValueByPath(fromObject, ["partialArgs"]) !== void 0) {
    throw new Error("partialArgs parameter is not supported in Gemini API.");
  }
  if (getValueByPath(fromObject, ["willContinue"]) !== void 0) {
    throw new Error("willContinue parameter is not supported in Gemini API.");
  }
  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);
  }
  if (getValueByPath(fromObject, ["streamFunctionCallArguments"]) !== void 0) {
    throw new Error("streamFunctionCallArguments parameter is not supported in Gemini API.");
  }
  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 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"], 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"], 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"], fromThinkingConfig);
  }
  const fromImageConfig = getValueByPath(fromObject, ["imageConfig"]);
  if (fromImageConfig != null) {
    setValueByPath(toObject, ["imageConfig"], imageConfigToMldev(fromImageConfig));
  }
  return toObject;
}
function generateContentConfigToVertex(apiClient, fromObject, parentObject) {
  const toObject = {};
  const fromSystemInstruction = getValueByPath(fromObject, [
    "systemInstruction"
  ]);
  if (parentObject !== void 0 && fromSystemInstruction != null) {
    setValueByPath(parentObject, ["systemInstruction"], 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"], 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"], fromModelSelectionConfig);
  }
  const fromSafetySettings = getValueByPath(fromObject, [
    "safetySettings"
  ]);
  if (parentObject !== void 0 && fromSafetySettings != null) {
    let transformedList = fromSafetySettings;
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return 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"], 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"], fromThinkingConfig);
  }
  const fromImageConfig = getValueByPath(fromObject, ["imageConfig"]);
  if (fromImageConfig != null) {
    setValueByPath(toObject, ["imageConfig"], imageConfigToVertex(fromImageConfig));
  }
  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 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 item;
      });
    }
    setValueByPath(toObject, ["contents"], transformedList);
  }
  const fromConfig = getValueByPath(fromObject, ["config"]);
  if (fromConfig != null) {
    setValueByPath(toObject, ["generationConfig"], generateContentConfigToVertex(apiClient, fromConfig, toObject));
  }
  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 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 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 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.");
  }
  if (getValueByPath(fromObject, ["labels"]) !== void 0) {
    throw new Error("labels 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 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 fromLabels = getValueByPath(fromObject, ["labels"]);
  if (parentObject !== void 0 && fromLabels != null) {
    setValueByPath(parentObject, ["labels"], fromLabels);
  }
  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 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) {
    generateImagesConfigToMldev(fromConfig, toObject);
  }
  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) {
    generateImagesConfigToVertex(fromConfig, toObject);
  }
  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 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 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);
  }
  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);
  }
  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.");
  }
  const fromLastFrame = getValueByPath(fromObject, ["lastFrame"]);
  if (parentObject !== void 0 && fromLastFrame != null) {
    setValueByPath(parentObject, ["instances[0]", "lastFrame"], imageToMldev(fromLastFrame));
  }
  const fromReferenceImages = getValueByPath(fromObject, [
    "referenceImages"
  ]);
  if (parentObject !== void 0 && fromReferenceImages != null) {
    let transformedList = fromReferenceImages;
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return videoGenerationReferenceImageToMldev(item);
      });
    }
    setValueByPath(parentObject, ["instances[0]", "referenceImages"], transformedList);
  }
  if (getValueByPath(fromObject, ["mask"]) !== void 0) {
    throw new Error("mask 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 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 fromMask = getValueByPath(fromObject, ["mask"]);
  if (parentObject !== void 0 && fromMask != null) {
    setValueByPath(parentObject, ["instances[0]", "mask"], videoGenerationMaskToVertex(fromMask));
  }
  const fromCompressionQuality = getValueByPath(fromObject, [
    "compressionQuality"
  ]);
  if (parentObject !== void 0 && fromCompressionQuality != null) {
    setValueByPath(parentObject, ["parameters", "compressionQuality"], fromCompressionQuality);
  }
  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 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;
}
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));
  }
  const fromVideo = getValueByPath(fromObject, ["video"]);
  if (fromVideo != null) {
    setValueByPath(toObject, ["instances[0]", "video"], videoToMldev(fromVideo));
  }
  const fromSource = getValueByPath(fromObject, ["source"]);
  if (fromSource != null) {
    generateVideosSourceToMldev(fromSource, toObject);
  }
  const fromConfig = getValueByPath(fromObject, ["config"]);
  if (fromConfig != null) {
    generateVideosConfigToMldev(fromConfig, toObject);
  }
  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) {
    generateVideosSourceToVertex(fromSource, toObject);
  }
  const fromConfig = getValueByPath(fromObject, ["config"]);
  if (fromConfig != null) {
    generateVideosConfigToVertex(fromConfig, toObject);
  }
  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 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 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));
  }
  const fromVideo = getValueByPath(fromObject, ["video"]);
  if (parentObject !== void 0 && fromVideo != null) {
    setValueByPath(parentObject, ["instances[0]", "video"], videoToMldev(fromVideo));
  }
  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 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 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 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 item;
      });
    }
    setValueByPath(toObject, ["labels"], transformedList);
  }
  return toObject;
}
function generatedVideoFromMldev(fromObject) {
  const toObject = {};
  const fromVideo = getValueByPath(fromObject, ["video"]);
  if (fromVideo != null) {
    setValueByPath(toObject, ["video"], videoFromMldev(fromVideo));
  }
  return toObject;
}
function generatedVideoFromVertex(fromObject) {
  const toObject = {};
  const fromVideo = getValueByPath(fromObject, ["_self"]);
  if (fromVideo != null) {
    setValueByPath(toObject, ["video"], videoFromVertex(fromVideo));
  }
  return toObject;
}
function generationConfigToVertex(fromObject) {
  const toObject = {};
  const fromModelSelectionConfig = getValueByPath(fromObject, [
    "modelSelectionConfig"
  ]);
  if (fromModelSelectionConfig != null) {
    setValueByPath(toObject, ["modelConfig"], fromModelSelectionConfig);
  }
  const fromResponseJsonSchema = getValueByPath(fromObject, [
    "responseJsonSchema"
  ]);
  if (fromResponseJsonSchema != null) {
    setValueByPath(toObject, ["responseJsonSchema"], fromResponseJsonSchema);
  }
  const fromAudioTimestamp = getValueByPath(fromObject, [
    "audioTimestamp"
  ]);
  if (fromAudioTimestamp != null) {
    setValueByPath(toObject, ["audioTimestamp"], fromAudioTimestamp);
  }
  const fromCandidateCount = getValueByPath(fromObject, [
    "candidateCount"
  ]);
  if (fromCandidateCount != null) {
    setValueByPath(toObject, ["candidateCount"], fromCandidateCount);
  }
  const fromEnableAffectiveDialog = getValueByPath(fromObject, [
    "enableAffectiveDialog"
  ]);
  if (fromEnableAffectiveDialog != null) {
    setValueByPath(toObject, ["enableAffectiveDialog"], fromEnableAffectiveDialog);
  }
  const fromFrequencyPenalty = getValueByPath(fromObject, [
    "frequencyPenalty"
  ]);
  if (fromFrequencyPenalty != null) {
    setValueByPath(toObject, ["frequencyPenalty"], fromFrequencyPenalty);
  }
  const fromLogprobs = getValueByPath(fromObject, ["logprobs"]);
  if (fromLogprobs != null) {
    setValueByPath(toObject, ["logprobs"], fromLogprobs);
  }
  const fromMaxOutputTokens = getValueByPath(fromObject, [
    "maxOutputTokens"
  ]);
  if (fromMaxOutputTokens != null) {
    setValueByPath(toObject, ["maxOutputTokens"], fromMaxOutputTokens);
  }
  const fromMediaResolution = getValueByPath(fromObject, [
    "mediaResolution"
  ]);
  if (fromMediaResolution != null) {
    setValueByPath(toObject, ["mediaResolution"], fromMediaResolution);
  }
  const fromPresencePenalty = getValueByPath(fromObject, [
    "presencePenalty"
  ]);
  if (fromPresencePenalty != null) {
    setValueByPath(toObject, ["presencePenalty"], fromPresencePenalty);
  }
  const fromResponseLogprobs = getValueByPath(fromObject, [
    "responseLogprobs"
  ]);
  if (fromResponseLogprobs != null) {
    setValueByPath(toObject, ["responseLogprobs"], fromResponseLogprobs);
  }
  const fromResponseMimeType = getValueByPath(fromObject, [
    "responseMimeType"
  ]);
  if (fromResponseMimeType != null) {
    setValueByPath(toObject, ["responseMimeType"], fromResponseMimeType);
  }
  const fromResponseModalities = getValueByPath(fromObject, [
    "responseModalities"
  ]);
  if (fromResponseModalities != null) {
    setValueByPath(toObject, ["responseModalities"], fromResponseModalities);
  }
  const fromResponseSchema = getValueByPath(fromObject, [
    "responseSchema"
  ]);
  if (fromResponseSchema != null) {
    setValueByPath(toObject, ["responseSchema"], fromResponseSchema);
  }
  const fromRoutingConfig = getValueByPath(fromObject, [
    "routingConfig"
  ]);
  if (fromRoutingConfig != null) {
    setValueByPath(toObject, ["routingConfig"], fromRoutingConfig);
  }
  const fromSeed = getValueByPath(fromObject, ["seed"]);
  if (fromSeed != null) {
    setValueByPath(toObject, ["seed"], fromSeed);
  }
  const fromSpeechConfig = getValueByPath(fromObject, ["speechConfig"]);
  if (fromSpeechConfig != null) {
    setValueByPath(toObject, ["speechConfig"], speechConfigToVertex(fromSpeechConfig));
  }
  const fromStopSequences = getValueByPath(fromObject, [
    "stopSequences"
  ]);
  if (fromStopSequences != null) {
    setValueByPath(toObject, ["stopSequences"], fromStopSequences);
  }
  const fromTemperature = getValueByPath(fromObject, ["temperature"]);
  if (fromTemperature != null) {
    setValueByPath(toObject, ["temperature"], fromTemperature);
  }
  const fromThinkingConfig = getValueByPath(fromObject, [
    "thinkingConfig"
  ]);
  if (fromThinkingConfig != null) {
    setValueByPath(toObject, ["thinkingConfig"], fromThinkingConfig);
  }
  const fromTopK = getValueByPath(fromObject, ["topK"]);
  if (fromTopK != null) {
    setValueByPath(toObject, ["topK"], fromTopK);
  }
  const fromTopP = getValueByPath(fromObject, ["topP"]);
  if (fromTopP != null) {
    setValueByPath(toObject, ["topP"], fromTopP);
  }
  if (getValueByPath(fromObject, ["enableEnhancedCivicAnswers"]) !== void 0) {
    throw new Error("enableEnhancedCivicAnswers parameter is not supported in Vertex AI.");
  }
  return toObject;
}
function getModelParametersToMldev(apiClient, fromObject) {
  const toObject = {};
  const fromModel = getValueByPath(fromObject, ["model"]);
  if (fromModel != null) {
    setValueByPath(toObject, ["_url", "name"], tModel(apiClient, fromModel));
  }
  return toObject;
}
function getModelParametersToVertex(apiClient, fromObject) {
  const toObject = {};
  const fromModel = getValueByPath(fromObject, ["model"]);
  if (fromModel != null) {
    setValueByPath(toObject, ["_url", "name"], tModel(apiClient, fromModel));
  }
  return toObject;
}
function googleMapsToMldev$1(fromObject) {
  const toObject = {};
  if (getValueByPath(fromObject, ["authConfig"]) !== void 0) {
    throw new Error("authConfig parameter is not supported in Gemini API.");
  }
  const fromEnableWidget = getValueByPath(fromObject, ["enableWidget"]);
  if (fromEnableWidget != null) {
    setValueByPath(toObject, ["enableWidget"], fromEnableWidget);
  }
  return toObject;
}
function googleSearchToMldev$1(fromObject) {
  const toObject = {};
  if (getValueByPath(fromObject, ["excludeDomains"]) !== void 0) {
    throw new Error("excludeDomains parameter is not supported in Gemini API.");
  }
  if (getValueByPath(fromObject, ["blockingConfidence"]) !== void 0) {
    throw new Error("blockingConfidence parameter is not supported in Gemini API.");
  }
  const fromTimeRangeFilter = getValueByPath(fromObject, [
    "timeRangeFilter"
  ]);
  if (fromTimeRangeFilter != null) {
    setValueByPath(toObject, ["timeRangeFilter"], fromTimeRangeFilter);
  }
  return toObject;
}
function imageConfigToMldev(fromObject) {
  const toObject = {};
  const fromAspectRatio = getValueByPath(fromObject, ["aspectRatio"]);
  if (fromAspectRatio != null) {
    setValueByPath(toObject, ["aspectRatio"], fromAspectRatio);
  }
  const fromImageSize = getValueByPath(fromObject, ["imageSize"]);
  if (fromImageSize != null) {
    setValueByPath(toObject, ["imageSize"], fromImageSize);
  }
  if (getValueByPath(fromObject, ["outputMimeType"]) !== void 0) {
    throw new Error("outputMimeType parameter is not supported in Gemini API.");
  }
  if (getValueByPath(fromObject, ["outputCompressionQuality"]) !== void 0) {
    throw new Error("outputCompressionQuality parameter is not supported in Gemini API.");
  }
  return toObject;
}
function imageConfigToVertex(fromObject) {
  const toObject = {};
  const fromAspectRatio = getValueByPath(fromObject, ["aspectRatio"]);
  if (fromAspectRatio != null) {
    setValueByPath(toObject, ["aspectRatio"], fromAspectRatio);
  }
  const fromImageSize = getValueByPath(fromObject, ["imageSize"]);
  if (fromImageSize != null) {
    setValueByPath(toObject, ["imageSize"], fromImageSize);
  }
  const fromOutputMimeType = getValueByPath(fromObject, [
    "outputMimeType"
  ]);
  if (fromOutputMimeType != null) {
    setValueByPath(toObject, ["imageOutputOptions", "mimeType"], fromOutputMimeType);
  }
  const fromOutputCompressionQuality = getValueByPath(fromObject, [
    "outputCompressionQuality"
  ]);
  if (fromOutputCompressionQuality != null) {
    setValueByPath(toObject, ["imageOutputOptions", "compressionQuality"], fromOutputCompressionQuality);
  }
  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 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 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 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 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 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 listModelsParametersToMldev(apiClient, fromObject) {
  const toObject = {};
  const fromConfig = getValueByPath(fromObject, ["config"]);
  if (fromConfig != null) {
    listModelsConfigToMldev(apiClient, fromConfig, toObject);
  }
  return toObject;
}
function listModelsParametersToVertex(apiClient, fromObject) {
  const toObject = {};
  const fromConfig = getValueByPath(fromObject, ["config"]);
  if (fromConfig != null) {
    listModelsConfigToVertex(apiClient, fromConfig, toObject);
  }
  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 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 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 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);
  }
  const fromTemperature = getValueByPath(fromObject, ["temperature"]);
  if (fromTemperature != null) {
    setValueByPath(toObject, ["temperature"], fromTemperature);
  }
  const fromMaxTemperature = getValueByPath(fromObject, [
    "maxTemperature"
  ]);
  if (fromMaxTemperature != null) {
    setValueByPath(toObject, ["maxTemperature"], fromMaxTemperature);
  }
  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 fromThinking = getValueByPath(fromObject, ["thinking"]);
  if (fromThinking != null) {
    setValueByPath(toObject, ["thinking"], fromThinking);
  }
  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 item;
      });
    }
    setValueByPath(toObject, ["checkpoints"], transformedList);
  }
  return toObject;
}
function partToMldev$1(fromObject) {
  const toObject = {};
  const fromMediaResolution = getValueByPath(fromObject, [
    "mediaResolution"
  ]);
  if (fromMediaResolution != null) {
    setValueByPath(toObject, ["mediaResolution"], fromMediaResolution);
  }
  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 fromFileData = getValueByPath(fromObject, ["fileData"]);
  if (fromFileData != null) {
    setValueByPath(toObject, ["fileData"], fileDataToMldev$1(fromFileData));
  }
  const fromFunctionCall = getValueByPath(fromObject, ["functionCall"]);
  if (fromFunctionCall != null) {
    setValueByPath(toObject, ["functionCall"], functionCallToMldev$1(fromFunctionCall));
  }
  const fromFunctionResponse = getValueByPath(fromObject, [
    "functionResponse"
  ]);
  if (fromFunctionResponse != null) {
    setValueByPath(toObject, ["functionResponse"], fromFunctionResponse);
  }
  const fromInlineData = getValueByPath(fromObject, ["inlineData"]);
  if (fromInlineData != null) {
    setValueByPath(toObject, ["inlineData"], blobToMldev$1(fromInlineData));
  }
  const fromText = getValueByPath(fromObject, ["text"]);
  if (fromText != null) {
    setValueByPath(toObject, ["text"], fromText);
  }
  const fromThought = getValueByPath(fromObject, ["thought"]);
  if (fromThought != null) {
    setValueByPath(toObject, ["thought"], fromThought);
  }
  const fromThoughtSignature = getValueByPath(fromObject, [
    "thoughtSignature"
  ]);
  if (fromThoughtSignature != null) {
    setValueByPath(toObject, ["thoughtSignature"], fromThoughtSignature);
  }
  const fromVideoMetadata = getValueByPath(fromObject, [
    "videoMetadata"
  ]);
  if (fromVideoMetadata != null) {
    setValueByPath(toObject, ["videoMetadata"], fromVideoMetadata);
  }
  return toObject;
}
function productImageToVertex(fromObject) {
  const toObject = {};
  const fromProductImage = getValueByPath(fromObject, ["productImage"]);
  if (fromProductImage != null) {
    setValueByPath(toObject, ["image"], imageToVertex(fromProductImage));
  }
  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", "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);
  }
  const fromLabels = getValueByPath(fromObject, ["labels"]);
  if (parentObject !== void 0 && fromLabels != null) {
    setValueByPath(parentObject, ["labels"], fromLabels);
  }
  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) {
    recontextImageSourceToVertex(fromSource, toObject);
  }
  const fromConfig = getValueByPath(fromObject, ["config"]);
  if (fromConfig != null) {
    recontextImageConfigToVertex(fromConfig, toObject);
  }
  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 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 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"], fromStyleImageConfig);
  }
  const fromSubjectImageConfig = getValueByPath(fromObject, [
    "subjectImageConfig"
  ]);
  if (fromSubjectImageConfig != null) {
    setValueByPath(toObject, ["subjectImageConfig"], fromSubjectImageConfig);
  }
  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 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 safetySettingToMldev(fromObject) {
  const toObject = {};
  const fromCategory = getValueByPath(fromObject, ["category"]);
  if (fromCategory != null) {
    setValueByPath(toObject, ["category"], fromCategory);
  }
  if (getValueByPath(fromObject, ["method"]) !== void 0) {
    throw new Error("method parameter is not supported in Gemini API.");
  }
  const fromThreshold = getValueByPath(fromObject, ["threshold"]);
  if (fromThreshold != null) {
    setValueByPath(toObject, ["threshold"], fromThreshold);
  }
  return toObject;
}
function scribbleImageToVertex(fromObject) {
  const toObject = {};
  const fromImage = getValueByPath(fromObject, ["image"]);
  if (fromImage != null) {
    setValueByPath(toObject, ["image"], imageToVertex(fromImage));
  }
  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);
  }
  const fromLabels = getValueByPath(fromObject, ["labels"]);
  if (parentObject !== void 0 && fromLabels != null) {
    setValueByPath(parentObject, ["labels"], fromLabels);
  }
  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) {
    segmentImageSourceToVertex(fromSource, toObject);
  }
  const fromConfig = getValueByPath(fromObject, ["config"]);
  if (fromConfig != null) {
    segmentImageConfigToVertex(fromConfig, toObject);
  }
  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 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 speechConfigToVertex(fromObject) {
  const toObject = {};
  const fromLanguageCode = getValueByPath(fromObject, ["languageCode"]);
  if (fromLanguageCode != null) {
    setValueByPath(toObject, ["languageCode"], fromLanguageCode);
  }
  const fromVoiceConfig = getValueByPath(fromObject, ["voiceConfig"]);
  if (fromVoiceConfig != null) {
    setValueByPath(toObject, ["voiceConfig"], fromVoiceConfig);
  }
  if (getValueByPath(fromObject, ["multiSpeakerVoiceConfig"]) !== void 0) {
    throw new Error("multiSpeakerVoiceConfig parameter is not supported in Vertex AI.");
  }
  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"], fromRetrievalConfig);
  }
  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 item;
      });
    }
    setValueByPath(toObject, ["functionDeclarations"], transformedList);
  }
  if (getValueByPath(fromObject, ["retrieval"]) !== void 0) {
    throw new Error("retrieval parameter is not supported in Gemini API.");
  }
  const fromGoogleSearchRetrieval = getValueByPath(fromObject, [
    "googleSearchRetrieval"
  ]);
  if (fromGoogleSearchRetrieval != null) {
    setValueByPath(toObject, ["googleSearchRetrieval"], fromGoogleSearchRetrieval);
  }
  const fromComputerUse = getValueByPath(fromObject, ["computerUse"]);
  if (fromComputerUse != null) {
    setValueByPath(toObject, ["computerUse"], fromComputerUse);
  }
  const fromFileSearch = getValueByPath(fromObject, ["fileSearch"]);
  if (fromFileSearch != null) {
    setValueByPath(toObject, ["fileSearch"], fromFileSearch);
  }
  const fromCodeExecution = getValueByPath(fromObject, [
    "codeExecution"
  ]);
  if (fromCodeExecution != null) {
    setValueByPath(toObject, ["codeExecution"], fromCodeExecution);
  }
  if (getValueByPath(fromObject, ["enterpriseWebSearch"]) !== void 0) {
    throw new Error("enterpriseWebSearch parameter is not supported in Gemini API.");
  }
  const fromGoogleMaps = getValueByPath(fromObject, ["googleMaps"]);
  if (fromGoogleMaps != null) {
    setValueByPath(toObject, ["googleMaps"], googleMapsToMldev$1(fromGoogleMaps));
  }
  const fromGoogleSearch = getValueByPath(fromObject, ["googleSearch"]);
  if (fromGoogleSearch != null) {
    setValueByPath(toObject, ["googleSearch"], googleSearchToMldev$1(fromGoogleSearch));
  }
  const fromUrlContext = getValueByPath(fromObject, ["urlContext"]);
  if (fromUrlContext != null) {
    setValueByPath(toObject, ["urlContext"], fromUrlContext);
  }
  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 fromGoogleSearchRetrieval = getValueByPath(fromObject, [
    "googleSearchRetrieval"
  ]);
  if (fromGoogleSearchRetrieval != null) {
    setValueByPath(toObject, ["googleSearchRetrieval"], fromGoogleSearchRetrieval);
  }
  const fromComputerUse = getValueByPath(fromObject, ["computerUse"]);
  if (fromComputerUse != null) {
    setValueByPath(toObject, ["computerUse"], fromComputerUse);
  }
  if (getValueByPath(fromObject, ["fileSearch"]) !== void 0) {
    throw new Error("fileSearch parameter is not supported in Vertex AI.");
  }
  const fromCodeExecution = getValueByPath(fromObject, [
    "codeExecution"
  ]);
  if (fromCodeExecution != null) {
    setValueByPath(toObject, ["codeExecution"], fromCodeExecution);
  }
  const fromEnterpriseWebSearch = getValueByPath(fromObject, [
    "enterpriseWebSearch"
  ]);
  if (fromEnterpriseWebSearch != null) {
    setValueByPath(toObject, ["enterpriseWebSearch"], fromEnterpriseWebSearch);
  }
  const fromGoogleMaps = getValueByPath(fromObject, ["googleMaps"]);
  if (fromGoogleMaps != null) {
    setValueByPath(toObject, ["googleMaps"], fromGoogleMaps);
  }
  const fromGoogleSearch = getValueByPath(fromObject, ["googleSearch"]);
  if (fromGoogleSearch != null) {
    setValueByPath(toObject, ["googleSearch"], fromGoogleSearch);
  }
  const fromUrlContext = getValueByPath(fromObject, ["urlContext"]);
  if (fromUrlContext != null) {
    setValueByPath(toObject, ["urlContext"], fromUrlContext);
  }
  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 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 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 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 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) {
    updateModelConfigToMldev(fromConfig, toObject);
  }
  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) {
    updateModelConfigToVertex(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 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 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 fromLabels = getValueByPath(fromObject, ["labels"]);
  if (parentObject !== void 0 && fromLabels != null) {
    setValueByPath(parentObject, ["labels"], fromLabels);
  }
  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) {
    upscaleImageAPIConfigInternalToVertex(fromConfig, toObject);
  }
  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 videoFromMldev(fromObject) {
  const toObject = {};
  const fromUri = getValueByPath(fromObject, ["uri"]);
  if (fromUri != null) {
    setValueByPath(toObject, ["uri"], fromUri);
  }
  const fromVideoBytes = getValueByPath(fromObject, ["encodedVideo"]);
  if (fromVideoBytes != null) {
    setValueByPath(toObject, ["videoBytes"], tBytes(fromVideoBytes));
  }
  const fromMimeType = getValueByPath(fromObject, ["encoding"]);
  if (fromMimeType != null) {
    setValueByPath(toObject, ["mimeType"], fromMimeType);
  }
  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 videoGenerationMaskToVertex(fromObject) {
  const toObject = {};
  const fromImage = getValueByPath(fromObject, ["image"]);
  if (fromImage != null) {
    setValueByPath(toObject, ["_self"], imageToVertex(fromImage));
  }
  const fromMaskMode = getValueByPath(fromObject, ["maskMode"]);
  if (fromMaskMode != null) {
    setValueByPath(toObject, ["maskMode"], fromMaskMode);
  }
  return toObject;
}
function videoGenerationReferenceImageToMldev(fromObject) {
  const toObject = {};
  const fromImage = getValueByPath(fromObject, ["image"]);
  if (fromImage != null) {
    setValueByPath(toObject, ["image"], imageToMldev(fromImage));
  }
  const fromReferenceType = getValueByPath(fromObject, [
    "referenceType"
  ]);
  if (fromReferenceType != null) {
    setValueByPath(toObject, ["referenceType"], fromReferenceType);
  }
  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 videoToMldev(fromObject) {
  const toObject = {};
  const fromUri = getValueByPath(fromObject, ["uri"]);
  if (fromUri != null) {
    setValueByPath(toObject, ["uri"], fromUri);
  }
  const fromVideoBytes = getValueByPath(fromObject, ["videoBytes"]);
  if (fromVideoBytes != null) {
    setValueByPath(toObject, ["encodedVideo"], tBytes(fromVideoBytes));
  }
  const fromMimeType = getValueByPath(fromObject, ["mimeType"]);
  if (fromMimeType != null) {
    setValueByPath(toObject, ["encoding"], fromMimeType);
  }
  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;
}
async function throwErrorIfNotOK(response) {
  var _a7;
  if (response === void 0) {
    throw new Error("response is undefined");
  }
  if (!response.ok) {
    const status = response.status;
    let errorBody;
    if ((_a7 = response.headers.get("content-type")) === null || _a7 === void 0 ? void 0 : _a7.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 (e4) {
      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 _a7;
  const existingHeader = (_a7 = headers[GOOGLE_API_CLIENT_HEADER]) !== null && _a7 !== void 0 ? _a7 : "";
  headers[GOOGLE_API_CLIENT_HEADER] = (existingHeader + ` ${MCP_LABEL}`).trimStart();
}
function isMcpCallableTool(object3) {
  return object3 !== null && typeof object3 === "object" && object3 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 t5 = yield __await(mcpClient.listTools({ cursor }));
      for (const tool of t5.tools) {
        yield yield __await(tool);
        numTools++;
      }
      if (!t5.nextCursor) {
        break;
      }
      cursor = t5.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);
  }
  Object.assign(serverMessage, data);
  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 = 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(config2) {
  var _a7, _b2, _c2;
  if ((_a7 = config2 === null || config2 === void 0 ? void 0 : config2.automaticFunctionCalling) === null || _a7 === void 0 ? void 0 : _a7.disable) {
    return true;
  }
  let callableToolsPresent = false;
  for (const tool of (_b2 = config2 === null || config2 === void 0 ? void 0 : config2.tools) !== null && _b2 !== void 0 ? _b2 : []) {
    if (isCallableTool(tool)) {
      callableToolsPresent = true;
      break;
    }
  }
  if (!callableToolsPresent) {
    return true;
  }
  const maxCalls = (_c2 = config2 === null || config2 === void 0 ? void 0 : config2.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 _a7, _b2, _c2;
  return (_c2 = (_b2 = (_a7 = params.config) === null || _a7 === void 0 ? void 0 : _a7.tools) === null || _b2 === void 0 ? void 0 : _b2.some((tool) => isCallableTool(tool))) !== null && _c2 !== void 0 ? _c2 : false;
}
function findAfcIncompatibleToolIndexes(params) {
  var _a7;
  const afcIncompatibleToolIndexes = [];
  if (!((_a7 = params === null || params === void 0 ? void 0 : params.config) === null || _a7 === void 0 ? void 0 : _a7.tools)) {
    return afcIncompatibleToolIndexes;
  }
  params.config.tools.forEach((tool, index) => {
    if (isCallableTool(tool)) {
      return;
    }
    const geminiTool = tool;
    if (geminiTool.functionDeclarations && geminiTool.functionDeclarations.length > 0) {
      afcIncompatibleToolIndexes.push(index);
    }
  });
  return afcIncompatibleToolIndexes;
}
function shouldAppendAfcHistory(config2) {
  var _a7;
  return !((_a7 = config2 === null || config2 === void 0 ? void 0 : config2.automaticFunctionCalling) === null || _a7 === void 0 ? void 0 : _a7.ignoreCallHistory);
}
function blobToMldev(fromObject) {
  const toObject = {};
  const fromData = getValueByPath(fromObject, ["data"]);
  if (fromData != null) {
    setValueByPath(toObject, ["data"], fromData);
  }
  if (getValueByPath(fromObject, ["displayName"]) !== void 0) {
    throw new Error("displayName parameter is not supported in Gemini API.");
  }
  const fromMimeType = getValueByPath(fromObject, ["mimeType"]);
  if (fromMimeType != null) {
    setValueByPath(toObject, ["mimeType"], fromMimeType);
  }
  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 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 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 functionCallToMldev(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);
  }
  if (getValueByPath(fromObject, ["partialArgs"]) !== void 0) {
    throw new Error("partialArgs parameter is not supported in Gemini API.");
  }
  if (getValueByPath(fromObject, ["willContinue"]) !== void 0) {
    throw new Error("willContinue parameter is not supported in Gemini API.");
  }
  return toObject;
}
function googleMapsToMldev(fromObject) {
  const toObject = {};
  if (getValueByPath(fromObject, ["authConfig"]) !== void 0) {
    throw new Error("authConfig parameter is not supported in Gemini API.");
  }
  const fromEnableWidget = getValueByPath(fromObject, ["enableWidget"]);
  if (fromEnableWidget != null) {
    setValueByPath(toObject, ["enableWidget"], fromEnableWidget);
  }
  return toObject;
}
function googleSearchToMldev(fromObject) {
  const toObject = {};
  if (getValueByPath(fromObject, ["excludeDomains"]) !== void 0) {
    throw new Error("excludeDomains parameter is not supported in Gemini API.");
  }
  if (getValueByPath(fromObject, ["blockingConfidence"]) !== void 0) {
    throw new Error("blockingConfidence parameter is not supported in Gemini API.");
  }
  const fromTimeRangeFilter = getValueByPath(fromObject, [
    "timeRangeFilter"
  ]);
  if (fromTimeRangeFilter != null) {
    setValueByPath(toObject, ["timeRangeFilter"], fromTimeRangeFilter);
  }
  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"], tLiveSpeechConfig(fromSpeechConfig));
  }
  const fromThinkingConfig = getValueByPath(fromObject, [
    "thinkingConfig"
  ]);
  if (parentObject !== void 0 && fromThinkingConfig != null) {
    setValueByPath(parentObject, ["setup", "generationConfig", "thinkingConfig"], fromThinkingConfig);
  }
  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"], fromInputAudioTranscription);
  }
  const fromOutputAudioTranscription = getValueByPath(fromObject, [
    "outputAudioTranscription"
  ]);
  if (parentObject !== void 0 && fromOutputAudioTranscription != null) {
    setValueByPath(parentObject, ["setup", "outputAudioTranscription"], fromOutputAudioTranscription);
  }
  const fromRealtimeInputConfig = getValueByPath(fromObject, [
    "realtimeInputConfig"
  ]);
  if (parentObject !== void 0 && fromRealtimeInputConfig != null) {
    setValueByPath(parentObject, ["setup", "realtimeInputConfig"], fromRealtimeInputConfig);
  }
  const fromContextWindowCompression = getValueByPath(fromObject, [
    "contextWindowCompression"
  ]);
  if (parentObject !== void 0 && fromContextWindowCompression != null) {
    setValueByPath(parentObject, ["setup", "contextWindowCompression"], fromContextWindowCompression);
  }
  const fromProactivity = getValueByPath(fromObject, ["proactivity"]);
  if (parentObject !== void 0 && fromProactivity != null) {
    setValueByPath(parentObject, ["setup", "proactivity"], 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 partToMldev(fromObject) {
  const toObject = {};
  const fromMediaResolution = getValueByPath(fromObject, [
    "mediaResolution"
  ]);
  if (fromMediaResolution != null) {
    setValueByPath(toObject, ["mediaResolution"], fromMediaResolution);
  }
  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 fromFileData = getValueByPath(fromObject, ["fileData"]);
  if (fromFileData != null) {
    setValueByPath(toObject, ["fileData"], fileDataToMldev(fromFileData));
  }
  const fromFunctionCall = getValueByPath(fromObject, ["functionCall"]);
  if (fromFunctionCall != null) {
    setValueByPath(toObject, ["functionCall"], functionCallToMldev(fromFunctionCall));
  }
  const fromFunctionResponse = getValueByPath(fromObject, [
    "functionResponse"
  ]);
  if (fromFunctionResponse != null) {
    setValueByPath(toObject, ["functionResponse"], fromFunctionResponse);
  }
  const fromInlineData = getValueByPath(fromObject, ["inlineData"]);
  if (fromInlineData != null) {
    setValueByPath(toObject, ["inlineData"], blobToMldev(fromInlineData));
  }
  const fromText = getValueByPath(fromObject, ["text"]);
  if (fromText != null) {
    setValueByPath(toObject, ["text"], fromText);
  }
  const fromThought = getValueByPath(fromObject, ["thought"]);
  if (fromThought != null) {
    setValueByPath(toObject, ["thought"], fromThought);
  }
  const fromThoughtSignature = getValueByPath(fromObject, [
    "thoughtSignature"
  ]);
  if (fromThoughtSignature != null) {
    setValueByPath(toObject, ["thoughtSignature"], fromThoughtSignature);
  }
  const fromVideoMetadata = getValueByPath(fromObject, [
    "videoMetadata"
  ]);
  if (fromVideoMetadata != null) {
    setValueByPath(toObject, ["videoMetadata"], fromVideoMetadata);
  }
  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 toolToMldev(fromObject) {
  const toObject = {};
  const fromFunctionDeclarations = getValueByPath(fromObject, [
    "functionDeclarations"
  ]);
  if (fromFunctionDeclarations != null) {
    let transformedList = fromFunctionDeclarations;
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return item;
      });
    }
    setValueByPath(toObject, ["functionDeclarations"], transformedList);
  }
  if (getValueByPath(fromObject, ["retrieval"]) !== void 0) {
    throw new Error("retrieval parameter is not supported in Gemini API.");
  }
  const fromGoogleSearchRetrieval = getValueByPath(fromObject, [
    "googleSearchRetrieval"
  ]);
  if (fromGoogleSearchRetrieval != null) {
    setValueByPath(toObject, ["googleSearchRetrieval"], fromGoogleSearchRetrieval);
  }
  const fromComputerUse = getValueByPath(fromObject, ["computerUse"]);
  if (fromComputerUse != null) {
    setValueByPath(toObject, ["computerUse"], fromComputerUse);
  }
  const fromFileSearch = getValueByPath(fromObject, ["fileSearch"]);
  if (fromFileSearch != null) {
    setValueByPath(toObject, ["fileSearch"], fromFileSearch);
  }
  const fromCodeExecution = getValueByPath(fromObject, [
    "codeExecution"
  ]);
  if (fromCodeExecution != null) {
    setValueByPath(toObject, ["codeExecution"], fromCodeExecution);
  }
  if (getValueByPath(fromObject, ["enterpriseWebSearch"]) !== void 0) {
    throw new Error("enterpriseWebSearch parameter is not supported in Gemini API.");
  }
  const fromGoogleMaps = getValueByPath(fromObject, ["googleMaps"]);
  if (fromGoogleMaps != null) {
    setValueByPath(toObject, ["googleMaps"], googleMapsToMldev(fromGoogleMaps));
  }
  const fromGoogleSearch = getValueByPath(fromObject, ["googleSearch"]);
  if (fromGoogleSearch != null) {
    setValueByPath(toObject, ["googleSearch"], googleSearchToMldev(fromGoogleSearch));
  }
  const fromUrlContext = getValueByPath(fromObject, ["urlContext"]);
  if (fromUrlContext != null) {
    setValueByPath(toObject, ["urlContext"], fromUrlContext);
  }
  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, config2) {
  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(config2 === null || config2 === void 0 ? void 0 : config2.lockAdditionalFields) && (config2 === null || config2 === void 0 ? void 0 : config2.lockAdditionalFields.length) === 0) {
      if (generatedMaskFromBidi) {
        requestDict["fieldMask"] = generatedMaskFromBidi;
      } else {
        delete requestDict["fieldMask"];
      }
    } else if ((config2 === null || config2 === void 0 ? void 0 : config2.lockAdditionalFields) && config2.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 createFileSearchStoreConfigToMldev(fromObject, parentObject) {
  const toObject = {};
  const fromDisplayName = getValueByPath(fromObject, ["displayName"]);
  if (parentObject !== void 0 && fromDisplayName != null) {
    setValueByPath(parentObject, ["displayName"], fromDisplayName);
  }
  return toObject;
}
function createFileSearchStoreParametersToMldev(fromObject) {
  const toObject = {};
  const fromConfig = getValueByPath(fromObject, ["config"]);
  if (fromConfig != null) {
    createFileSearchStoreConfigToMldev(fromConfig, toObject);
  }
  return toObject;
}
function deleteFileSearchStoreConfigToMldev(fromObject, parentObject) {
  const toObject = {};
  const fromForce = getValueByPath(fromObject, ["force"]);
  if (parentObject !== void 0 && fromForce != null) {
    setValueByPath(parentObject, ["_query", "force"], fromForce);
  }
  return toObject;
}
function deleteFileSearchStoreParametersToMldev(fromObject) {
  const toObject = {};
  const fromName = getValueByPath(fromObject, ["name"]);
  if (fromName != null) {
    setValueByPath(toObject, ["_url", "name"], fromName);
  }
  const fromConfig = getValueByPath(fromObject, ["config"]);
  if (fromConfig != null) {
    deleteFileSearchStoreConfigToMldev(fromConfig, toObject);
  }
  return toObject;
}
function getFileSearchStoreParametersToMldev(fromObject) {
  const toObject = {};
  const fromName = getValueByPath(fromObject, ["name"]);
  if (fromName != null) {
    setValueByPath(toObject, ["_url", "name"], fromName);
  }
  return toObject;
}
function importFileConfigToMldev(fromObject, parentObject) {
  const toObject = {};
  const fromCustomMetadata = getValueByPath(fromObject, [
    "customMetadata"
  ]);
  if (parentObject !== void 0 && fromCustomMetadata != null) {
    let transformedList = fromCustomMetadata;
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return item;
      });
    }
    setValueByPath(parentObject, ["customMetadata"], transformedList);
  }
  const fromChunkingConfig = getValueByPath(fromObject, [
    "chunkingConfig"
  ]);
  if (parentObject !== void 0 && fromChunkingConfig != null) {
    setValueByPath(parentObject, ["chunkingConfig"], fromChunkingConfig);
  }
  return toObject;
}
function importFileOperationFromMldev(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"], importFileResponseFromMldev(fromResponse));
  }
  return toObject;
}
function importFileParametersToMldev(fromObject) {
  const toObject = {};
  const fromFileSearchStoreName = getValueByPath(fromObject, [
    "fileSearchStoreName"
  ]);
  if (fromFileSearchStoreName != null) {
    setValueByPath(toObject, ["_url", "file_search_store_name"], fromFileSearchStoreName);
  }
  const fromFileName = getValueByPath(fromObject, ["fileName"]);
  if (fromFileName != null) {
    setValueByPath(toObject, ["fileName"], fromFileName);
  }
  const fromConfig = getValueByPath(fromObject, ["config"]);
  if (fromConfig != null) {
    importFileConfigToMldev(fromConfig, toObject);
  }
  return toObject;
}
function importFileResponseFromMldev(fromObject) {
  const toObject = {};
  const fromSdkHttpResponse = getValueByPath(fromObject, [
    "sdkHttpResponse"
  ]);
  if (fromSdkHttpResponse != null) {
    setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse);
  }
  const fromParent = getValueByPath(fromObject, ["parent"]);
  if (fromParent != null) {
    setValueByPath(toObject, ["parent"], fromParent);
  }
  const fromDocumentName = getValueByPath(fromObject, ["documentName"]);
  if (fromDocumentName != null) {
    setValueByPath(toObject, ["documentName"], fromDocumentName);
  }
  return toObject;
}
function listFileSearchStoresConfigToMldev(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 listFileSearchStoresParametersToMldev(fromObject) {
  const toObject = {};
  const fromConfig = getValueByPath(fromObject, ["config"]);
  if (fromConfig != null) {
    listFileSearchStoresConfigToMldev(fromConfig, toObject);
  }
  return toObject;
}
function listFileSearchStoresResponseFromMldev(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 fromFileSearchStores = getValueByPath(fromObject, [
    "fileSearchStores"
  ]);
  if (fromFileSearchStores != null) {
    let transformedList = fromFileSearchStores;
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return item;
      });
    }
    setValueByPath(toObject, ["fileSearchStores"], transformedList);
  }
  return toObject;
}
function uploadToFileSearchStoreConfigToMldev(fromObject, parentObject) {
  const toObject = {};
  const fromMimeType = getValueByPath(fromObject, ["mimeType"]);
  if (parentObject !== void 0 && fromMimeType != null) {
    setValueByPath(parentObject, ["mimeType"], fromMimeType);
  }
  const fromDisplayName = getValueByPath(fromObject, ["displayName"]);
  if (parentObject !== void 0 && fromDisplayName != null) {
    setValueByPath(parentObject, ["displayName"], fromDisplayName);
  }
  const fromCustomMetadata = getValueByPath(fromObject, [
    "customMetadata"
  ]);
  if (parentObject !== void 0 && fromCustomMetadata != null) {
    let transformedList = fromCustomMetadata;
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return item;
      });
    }
    setValueByPath(parentObject, ["customMetadata"], transformedList);
  }
  const fromChunkingConfig = getValueByPath(fromObject, [
    "chunkingConfig"
  ]);
  if (parentObject !== void 0 && fromChunkingConfig != null) {
    setValueByPath(parentObject, ["chunkingConfig"], fromChunkingConfig);
  }
  return toObject;
}
function uploadToFileSearchStoreParametersToMldev(fromObject) {
  const toObject = {};
  const fromFileSearchStoreName = getValueByPath(fromObject, [
    "fileSearchStoreName"
  ]);
  if (fromFileSearchStoreName != null) {
    setValueByPath(toObject, ["_url", "file_search_store_name"], fromFileSearchStoreName);
  }
  const fromConfig = getValueByPath(fromObject, ["config"]);
  if (fromConfig != null) {
    uploadToFileSearchStoreConfigToMldev(fromConfig, toObject);
  }
  return toObject;
}
function uploadToFileSearchStoreResumableResponseFromMldev(fromObject) {
  const toObject = {};
  const fromSdkHttpResponse = getValueByPath(fromObject, [
    "sdkHttpResponse"
  ]);
  if (fromSdkHttpResponse != null) {
    setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse);
  }
  return toObject;
}
function deleteDocumentConfigToMldev(fromObject, parentObject) {
  const toObject = {};
  const fromForce = getValueByPath(fromObject, ["force"]);
  if (parentObject !== void 0 && fromForce != null) {
    setValueByPath(parentObject, ["_query", "force"], fromForce);
  }
  return toObject;
}
function deleteDocumentParametersToMldev(fromObject) {
  const toObject = {};
  const fromName = getValueByPath(fromObject, ["name"]);
  if (fromName != null) {
    setValueByPath(toObject, ["_url", "name"], fromName);
  }
  const fromConfig = getValueByPath(fromObject, ["config"]);
  if (fromConfig != null) {
    deleteDocumentConfigToMldev(fromConfig, toObject);
  }
  return toObject;
}
function getDocumentParametersToMldev(fromObject) {
  const toObject = {};
  const fromName = getValueByPath(fromObject, ["name"]);
  if (fromName != null) {
    setValueByPath(toObject, ["_url", "name"], fromName);
  }
  return toObject;
}
function listDocumentsConfigToMldev(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 listDocumentsParametersToMldev(fromObject) {
  const toObject = {};
  const fromParent = getValueByPath(fromObject, ["parent"]);
  if (fromParent != null) {
    setValueByPath(toObject, ["_url", "parent"], fromParent);
  }
  const fromConfig = getValueByPath(fromObject, ["config"]);
  if (fromConfig != null) {
    listDocumentsConfigToMldev(fromConfig, toObject);
  }
  return toObject;
}
function listDocumentsResponseFromMldev(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 fromDocuments = getValueByPath(fromObject, ["documents"]);
  if (fromDocuments != null) {
    let transformedList = fromDocuments;
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return item;
      });
    }
    setValueByPath(toObject, ["documents"], transformedList);
  }
  return toObject;
}
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 _a7, _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: (_a7 = params.config) === null || _a7 === void 0 ? void 0 : _a7.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 cancelTuningJobParametersToMldev(fromObject, _rootObject) {
  const toObject = {};
  const fromName = getValueByPath(fromObject, ["name"]);
  if (fromName != null) {
    setValueByPath(toObject, ["_url", "name"], fromName);
  }
  return toObject;
}
function cancelTuningJobParametersToVertex(fromObject, _rootObject) {
  const toObject = {};
  const fromName = getValueByPath(fromObject, ["name"]);
  if (fromName != null) {
    setValueByPath(toObject, ["_url", "name"], fromName);
  }
  return toObject;
}
function createTuningJobConfigToMldev(fromObject, parentObject, _rootObject) {
  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);
  }
  if (getValueByPath(fromObject, ["labels"]) !== void 0) {
    throw new Error("labels parameter is not supported in Gemini API.");
  }
  if (getValueByPath(fromObject, ["beta"]) !== void 0) {
    throw new Error("beta parameter is not supported in Gemini API.");
  }
  return toObject;
}
function createTuningJobConfigToVertex(fromObject, parentObject, rootObject) {
  const toObject = {};
  let discriminatorValidationDataset = getValueByPath(rootObject, [
    "config",
    "method"
  ]);
  if (discriminatorValidationDataset === void 0) {
    discriminatorValidationDataset = "SUPERVISED_FINE_TUNING";
  }
  if (discriminatorValidationDataset === "SUPERVISED_FINE_TUNING") {
    const fromValidationDataset = getValueByPath(fromObject, [
      "validationDataset"
    ]);
    if (parentObject !== void 0 && fromValidationDataset != null) {
      setValueByPath(parentObject, ["supervisedTuningSpec"], tuningValidationDatasetToVertex(fromValidationDataset));
    }
  } else if (discriminatorValidationDataset === "PREFERENCE_TUNING") {
    const fromValidationDataset = getValueByPath(fromObject, [
      "validationDataset"
    ]);
    if (parentObject !== void 0 && fromValidationDataset != null) {
      setValueByPath(parentObject, ["preferenceOptimizationSpec"], tuningValidationDatasetToVertex(fromValidationDataset));
    }
  }
  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);
  }
  let discriminatorEpochCount = getValueByPath(rootObject, [
    "config",
    "method"
  ]);
  if (discriminatorEpochCount === void 0) {
    discriminatorEpochCount = "SUPERVISED_FINE_TUNING";
  }
  if (discriminatorEpochCount === "SUPERVISED_FINE_TUNING") {
    const fromEpochCount = getValueByPath(fromObject, ["epochCount"]);
    if (parentObject !== void 0 && fromEpochCount != null) {
      setValueByPath(parentObject, ["supervisedTuningSpec", "hyperParameters", "epochCount"], fromEpochCount);
    }
  } else if (discriminatorEpochCount === "PREFERENCE_TUNING") {
    const fromEpochCount = getValueByPath(fromObject, ["epochCount"]);
    if (parentObject !== void 0 && fromEpochCount != null) {
      setValueByPath(parentObject, ["preferenceOptimizationSpec", "hyperParameters", "epochCount"], fromEpochCount);
    }
  }
  let discriminatorLearningRateMultiplier = getValueByPath(rootObject, [
    "config",
    "method"
  ]);
  if (discriminatorLearningRateMultiplier === void 0) {
    discriminatorLearningRateMultiplier = "SUPERVISED_FINE_TUNING";
  }
  if (discriminatorLearningRateMultiplier === "SUPERVISED_FINE_TUNING") {
    const fromLearningRateMultiplier = getValueByPath(fromObject, [
      "learningRateMultiplier"
    ]);
    if (parentObject !== void 0 && fromLearningRateMultiplier != null) {
      setValueByPath(parentObject, ["supervisedTuningSpec", "hyperParameters", "learningRateMultiplier"], fromLearningRateMultiplier);
    }
  } else if (discriminatorLearningRateMultiplier === "PREFERENCE_TUNING") {
    const fromLearningRateMultiplier = getValueByPath(fromObject, [
      "learningRateMultiplier"
    ]);
    if (parentObject !== void 0 && fromLearningRateMultiplier != null) {
      setValueByPath(parentObject, [
        "preferenceOptimizationSpec",
        "hyperParameters",
        "learningRateMultiplier"
      ], fromLearningRateMultiplier);
    }
  }
  let discriminatorExportLastCheckpointOnly = getValueByPath(rootObject, ["config", "method"]);
  if (discriminatorExportLastCheckpointOnly === void 0) {
    discriminatorExportLastCheckpointOnly = "SUPERVISED_FINE_TUNING";
  }
  if (discriminatorExportLastCheckpointOnly === "SUPERVISED_FINE_TUNING") {
    const fromExportLastCheckpointOnly = getValueByPath(fromObject, [
      "exportLastCheckpointOnly"
    ]);
    if (parentObject !== void 0 && fromExportLastCheckpointOnly != null) {
      setValueByPath(parentObject, ["supervisedTuningSpec", "exportLastCheckpointOnly"], fromExportLastCheckpointOnly);
    }
  } else if (discriminatorExportLastCheckpointOnly === "PREFERENCE_TUNING") {
    const fromExportLastCheckpointOnly = getValueByPath(fromObject, [
      "exportLastCheckpointOnly"
    ]);
    if (parentObject !== void 0 && fromExportLastCheckpointOnly != null) {
      setValueByPath(parentObject, ["preferenceOptimizationSpec", "exportLastCheckpointOnly"], fromExportLastCheckpointOnly);
    }
  }
  let discriminatorAdapterSize = getValueByPath(rootObject, [
    "config",
    "method"
  ]);
  if (discriminatorAdapterSize === void 0) {
    discriminatorAdapterSize = "SUPERVISED_FINE_TUNING";
  }
  if (discriminatorAdapterSize === "SUPERVISED_FINE_TUNING") {
    const fromAdapterSize = getValueByPath(fromObject, ["adapterSize"]);
    if (parentObject !== void 0 && fromAdapterSize != null) {
      setValueByPath(parentObject, ["supervisedTuningSpec", "hyperParameters", "adapterSize"], fromAdapterSize);
    }
  } else if (discriminatorAdapterSize === "PREFERENCE_TUNING") {
    const fromAdapterSize = getValueByPath(fromObject, ["adapterSize"]);
    if (parentObject !== void 0 && fromAdapterSize != null) {
      setValueByPath(parentObject, ["preferenceOptimizationSpec", "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.");
  }
  const fromLabels = getValueByPath(fromObject, ["labels"]);
  if (parentObject !== void 0 && fromLabels != null) {
    setValueByPath(parentObject, ["labels"], fromLabels);
  }
  const fromBeta = getValueByPath(fromObject, ["beta"]);
  if (parentObject !== void 0 && fromBeta != null) {
    setValueByPath(parentObject, ["preferenceOptimizationSpec", "hyperParameters", "beta"], fromBeta);
  }
  return toObject;
}
function createTuningJobParametersPrivateToMldev(fromObject, rootObject) {
  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) {
    tuningDatasetToMldev(fromTrainingDataset);
  }
  const fromConfig = getValueByPath(fromObject, ["config"]);
  if (fromConfig != null) {
    createTuningJobConfigToMldev(fromConfig, toObject);
  }
  return toObject;
}
function createTuningJobParametersPrivateToVertex(fromObject, rootObject) {
  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) {
    tuningDatasetToVertex(fromTrainingDataset, toObject, rootObject);
  }
  const fromConfig = getValueByPath(fromObject, ["config"]);
  if (fromConfig != null) {
    createTuningJobConfigToVertex(fromConfig, toObject, rootObject);
  }
  return toObject;
}
function getTuningJobParametersToMldev(fromObject, _rootObject) {
  const toObject = {};
  const fromName = getValueByPath(fromObject, ["name"]);
  if (fromName != null) {
    setValueByPath(toObject, ["_url", "name"], fromName);
  }
  return toObject;
}
function getTuningJobParametersToVertex(fromObject, _rootObject) {
  const toObject = {};
  const fromName = getValueByPath(fromObject, ["name"]);
  if (fromName != null) {
    setValueByPath(toObject, ["_url", "name"], fromName);
  }
  return toObject;
}
function listTuningJobsConfigToMldev(fromObject, parentObject, _rootObject) {
  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 listTuningJobsConfigToVertex(fromObject, parentObject, _rootObject) {
  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, rootObject) {
  const toObject = {};
  const fromConfig = getValueByPath(fromObject, ["config"]);
  if (fromConfig != null) {
    listTuningJobsConfigToMldev(fromConfig, toObject);
  }
  return toObject;
}
function listTuningJobsParametersToVertex(fromObject, rootObject) {
  const toObject = {};
  const fromConfig = getValueByPath(fromObject, ["config"]);
  if (fromConfig != null) {
    listTuningJobsConfigToVertex(fromConfig, toObject);
  }
  return toObject;
}
function listTuningJobsResponseFromMldev(fromObject, rootObject) {
  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 listTuningJobsResponseFromVertex(fromObject, rootObject) {
  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;
}
function tunedModelFromMldev(fromObject, _rootObject) {
  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 tuningDatasetToMldev(fromObject, _rootObject) {
  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 item;
      });
    }
    setValueByPath(toObject, ["examples", "examples"], transformedList);
  }
  return toObject;
}
function tuningDatasetToVertex(fromObject, parentObject, rootObject) {
  const toObject = {};
  let discriminatorGcsUri = getValueByPath(rootObject, [
    "config",
    "method"
  ]);
  if (discriminatorGcsUri === void 0) {
    discriminatorGcsUri = "SUPERVISED_FINE_TUNING";
  }
  if (discriminatorGcsUri === "SUPERVISED_FINE_TUNING") {
    const fromGcsUri = getValueByPath(fromObject, ["gcsUri"]);
    if (parentObject !== void 0 && fromGcsUri != null) {
      setValueByPath(parentObject, ["supervisedTuningSpec", "trainingDatasetUri"], fromGcsUri);
    }
  } else if (discriminatorGcsUri === "PREFERENCE_TUNING") {
    const fromGcsUri = getValueByPath(fromObject, ["gcsUri"]);
    if (parentObject !== void 0 && fromGcsUri != null) {
      setValueByPath(parentObject, ["preferenceOptimizationSpec", "trainingDatasetUri"], fromGcsUri);
    }
  }
  let discriminatorVertexDatasetResource = getValueByPath(rootObject, [
    "config",
    "method"
  ]);
  if (discriminatorVertexDatasetResource === void 0) {
    discriminatorVertexDatasetResource = "SUPERVISED_FINE_TUNING";
  }
  if (discriminatorVertexDatasetResource === "SUPERVISED_FINE_TUNING") {
    const fromVertexDatasetResource = getValueByPath(fromObject, [
      "vertexDatasetResource"
    ]);
    if (parentObject !== void 0 && fromVertexDatasetResource != null) {
      setValueByPath(parentObject, ["supervisedTuningSpec", "trainingDatasetUri"], fromVertexDatasetResource);
    }
  } else if (discriminatorVertexDatasetResource === "PREFERENCE_TUNING") {
    const fromVertexDatasetResource = getValueByPath(fromObject, [
      "vertexDatasetResource"
    ]);
    if (parentObject !== void 0 && fromVertexDatasetResource != null) {
      setValueByPath(parentObject, ["preferenceOptimizationSpec", "trainingDatasetUri"], fromVertexDatasetResource);
    }
  }
  if (getValueByPath(fromObject, ["examples"]) !== void 0) {
    throw new Error("examples parameter is not supported in Vertex AI.");
  }
  return toObject;
}
function tuningJobFromMldev(fromObject, rootObject) {
  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));
  }
  return toObject;
}
function tuningJobFromVertex(fromObject, _rootObject) {
  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"], 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 fromPreferenceOptimizationSpec = getValueByPath(fromObject, [
    "preferenceOptimizationSpec"
  ]);
  if (fromPreferenceOptimizationSpec != null) {
    setValueByPath(toObject, ["preferenceOptimizationSpec"], fromPreferenceOptimizationSpec);
  }
  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);
  }
  const fromVeoTuningSpec = getValueByPath(fromObject, [
    "veoTuningSpec"
  ]);
  if (fromVeoTuningSpec != null) {
    setValueByPath(toObject, ["veoTuningSpec"], fromVeoTuningSpec);
  }
  return toObject;
}
function tuningOperationFromMldev(fromObject, _rootObject) {
  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 tuningValidationDatasetToVertex(fromObject, _rootObject) {
  const toObject = {};
  const fromGcsUri = getValueByPath(fromObject, ["gcsUri"]);
  if (fromGcsUri != null) {
    setValueByPath(toObject, ["validationDatasetUri"], fromGcsUri);
  }
  const fromVertexDatasetResource = getValueByPath(fromObject, [
    "vertexDatasetResource"
  ]);
  if (fromVertexDatasetResource != null) {
    setValueByPath(toObject, ["validationDatasetUri"], fromVertexDatasetResource);
  }
  return toObject;
}
async function uploadBlob(file, uploadUrl, apiClient) {
  var _a7;
  const response = await uploadBlobInternal(file, uploadUrl, apiClient);
  const responseJson = await (response === null || response === void 0 ? void 0 : response.json());
  if (((_a7 = response === null || response === void 0 ? void 0 : response.headers) === null || _a7 === void 0 ? void 0 : _a7[X_GOOG_UPLOAD_STATUS_HEADER_FIELD]) !== "final") {
    throw new Error("Failed to upload file: Upload status is not finalized.");
  }
  return responseJson["file"];
}
async function uploadBlobToFileSearchStore(file, uploadUrl, apiClient) {
  var _a7;
  const response = await uploadBlobInternal(file, uploadUrl, apiClient);
  const responseJson = await (response === null || response === void 0 ? void 0 : response.json());
  if (((_a7 = response === null || response === void 0 ? void 0 : response.headers) === null || _a7 === void 0 ? void 0 : _a7[X_GOOG_UPLOAD_STATUS_HEADER_FIELD]) !== "final") {
    throw new Error("Failed to upload file: Upload status is not finalized.");
  }
  const resp = uploadToFileSearchStoreOperationFromMldev(responseJson);
  const typedResp = new UploadToFileSearchStoreOperation();
  Object.assign(typedResp, resp);
  return typedResp;
}
async function uploadBlobInternal(file, uploadUrl, apiClient) {
  var _a7, _b2;
  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 ((_a7 = response === null || response === void 0 ? void 0 : response.headers) === null || _a7 === void 0 ? void 0 : _a7[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.");
    }
  }
  return response;
}
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 _a7, _b2, _c2;
  return (_c2 = (_b2 = (_a7 = process === null || process === void 0 ? void 0 : process.env) === null || _a7 === void 0 ? void 0 : _a7[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, FunctionResponseScheduling, Type, Mode, ApiSpec, AuthType, HttpElementLocation, PhishBlockThreshold, ThinkingLevel, HarmCategory, HarmBlockMethod, HarmBlockThreshold, FinishReason, HarmProbability, HarmSeverity, UrlRetrievalStatus, BlockedReason, TrafficType, Modality, MediaResolution, TuningMode, AdapterSize, JobState, TuningTask, PartMediaResolutionLevel, FeatureSelectionPreference, Behavior, DynamicRetrievalConfigMode, Environment, FunctionCallingConfigMode, SafetyFilterLevel, PersonGeneration, ImagePromptLanguage, MaskReferenceMode, ControlReferenceType, SubjectReferenceType, EditMode, SegmentMode, VideoGenerationReferenceType, VideoGenerationMaskMode, VideoCompressionQuality, TuningMethod, DocumentState, FileState, FileSource, TurnCompleteReason, MediaModality, StartSensitivity, EndSensitivity, ActivityHandling, TurnCoverage, Scale, MusicGenerationMode, LiveMusicPlaybackControl, HttpResponse, GenerateContentResponse, EmbedContentResponse, GenerateImagesResponse, EditImageResponse, UpscaleImageResponse, RecontextImageResponse, SegmentImageResponse, ListModelsResponse, DeleteModelResponse, CountTokensResponse, ComputeTokensResponse, GenerateVideosOperation, ListTuningJobsResponse, DeleteCachedContentResponse, ListCachedContentsResponse, ListDocumentsResponse, ListFileSearchStoresResponse, UploadToFileSearchStoreResumableResponse, ImportFileOperation, ListFilesResponse, CreateFileResponse, DeleteFileResponse, ListBatchJobsResponse, LiveServerMessage, LiveMusicServerMessage, UploadToFileSearchStoreOperation, 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, Documents, FileSearchStores, 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({
  "packages/core/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(moveValueByPath, "moveValueByPath");
    __name(_moveValueRecursive, "_moveValueRecursive");
    __name(tBytes$1, "tBytes$1");
    __name(fetchPredictOperationParametersToVertex, "fetchPredictOperationParametersToVertex");
    __name(generateVideosOperationFromMldev$1, "generateVideosOperationFromMldev$1");
    __name(generateVideosOperationFromVertex$1, "generateVideosOperationFromVertex$1");
    __name(generateVideosResponseFromMldev$1, "generateVideosResponseFromMldev$1");
    __name(generateVideosResponseFromVertex$1, "generateVideosResponseFromVertex$1");
    __name(generatedVideoFromMldev$1, "generatedVideoFromMldev$1");
    __name(generatedVideoFromVertex$1, "generatedVideoFromVertex$1");
    __name(getOperationParametersToMldev, "getOperationParametersToMldev");
    __name(getOperationParametersToVertex, "getOperationParametersToVertex");
    __name(importFileOperationFromMldev$1, "importFileOperationFromMldev$1");
    __name(importFileResponseFromMldev$1, "importFileResponseFromMldev$1");
    __name(uploadToFileSearchStoreOperationFromMldev, "uploadToFileSearchStoreOperationFromMldev");
    __name(uploadToFileSearchStoreResponseFromMldev, "uploadToFileSearchStoreResponseFromMldev");
    __name(videoFromMldev$1, "videoFromMldev$1");
    __name(videoFromVertex$1, "videoFromVertex$1");
    (function(Outcome3) {
      Outcome3["OUTCOME_UNSPECIFIED"] = "OUTCOME_UNSPECIFIED";
      Outcome3["OUTCOME_OK"] = "OUTCOME_OK";
      Outcome3["OUTCOME_FAILED"] = "OUTCOME_FAILED";
      Outcome3["OUTCOME_DEADLINE_EXCEEDED"] = "OUTCOME_DEADLINE_EXCEEDED";
    })(Outcome || (Outcome = {}));
    (function(Language3) {
      Language3["LANGUAGE_UNSPECIFIED"] = "LANGUAGE_UNSPECIFIED";
      Language3["PYTHON"] = "PYTHON";
    })(Language || (Language = {}));
    (function(FunctionResponseScheduling3) {
      FunctionResponseScheduling3["SCHEDULING_UNSPECIFIED"] = "SCHEDULING_UNSPECIFIED";
      FunctionResponseScheduling3["SILENT"] = "SILENT";
      FunctionResponseScheduling3["WHEN_IDLE"] = "WHEN_IDLE";
      FunctionResponseScheduling3["INTERRUPT"] = "INTERRUPT";
    })(FunctionResponseScheduling || (FunctionResponseScheduling = {}));
    (function(Type3) {
      Type3["TYPE_UNSPECIFIED"] = "TYPE_UNSPECIFIED";
      Type3["STRING"] = "STRING";
      Type3["NUMBER"] = "NUMBER";
      Type3["INTEGER"] = "INTEGER";
      Type3["BOOLEAN"] = "BOOLEAN";
      Type3["ARRAY"] = "ARRAY";
      Type3["OBJECT"] = "OBJECT";
      Type3["NULL"] = "NULL";
    })(Type || (Type = {}));
    (function(Mode3) {
      Mode3["MODE_UNSPECIFIED"] = "MODE_UNSPECIFIED";
      Mode3["MODE_DYNAMIC"] = "MODE_DYNAMIC";
    })(Mode || (Mode = {}));
    (function(ApiSpec3) {
      ApiSpec3["API_SPEC_UNSPECIFIED"] = "API_SPEC_UNSPECIFIED";
      ApiSpec3["SIMPLE_SEARCH"] = "SIMPLE_SEARCH";
      ApiSpec3["ELASTIC_SEARCH"] = "ELASTIC_SEARCH";
    })(ApiSpec || (ApiSpec = {}));
    (function(AuthType4) {
      AuthType4["AUTH_TYPE_UNSPECIFIED"] = "AUTH_TYPE_UNSPECIFIED";
      AuthType4["NO_AUTH"] = "NO_AUTH";
      AuthType4["API_KEY_AUTH"] = "API_KEY_AUTH";
      AuthType4["HTTP_BASIC_AUTH"] = "HTTP_BASIC_AUTH";
      AuthType4["GOOGLE_SERVICE_ACCOUNT_AUTH"] = "GOOGLE_SERVICE_ACCOUNT_AUTH";
      AuthType4["OAUTH"] = "OAUTH";
      AuthType4["OIDC_AUTH"] = "OIDC_AUTH";
    })(AuthType || (AuthType = {}));
    (function(HttpElementLocation3) {
      HttpElementLocation3["HTTP_IN_UNSPECIFIED"] = "HTTP_IN_UNSPECIFIED";
      HttpElementLocation3["HTTP_IN_QUERY"] = "HTTP_IN_QUERY";
      HttpElementLocation3["HTTP_IN_HEADER"] = "HTTP_IN_HEADER";
      HttpElementLocation3["HTTP_IN_PATH"] = "HTTP_IN_PATH";
      HttpElementLocation3["HTTP_IN_BODY"] = "HTTP_IN_BODY";
      HttpElementLocation3["HTTP_IN_COOKIE"] = "HTTP_IN_COOKIE";
    })(HttpElementLocation || (HttpElementLocation = {}));
    (function(PhishBlockThreshold3) {
      PhishBlockThreshold3["PHISH_BLOCK_THRESHOLD_UNSPECIFIED"] = "PHISH_BLOCK_THRESHOLD_UNSPECIFIED";
      PhishBlockThreshold3["BLOCK_LOW_AND_ABOVE"] = "BLOCK_LOW_AND_ABOVE";
      PhishBlockThreshold3["BLOCK_MEDIUM_AND_ABOVE"] = "BLOCK_MEDIUM_AND_ABOVE";
      PhishBlockThreshold3["BLOCK_HIGH_AND_ABOVE"] = "BLOCK_HIGH_AND_ABOVE";
      PhishBlockThreshold3["BLOCK_HIGHER_AND_ABOVE"] = "BLOCK_HIGHER_AND_ABOVE";
      PhishBlockThreshold3["BLOCK_VERY_HIGH_AND_ABOVE"] = "BLOCK_VERY_HIGH_AND_ABOVE";
      PhishBlockThreshold3["BLOCK_ONLY_EXTREMELY_HIGH"] = "BLOCK_ONLY_EXTREMELY_HIGH";
    })(PhishBlockThreshold || (PhishBlockThreshold = {}));
    (function(ThinkingLevel3) {
      ThinkingLevel3["THINKING_LEVEL_UNSPECIFIED"] = "THINKING_LEVEL_UNSPECIFIED";
      ThinkingLevel3["LOW"] = "LOW";
      ThinkingLevel3["HIGH"] = "HIGH";
    })(ThinkingLevel || (ThinkingLevel = {}));
    (function(HarmCategory3) {
      HarmCategory3["HARM_CATEGORY_UNSPECIFIED"] = "HARM_CATEGORY_UNSPECIFIED";
      HarmCategory3["HARM_CATEGORY_HARASSMENT"] = "HARM_CATEGORY_HARASSMENT";
      HarmCategory3["HARM_CATEGORY_HATE_SPEECH"] = "HARM_CATEGORY_HATE_SPEECH";
      HarmCategory3["HARM_CATEGORY_SEXUALLY_EXPLICIT"] = "HARM_CATEGORY_SEXUALLY_EXPLICIT";
      HarmCategory3["HARM_CATEGORY_DANGEROUS_CONTENT"] = "HARM_CATEGORY_DANGEROUS_CONTENT";
      HarmCategory3["HARM_CATEGORY_CIVIC_INTEGRITY"] = "HARM_CATEGORY_CIVIC_INTEGRITY";
      HarmCategory3["HARM_CATEGORY_IMAGE_HATE"] = "HARM_CATEGORY_IMAGE_HATE";
      HarmCategory3["HARM_CATEGORY_IMAGE_DANGEROUS_CONTENT"] = "HARM_CATEGORY_IMAGE_DANGEROUS_CONTENT";
      HarmCategory3["HARM_CATEGORY_IMAGE_HARASSMENT"] = "HARM_CATEGORY_IMAGE_HARASSMENT";
      HarmCategory3["HARM_CATEGORY_IMAGE_SEXUALLY_EXPLICIT"] = "HARM_CATEGORY_IMAGE_SEXUALLY_EXPLICIT";
      HarmCategory3["HARM_CATEGORY_JAILBREAK"] = "HARM_CATEGORY_JAILBREAK";
    })(HarmCategory || (HarmCategory = {}));
    (function(HarmBlockMethod3) {
      HarmBlockMethod3["HARM_BLOCK_METHOD_UNSPECIFIED"] = "HARM_BLOCK_METHOD_UNSPECIFIED";
      HarmBlockMethod3["SEVERITY"] = "SEVERITY";
      HarmBlockMethod3["PROBABILITY"] = "PROBABILITY";
    })(HarmBlockMethod || (HarmBlockMethod = {}));
    (function(HarmBlockThreshold3) {
      HarmBlockThreshold3["HARM_BLOCK_THRESHOLD_UNSPECIFIED"] = "HARM_BLOCK_THRESHOLD_UNSPECIFIED";
      HarmBlockThreshold3["BLOCK_LOW_AND_ABOVE"] = "BLOCK_LOW_AND_ABOVE";
      HarmBlockThreshold3["BLOCK_MEDIUM_AND_ABOVE"] = "BLOCK_MEDIUM_AND_ABOVE";
      HarmBlockThreshold3["BLOCK_ONLY_HIGH"] = "BLOCK_ONLY_HIGH";
      HarmBlockThreshold3["BLOCK_NONE"] = "BLOCK_NONE";
      HarmBlockThreshold3["OFF"] = "OFF";
    })(HarmBlockThreshold || (HarmBlockThreshold = {}));
    (function(FinishReason3) {
      FinishReason3["FINISH_REASON_UNSPECIFIED"] = "FINISH_REASON_UNSPECIFIED";
      FinishReason3["STOP"] = "STOP";
      FinishReason3["MAX_TOKENS"] = "MAX_TOKENS";
      FinishReason3["SAFETY"] = "SAFETY";
      FinishReason3["RECITATION"] = "RECITATION";
      FinishReason3["LANGUAGE"] = "LANGUAGE";
      FinishReason3["OTHER"] = "OTHER";
      FinishReason3["BLOCKLIST"] = "BLOCKLIST";
      FinishReason3["PROHIBITED_CONTENT"] = "PROHIBITED_CONTENT";
      FinishReason3["SPII"] = "SPII";
      FinishReason3["MALFORMED_FUNCTION_CALL"] = "MALFORMED_FUNCTION_CALL";
      FinishReason3["IMAGE_SAFETY"] = "IMAGE_SAFETY";
      FinishReason3["UNEXPECTED_TOOL_CALL"] = "UNEXPECTED_TOOL_CALL";
      FinishReason3["IMAGE_PROHIBITED_CONTENT"] = "IMAGE_PROHIBITED_CONTENT";
      FinishReason3["NO_IMAGE"] = "NO_IMAGE";
    })(FinishReason || (FinishReason = {}));
    (function(HarmProbability3) {
      HarmProbability3["HARM_PROBABILITY_UNSPECIFIED"] = "HARM_PROBABILITY_UNSPECIFIED";
      HarmProbability3["NEGLIGIBLE"] = "NEGLIGIBLE";
      HarmProbability3["LOW"] = "LOW";
      HarmProbability3["MEDIUM"] = "MEDIUM";
      HarmProbability3["HIGH"] = "HIGH";
    })(HarmProbability || (HarmProbability = {}));
    (function(HarmSeverity3) {
      HarmSeverity3["HARM_SEVERITY_UNSPECIFIED"] = "HARM_SEVERITY_UNSPECIFIED";
      HarmSeverity3["HARM_SEVERITY_NEGLIGIBLE"] = "HARM_SEVERITY_NEGLIGIBLE";
      HarmSeverity3["HARM_SEVERITY_LOW"] = "HARM_SEVERITY_LOW";
      HarmSeverity3["HARM_SEVERITY_MEDIUM"] = "HARM_SEVERITY_MEDIUM";
      HarmSeverity3["HARM_SEVERITY_HIGH"] = "HARM_SEVERITY_HIGH";
    })(HarmSeverity || (HarmSeverity = {}));
    (function(UrlRetrievalStatus3) {
      UrlRetrievalStatus3["URL_RETRIEVAL_STATUS_UNSPECIFIED"] = "URL_RETRIEVAL_STATUS_UNSPECIFIED";
      UrlRetrievalStatus3["URL_RETRIEVAL_STATUS_SUCCESS"] = "URL_RETRIEVAL_STATUS_SUCCESS";
      UrlRetrievalStatus3["URL_RETRIEVAL_STATUS_ERROR"] = "URL_RETRIEVAL_STATUS_ERROR";
      UrlRetrievalStatus3["URL_RETRIEVAL_STATUS_PAYWALL"] = "URL_RETRIEVAL_STATUS_PAYWALL";
      UrlRetrievalStatus3["URL_RETRIEVAL_STATUS_UNSAFE"] = "URL_RETRIEVAL_STATUS_UNSAFE";
    })(UrlRetrievalStatus || (UrlRetrievalStatus = {}));
    (function(BlockedReason3) {
      BlockedReason3["BLOCKED_REASON_UNSPECIFIED"] = "BLOCKED_REASON_UNSPECIFIED";
      BlockedReason3["SAFETY"] = "SAFETY";
      BlockedReason3["OTHER"] = "OTHER";
      BlockedReason3["BLOCKLIST"] = "BLOCKLIST";
      BlockedReason3["PROHIBITED_CONTENT"] = "PROHIBITED_CONTENT";
      BlockedReason3["IMAGE_SAFETY"] = "IMAGE_SAFETY";
      BlockedReason3["MODEL_ARMOR"] = "MODEL_ARMOR";
      BlockedReason3["JAILBREAK"] = "JAILBREAK";
    })(BlockedReason || (BlockedReason = {}));
    (function(TrafficType3) {
      TrafficType3["TRAFFIC_TYPE_UNSPECIFIED"] = "TRAFFIC_TYPE_UNSPECIFIED";
      TrafficType3["ON_DEMAND"] = "ON_DEMAND";
      TrafficType3["PROVISIONED_THROUGHPUT"] = "PROVISIONED_THROUGHPUT";
    })(TrafficType || (TrafficType = {}));
    (function(Modality3) {
      Modality3["MODALITY_UNSPECIFIED"] = "MODALITY_UNSPECIFIED";
      Modality3["TEXT"] = "TEXT";
      Modality3["IMAGE"] = "IMAGE";
      Modality3["AUDIO"] = "AUDIO";
    })(Modality || (Modality = {}));
    (function(MediaResolution3) {
      MediaResolution3["MEDIA_RESOLUTION_UNSPECIFIED"] = "MEDIA_RESOLUTION_UNSPECIFIED";
      MediaResolution3["MEDIA_RESOLUTION_LOW"] = "MEDIA_RESOLUTION_LOW";
      MediaResolution3["MEDIA_RESOLUTION_MEDIUM"] = "MEDIA_RESOLUTION_MEDIUM";
      MediaResolution3["MEDIA_RESOLUTION_HIGH"] = "MEDIA_RESOLUTION_HIGH";
    })(MediaResolution || (MediaResolution = {}));
    (function(TuningMode3) {
      TuningMode3["TUNING_MODE_UNSPECIFIED"] = "TUNING_MODE_UNSPECIFIED";
      TuningMode3["TUNING_MODE_FULL"] = "TUNING_MODE_FULL";
      TuningMode3["TUNING_MODE_PEFT_ADAPTER"] = "TUNING_MODE_PEFT_ADAPTER";
    })(TuningMode || (TuningMode = {}));
    (function(AdapterSize3) {
      AdapterSize3["ADAPTER_SIZE_UNSPECIFIED"] = "ADAPTER_SIZE_UNSPECIFIED";
      AdapterSize3["ADAPTER_SIZE_ONE"] = "ADAPTER_SIZE_ONE";
      AdapterSize3["ADAPTER_SIZE_TWO"] = "ADAPTER_SIZE_TWO";
      AdapterSize3["ADAPTER_SIZE_FOUR"] = "ADAPTER_SIZE_FOUR";
      AdapterSize3["ADAPTER_SIZE_EIGHT"] = "ADAPTER_SIZE_EIGHT";
      AdapterSize3["ADAPTER_SIZE_SIXTEEN"] = "ADAPTER_SIZE_SIXTEEN";
      AdapterSize3["ADAPTER_SIZE_THIRTY_TWO"] = "ADAPTER_SIZE_THIRTY_TWO";
    })(AdapterSize || (AdapterSize = {}));
    (function(JobState3) {
      JobState3["JOB_STATE_UNSPECIFIED"] = "JOB_STATE_UNSPECIFIED";
      JobState3["JOB_STATE_QUEUED"] = "JOB_STATE_QUEUED";
      JobState3["JOB_STATE_PENDING"] = "JOB_STATE_PENDING";
      JobState3["JOB_STATE_RUNNING"] = "JOB_STATE_RUNNING";
      JobState3["JOB_STATE_SUCCEEDED"] = "JOB_STATE_SUCCEEDED";
      JobState3["JOB_STATE_FAILED"] = "JOB_STATE_FAILED";
      JobState3["JOB_STATE_CANCELLING"] = "JOB_STATE_CANCELLING";
      JobState3["JOB_STATE_CANCELLED"] = "JOB_STATE_CANCELLED";
      JobState3["JOB_STATE_PAUSED"] = "JOB_STATE_PAUSED";
      JobState3["JOB_STATE_EXPIRED"] = "JOB_STATE_EXPIRED";
      JobState3["JOB_STATE_UPDATING"] = "JOB_STATE_UPDATING";
      JobState3["JOB_STATE_PARTIALLY_SUCCEEDED"] = "JOB_STATE_PARTIALLY_SUCCEEDED";
    })(JobState || (JobState = {}));
    (function(TuningTask3) {
      TuningTask3["TUNING_TASK_UNSPECIFIED"] = "TUNING_TASK_UNSPECIFIED";
      TuningTask3["TUNING_TASK_I2V"] = "TUNING_TASK_I2V";
      TuningTask3["TUNING_TASK_T2V"] = "TUNING_TASK_T2V";
      TuningTask3["TUNING_TASK_R2V"] = "TUNING_TASK_R2V";
    })(TuningTask || (TuningTask = {}));
    (function(PartMediaResolutionLevel3) {
      PartMediaResolutionLevel3["MEDIA_RESOLUTION_UNSPECIFIED"] = "MEDIA_RESOLUTION_UNSPECIFIED";
      PartMediaResolutionLevel3["MEDIA_RESOLUTION_LOW"] = "MEDIA_RESOLUTION_LOW";
      PartMediaResolutionLevel3["MEDIA_RESOLUTION_MEDIUM"] = "MEDIA_RESOLUTION_MEDIUM";
      PartMediaResolutionLevel3["MEDIA_RESOLUTION_HIGH"] = "MEDIA_RESOLUTION_HIGH";
    })(PartMediaResolutionLevel || (PartMediaResolutionLevel = {}));
    (function(FeatureSelectionPreference3) {
      FeatureSelectionPreference3["FEATURE_SELECTION_PREFERENCE_UNSPECIFIED"] = "FEATURE_SELECTION_PREFERENCE_UNSPECIFIED";
      FeatureSelectionPreference3["PRIORITIZE_QUALITY"] = "PRIORITIZE_QUALITY";
      FeatureSelectionPreference3["BALANCED"] = "BALANCED";
      FeatureSelectionPreference3["PRIORITIZE_COST"] = "PRIORITIZE_COST";
    })(FeatureSelectionPreference || (FeatureSelectionPreference = {}));
    (function(Behavior3) {
      Behavior3["UNSPECIFIED"] = "UNSPECIFIED";
      Behavior3["BLOCKING"] = "BLOCKING";
      Behavior3["NON_BLOCKING"] = "NON_BLOCKING";
    })(Behavior || (Behavior = {}));
    (function(DynamicRetrievalConfigMode3) {
      DynamicRetrievalConfigMode3["MODE_UNSPECIFIED"] = "MODE_UNSPECIFIED";
      DynamicRetrievalConfigMode3["MODE_DYNAMIC"] = "MODE_DYNAMIC";
    })(DynamicRetrievalConfigMode || (DynamicRetrievalConfigMode = {}));
    (function(Environment3) {
      Environment3["ENVIRONMENT_UNSPECIFIED"] = "ENVIRONMENT_UNSPECIFIED";
      Environment3["ENVIRONMENT_BROWSER"] = "ENVIRONMENT_BROWSER";
    })(Environment || (Environment = {}));
    (function(FunctionCallingConfigMode3) {
      FunctionCallingConfigMode3["MODE_UNSPECIFIED"] = "MODE_UNSPECIFIED";
      FunctionCallingConfigMode3["AUTO"] = "AUTO";
      FunctionCallingConfigMode3["ANY"] = "ANY";
      FunctionCallingConfigMode3["NONE"] = "NONE";
      FunctionCallingConfigMode3["VALIDATED"] = "VALIDATED";
    })(FunctionCallingConfigMode || (FunctionCallingConfigMode = {}));
    (function(SafetyFilterLevel3) {
      SafetyFilterLevel3["BLOCK_LOW_AND_ABOVE"] = "BLOCK_LOW_AND_ABOVE";
      SafetyFilterLevel3["BLOCK_MEDIUM_AND_ABOVE"] = "BLOCK_MEDIUM_AND_ABOVE";
      SafetyFilterLevel3["BLOCK_ONLY_HIGH"] = "BLOCK_ONLY_HIGH";
      SafetyFilterLevel3["BLOCK_NONE"] = "BLOCK_NONE";
    })(SafetyFilterLevel || (SafetyFilterLevel = {}));
    (function(PersonGeneration3) {
      PersonGeneration3["DONT_ALLOW"] = "DONT_ALLOW";
      PersonGeneration3["ALLOW_ADULT"] = "ALLOW_ADULT";
      PersonGeneration3["ALLOW_ALL"] = "ALLOW_ALL";
    })(PersonGeneration || (PersonGeneration = {}));
    (function(ImagePromptLanguage3) {
      ImagePromptLanguage3["auto"] = "auto";
      ImagePromptLanguage3["en"] = "en";
      ImagePromptLanguage3["ja"] = "ja";
      ImagePromptLanguage3["ko"] = "ko";
      ImagePromptLanguage3["hi"] = "hi";
      ImagePromptLanguage3["zh"] = "zh";
      ImagePromptLanguage3["pt"] = "pt";
      ImagePromptLanguage3["es"] = "es";
    })(ImagePromptLanguage || (ImagePromptLanguage = {}));
    (function(MaskReferenceMode3) {
      MaskReferenceMode3["MASK_MODE_DEFAULT"] = "MASK_MODE_DEFAULT";
      MaskReferenceMode3["MASK_MODE_USER_PROVIDED"] = "MASK_MODE_USER_PROVIDED";
      MaskReferenceMode3["MASK_MODE_BACKGROUND"] = "MASK_MODE_BACKGROUND";
      MaskReferenceMode3["MASK_MODE_FOREGROUND"] = "MASK_MODE_FOREGROUND";
      MaskReferenceMode3["MASK_MODE_SEMANTIC"] = "MASK_MODE_SEMANTIC";
    })(MaskReferenceMode || (MaskReferenceMode = {}));
    (function(ControlReferenceType3) {
      ControlReferenceType3["CONTROL_TYPE_DEFAULT"] = "CONTROL_TYPE_DEFAULT";
      ControlReferenceType3["CONTROL_TYPE_CANNY"] = "CONTROL_TYPE_CANNY";
      ControlReferenceType3["CONTROL_TYPE_SCRIBBLE"] = "CONTROL_TYPE_SCRIBBLE";
      ControlReferenceType3["CONTROL_TYPE_FACE_MESH"] = "CONTROL_TYPE_FACE_MESH";
    })(ControlReferenceType || (ControlReferenceType = {}));
    (function(SubjectReferenceType3) {
      SubjectReferenceType3["SUBJECT_TYPE_DEFAULT"] = "SUBJECT_TYPE_DEFAULT";
      SubjectReferenceType3["SUBJECT_TYPE_PERSON"] = "SUBJECT_TYPE_PERSON";
      SubjectReferenceType3["SUBJECT_TYPE_ANIMAL"] = "SUBJECT_TYPE_ANIMAL";
      SubjectReferenceType3["SUBJECT_TYPE_PRODUCT"] = "SUBJECT_TYPE_PRODUCT";
    })(SubjectReferenceType || (SubjectReferenceType = {}));
    (function(EditMode3) {
      EditMode3["EDIT_MODE_DEFAULT"] = "EDIT_MODE_DEFAULT";
      EditMode3["EDIT_MODE_INPAINT_REMOVAL"] = "EDIT_MODE_INPAINT_REMOVAL";
      EditMode3["EDIT_MODE_INPAINT_INSERTION"] = "EDIT_MODE_INPAINT_INSERTION";
      EditMode3["EDIT_MODE_OUTPAINT"] = "EDIT_MODE_OUTPAINT";
      EditMode3["EDIT_MODE_CONTROLLED_EDITING"] = "EDIT_MODE_CONTROLLED_EDITING";
      EditMode3["EDIT_MODE_STYLE"] = "EDIT_MODE_STYLE";
      EditMode3["EDIT_MODE_BGSWAP"] = "EDIT_MODE_BGSWAP";
      EditMode3["EDIT_MODE_PRODUCT_IMAGE"] = "EDIT_MODE_PRODUCT_IMAGE";
    })(EditMode || (EditMode = {}));
    (function(SegmentMode3) {
      SegmentMode3["FOREGROUND"] = "FOREGROUND";
      SegmentMode3["BACKGROUND"] = "BACKGROUND";
      SegmentMode3["PROMPT"] = "PROMPT";
      SegmentMode3["SEMANTIC"] = "SEMANTIC";
      SegmentMode3["INTERACTIVE"] = "INTERACTIVE";
    })(SegmentMode || (SegmentMode = {}));
    (function(VideoGenerationReferenceType3) {
      VideoGenerationReferenceType3["ASSET"] = "ASSET";
      VideoGenerationReferenceType3["STYLE"] = "STYLE";
    })(VideoGenerationReferenceType || (VideoGenerationReferenceType = {}));
    (function(VideoGenerationMaskMode3) {
      VideoGenerationMaskMode3["INSERT"] = "INSERT";
      VideoGenerationMaskMode3["REMOVE"] = "REMOVE";
      VideoGenerationMaskMode3["REMOVE_STATIC"] = "REMOVE_STATIC";
      VideoGenerationMaskMode3["OUTPAINT"] = "OUTPAINT";
    })(VideoGenerationMaskMode || (VideoGenerationMaskMode = {}));
    (function(VideoCompressionQuality3) {
      VideoCompressionQuality3["OPTIMIZED"] = "OPTIMIZED";
      VideoCompressionQuality3["LOSSLESS"] = "LOSSLESS";
    })(VideoCompressionQuality || (VideoCompressionQuality = {}));
    (function(TuningMethod3) {
      TuningMethod3["SUPERVISED_FINE_TUNING"] = "SUPERVISED_FINE_TUNING";
      TuningMethod3["PREFERENCE_TUNING"] = "PREFERENCE_TUNING";
    })(TuningMethod || (TuningMethod = {}));
    (function(DocumentState3) {
      DocumentState3["STATE_UNSPECIFIED"] = "STATE_UNSPECIFIED";
      DocumentState3["STATE_PENDING"] = "STATE_PENDING";
      DocumentState3["STATE_ACTIVE"] = "STATE_ACTIVE";
      DocumentState3["STATE_FAILED"] = "STATE_FAILED";
    })(DocumentState || (DocumentState = {}));
    (function(FileState3) {
      FileState3["STATE_UNSPECIFIED"] = "STATE_UNSPECIFIED";
      FileState3["PROCESSING"] = "PROCESSING";
      FileState3["ACTIVE"] = "ACTIVE";
      FileState3["FAILED"] = "FAILED";
    })(FileState || (FileState = {}));
    (function(FileSource3) {
      FileSource3["SOURCE_UNSPECIFIED"] = "SOURCE_UNSPECIFIED";
      FileSource3["UPLOADED"] = "UPLOADED";
      FileSource3["GENERATED"] = "GENERATED";
    })(FileSource || (FileSource = {}));
    (function(TurnCompleteReason3) {
      TurnCompleteReason3["TURN_COMPLETE_REASON_UNSPECIFIED"] = "TURN_COMPLETE_REASON_UNSPECIFIED";
      TurnCompleteReason3["MALFORMED_FUNCTION_CALL"] = "MALFORMED_FUNCTION_CALL";
      TurnCompleteReason3["RESPONSE_REJECTED"] = "RESPONSE_REJECTED";
      TurnCompleteReason3["NEED_MORE_INPUT"] = "NEED_MORE_INPUT";
    })(TurnCompleteReason || (TurnCompleteReason = {}));
    (function(MediaModality3) {
      MediaModality3["MODALITY_UNSPECIFIED"] = "MODALITY_UNSPECIFIED";
      MediaModality3["TEXT"] = "TEXT";
      MediaModality3["IMAGE"] = "IMAGE";
      MediaModality3["VIDEO"] = "VIDEO";
      MediaModality3["AUDIO"] = "AUDIO";
      MediaModality3["DOCUMENT"] = "DOCUMENT";
    })(MediaModality || (MediaModality = {}));
    (function(StartSensitivity3) {
      StartSensitivity3["START_SENSITIVITY_UNSPECIFIED"] = "START_SENSITIVITY_UNSPECIFIED";
      StartSensitivity3["START_SENSITIVITY_HIGH"] = "START_SENSITIVITY_HIGH";
      StartSensitivity3["START_SENSITIVITY_LOW"] = "START_SENSITIVITY_LOW";
    })(StartSensitivity || (StartSensitivity = {}));
    (function(EndSensitivity3) {
      EndSensitivity3["END_SENSITIVITY_UNSPECIFIED"] = "END_SENSITIVITY_UNSPECIFIED";
      EndSensitivity3["END_SENSITIVITY_HIGH"] = "END_SENSITIVITY_HIGH";
      EndSensitivity3["END_SENSITIVITY_LOW"] = "END_SENSITIVITY_LOW";
    })(EndSensitivity || (EndSensitivity = {}));
    (function(ActivityHandling3) {
      ActivityHandling3["ACTIVITY_HANDLING_UNSPECIFIED"] = "ACTIVITY_HANDLING_UNSPECIFIED";
      ActivityHandling3["START_OF_ACTIVITY_INTERRUPTS"] = "START_OF_ACTIVITY_INTERRUPTS";
      ActivityHandling3["NO_INTERRUPTION"] = "NO_INTERRUPTION";
    })(ActivityHandling || (ActivityHandling = {}));
    (function(TurnCoverage3) {
      TurnCoverage3["TURN_COVERAGE_UNSPECIFIED"] = "TURN_COVERAGE_UNSPECIFIED";
      TurnCoverage3["TURN_INCLUDES_ONLY_ACTIVITY"] = "TURN_INCLUDES_ONLY_ACTIVITY";
      TurnCoverage3["TURN_INCLUDES_ALL_INPUT"] = "TURN_INCLUDES_ALL_INPUT";
    })(TurnCoverage || (TurnCoverage = {}));
    (function(Scale3) {
      Scale3["SCALE_UNSPECIFIED"] = "SCALE_UNSPECIFIED";
      Scale3["C_MAJOR_A_MINOR"] = "C_MAJOR_A_MINOR";
      Scale3["D_FLAT_MAJOR_B_FLAT_MINOR"] = "D_FLAT_MAJOR_B_FLAT_MINOR";
      Scale3["D_MAJOR_B_MINOR"] = "D_MAJOR_B_MINOR";
      Scale3["E_FLAT_MAJOR_C_MINOR"] = "E_FLAT_MAJOR_C_MINOR";
      Scale3["E_MAJOR_D_FLAT_MINOR"] = "E_MAJOR_D_FLAT_MINOR";
      Scale3["F_MAJOR_D_MINOR"] = "F_MAJOR_D_MINOR";
      Scale3["G_FLAT_MAJOR_E_FLAT_MINOR"] = "G_FLAT_MAJOR_E_FLAT_MINOR";
      Scale3["G_MAJOR_E_MINOR"] = "G_MAJOR_E_MINOR";
      Scale3["A_FLAT_MAJOR_F_MINOR"] = "A_FLAT_MAJOR_F_MINOR";
      Scale3["A_MAJOR_G_FLAT_MINOR"] = "A_MAJOR_G_FLAT_MINOR";
      Scale3["B_FLAT_MAJOR_G_MINOR"] = "B_FLAT_MAJOR_G_MINOR";
      Scale3["B_MAJOR_A_FLAT_MINOR"] = "B_MAJOR_A_FLAT_MINOR";
    })(Scale || (Scale = {}));
    (function(MusicGenerationMode3) {
      MusicGenerationMode3["MUSIC_GENERATION_MODE_UNSPECIFIED"] = "MUSIC_GENERATION_MODE_UNSPECIFIED";
      MusicGenerationMode3["QUALITY"] = "QUALITY";
      MusicGenerationMode3["DIVERSITY"] = "DIVERSITY";
      MusicGenerationMode3["VOCALIZATION"] = "VOCALIZATION";
    })(MusicGenerationMode || (MusicGenerationMode = {}));
    (function(LiveMusicPlaybackControl3) {
      LiveMusicPlaybackControl3["PLAYBACK_CONTROL_UNSPECIFIED"] = "PLAYBACK_CONTROL_UNSPECIFIED";
      LiveMusicPlaybackControl3["PLAY"] = "PLAY";
      LiveMusicPlaybackControl3["PAUSE"] = "PAUSE";
      LiveMusicPlaybackControl3["STOP"] = "STOP";
      LiveMusicPlaybackControl3["RESET_CONTEXT"] = "RESET_CONTEXT";
    })(LiveMusicPlaybackControl || (LiveMusicPlaybackControl = {}));
    __name(createPartFromText, "createPartFromText");
    __name(_isPart, "_isPart");
    __name(_toParts, "_toParts");
    __name(createUserContent, "createUserContent");
    __name(createModelContent, "createModelContent");
    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 _a7, _b2, _c2, _d, _e2, _f, _g, _h;
        if (((_d = (_c2 = (_b2 = (_a7 = this.candidates) === null || _a7 === void 0 ? void 0 : _a7[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 = (_e2 = this.candidates) === null || _e2 === void 0 ? void 0 : _e2[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" && fieldName !== "thoughtSignature" && (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 _a7, _b2, _c2, _d, _e2, _f, _g, _h;
        if (((_d = (_c2 = (_b2 = (_a7 = this.candidates) === null || _a7 === void 0 ? void 0 : _a7[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 = (_e2 = this.candidates) === null || _e2 === void 0 ? void 0 : _e2[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 _a7, _b2, _c2, _d, _e2, _f, _g, _h;
        if (((_d = (_c2 = (_b2 = (_a7 = this.candidates) === null || _a7 === void 0 ? void 0 : _a7[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 = (_e2 = this.candidates) === null || _e2 === void 0 ? void 0 : _e2[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 _a7, _b2, _c2, _d, _e2, _f, _g, _h, _j;
        if (((_d = (_c2 = (_b2 = (_a7 = this.candidates) === null || _a7 === void 0 ? void 0 : _a7[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 = (_e2 = this.candidates) === null || _e2 === void 0 ? void 0 : _e2[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 _a7, _b2, _c2, _d, _e2, _f, _g, _h, _j;
        if (((_d = (_c2 = (_b2 = (_a7 = this.candidates) === null || _a7 === void 0 ? void 0 : _a7[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 = (_e2 = this.candidates) === null || _e2 === void 0 ? void 0 : _e2[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");
      }
    };
    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();
        let response;
        const op = apiResponse;
        if (_isVertexAI) {
          response = generateVideosOperationFromVertex$1(op);
        } else {
          response = generateVideosOperationFromMldev$1(op);
        }
        Object.assign(operation, response);
        return operation;
      }
    };
    ListTuningJobsResponse = class {
      static {
        __name(this, "ListTuningJobsResponse");
      }
    };
    DeleteCachedContentResponse = class {
      static {
        __name(this, "DeleteCachedContentResponse");
      }
    };
    ListCachedContentsResponse = class {
      static {
        __name(this, "ListCachedContentsResponse");
      }
    };
    ListDocumentsResponse = class {
      static {
        __name(this, "ListDocumentsResponse");
      }
    };
    ListFileSearchStoresResponse = class {
      static {
        __name(this, "ListFileSearchStoresResponse");
      }
    };
    UploadToFileSearchStoreResumableResponse = class {
      static {
        __name(this, "UploadToFileSearchStoreResumableResponse");
      }
    };
    ImportFileOperation = class _ImportFileOperation {
      static {
        __name(this, "ImportFileOperation");
      }
      /**
       * 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 _ImportFileOperation();
        const op = apiResponse;
        const response = importFileOperationFromMldev$1(op);
        Object.assign(operation, response);
        return operation;
      }
    };
    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 _a7, _b2, _c2;
        let text = "";
        let anyTextPartFound = false;
        const nonTextParts = [];
        for (const part of (_c2 = (_b2 = (_a7 = this.serverContent) === null || _a7 === void 0 ? void 0 : _a7.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 _a7, _b2, _c2;
        let data = "";
        const nonDataParts = [];
        for (const part of (_c2 = (_b2 = (_a7 = this.serverContent) === null || _a7 === void 0 ? void 0 : _a7.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;
      }
    };
    UploadToFileSearchStoreOperation = class _UploadToFileSearchStoreOperation {
      static {
        __name(this, "UploadToFileSearchStoreOperation");
      }
      /**
       * 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 _UploadToFileSearchStoreOperation();
        const op = apiResponse;
        const response = uploadToFileSearchStoreOperationFromMldev(op);
        Object.assign(operation, response);
        return operation;
      }
    };
    __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(tRecvBatchJobDestination, "tRecvBatchJobDestination");
    __name(tBatchJobName, "tBatchJobName");
    __name(tJobState, "tJobState");
    __name(batchJobDestinationFromMldev, "batchJobDestinationFromMldev");
    __name(batchJobDestinationFromVertex, "batchJobDestinationFromVertex");
    __name(batchJobDestinationToVertex, "batchJobDestinationToVertex");
    __name(batchJobFromMldev, "batchJobFromMldev");
    __name(batchJobFromVertex, "batchJobFromVertex");
    __name(batchJobSourceFromVertex, "batchJobSourceFromVertex");
    __name(batchJobSourceToMldev, "batchJobSourceToMldev");
    __name(batchJobSourceToVertex, "batchJobSourceToVertex");
    __name(blobToMldev$4, "blobToMldev$4");
    __name(cancelBatchJobParametersToMldev, "cancelBatchJobParametersToMldev");
    __name(cancelBatchJobParametersToVertex, "cancelBatchJobParametersToVertex");
    __name(candidateFromMldev$1, "candidateFromMldev$1");
    __name(citationMetadataFromMldev$1, "citationMetadataFromMldev$1");
    __name(contentToMldev$4, "contentToMldev$4");
    __name(createBatchJobConfigToMldev, "createBatchJobConfigToMldev");
    __name(createBatchJobConfigToVertex, "createBatchJobConfigToVertex");
    __name(createBatchJobParametersToMldev, "createBatchJobParametersToMldev");
    __name(createBatchJobParametersToVertex, "createBatchJobParametersToVertex");
    __name(createEmbeddingsBatchJobConfigToMldev, "createEmbeddingsBatchJobConfigToMldev");
    __name(createEmbeddingsBatchJobParametersToMldev, "createEmbeddingsBatchJobParametersToMldev");
    __name(deleteBatchJobParametersToMldev, "deleteBatchJobParametersToMldev");
    __name(deleteBatchJobParametersToVertex, "deleteBatchJobParametersToVertex");
    __name(deleteResourceJobFromMldev, "deleteResourceJobFromMldev");
    __name(deleteResourceJobFromVertex, "deleteResourceJobFromVertex");
    __name(embedContentBatchToMldev, "embedContentBatchToMldev");
    __name(embedContentConfigToMldev$1, "embedContentConfigToMldev$1");
    __name(embeddingsBatchJobSourceToMldev, "embeddingsBatchJobSourceToMldev");
    __name(fileDataToMldev$4, "fileDataToMldev$4");
    __name(functionCallToMldev$4, "functionCallToMldev$4");
    __name(functionCallingConfigToMldev$2, "functionCallingConfigToMldev$2");
    __name(generateContentConfigToMldev$1, "generateContentConfigToMldev$1");
    __name(generateContentResponseFromMldev$1, "generateContentResponseFromMldev$1");
    __name(getBatchJobParametersToMldev, "getBatchJobParametersToMldev");
    __name(getBatchJobParametersToVertex, "getBatchJobParametersToVertex");
    __name(googleMapsToMldev$4, "googleMapsToMldev$4");
    __name(googleSearchToMldev$4, "googleSearchToMldev$4");
    __name(imageConfigToMldev$1, "imageConfigToMldev$1");
    __name(inlinedRequestToMldev, "inlinedRequestToMldev");
    __name(inlinedResponseFromMldev, "inlinedResponseFromMldev");
    __name(listBatchJobsConfigToMldev, "listBatchJobsConfigToMldev");
    __name(listBatchJobsConfigToVertex, "listBatchJobsConfigToVertex");
    __name(listBatchJobsParametersToMldev, "listBatchJobsParametersToMldev");
    __name(listBatchJobsParametersToVertex, "listBatchJobsParametersToVertex");
    __name(listBatchJobsResponseFromMldev, "listBatchJobsResponseFromMldev");
    __name(listBatchJobsResponseFromVertex, "listBatchJobsResponseFromVertex");
    __name(partToMldev$4, "partToMldev$4");
    __name(safetySettingToMldev$1, "safetySettingToMldev$1");
    __name(toolConfigToMldev$2, "toolConfigToMldev$2");
    __name(toolToMldev$4, "toolToMldev$4");
    (function(PagedItem3) {
      PagedItem3["PAGED_ITEM_BATCH_JOBS"] = "batchJobs";
      PagedItem3["PAGED_ITEM_MODELS"] = "models";
      PagedItem3["PAGED_ITEM_TUNING_JOBS"] = "tuningJobs";
      PagedItem3["PAGED_ITEM_FILES"] = "files";
      PagedItem3["PAGED_ITEM_CACHED_CONTENTS"] = "cachedContents";
      PagedItem3["PAGED_ITEM_FILE_SEARCH_STORES"] = "fileSearchStores";
      PagedItem3["PAGED_ITEM_DOCUMENTS"] = "documents";
    })(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 _a7, _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 = (_a7 = requestParams["config"]) === null || _a7 === void 0 ? void 0 : _a7["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 _a7;
        if (((_a7 = this.params["config"]) === null || _a7 === void 0 ? void 0 : _a7["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) => {
          if (this.apiClient.isVertexAI()) {
            params.config = this.formatDestination(params.src, params.config);
          }
          return this.createInternal(params);
        };
        this.createEmbeddings = async (params) => {
          console.warn("batches.createEmbeddings() is experimental and may change without notice.");
          if (this.apiClient.isVertexAI()) {
            throw new Error("Vertex AI does not support batches.createEmbeddings.");
          }
          return this.createEmbeddingsInternal(params);
        };
        this.list = async (params = {}) => {
          return new Pager(PagedItem.PAGED_ITEM_BATCH_JOBS, (x3) => this.listInternal(x3), await this.listInternal(params), params);
        };
      }
      // Helper function to handle inlined generate content requests
      createInlinedGenerateContentRequest(params) {
        const body = createBatchJobParametersToMldev(
          this.apiClient,
          // Use instance apiClient
          params
        );
        const urlParams = body["_url"];
        const path125 = formatMap("{model}:batchGenerateContent", urlParams);
        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 = Object.assign({}, 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"];
        return { path: path125, body };
      }
      // Helper function to get the first GCS URI
      getGcsUri(src) {
        if (typeof src === "string") {
          return src.startsWith("gs://") ? src : void 0;
        }
        if (!Array.isArray(src) && src.gcsUri && src.gcsUri.length > 0) {
          return src.gcsUri[0];
        }
        return void 0;
      }
      // Helper function to get the BigQuery URI
      getBigqueryUri(src) {
        if (typeof src === "string") {
          return src.startsWith("bq://") ? src : void 0;
        }
        if (!Array.isArray(src)) {
          return src.bigqueryUri;
        }
        return void 0;
      }
      // Function to format the destination configuration for Vertex AI
      formatDestination(src, config2) {
        const newConfig = config2 ? Object.assign({}, config2) : {};
        const timestampStr = Date.now().toString();
        if (!newConfig.displayName) {
          newConfig.displayName = `genaiBatchJob_${timestampStr}`;
        }
        if (newConfig.dest === void 0) {
          const gcsUri = this.getGcsUri(src);
          const bigqueryUri = this.getBigqueryUri(src);
          if (gcsUri) {
            if (gcsUri.endsWith(".jsonl")) {
              newConfig.dest = `${gcsUri.slice(0, -6)}/dest`;
            } else {
              newConfig.dest = `${gcsUri}_dest_${timestampStr}`;
            }
          } else if (bigqueryUri) {
            newConfig.dest = `${bigqueryUri}_dest_${timestampStr}`;
          } else {
            throw new Error("Unsupported source for Vertex AI: No GCS or BigQuery URI found.");
          }
        }
        return newConfig;
      }
      /**
       * Internal method to create batch job.
       *
       * @param params - The parameters for create batch job request.
       * @return The created batch job.
       *
       */
      async createInternal(params) {
        var _a7, _b2, _c2, _d;
        let response;
        let path125 = "";
        let queryParams = {};
        if (this.apiClient.isVertexAI()) {
          const body = createBatchJobParametersToVertex(this.apiClient, params);
          path125 = formatMap("batchPredictionJobs", body["_url"]);
          queryParams = body["_query"];
          delete body["_url"];
          delete body["_query"];
          response = this.apiClient.request({
            path: path125,
            queryParams,
            body: JSON.stringify(body),
            httpMethod: "POST",
            httpOptions: (_a7 = params.config) === null || _a7 === void 0 ? void 0 : _a7.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);
          path125 = formatMap("{model}:batchGenerateContent", body["_url"]);
          queryParams = body["_query"];
          delete body["_url"];
          delete body["_query"];
          response = this.apiClient.request({
            path: path125,
            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;
          });
        }
      }
      /**
       * Internal method to create batch job.
       *
       * @param params - The parameters for create batch job request.
       * @return The created batch job.
       *
       */
      async createEmbeddingsInternal(params) {
        var _a7, _b2;
        let response;
        let path125 = "";
        let queryParams = {};
        if (this.apiClient.isVertexAI()) {
          throw new Error("This method is only supported by the Gemini Developer API.");
        } else {
          const body = createEmbeddingsBatchJobParametersToMldev(this.apiClient, params);
          path125 = formatMap("{model}:asyncBatchEmbedContent", body["_url"]);
          queryParams = body["_query"];
          delete body["_url"];
          delete body["_query"];
          response = this.apiClient.request({
            path: path125,
            queryParams,
            body: JSON.stringify(body),
            httpMethod: "POST",
            httpOptions: (_a7 = params.config) === null || _a7 === void 0 ? void 0 : _a7.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;
          });
        }
      }
      /**
       * 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 _a7, _b2, _c2, _d;
        let response;
        let path125 = "";
        let queryParams = {};
        if (this.apiClient.isVertexAI()) {
          const body = getBatchJobParametersToVertex(this.apiClient, params);
          path125 = formatMap("batchPredictionJobs/{name}", body["_url"]);
          queryParams = body["_query"];
          delete body["_url"];
          delete body["_query"];
          response = this.apiClient.request({
            path: path125,
            queryParams,
            body: JSON.stringify(body),
            httpMethod: "GET",
            httpOptions: (_a7 = params.config) === null || _a7 === void 0 ? void 0 : _a7.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);
          path125 = formatMap("batches/{name}", body["_url"]);
          queryParams = body["_query"];
          delete body["_url"];
          delete body["_query"];
          response = this.apiClient.request({
            path: path125,
            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 _a7, _b2, _c2, _d;
        let path125 = "";
        let queryParams = {};
        if (this.apiClient.isVertexAI()) {
          const body = cancelBatchJobParametersToVertex(this.apiClient, params);
          path125 = formatMap("batchPredictionJobs/{name}:cancel", body["_url"]);
          queryParams = body["_query"];
          delete body["_url"];
          delete body["_query"];
          await this.apiClient.request({
            path: path125,
            queryParams,
            body: JSON.stringify(body),
            httpMethod: "POST",
            httpOptions: (_a7 = params.config) === null || _a7 === void 0 ? void 0 : _a7.httpOptions,
            abortSignal: (_b2 = params.config) === null || _b2 === void 0 ? void 0 : _b2.abortSignal
          });
        } else {
          const body = cancelBatchJobParametersToMldev(this.apiClient, params);
          path125 = formatMap("batches/{name}:cancel", body["_url"]);
          queryParams = body["_query"];
          delete body["_url"];
          delete body["_query"];
          await this.apiClient.request({
            path: path125,
            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 _a7, _b2, _c2, _d;
        let response;
        let path125 = "";
        let queryParams = {};
        if (this.apiClient.isVertexAI()) {
          const body = listBatchJobsParametersToVertex(params);
          path125 = formatMap("batchPredictionJobs", body["_url"]);
          queryParams = body["_query"];
          delete body["_url"];
          delete body["_query"];
          response = this.apiClient.request({
            path: path125,
            queryParams,
            body: JSON.stringify(body),
            httpMethod: "GET",
            httpOptions: (_a7 = params.config) === null || _a7 === void 0 ? void 0 : _a7.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);
          path125 = formatMap("batches", body["_url"]);
          queryParams = body["_query"];
          delete body["_url"];
          delete body["_query"];
          response = this.apiClient.request({
            path: path125,
            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 _a7, _b2, _c2, _d;
        let response;
        let path125 = "";
        let queryParams = {};
        if (this.apiClient.isVertexAI()) {
          const body = deleteBatchJobParametersToVertex(this.apiClient, params);
          path125 = formatMap("batchPredictionJobs/{name}", body["_url"]);
          queryParams = body["_query"];
          delete body["_url"];
          delete body["_query"];
          response = this.apiClient.request({
            path: path125,
            queryParams,
            body: JSON.stringify(body),
            httpMethod: "DELETE",
            httpOptions: (_a7 = params.config) === null || _a7 === void 0 ? void 0 : _a7.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);
          path125 = formatMap("batches/{name}", body["_url"]);
          queryParams = body["_query"];
          delete body["_url"];
          delete body["_query"];
          response = this.apiClient.request({
            path: path125,
            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(blobToMldev$3, "blobToMldev$3");
    __name(contentToMldev$3, "contentToMldev$3");
    __name(createCachedContentConfigToMldev, "createCachedContentConfigToMldev");
    __name(createCachedContentConfigToVertex, "createCachedContentConfigToVertex");
    __name(createCachedContentParametersToMldev, "createCachedContentParametersToMldev");
    __name(createCachedContentParametersToVertex, "createCachedContentParametersToVertex");
    __name(deleteCachedContentParametersToMldev, "deleteCachedContentParametersToMldev");
    __name(deleteCachedContentParametersToVertex, "deleteCachedContentParametersToVertex");
    __name(deleteCachedContentResponseFromMldev, "deleteCachedContentResponseFromMldev");
    __name(deleteCachedContentResponseFromVertex, "deleteCachedContentResponseFromVertex");
    __name(fileDataToMldev$3, "fileDataToMldev$3");
    __name(functionCallToMldev$3, "functionCallToMldev$3");
    __name(functionCallingConfigToMldev$1, "functionCallingConfigToMldev$1");
    __name(functionDeclarationToVertex$2, "functionDeclarationToVertex$2");
    __name(getCachedContentParametersToMldev, "getCachedContentParametersToMldev");
    __name(getCachedContentParametersToVertex, "getCachedContentParametersToVertex");
    __name(googleMapsToMldev$3, "googleMapsToMldev$3");
    __name(googleSearchToMldev$3, "googleSearchToMldev$3");
    __name(listCachedContentsConfigToMldev, "listCachedContentsConfigToMldev");
    __name(listCachedContentsConfigToVertex, "listCachedContentsConfigToVertex");
    __name(listCachedContentsParametersToMldev, "listCachedContentsParametersToMldev");
    __name(listCachedContentsParametersToVertex, "listCachedContentsParametersToVertex");
    __name(listCachedContentsResponseFromMldev, "listCachedContentsResponseFromMldev");
    __name(listCachedContentsResponseFromVertex, "listCachedContentsResponseFromVertex");
    __name(partToMldev$3, "partToMldev$3");
    __name(toolConfigToMldev$1, "toolConfigToMldev$1");
    __name(toolToMldev$3, "toolToMldev$3");
    __name(toolToVertex$2, "toolToVertex$2");
    __name(updateCachedContentConfigToMldev, "updateCachedContentConfigToMldev");
    __name(updateCachedContentConfigToVertex, "updateCachedContentConfigToVertex");
    __name(updateCachedContentParametersToMldev, "updateCachedContentParametersToMldev");
    __name(updateCachedContentParametersToVertex, "updateCachedContentParametersToVertex");
    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, (x3) => this.listInternal(x3), 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 _a7, _b2, _c2, _d;
        let response;
        let path125 = "";
        let queryParams = {};
        if (this.apiClient.isVertexAI()) {
          const body = createCachedContentParametersToVertex(this.apiClient, params);
          path125 = formatMap("cachedContents", body["_url"]);
          queryParams = body["_query"];
          delete body["_url"];
          delete body["_query"];
          response = this.apiClient.request({
            path: path125,
            queryParams,
            body: JSON.stringify(body),
            httpMethod: "POST",
            httpOptions: (_a7 = params.config) === null || _a7 === void 0 ? void 0 : _a7.httpOptions,
            abortSignal: (_b2 = params.config) === null || _b2 === void 0 ? void 0 : _b2.abortSignal
          }).then((httpResponse) => {
            return httpResponse.json();
          });
          return response.then((resp) => {
            return resp;
          });
        } else {
          const body = createCachedContentParametersToMldev(this.apiClient, params);
          path125 = formatMap("cachedContents", body["_url"]);
          queryParams = body["_query"];
          delete body["_url"];
          delete body["_query"];
          response = this.apiClient.request({
            path: path125,
            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((resp) => {
            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 _a7, _b2, _c2, _d;
        let response;
        let path125 = "";
        let queryParams = {};
        if (this.apiClient.isVertexAI()) {
          const body = getCachedContentParametersToVertex(this.apiClient, params);
          path125 = formatMap("{name}", body["_url"]);
          queryParams = body["_query"];
          delete body["_url"];
          delete body["_query"];
          response = this.apiClient.request({
            path: path125,
            queryParams,
            body: JSON.stringify(body),
            httpMethod: "GET",
            httpOptions: (_a7 = params.config) === null || _a7 === void 0 ? void 0 : _a7.httpOptions,
            abortSignal: (_b2 = params.config) === null || _b2 === void 0 ? void 0 : _b2.abortSignal
          }).then((httpResponse) => {
            return httpResponse.json();
          });
          return response.then((resp) => {
            return resp;
          });
        } else {
          const body = getCachedContentParametersToMldev(this.apiClient, params);
          path125 = formatMap("{name}", body["_url"]);
          queryParams = body["_query"];
          delete body["_url"];
          delete body["_query"];
          response = this.apiClient.request({
            path: path125,
            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((resp) => {
            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 _a7, _b2, _c2, _d;
        let response;
        let path125 = "";
        let queryParams = {};
        if (this.apiClient.isVertexAI()) {
          const body = deleteCachedContentParametersToVertex(this.apiClient, params);
          path125 = formatMap("{name}", body["_url"]);
          queryParams = body["_query"];
          delete body["_url"];
          delete body["_query"];
          response = this.apiClient.request({
            path: path125,
            queryParams,
            body: JSON.stringify(body),
            httpMethod: "DELETE",
            httpOptions: (_a7 = params.config) === null || _a7 === void 0 ? void 0 : _a7.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);
          path125 = formatMap("{name}", body["_url"]);
          queryParams = body["_query"];
          delete body["_url"];
          delete body["_query"];
          response = this.apiClient.request({
            path: path125,
            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 _a7, _b2, _c2, _d;
        let response;
        let path125 = "";
        let queryParams = {};
        if (this.apiClient.isVertexAI()) {
          const body = updateCachedContentParametersToVertex(this.apiClient, params);
          path125 = formatMap("{name}", body["_url"]);
          queryParams = body["_query"];
          delete body["_url"];
          delete body["_query"];
          response = this.apiClient.request({
            path: path125,
            queryParams,
            body: JSON.stringify(body),
            httpMethod: "PATCH",
            httpOptions: (_a7 = params.config) === null || _a7 === void 0 ? void 0 : _a7.httpOptions,
            abortSignal: (_b2 = params.config) === null || _b2 === void 0 ? void 0 : _b2.abortSignal
          }).then((httpResponse) => {
            return httpResponse.json();
          });
          return response.then((resp) => {
            return resp;
          });
        } else {
          const body = updateCachedContentParametersToMldev(this.apiClient, params);
          path125 = formatMap("{name}", body["_url"]);
          queryParams = body["_query"];
          delete body["_url"];
          delete body["_query"];
          response = this.apiClient.request({
            path: path125,
            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((resp) => {
            return resp;
          });
        }
      }
      async listInternal(params) {
        var _a7, _b2, _c2, _d;
        let response;
        let path125 = "";
        let queryParams = {};
        if (this.apiClient.isVertexAI()) {
          const body = listCachedContentsParametersToVertex(params);
          path125 = formatMap("cachedContents", body["_url"]);
          queryParams = body["_query"];
          delete body["_url"];
          delete body["_query"];
          response = this.apiClient.request({
            path: path125,
            queryParams,
            body: JSON.stringify(body),
            httpMethod: "GET",
            httpOptions: (_a7 = params.config) === null || _a7 === void 0 ? void 0 : _a7.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);
          path125 = formatMap("cachedContents", body["_url"]);
          queryParams = body["_query"];
          delete body["_url"];
          delete body["_query"];
          response = this.apiClient.request({
            path: path125,
            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, config2 = {}, history = []) {
        this.apiClient = apiClient;
        this.modelsModule = modelsModule;
        this.model = model;
        this.config = config2;
        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 _a7;
        await this.sendPromise;
        const inputContent = tContent(params.message);
        const responsePromise = this.modelsModule.generateContent({
          model: this.model,
          contents: this.getHistory(true).concat(inputContent),
          config: (_a7 = params.config) !== null && _a7 !== void 0 ? _a7 : this.config
        });
        this.sendPromise = (async () => {
          var _a8, _b2, _c2;
          const response = await responsePromise;
          const outputContent = (_b2 = (_a8 = response.candidates) === null || _a8 === void 0 ? void 0 : _a8[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 _a7;
        await this.sendPromise;
        const inputContent = tContent(params.message);
        const streamResponse2 = this.modelsModule.generateContentStream({
          model: this.model,
          contents: this.getHistory(true).concat(inputContent),
          config: (_a7 = params.config) !== null && _a7 !== void 0 ? _a7 : 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 _a7, _b2;
        return __asyncGenerator(this, arguments, /* @__PURE__ */ __name(function* processStreamResponse_1() {
          var _c2, e_1, _d, _e2;
          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) {
              _e2 = streamResponse_1_1.value;
              _f = false;
              const chunk = _e2;
              if (isValidResponse(chunk)) {
                const content = (_b2 = (_a7 = chunk.candidates) === null || _a7 === void 0 ? void 0 : _a7[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(createFileParametersToMldev, "createFileParametersToMldev");
    __name(createFileResponseFromMldev, "createFileResponseFromMldev");
    __name(deleteFileParametersToMldev, "deleteFileParametersToMldev");
    __name(deleteFileResponseFromMldev, "deleteFileResponseFromMldev");
    __name(getFileParametersToMldev, "getFileParametersToMldev");
    __name(listFilesConfigToMldev, "listFilesConfigToMldev");
    __name(listFilesParametersToMldev, "listFilesParametersToMldev");
    __name(listFilesResponseFromMldev, "listFilesResponseFromMldev");
    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, (x3) => this.listInternal(x3), 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((resp) => {
          return resp;
        });
      }
      /**
       * 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 _a7, _b2;
        let response;
        let path125 = "";
        let queryParams = {};
        if (this.apiClient.isVertexAI()) {
          throw new Error("This method is only supported by the Gemini Developer API.");
        } else {
          const body = listFilesParametersToMldev(params);
          path125 = formatMap("files", body["_url"]);
          queryParams = body["_query"];
          delete body["_url"];
          delete body["_query"];
          response = this.apiClient.request({
            path: path125,
            queryParams,
            body: JSON.stringify(body),
            httpMethod: "GET",
            httpOptions: (_a7 = params.config) === null || _a7 === void 0 ? void 0 : _a7.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 _a7, _b2;
        let response;
        let path125 = "";
        let queryParams = {};
        if (this.apiClient.isVertexAI()) {
          throw new Error("This method is only supported by the Gemini Developer API.");
        } else {
          const body = createFileParametersToMldev(params);
          path125 = formatMap("upload/v1beta/files", body["_url"]);
          queryParams = body["_query"];
          delete body["_url"];
          delete body["_query"];
          response = this.apiClient.request({
            path: path125,
            queryParams,
            body: JSON.stringify(body),
            httpMethod: "POST",
            httpOptions: (_a7 = params.config) === null || _a7 === void 0 ? void 0 : _a7.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 _a7, _b2;
        let response;
        let path125 = "";
        let queryParams = {};
        if (this.apiClient.isVertexAI()) {
          throw new Error("This method is only supported by the Gemini Developer API.");
        } else {
          const body = getFileParametersToMldev(params);
          path125 = formatMap("files/{file}", body["_url"]);
          queryParams = body["_query"];
          delete body["_url"];
          delete body["_query"];
          response = this.apiClient.request({
            path: path125,
            queryParams,
            body: JSON.stringify(body),
            httpMethod: "GET",
            httpOptions: (_a7 = params.config) === null || _a7 === void 0 ? void 0 : _a7.httpOptions,
            abortSignal: (_b2 = params.config) === null || _b2 === void 0 ? void 0 : _b2.abortSignal
          }).then((httpResponse) => {
            return httpResponse.json();
          });
          return response.then((resp) => {
            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 _a7, _b2;
        let response;
        let path125 = "";
        let queryParams = {};
        if (this.apiClient.isVertexAI()) {
          throw new Error("This method is only supported by the Gemini Developer API.");
        } else {
          const body = deleteFileParametersToMldev(params);
          path125 = formatMap("files/{file}", body["_url"]);
          queryParams = body["_query"];
          delete body["_url"];
          delete body["_query"];
          response = this.apiClient.request({
            path: path125,
            queryParams,
            body: JSON.stringify(body),
            httpMethod: "DELETE",
            httpOptions: (_a7 = params.config) === null || _a7 === void 0 ? void 0 : _a7.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(blobToMldev$2, "blobToMldev$2");
    __name(contentToMldev$2, "contentToMldev$2");
    __name(fileDataToMldev$2, "fileDataToMldev$2");
    __name(functionCallToMldev$2, "functionCallToMldev$2");
    __name(functionDeclarationToVertex$1, "functionDeclarationToVertex$1");
    __name(generationConfigToVertex$1, "generationConfigToVertex$1");
    __name(googleMapsToMldev$2, "googleMapsToMldev$2");
    __name(googleSearchToMldev$2, "googleSearchToMldev$2");
    __name(liveConnectConfigToMldev$1, "liveConnectConfigToMldev$1");
    __name(liveConnectConfigToVertex, "liveConnectConfigToVertex");
    __name(liveConnectParametersToMldev, "liveConnectParametersToMldev");
    __name(liveConnectParametersToVertex, "liveConnectParametersToVertex");
    __name(liveMusicSetConfigParametersToMldev, "liveMusicSetConfigParametersToMldev");
    __name(liveMusicSetWeightedPromptsParametersToMldev, "liveMusicSetWeightedPromptsParametersToMldev");
    __name(liveSendRealtimeInputParametersToMldev, "liveSendRealtimeInputParametersToMldev");
    __name(liveSendRealtimeInputParametersToVertex, "liveSendRealtimeInputParametersToVertex");
    __name(liveServerMessageFromVertex, "liveServerMessageFromVertex");
    __name(partToMldev$2, "partToMldev$2");
    __name(sessionResumptionConfigToMldev$1, "sessionResumptionConfigToMldev$1");
    __name(speechConfigToVertex$1, "speechConfigToVertex$1");
    __name(toolToMldev$2, "toolToMldev$2");
    __name(toolToVertex$1, "toolToVertex$1");
    __name(usageMetadataFromVertex, "usageMetadataFromVertex");
    __name(blobToMldev$1, "blobToMldev$1");
    __name(candidateFromMldev, "candidateFromMldev");
    __name(citationMetadataFromMldev, "citationMetadataFromMldev");
    __name(computeTokensParametersToVertex, "computeTokensParametersToVertex");
    __name(computeTokensResponseFromVertex, "computeTokensResponseFromVertex");
    __name(contentEmbeddingFromVertex, "contentEmbeddingFromVertex");
    __name(contentEmbeddingStatisticsFromVertex, "contentEmbeddingStatisticsFromVertex");
    __name(contentToMldev$1, "contentToMldev$1");
    __name(controlReferenceConfigToVertex, "controlReferenceConfigToVertex");
    __name(countTokensConfigToMldev, "countTokensConfigToMldev");
    __name(countTokensConfigToVertex, "countTokensConfigToVertex");
    __name(countTokensParametersToMldev, "countTokensParametersToMldev");
    __name(countTokensParametersToVertex, "countTokensParametersToVertex");
    __name(countTokensResponseFromMldev, "countTokensResponseFromMldev");
    __name(countTokensResponseFromVertex, "countTokensResponseFromVertex");
    __name(deleteModelParametersToMldev, "deleteModelParametersToMldev");
    __name(deleteModelParametersToVertex, "deleteModelParametersToVertex");
    __name(deleteModelResponseFromMldev, "deleteModelResponseFromMldev");
    __name(deleteModelResponseFromVertex, "deleteModelResponseFromVertex");
    __name(editImageConfigToVertex, "editImageConfigToVertex");
    __name(editImageParametersInternalToVertex, "editImageParametersInternalToVertex");
    __name(editImageResponseFromVertex, "editImageResponseFromVertex");
    __name(embedContentConfigToMldev, "embedContentConfigToMldev");
    __name(embedContentConfigToVertex, "embedContentConfigToVertex");
    __name(embedContentParametersToMldev, "embedContentParametersToMldev");
    __name(embedContentParametersToVertex, "embedContentParametersToVertex");
    __name(embedContentResponseFromMldev, "embedContentResponseFromMldev");
    __name(embedContentResponseFromVertex, "embedContentResponseFromVertex");
    __name(endpointFromVertex, "endpointFromVertex");
    __name(fileDataToMldev$1, "fileDataToMldev$1");
    __name(functionCallToMldev$1, "functionCallToMldev$1");
    __name(functionCallingConfigToMldev, "functionCallingConfigToMldev");
    __name(functionDeclarationToVertex, "functionDeclarationToVertex");
    __name(generateContentConfigToMldev, "generateContentConfigToMldev");
    __name(generateContentConfigToVertex, "generateContentConfigToVertex");
    __name(generateContentParametersToMldev, "generateContentParametersToMldev");
    __name(generateContentParametersToVertex, "generateContentParametersToVertex");
    __name(generateContentResponseFromMldev, "generateContentResponseFromMldev");
    __name(generateContentResponseFromVertex, "generateContentResponseFromVertex");
    __name(generateImagesConfigToMldev, "generateImagesConfigToMldev");
    __name(generateImagesConfigToVertex, "generateImagesConfigToVertex");
    __name(generateImagesParametersToMldev, "generateImagesParametersToMldev");
    __name(generateImagesParametersToVertex, "generateImagesParametersToVertex");
    __name(generateImagesResponseFromMldev, "generateImagesResponseFromMldev");
    __name(generateImagesResponseFromVertex, "generateImagesResponseFromVertex");
    __name(generateVideosConfigToMldev, "generateVideosConfigToMldev");
    __name(generateVideosConfigToVertex, "generateVideosConfigToVertex");
    __name(generateVideosOperationFromMldev, "generateVideosOperationFromMldev");
    __name(generateVideosOperationFromVertex, "generateVideosOperationFromVertex");
    __name(generateVideosParametersToMldev, "generateVideosParametersToMldev");
    __name(generateVideosParametersToVertex, "generateVideosParametersToVertex");
    __name(generateVideosResponseFromMldev, "generateVideosResponseFromMldev");
    __name(generateVideosResponseFromVertex, "generateVideosResponseFromVertex");
    __name(generateVideosSourceToMldev, "generateVideosSourceToMldev");
    __name(generateVideosSourceToVertex, "generateVideosSourceToVertex");
    __name(generatedImageFromMldev, "generatedImageFromMldev");
    __name(generatedImageFromVertex, "generatedImageFromVertex");
    __name(generatedImageMaskFromVertex, "generatedImageMaskFromVertex");
    __name(generatedVideoFromMldev, "generatedVideoFromMldev");
    __name(generatedVideoFromVertex, "generatedVideoFromVertex");
    __name(generationConfigToVertex, "generationConfigToVertex");
    __name(getModelParametersToMldev, "getModelParametersToMldev");
    __name(getModelParametersToVertex, "getModelParametersToVertex");
    __name(googleMapsToMldev$1, "googleMapsToMldev$1");
    __name(googleSearchToMldev$1, "googleSearchToMldev$1");
    __name(imageConfigToMldev, "imageConfigToMldev");
    __name(imageConfigToVertex, "imageConfigToVertex");
    __name(imageFromMldev, "imageFromMldev");
    __name(imageFromVertex, "imageFromVertex");
    __name(imageToMldev, "imageToMldev");
    __name(imageToVertex, "imageToVertex");
    __name(listModelsConfigToMldev, "listModelsConfigToMldev");
    __name(listModelsConfigToVertex, "listModelsConfigToVertex");
    __name(listModelsParametersToMldev, "listModelsParametersToMldev");
    __name(listModelsParametersToVertex, "listModelsParametersToVertex");
    __name(listModelsResponseFromMldev, "listModelsResponseFromMldev");
    __name(listModelsResponseFromVertex, "listModelsResponseFromVertex");
    __name(maskReferenceConfigToVertex, "maskReferenceConfigToVertex");
    __name(modelFromMldev, "modelFromMldev");
    __name(modelFromVertex, "modelFromVertex");
    __name(partToMldev$1, "partToMldev$1");
    __name(productImageToVertex, "productImageToVertex");
    __name(recontextImageConfigToVertex, "recontextImageConfigToVertex");
    __name(recontextImageParametersToVertex, "recontextImageParametersToVertex");
    __name(recontextImageResponseFromVertex, "recontextImageResponseFromVertex");
    __name(recontextImageSourceToVertex, "recontextImageSourceToVertex");
    __name(referenceImageAPIInternalToVertex, "referenceImageAPIInternalToVertex");
    __name(safetyAttributesFromMldev, "safetyAttributesFromMldev");
    __name(safetyAttributesFromVertex, "safetyAttributesFromVertex");
    __name(safetySettingToMldev, "safetySettingToMldev");
    __name(scribbleImageToVertex, "scribbleImageToVertex");
    __name(segmentImageConfigToVertex, "segmentImageConfigToVertex");
    __name(segmentImageParametersToVertex, "segmentImageParametersToVertex");
    __name(segmentImageResponseFromVertex, "segmentImageResponseFromVertex");
    __name(segmentImageSourceToVertex, "segmentImageSourceToVertex");
    __name(speechConfigToVertex, "speechConfigToVertex");
    __name(toolConfigToMldev, "toolConfigToMldev");
    __name(toolToMldev$1, "toolToMldev$1");
    __name(toolToVertex, "toolToVertex");
    __name(tunedModelInfoFromMldev, "tunedModelInfoFromMldev");
    __name(tunedModelInfoFromVertex, "tunedModelInfoFromVertex");
    __name(updateModelConfigToMldev, "updateModelConfigToMldev");
    __name(updateModelConfigToVertex, "updateModelConfigToVertex");
    __name(updateModelParametersToMldev, "updateModelParametersToMldev");
    __name(updateModelParametersToVertex, "updateModelParametersToVertex");
    __name(upscaleImageAPIConfigInternalToVertex, "upscaleImageAPIConfigInternalToVertex");
    __name(upscaleImageAPIParametersInternalToVertex, "upscaleImageAPIParametersInternalToVertex");
    __name(upscaleImageResponseFromVertex, "upscaleImageResponseFromVertex");
    __name(videoFromMldev, "videoFromMldev");
    __name(videoFromVertex, "videoFromVertex");
    __name(videoGenerationMaskToVertex, "videoGenerationMaskToVertex");
    __name(videoGenerationReferenceImageToMldev, "videoGenerationReferenceImageToMldev");
    __name(videoGenerationReferenceImageToVertex, "videoGenerationReferenceImageToVertex");
    __name(videoToMldev, "videoToMldev");
    __name(videoToVertex, "videoToVertex");
    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.30.0";
    LIBRARY_LABEL = `google-genai-sdk/${SDK_VERSION}`;
    VERTEX_AI_API_DEFAULT_VERSION = "v1beta1";
    GOOGLE_AI_API_DEFAULT_VERSION = "v1beta";
    responseLineRE = /^\s*data: (.*)(?:\n\n|\r\r|\r\n\r\n)/;
    ApiClient = class {
      static {
        __name(this, "ApiClient");
      }
      constructor(opts) {
        var _a7, _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 = (_a7 = this.clientOptions.apiVersion) !== null && _a7 !== void 0 ? _a7 : 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 _a7;
        return (_a7 = this.clientOptions.vertexai) !== null && _a7 !== void 0 ? _a7 : 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(path125, httpOptions, prependProjectLocation) {
        const urlElement = [this.getRequestUrlInternal(httpOptions)];
        if (prependProjectLocation) {
          urlElement.push(this.getBaseResourcePath());
        }
        if (path125 !== "") {
          urlElement.push(path125);
        }
        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, url2.toString(), 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, url2.toString(), request4.abortSignal);
        return this.streamApiCall(url2, requestInit, request4.httpMethod);
      }
      async includeExtraHttpOptionsToRequestInit(requestInit, httpOptions, url2, 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, url2);
        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((e4) => {
          if (e4 instanceof Error) {
            throw e4;
          } else {
            throw new Error(JSON.stringify(e4));
          }
        });
      }
      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((e4) => {
          if (e4 instanceof Error) {
            throw e4;
          } else {
            throw new Error(JSON.stringify(e4));
          }
        });
      }
      processStreamResponse(response) {
        var _a7;
        return __asyncGenerator(this, arguments, /* @__PURE__ */ __name(function* processStreamResponse_1() {
          const reader = (_a7 = response === null || response === void 0 ? void 0 : response.body) === null || _a7 === void 0 ? void 0 : _a7.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 (e4) {
                const error2 = e4;
                if (error2.name === "ApiError") {
                  throw e4;
                }
              }
              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 (e4) {
                  throw new Error(`exception parsing stream chunk ${processedChunkString}. ${e4}`);
                }
              }
            }
          } finally {
            reader.releaseLock();
          }
        }, "processStreamResponse_1"));
      }
      async apiCall(url2, requestInit) {
        return fetch(url2, requestInit).catch((e4) => {
          throw new Error(`exception ${e4} 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, url2) {
        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, url2);
        return headers;
      }
      getFileName(file) {
        var _a7;
        let fileName = "";
        if (typeof file === "string") {
          fileName = file.replace(/[/\\]+$/, "");
          fileName = (_a7 = fileName.split(/[/\\]/).pop()) !== null && _a7 !== void 0 ? _a7 : "";
        }
        return fileName;
      }
      /**
       * 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 types.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, config2) {
        var _a7;
        const fileToUpload = {};
        if (config2 != null) {
          fileToUpload.mimeType = config2.mimeType;
          fileToUpload.name = config2.name;
          fileToUpload.displayName = config2.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 = (_a7 = config2 === null || config2 === void 0 ? void 0 : config2.mimeType) !== null && _a7 !== void 0 ? _a7 : fileStat.type;
        if (mimeType === void 0 || mimeType === "") {
          throw new Error("Can not determine mimeType. Please provide mimeType in the config.");
        }
        fileToUpload.mimeType = mimeType;
        const body = {
          file: fileToUpload
        };
        const fileName = this.getFileName(file);
        const path125 = formatMap("upload/v1beta/files", body["_url"]);
        const uploadUrl = await this.fetchUploadUrl(path125, fileToUpload.sizeBytes, fileToUpload.mimeType, fileName, body, config2 === null || config2 === void 0 ? void 0 : config2.httpOptions);
        return uploader.upload(file, uploadUrl, this);
      }
      /**
       * Uploads a file to a given file search store asynchronously using Gemini API only, this is not supported
       * in Vertex AI.
       *
       * @param fileSearchStoreName The name of the file search store to upload the file to.
       * @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 uploadFileToFileSearchStore(fileSearchStoreName, file, config2) {
        var _a7;
        const uploader = this.clientOptions.uploader;
        const fileStat = await uploader.stat(file);
        const sizeBytes = String(fileStat.size);
        const mimeType = (_a7 = config2 === null || config2 === void 0 ? void 0 : config2.mimeType) !== null && _a7 !== void 0 ? _a7 : fileStat.type;
        if (mimeType === void 0 || mimeType === "") {
          throw new Error("Can not determine mimeType. Please provide mimeType in the config.");
        }
        const path125 = `upload/v1beta/${fileSearchStoreName}:uploadToFileSearchStore`;
        const fileName = this.getFileName(file);
        const body = {};
        if (config2 === null || config2 === void 0 ? void 0 : config2.customMetadata) {
          body["customMetadata"] = config2.customMetadata;
        }
        if (config2 === null || config2 === void 0 ? void 0 : config2.chunkingConfig) {
          body["chunkingConfig"] = config2.chunkingConfig;
        }
        const uploadUrl = await this.fetchUploadUrl(path125, sizeBytes, mimeType, fileName, body, config2 === null || config2 === void 0 ? void 0 : config2.httpOptions);
        return uploader.uploadToFileSearchStore(file, uploadUrl, this);
      }
      /**
       * Downloads a file asynchronously to the specified path.
       *
       * @params params - The parameters for the download request, see {@link
       * types.DownloadFileParameters}
       */
      async downloadFile(params) {
        const downloader = this.clientOptions.downloader;
        await downloader.download(params, this);
      }
      async fetchUploadUrl(path125, sizeBytes, mimeType, fileName, body, configHttpOptions) {
        var _a7;
        let httpOptions = {};
        if (configHttpOptions) {
          httpOptions = configHttpOptions;
        } else {
          httpOptions = {
            apiVersion: "",
            headers: Object.assign({ "Content-Type": "application/json", "X-Goog-Upload-Protocol": "resumable", "X-Goog-Upload-Command": "start", "X-Goog-Upload-Header-Content-Length": `${sizeBytes}`, "X-Goog-Upload-Header-Content-Type": `${mimeType}` }, fileName ? { "X-Goog-Upload-File-Name": fileName } : {})
          };
        }
        const httpResponse = await this.request({
          path: path125,
          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 = (_a7 = httpResponse === null || httpResponse === void 0 ? void 0 : httpResponse.headers) === null || _a7 === void 0 ? void 0 : _a7["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 = [], config2) {
        this.mcpTools = [];
        this.functionNameToMcpClient = {};
        this.mcpClients = mcpClients;
        this.config = config2;
      }
      /**
       * Creates a McpCallableTool.
       */
      static create(mcpClients, config2) {
        return new _McpCallableTool(mcpClients, config2);
      }
      /**
       * 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 _a7, 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, _e2 = (e_1 = void 0, __asyncValues(listAllTools(mcpClient))), _f; _f = await _e2.next(), _a7 = _f.done, !_a7; _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 && !_a7 && (_b2 = _e2.return)) await _b2.call(_e2);
            } 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 _a7, _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((resolve30) => {
          onopenResolve = resolve30;
        });
        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: (_a7 = callbacks === null || callbacks === void 0 ? void 0 : callbacks.onerror) !== null && _a7 !== void 0 ? _a7 : function(e4) {
          },
          onclose: (_b2 = callbacks === null || callbacks === void 0 ? void 0 : callbacks.onclose) !== null && _b2 !== void 0 ? _b2 : function(e4) {
          }
        };
        const conn = this.webSocketFactory.create(url2, headersToMap$1(headers), websocketCallbacks);
        conn.connect();
        await onopenPromise;
        const model = tModel(this.apiClient, params.model);
        const setup = { model };
        const clientMessage = { 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 clientContent = liveMusicSetWeightedPromptsParametersToMldev(params);
        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);
        this.conn.send(JSON.stringify(setConfigParameters));
      }
      sendPlaybackControl(playbackControl) {
        const clientMessage = { 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 _a7, _b2, _c2, _d, _e2, _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, url2);
        } 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((resolve30) => {
          onopenResolve = resolve30;
        });
        const callbacks = params.callbacks;
        const onopenAwaitedCallback = /* @__PURE__ */ __name(function() {
          var _a8;
          (_a8 = callbacks === null || callbacks === void 0 ? void 0 : callbacks.onopen) === null || _a8 === void 0 ? void 0 : _a8.call(callbacks);
          onopenResolve({});
        }, "onopenAwaitedCallback");
        const apiClient = this.apiClient;
        const websocketCallbacks = {
          onopen: onopenAwaitedCallback,
          onmessage: /* @__PURE__ */ __name((event) => {
            void handleWebSocketMessage(apiClient, callbacks.onmessage, event);
          }, "onmessage"),
          onerror: (_a7 = callbacks === null || callbacks === void 0 ? void 0 : callbacks.onerror) !== null && _a7 !== void 0 ? _a7 : function(e4) {
          },
          onclose: (_b2 = callbacks === null || callbacks === void 0 ? void 0 : callbacks.onclose) !== null && _b2 !== void 0 ? _b2 : function(e4) {
          }
        };
        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 = (_e2 = params.config) === null || _e2 === void 0 ? void 0 : _e2.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) => contentToMldev$1(item));
            }
          } catch (_a7) {
            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(findAfcIncompatibleToolIndexes, "findAfcIncompatibleToolIndexes");
    __name(shouldAppendAfcHistory, "shouldAppendAfcHistory");
    Models = class extends BaseModule {
      static {
        __name(this, "Models");
      }
      constructor(apiClient) {
        super();
        this.apiClient = apiClient;
        this.generateContent = async (params) => {
          var _a7, _b2, _c2, _d, _e2;
          const transformedParams = await this.processParamsMaybeAddMcpUsage(params);
          this.maybeMoveToResponseJsonSchem(params);
          if (!hasCallableTools(params) || shouldDisableAfc(params.config)) {
            return await this.generateContentInternal(transformedParams);
          }
          const incompatibleToolIndexes = findAfcIncompatibleToolIndexes(params);
          if (incompatibleToolIndexes.length > 0) {
            const formattedIndexes = incompatibleToolIndexes.map((index) => `tools[${index}]`).join(", ");
            throw new Error(`Automatic function calling with CallableTools (or MCP objects) and basic FunctionDeclarations is not yet supported. Incompatible tools found at ${formattedIndexes}.`);
          }
          let response;
          let functionResponseContent;
          const automaticFunctionCallingHistory = tContents(transformedParams.contents);
          const maxRemoteCalls = (_c2 = (_b2 = (_a7 = transformedParams.config) === null || _a7 === void 0 ? void 0 : _a7.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 (_e2 = (_d = params.config) === null || _d === void 0 ? void 0 : _d.tools) !== null && _e2 !== void 0 ? _e2 : []) {
              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) => {
          var _a7, _b2, _c2, _d, _e2;
          this.maybeMoveToResponseJsonSchem(params);
          if (shouldDisableAfc(params.config)) {
            const transformedParams = await this.processParamsMaybeAddMcpUsage(params);
            return await this.generateContentStreamInternal(transformedParams);
          }
          const incompatibleToolIndexes = findAfcIncompatibleToolIndexes(params);
          if (incompatibleToolIndexes.length > 0) {
            const formattedIndexes = incompatibleToolIndexes.map((index) => `tools[${index}]`).join(", ");
            throw new Error(`Incompatible tools found at ${formattedIndexes}. Automatic function calling with CallableTools (or MCP objects) and basic FunctionDeclarations" is not yet supported.`);
          }
          const streamFunctionCall = (_c2 = (_b2 = (_a7 = params === null || params === void 0 ? void 0 : params.config) === null || _a7 === void 0 ? void 0 : _a7.toolConfig) === null || _b2 === void 0 ? void 0 : _b2.functionCallingConfig) === null || _c2 === void 0 ? void 0 : _c2.streamFunctionCallArguments;
          const disableAfc = (_e2 = (_d = params === null || params === void 0 ? void 0 : params.config) === null || _d === void 0 ? void 0 : _d.automaticFunctionCalling) === null || _e2 === void 0 ? void 0 : _e2.disable;
          if (streamFunctionCall && !disableAfc) {
            throw new Error("Running in streaming mode with 'streamFunctionCallArguments' enabled, this feature is not compatible with automatic function calling (AFC). Please set 'config.automaticFunctionCalling.disable' to true to disable AFC or leave 'config.toolConfig.functionCallingConfig.streamFunctionCallArguments' to be undefined or set to false to disable streaming function call arguments feature.");
          }
          return await this.processAfcStream(params);
        };
        this.generateImages = async (params) => {
          return await this.generateImagesInternal(params).then((apiResponse) => {
            var _a7;
            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) && ((_a7 = generatedImage === null || generatedImage === void 0 ? void 0 : generatedImage.safetyAttributes) === null || _a7 === void 0 ? void 0 : _a7.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 _a7;
          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 ((_a7 = actualParams.config) === null || _a7 === void 0 ? void 0 : _a7.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, (x3) => this.listInternal(x3), 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) => {
          var _a7, _b2, _c2, _d, _e2, _f;
          if ((params.prompt || params.image || params.video) && params.source) {
            throw new Error("Source and prompt/image/video are mutually exclusive. Please only use source.");
          }
          if (!this.apiClient.isVertexAI()) {
            if (((_a7 = params.video) === null || _a7 === void 0 ? void 0 : _a7.uri) && ((_b2 = params.video) === null || _b2 === void 0 ? void 0 : _b2.videoBytes)) {
              params.video = {
                uri: params.video.uri,
                mimeType: params.video.mimeType
              };
            } else if (((_d = (_c2 = params.source) === null || _c2 === void 0 ? void 0 : _c2.video) === null || _d === void 0 ? void 0 : _d.uri) && ((_f = (_e2 = params.source) === null || _e2 === void 0 ? void 0 : _e2.video) === null || _f === void 0 ? void 0 : _f.videoBytes)) {
              params.source.video = {
                uri: params.source.video.uri,
                mimeType: params.source.video.mimeType
              };
            }
          }
          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 _a7, _b2, _c2;
        const tools = (_a7 = params.config) === null || _a7 === void 0 ? void 0 : _a7.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 _a7, _b2, _c2;
        const afcTools = /* @__PURE__ */ new Map();
        for (const tool of (_b2 = (_a7 = params.config) === null || _a7 === void 0 ? void 0 : _a7.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 _a7, _b2, _c2;
        const maxRemoteCalls = (_c2 = (_b2 = (_a7 = params.config) === null || _a7 === void 0 ? void 0 : _a7.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 _a8, _b3;
          return __asyncGenerator(this, arguments, function* () {
            var _c3, e_1, _d, _e2;
            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) {
                  _e2 = response_1_1.value;
                  _f = false;
                  const chunk = _e2;
                  yield yield __await(chunk);
                  if (chunk.candidates && ((_a8 = chunk.candidates[0]) === null || _a8 === void 0 ? void 0 : _a8.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 _a7, _b2, _c2, _d;
        let response;
        let path125 = "";
        let queryParams = {};
        if (this.apiClient.isVertexAI()) {
          const body = generateContentParametersToVertex(this.apiClient, params);
          path125 = formatMap("{model}:generateContent", body["_url"]);
          queryParams = body["_query"];
          delete body["_url"];
          delete body["_query"];
          response = this.apiClient.request({
            path: path125,
            queryParams,
            body: JSON.stringify(body),
            httpMethod: "POST",
            httpOptions: (_a7 = params.config) === null || _a7 === void 0 ? void 0 : _a7.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);
          path125 = formatMap("{model}:generateContent", body["_url"]);
          queryParams = body["_query"];
          delete body["_url"];
          delete body["_query"];
          response = this.apiClient.request({
            path: path125,
            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 _a7, _b2, _c2, _d;
        let response;
        let path125 = "";
        let queryParams = {};
        if (this.apiClient.isVertexAI()) {
          const body = generateContentParametersToVertex(this.apiClient, params);
          path125 = formatMap("{model}:streamGenerateContent?alt=sse", body["_url"]);
          queryParams = body["_query"];
          delete body["_url"];
          delete body["_query"];
          const apiClient = this.apiClient;
          response = apiClient.requestStream({
            path: path125,
            queryParams,
            body: JSON.stringify(body),
            httpMethod: "POST",
            httpOptions: (_a7 = params.config) === null || _a7 === void 0 ? void 0 : _a7.httpOptions,
            abortSignal: (_b2 = params.config) === null || _b2 === void 0 ? void 0 : _b2.abortSignal
          });
          return response.then(function(apiResponse) {
            return __asyncGenerator(this, arguments, function* () {
              var _a8, e_2, _b3, _c3;
              try {
                for (var _d2 = true, apiResponse_1 = __asyncValues(apiResponse), apiResponse_1_1; apiResponse_1_1 = yield __await(apiResponse_1.next()), _a8 = apiResponse_1_1.done, !_a8; _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 && !_a8 && (_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);
          path125 = formatMap("{model}:streamGenerateContent?alt=sse", body["_url"]);
          queryParams = body["_query"];
          delete body["_url"];
          delete body["_query"];
          const apiClient = this.apiClient;
          response = apiClient.requestStream({
            path: path125,
            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 _a8, e_3, _b3, _c3;
              try {
                for (var _d2 = true, apiResponse_2 = __asyncValues(apiResponse), apiResponse_2_1; apiResponse_2_1 = yield __await(apiResponse_2.next()), _a8 = apiResponse_2_1.done, !_a8; _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 && !_a8 && (_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 _a7, _b2, _c2, _d;
        let response;
        let path125 = "";
        let queryParams = {};
        if (this.apiClient.isVertexAI()) {
          const body = embedContentParametersToVertex(this.apiClient, params);
          path125 = formatMap("{model}:predict", body["_url"]);
          queryParams = body["_query"];
          delete body["_url"];
          delete body["_query"];
          response = this.apiClient.request({
            path: path125,
            queryParams,
            body: JSON.stringify(body),
            httpMethod: "POST",
            httpOptions: (_a7 = params.config) === null || _a7 === void 0 ? void 0 : _a7.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);
          path125 = formatMap("{model}:batchEmbedContents", body["_url"]);
          queryParams = body["_query"];
          delete body["_url"];
          delete body["_query"];
          response = this.apiClient.request({
            path: path125,
            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;
          });
        }
      }
      /**
       * Private method for generating images.
       */
      async generateImagesInternal(params) {
        var _a7, _b2, _c2, _d;
        let response;
        let path125 = "";
        let queryParams = {};
        if (this.apiClient.isVertexAI()) {
          const body = generateImagesParametersToVertex(this.apiClient, params);
          path125 = formatMap("{model}:predict", body["_url"]);
          queryParams = body["_query"];
          delete body["_url"];
          delete body["_query"];
          response = this.apiClient.request({
            path: path125,
            queryParams,
            body: JSON.stringify(body),
            httpMethod: "POST",
            httpOptions: (_a7 = params.config) === null || _a7 === void 0 ? void 0 : _a7.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);
          path125 = formatMap("{model}:predict", body["_url"]);
          queryParams = body["_query"];
          delete body["_url"];
          delete body["_query"];
          response = this.apiClient.request({
            path: path125,
            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;
          });
        }
      }
      /**
       * Private method for editing an image.
       */
      async editImageInternal(params) {
        var _a7, _b2;
        let response;
        let path125 = "";
        let queryParams = {};
        if (this.apiClient.isVertexAI()) {
          const body = editImageParametersInternalToVertex(this.apiClient, params);
          path125 = formatMap("{model}:predict", body["_url"]);
          queryParams = body["_query"];
          delete body["_url"];
          delete body["_query"];
          response = this.apiClient.request({
            path: path125,
            queryParams,
            body: JSON.stringify(body),
            httpMethod: "POST",
            httpOptions: (_a7 = params.config) === null || _a7 === void 0 ? void 0 : _a7.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.");
        }
      }
      /**
       * Private method for upscaling an image.
       */
      async upscaleImageInternal(params) {
        var _a7, _b2;
        let response;
        let path125 = "";
        let queryParams = {};
        if (this.apiClient.isVertexAI()) {
          const body = upscaleImageAPIParametersInternalToVertex(this.apiClient, params);
          path125 = formatMap("{model}:predict", body["_url"]);
          queryParams = body["_query"];
          delete body["_url"];
          delete body["_query"];
          response = this.apiClient.request({
            path: path125,
            queryParams,
            body: JSON.stringify(body),
            httpMethod: "POST",
            httpOptions: (_a7 = params.config) === null || _a7 === void 0 ? void 0 : _a7.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 _a7, _b2;
        let response;
        let path125 = "";
        let queryParams = {};
        if (this.apiClient.isVertexAI()) {
          const body = recontextImageParametersToVertex(this.apiClient, params);
          path125 = formatMap("{model}:predict", body["_url"]);
          queryParams = body["_query"];
          delete body["_url"];
          delete body["_query"];
          response = this.apiClient.request({
            path: path125,
            queryParams,
            body: JSON.stringify(body),
            httpMethod: "POST",
            httpOptions: (_a7 = params.config) === null || _a7 === void 0 ? void 0 : _a7.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 _a7, _b2;
        let response;
        let path125 = "";
        let queryParams = {};
        if (this.apiClient.isVertexAI()) {
          const body = segmentImageParametersToVertex(this.apiClient, params);
          path125 = formatMap("{model}:predict", body["_url"]);
          queryParams = body["_query"];
          delete body["_url"];
          delete body["_query"];
          response = this.apiClient.request({
            path: path125,
            queryParams,
            body: JSON.stringify(body),
            httpMethod: "POST",
            httpOptions: (_a7 = params.config) === null || _a7 === void 0 ? void 0 : _a7.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 _a7, _b2, _c2, _d;
        let response;
        let path125 = "";
        let queryParams = {};
        if (this.apiClient.isVertexAI()) {
          const body = getModelParametersToVertex(this.apiClient, params);
          path125 = formatMap("{name}", body["_url"]);
          queryParams = body["_query"];
          delete body["_url"];
          delete body["_query"];
          response = this.apiClient.request({
            path: path125,
            queryParams,
            body: JSON.stringify(body),
            httpMethod: "GET",
            httpOptions: (_a7 = params.config) === null || _a7 === void 0 ? void 0 : _a7.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);
          path125 = formatMap("{name}", body["_url"]);
          queryParams = body["_query"];
          delete body["_url"];
          delete body["_query"];
          response = this.apiClient.request({
            path: path125,
            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 _a7, _b2, _c2, _d;
        let response;
        let path125 = "";
        let queryParams = {};
        if (this.apiClient.isVertexAI()) {
          const body = listModelsParametersToVertex(this.apiClient, params);
          path125 = formatMap("{models_url}", body["_url"]);
          queryParams = body["_query"];
          delete body["_url"];
          delete body["_query"];
          response = this.apiClient.request({
            path: path125,
            queryParams,
            body: JSON.stringify(body),
            httpMethod: "GET",
            httpOptions: (_a7 = params.config) === null || _a7 === void 0 ? void 0 : _a7.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);
          path125 = formatMap("{models_url}", body["_url"]);
          queryParams = body["_query"];
          delete body["_url"];
          delete body["_query"];
          response = this.apiClient.request({
            path: path125,
            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 _a7, _b2, _c2, _d;
        let response;
        let path125 = "";
        let queryParams = {};
        if (this.apiClient.isVertexAI()) {
          const body = updateModelParametersToVertex(this.apiClient, params);
          path125 = formatMap("{model}", body["_url"]);
          queryParams = body["_query"];
          delete body["_url"];
          delete body["_query"];
          response = this.apiClient.request({
            path: path125,
            queryParams,
            body: JSON.stringify(body),
            httpMethod: "PATCH",
            httpOptions: (_a7 = params.config) === null || _a7 === void 0 ? void 0 : _a7.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);
          path125 = formatMap("{name}", body["_url"]);
          queryParams = body["_query"];
          delete body["_url"];
          delete body["_query"];
          response = this.apiClient.request({
            path: path125,
            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 _a7, _b2, _c2, _d;
        let response;
        let path125 = "";
        let queryParams = {};
        if (this.apiClient.isVertexAI()) {
          const body = deleteModelParametersToVertex(this.apiClient, params);
          path125 = formatMap("{name}", body["_url"]);
          queryParams = body["_query"];
          delete body["_url"];
          delete body["_query"];
          response = this.apiClient.request({
            path: path125,
            queryParams,
            body: JSON.stringify(body),
            httpMethod: "DELETE",
            httpOptions: (_a7 = params.config) === null || _a7 === void 0 ? void 0 : _a7.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);
          path125 = formatMap("{name}", body["_url"]);
          queryParams = body["_query"];
          delete body["_url"];
          delete body["_query"];
          response = this.apiClient.request({
            path: path125,
            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 _a7, _b2, _c2, _d;
        let response;
        let path125 = "";
        let queryParams = {};
        if (this.apiClient.isVertexAI()) {
          const body = countTokensParametersToVertex(this.apiClient, params);
          path125 = formatMap("{model}:countTokens", body["_url"]);
          queryParams = body["_query"];
          delete body["_url"];
          delete body["_query"];
          response = this.apiClient.request({
            path: path125,
            queryParams,
            body: JSON.stringify(body),
            httpMethod: "POST",
            httpOptions: (_a7 = params.config) === null || _a7 === void 0 ? void 0 : _a7.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);
          path125 = formatMap("{model}:countTokens", body["_url"]);
          queryParams = body["_query"];
          delete body["_url"];
          delete body["_query"];
          response = this.apiClient.request({
            path: path125,
            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 _a7, _b2;
        let response;
        let path125 = "";
        let queryParams = {};
        if (this.apiClient.isVertexAI()) {
          const body = computeTokensParametersToVertex(this.apiClient, params);
          path125 = formatMap("{model}:computeTokens", body["_url"]);
          queryParams = body["_query"];
          delete body["_url"];
          delete body["_query"];
          response = this.apiClient.request({
            path: path125,
            queryParams,
            body: JSON.stringify(body),
            httpMethod: "POST",
            httpOptions: (_a7 = params.config) === null || _a7 === void 0 ? void 0 : _a7.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.");
        }
      }
      /**
       * Private method for generating videos.
       */
      async generateVideosInternal(params) {
        var _a7, _b2, _c2, _d;
        let response;
        let path125 = "";
        let queryParams = {};
        if (this.apiClient.isVertexAI()) {
          const body = generateVideosParametersToVertex(this.apiClient, params);
          path125 = formatMap("{model}:predictLongRunning", body["_url"]);
          queryParams = body["_query"];
          delete body["_url"];
          delete body["_query"];
          response = this.apiClient.request({
            path: path125,
            queryParams,
            body: JSON.stringify(body),
            httpMethod: "POST",
            httpOptions: (_a7 = params.config) === null || _a7 === void 0 ? void 0 : _a7.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);
          path125 = formatMap("{model}:predictLongRunning", body["_url"]);
          queryParams = body["_query"];
          delete body["_url"];
          delete body["_query"];
          response = this.apiClient.request({
            path: path125,
            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;
          });
        }
      }
    };
    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 config2 = 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 (config2 && "httpOptions" in config2) {
            httpOptions = config2.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: config2
          });
          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 config2 = 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 (config2 && "httpOptions" in config2) {
            httpOptions = config2.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: config2
          });
          return operation._fromAPIResponse({
            apiResponse: rawOperation,
            _isVertexAI: false
          });
        }
      }
      async getVideosOperationInternal(params) {
        var _a7, _b2, _c2, _d;
        let response;
        let path125 = "";
        let queryParams = {};
        if (this.apiClient.isVertexAI()) {
          const body = getOperationParametersToVertex(params);
          path125 = formatMap("{operationName}", body["_url"]);
          queryParams = body["_query"];
          delete body["_url"];
          delete body["_query"];
          response = this.apiClient.request({
            path: path125,
            queryParams,
            body: JSON.stringify(body),
            httpMethod: "GET",
            httpOptions: (_a7 = params.config) === null || _a7 === void 0 ? void 0 : _a7.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);
          path125 = formatMap("{operationName}", body["_url"]);
          queryParams = body["_query"];
          delete body["_url"];
          delete body["_query"];
          response = this.apiClient.request({
            path: path125,
            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 _a7, _b2;
        let response;
        let path125 = "";
        let queryParams = {};
        if (this.apiClient.isVertexAI()) {
          const body = fetchPredictOperationParametersToVertex(params);
          path125 = formatMap("{resourceName}:fetchPredictOperation", body["_url"]);
          queryParams = body["_query"];
          delete body["_url"];
          delete body["_query"];
          response = this.apiClient.request({
            path: path125,
            queryParams,
            body: JSON.stringify(body),
            httpMethod: "POST",
            httpOptions: (_a7 = params.config) === null || _a7 === void 0 ? void 0 : _a7.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(blobToMldev, "blobToMldev");
    __name(contentToMldev, "contentToMldev");
    __name(createAuthTokenConfigToMldev, "createAuthTokenConfigToMldev");
    __name(createAuthTokenParametersToMldev, "createAuthTokenParametersToMldev");
    __name(fileDataToMldev, "fileDataToMldev");
    __name(functionCallToMldev, "functionCallToMldev");
    __name(googleMapsToMldev, "googleMapsToMldev");
    __name(googleSearchToMldev, "googleSearchToMldev");
    __name(liveConnectConfigToMldev, "liveConnectConfigToMldev");
    __name(liveConnectConstraintsToMldev, "liveConnectConstraintsToMldev");
    __name(partToMldev, "partToMldev");
    __name(sessionResumptionConfigToMldev, "sessionResumptionConfigToMldev");
    __name(toolToMldev, "toolToMldev");
    __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 _a7, _b2;
        let response;
        let path125 = "";
        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);
          path125 = 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: path125,
            queryParams,
            body: JSON.stringify(transformedBody),
            httpMethod: "POST",
            httpOptions: (_a7 = params.config) === null || _a7 === void 0 ? void 0 : _a7.httpOptions,
            abortSignal: (_b2 = params.config) === null || _b2 === void 0 ? void 0 : _b2.abortSignal
          }).then((httpResponse) => {
            return httpResponse.json();
          });
          return response.then((resp) => {
            return resp;
          });
        }
      }
    };
    __name(createFileSearchStoreConfigToMldev, "createFileSearchStoreConfigToMldev");
    __name(createFileSearchStoreParametersToMldev, "createFileSearchStoreParametersToMldev");
    __name(deleteFileSearchStoreConfigToMldev, "deleteFileSearchStoreConfigToMldev");
    __name(deleteFileSearchStoreParametersToMldev, "deleteFileSearchStoreParametersToMldev");
    __name(getFileSearchStoreParametersToMldev, "getFileSearchStoreParametersToMldev");
    __name(importFileConfigToMldev, "importFileConfigToMldev");
    __name(importFileOperationFromMldev, "importFileOperationFromMldev");
    __name(importFileParametersToMldev, "importFileParametersToMldev");
    __name(importFileResponseFromMldev, "importFileResponseFromMldev");
    __name(listFileSearchStoresConfigToMldev, "listFileSearchStoresConfigToMldev");
    __name(listFileSearchStoresParametersToMldev, "listFileSearchStoresParametersToMldev");
    __name(listFileSearchStoresResponseFromMldev, "listFileSearchStoresResponseFromMldev");
    __name(uploadToFileSearchStoreConfigToMldev, "uploadToFileSearchStoreConfigToMldev");
    __name(uploadToFileSearchStoreParametersToMldev, "uploadToFileSearchStoreParametersToMldev");
    __name(uploadToFileSearchStoreResumableResponseFromMldev, "uploadToFileSearchStoreResumableResponseFromMldev");
    __name(deleteDocumentConfigToMldev, "deleteDocumentConfigToMldev");
    __name(deleteDocumentParametersToMldev, "deleteDocumentParametersToMldev");
    __name(getDocumentParametersToMldev, "getDocumentParametersToMldev");
    __name(listDocumentsConfigToMldev, "listDocumentsConfigToMldev");
    __name(listDocumentsParametersToMldev, "listDocumentsParametersToMldev");
    __name(listDocumentsResponseFromMldev, "listDocumentsResponseFromMldev");
    Documents = class extends BaseModule {
      static {
        __name(this, "Documents");
      }
      constructor(apiClient) {
        super();
        this.apiClient = apiClient;
        this.list = async (params) => {
          return new Pager(PagedItem.PAGED_ITEM_DOCUMENTS, (x3) => this.listInternal({
            parent: params.parent,
            config: x3.config
          }), await this.listInternal(params), params);
        };
      }
      /**
       * Gets a Document.
       *
       * @param params - The parameters for getting a document.
       * @return Document.
       */
      async get(params) {
        var _a7, _b2;
        let response;
        let path125 = "";
        let queryParams = {};
        if (this.apiClient.isVertexAI()) {
          throw new Error("This method is only supported by the Gemini Developer API.");
        } else {
          const body = getDocumentParametersToMldev(params);
          path125 = formatMap("{name}", body["_url"]);
          queryParams = body["_query"];
          delete body["_url"];
          delete body["_query"];
          response = this.apiClient.request({
            path: path125,
            queryParams,
            body: JSON.stringify(body),
            httpMethod: "GET",
            httpOptions: (_a7 = params.config) === null || _a7 === void 0 ? void 0 : _a7.httpOptions,
            abortSignal: (_b2 = params.config) === null || _b2 === void 0 ? void 0 : _b2.abortSignal
          }).then((httpResponse) => {
            return httpResponse.json();
          });
          return response.then((resp) => {
            return resp;
          });
        }
      }
      /**
       * Deletes a Document.
       *
       * @param params - The parameters for deleting a document.
       */
      async delete(params) {
        var _a7, _b2;
        let path125 = "";
        let queryParams = {};
        if (this.apiClient.isVertexAI()) {
          throw new Error("This method is only supported by the Gemini Developer API.");
        } else {
          const body = deleteDocumentParametersToMldev(params);
          path125 = formatMap("{name}", body["_url"]);
          queryParams = body["_query"];
          delete body["_url"];
          delete body["_query"];
          await this.apiClient.request({
            path: path125,
            queryParams,
            body: JSON.stringify(body),
            httpMethod: "DELETE",
            httpOptions: (_a7 = params.config) === null || _a7 === void 0 ? void 0 : _a7.httpOptions,
            abortSignal: (_b2 = params.config) === null || _b2 === void 0 ? void 0 : _b2.abortSignal
          });
        }
      }
      /**
       * Lists all Documents in a FileSearchStore.
       *
       * @param params - The parameters for listing documents.
       * @return ListDocumentsResponse.
       */
      async listInternal(params) {
        var _a7, _b2;
        let response;
        let path125 = "";
        let queryParams = {};
        if (this.apiClient.isVertexAI()) {
          throw new Error("This method is only supported by the Gemini Developer API.");
        } else {
          const body = listDocumentsParametersToMldev(params);
          path125 = formatMap("{parent}/documents", body["_url"]);
          queryParams = body["_query"];
          delete body["_url"];
          delete body["_query"];
          response = this.apiClient.request({
            path: path125,
            queryParams,
            body: JSON.stringify(body),
            httpMethod: "GET",
            httpOptions: (_a7 = params.config) === null || _a7 === void 0 ? void 0 : _a7.httpOptions,
            abortSignal: (_b2 = params.config) === null || _b2 === void 0 ? void 0 : _b2.abortSignal
          }).then((httpResponse) => {
            return httpResponse.json();
          });
          return response.then((apiResponse) => {
            const resp = listDocumentsResponseFromMldev(apiResponse);
            const typedResp = new ListDocumentsResponse();
            Object.assign(typedResp, resp);
            return typedResp;
          });
        }
      }
    };
    FileSearchStores = class extends BaseModule {
      static {
        __name(this, "FileSearchStores");
      }
      constructor(apiClient, documents = new Documents(apiClient)) {
        super();
        this.apiClient = apiClient;
        this.documents = documents;
        this.list = async (params = {}) => {
          return new Pager(PagedItem.PAGED_ITEM_FILE_SEARCH_STORES, (x3) => this.listInternal(x3), await this.listInternal(params), params);
        };
      }
      /**
       * Uploads a file asynchronously to a given File Search Store.
       * 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.
       *
       * This section can contain multiple paragraphs and code examples.
       *
       * @param params - Optional parameters specified in the
       *        `types.UploadToFileSearchStoreParameters` interface.
       *         @see {@link types.UploadToFileSearchStoreParameters#config} for the optional
       *         config in the parameters.
       * @return A promise that resolves to a long running operation.
       * @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 a given file search store.
       *
       * ```ts
       * const operation = await ai.fileSearchStores.upload({fileSearchStoreName: 'fileSearchStores/foo-bar', file: 'file.txt', config: {
       *   mimeType: 'text/plain',
       * }});
       * console.log(operation.name);
       * ```
       */
      async uploadToFileSearchStore(params) {
        if (this.apiClient.isVertexAI()) {
          throw new Error("Vertex AI does not support uploading files to a file search store.");
        }
        return this.apiClient.uploadFileToFileSearchStore(params.fileSearchStoreName, params.file, params.config);
      }
      /**
       * Creates a File Search Store.
       *
       * @param params - The parameters for creating a File Search Store.
       * @return FileSearchStore.
       */
      async create(params) {
        var _a7, _b2;
        let response;
        let path125 = "";
        let queryParams = {};
        if (this.apiClient.isVertexAI()) {
          throw new Error("This method is only supported by the Gemini Developer API.");
        } else {
          const body = createFileSearchStoreParametersToMldev(params);
          path125 = formatMap("fileSearchStores", body["_url"]);
          queryParams = body["_query"];
          delete body["_url"];
          delete body["_query"];
          response = this.apiClient.request({
            path: path125,
            queryParams,
            body: JSON.stringify(body),
            httpMethod: "POST",
            httpOptions: (_a7 = params.config) === null || _a7 === void 0 ? void 0 : _a7.httpOptions,
            abortSignal: (_b2 = params.config) === null || _b2 === void 0 ? void 0 : _b2.abortSignal
          }).then((httpResponse) => {
            return httpResponse.json();
          });
          return response.then((resp) => {
            return resp;
          });
        }
      }
      /**
       * Gets a File Search Store.
       *
       * @param params - The parameters for getting a File Search Store.
       * @return FileSearchStore.
       */
      async get(params) {
        var _a7, _b2;
        let response;
        let path125 = "";
        let queryParams = {};
        if (this.apiClient.isVertexAI()) {
          throw new Error("This method is only supported by the Gemini Developer API.");
        } else {
          const body = getFileSearchStoreParametersToMldev(params);
          path125 = formatMap("{name}", body["_url"]);
          queryParams = body["_query"];
          delete body["_url"];
          delete body["_query"];
          response = this.apiClient.request({
            path: path125,
            queryParams,
            body: JSON.stringify(body),
            httpMethod: "GET",
            httpOptions: (_a7 = params.config) === null || _a7 === void 0 ? void 0 : _a7.httpOptions,
            abortSignal: (_b2 = params.config) === null || _b2 === void 0 ? void 0 : _b2.abortSignal
          }).then((httpResponse) => {
            return httpResponse.json();
          });
          return response.then((resp) => {
            return resp;
          });
        }
      }
      /**
       * Deletes a File Search Store.
       *
       * @param params - The parameters for deleting a File Search Store.
       */
      async delete(params) {
        var _a7, _b2;
        let path125 = "";
        let queryParams = {};
        if (this.apiClient.isVertexAI()) {
          throw new Error("This method is only supported by the Gemini Developer API.");
        } else {
          const body = deleteFileSearchStoreParametersToMldev(params);
          path125 = formatMap("{name}", body["_url"]);
          queryParams = body["_query"];
          delete body["_url"];
          delete body["_query"];
          await this.apiClient.request({
            path: path125,
            queryParams,
            body: JSON.stringify(body),
            httpMethod: "DELETE",
            httpOptions: (_a7 = params.config) === null || _a7 === void 0 ? void 0 : _a7.httpOptions,
            abortSignal: (_b2 = params.config) === null || _b2 === void 0 ? void 0 : _b2.abortSignal
          });
        }
      }
      /**
       * Lists all FileSearchStore owned by the user.
       *
       * @param params - The parameters for listing file search stores.
       * @return ListFileSearchStoresResponse.
       */
      async listInternal(params) {
        var _a7, _b2;
        let response;
        let path125 = "";
        let queryParams = {};
        if (this.apiClient.isVertexAI()) {
          throw new Error("This method is only supported by the Gemini Developer API.");
        } else {
          const body = listFileSearchStoresParametersToMldev(params);
          path125 = formatMap("fileSearchStores", body["_url"]);
          queryParams = body["_query"];
          delete body["_url"];
          delete body["_query"];
          response = this.apiClient.request({
            path: path125,
            queryParams,
            body: JSON.stringify(body),
            httpMethod: "GET",
            httpOptions: (_a7 = params.config) === null || _a7 === void 0 ? void 0 : _a7.httpOptions,
            abortSignal: (_b2 = params.config) === null || _b2 === void 0 ? void 0 : _b2.abortSignal
          }).then((httpResponse) => {
            return httpResponse.json();
          });
          return response.then((apiResponse) => {
            const resp = listFileSearchStoresResponseFromMldev(apiResponse);
            const typedResp = new ListFileSearchStoresResponse();
            Object.assign(typedResp, resp);
            return typedResp;
          });
        }
      }
      async uploadToFileSearchStoreInternal(params) {
        var _a7, _b2;
        let response;
        let path125 = "";
        let queryParams = {};
        if (this.apiClient.isVertexAI()) {
          throw new Error("This method is only supported by the Gemini Developer API.");
        } else {
          const body = uploadToFileSearchStoreParametersToMldev(params);
          path125 = formatMap("upload/v1beta/{file_search_store_name}:uploadToFileSearchStore", body["_url"]);
          queryParams = body["_query"];
          delete body["_url"];
          delete body["_query"];
          response = this.apiClient.request({
            path: path125,
            queryParams,
            body: JSON.stringify(body),
            httpMethod: "POST",
            httpOptions: (_a7 = params.config) === null || _a7 === void 0 ? void 0 : _a7.httpOptions,
            abortSignal: (_b2 = params.config) === null || _b2 === void 0 ? void 0 : _b2.abortSignal
          }).then((httpResponse) => {
            return httpResponse.json();
          });
          return response.then((apiResponse) => {
            const resp = uploadToFileSearchStoreResumableResponseFromMldev(apiResponse);
            const typedResp = new UploadToFileSearchStoreResumableResponse();
            Object.assign(typedResp, resp);
            return typedResp;
          });
        }
      }
      /**
       * Imports a File from File Service to a FileSearchStore.
       *
       * This is a long-running operation, see aip.dev/151
       *
       * @param params - The parameters for importing a file to a file search store.
       * @return ImportFileOperation.
       */
      async importFile(params) {
        var _a7, _b2;
        let response;
        let path125 = "";
        let queryParams = {};
        if (this.apiClient.isVertexAI()) {
          throw new Error("This method is only supported by the Gemini Developer API.");
        } else {
          const body = importFileParametersToMldev(params);
          path125 = formatMap("{file_search_store_name}:importFile", body["_url"]);
          queryParams = body["_query"];
          delete body["_url"];
          delete body["_query"];
          response = this.apiClient.request({
            path: path125,
            queryParams,
            body: JSON.stringify(body),
            httpMethod: "POST",
            httpOptions: (_a7 = params.config) === null || _a7 === void 0 ? void 0 : _a7.httpOptions,
            abortSignal: (_b2 = params.config) === null || _b2 === void 0 ? void 0 : _b2.abortSignal
          }).then((httpResponse) => {
            return httpResponse.json();
          });
          return response.then((apiResponse) => {
            const resp = importFileOperationFromMldev(apiResponse);
            const typedResp = new ImportFileOperation();
            Object.assign(typedResp, resp);
            return typedResp;
          });
        }
      }
    };
    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, url2) {
        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, url2);
      }
      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, url2) {
        if (this.googleAuth === void 0) {
          throw new Error("Trying to set google-auth headers but googleAuth is unset");
        }
        const authHeaders = await this.googleAuth.getRequestHeaders(url2);
        for (const [key, value] of authHeaders) {
          if (headers.get(key) !== null) {
            continue;
          }
          headers.append(key, value);
        }
      }
    };
    __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);
            const body = Readable.fromWeb(response.responseInternal.body);
            body.pipe(writer);
            await finished(writer);
          } else {
            try {
              await writeFile(params.downloadPath, response, {
                encoding: "base64"
              });
            } catch (error2) {
              throw new Error(`Failed to write file to ${params.downloadPath}: ${error2}`);
            }
          }
        }
      }
    };
    __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(cancelTuningJobParametersToMldev, "cancelTuningJobParametersToMldev");
    __name(cancelTuningJobParametersToVertex, "cancelTuningJobParametersToVertex");
    __name(createTuningJobConfigToMldev, "createTuningJobConfigToMldev");
    __name(createTuningJobConfigToVertex, "createTuningJobConfigToVertex");
    __name(createTuningJobParametersPrivateToMldev, "createTuningJobParametersPrivateToMldev");
    __name(createTuningJobParametersPrivateToVertex, "createTuningJobParametersPrivateToVertex");
    __name(getTuningJobParametersToMldev, "getTuningJobParametersToMldev");
    __name(getTuningJobParametersToVertex, "getTuningJobParametersToVertex");
    __name(listTuningJobsConfigToMldev, "listTuningJobsConfigToMldev");
    __name(listTuningJobsConfigToVertex, "listTuningJobsConfigToVertex");
    __name(listTuningJobsParametersToMldev, "listTuningJobsParametersToMldev");
    __name(listTuningJobsParametersToVertex, "listTuningJobsParametersToVertex");
    __name(listTuningJobsResponseFromMldev, "listTuningJobsResponseFromMldev");
    __name(listTuningJobsResponseFromVertex, "listTuningJobsResponseFromVertex");
    __name(tunedModelFromMldev, "tunedModelFromMldev");
    __name(tuningDatasetToMldev, "tuningDatasetToMldev");
    __name(tuningDatasetToVertex, "tuningDatasetToVertex");
    __name(tuningJobFromMldev, "tuningJobFromMldev");
    __name(tuningJobFromVertex, "tuningJobFromVertex");
    __name(tuningOperationFromMldev, "tuningOperationFromMldev");
    __name(tuningValidationDatasetToVertex, "tuningValidationDatasetToVertex");
    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, (x3) => this.listInternal(x3), await this.listInternal(params), params);
        };
        this.tune = async (params) => {
          var _a7;
          if (this.apiClient.isVertexAI()) {
            if (params.baseModel.startsWith("projects/")) {
              const preTunedModel = {
                tunedModelName: params.baseModel
              };
              if ((_a7 = params.config) === null || _a7 === void 0 ? void 0 : _a7.preTunedModelCheckpointId) {
                preTunedModel.checkpointId = params.config.preTunedModelCheckpointId;
              }
              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 _a7, _b2, _c2, _d;
        let response;
        let path125 = "";
        let queryParams = {};
        if (this.apiClient.isVertexAI()) {
          const body = getTuningJobParametersToVertex(params);
          path125 = formatMap("{name}", body["_url"]);
          queryParams = body["_query"];
          delete body["_url"];
          delete body["_query"];
          response = this.apiClient.request({
            path: path125,
            queryParams,
            body: JSON.stringify(body),
            httpMethod: "GET",
            httpOptions: (_a7 = params.config) === null || _a7 === void 0 ? void 0 : _a7.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);
          path125 = formatMap("{name}", body["_url"]);
          queryParams = body["_query"];
          delete body["_url"];
          delete body["_query"];
          response = this.apiClient.request({
            path: path125,
            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 _a7, _b2, _c2, _d;
        let response;
        let path125 = "";
        let queryParams = {};
        if (this.apiClient.isVertexAI()) {
          const body = listTuningJobsParametersToVertex(params);
          path125 = formatMap("tuningJobs", body["_url"]);
          queryParams = body["_query"];
          delete body["_url"];
          delete body["_query"];
          response = this.apiClient.request({
            path: path125,
            queryParams,
            body: JSON.stringify(body),
            httpMethod: "GET",
            httpOptions: (_a7 = params.config) === null || _a7 === void 0 ? void 0 : _a7.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);
          path125 = formatMap("tunedModels", body["_url"]);
          queryParams = body["_query"];
          delete body["_url"];
          delete body["_query"];
          response = this.apiClient.request({
            path: path125,
            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 _a7, _b2, _c2, _d;
        let path125 = "";
        let queryParams = {};
        if (this.apiClient.isVertexAI()) {
          const body = cancelTuningJobParametersToVertex(params);
          path125 = formatMap("{name}:cancel", body["_url"]);
          queryParams = body["_query"];
          delete body["_url"];
          delete body["_query"];
          await this.apiClient.request({
            path: path125,
            queryParams,
            body: JSON.stringify(body),
            httpMethod: "POST",
            httpOptions: (_a7 = params.config) === null || _a7 === void 0 ? void 0 : _a7.httpOptions,
            abortSignal: (_b2 = params.config) === null || _b2 === void 0 ? void 0 : _b2.abortSignal
          });
        } else {
          const body = cancelTuningJobParametersToMldev(params);
          path125 = formatMap("{name}:cancel", body["_url"]);
          queryParams = body["_query"];
          delete body["_url"];
          delete body["_query"];
          await this.apiClient.request({
            path: path125,
            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 _a7, _b2;
        let response;
        let path125 = "";
        let queryParams = {};
        if (this.apiClient.isVertexAI()) {
          const body = createTuningJobParametersPrivateToVertex(params, params);
          path125 = formatMap("tuningJobs", body["_url"]);
          queryParams = body["_query"];
          delete body["_url"];
          delete body["_query"];
          response = this.apiClient.request({
            path: path125,
            queryParams,
            body: JSON.stringify(body),
            httpMethod: "POST",
            httpOptions: (_a7 = params.config) === null || _a7 === void 0 ? void 0 : _a7.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 _a7, _b2;
        let response;
        let path125 = "";
        let queryParams = {};
        if (this.apiClient.isVertexAI()) {
          throw new Error("This method is only supported by the Gemini Developer API.");
        } else {
          const body = createTuningJobParametersPrivateToMldev(params);
          path125 = formatMap("tunedModels", body["_url"]);
          queryParams = body["_query"];
          delete body["_url"];
          delete body["_query"];
          response = this.apiClient.request({
            path: path125,
            queryParams,
            body: JSON.stringify(body),
            httpMethod: "POST",
            httpOptions: (_a7 = params.config) === null || _a7 === void 0 ? void 0 : _a7.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(uploadBlobToFileSearchStore, "uploadBlobToFileSearchStore");
    __name(uploadBlobInternal, "uploadBlobInternal");
    __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 fs5.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);
        }
      }
      async uploadToFileSearchStore(file, uploadUrl, apiClient) {
        if (typeof file === "string") {
          return await this.uploadFileToFileSearchStoreFromPath(file, uploadUrl, apiClient);
        } else {
          return uploadBlobToFileSearchStore(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 _a7;
        const response = await this.uploadFileFromPathInternal(file, uploadUrl, apiClient);
        const responseJson = await (response === null || response === void 0 ? void 0 : response.json());
        if (((_a7 = response === null || response === void 0 ? void 0 : response.headers) === null || _a7 === void 0 ? void 0 : _a7[X_GOOG_UPLOAD_STATUS_HEADER_FIELD]) !== "final") {
          throw new Error("Failed to upload file: Upload status is not finalized.");
        }
        return responseJson["file"];
      }
      async uploadFileToFileSearchStoreFromPath(file, uploadUrl, apiClient) {
        var _a7;
        const response = await this.uploadFileFromPathInternal(file, uploadUrl, apiClient);
        const responseJson = await (response === null || response === void 0 ? void 0 : response.json());
        if (((_a7 = response === null || response === void 0 ? void 0 : response.headers) === null || _a7 === void 0 ? void 0 : _a7[X_GOOG_UPLOAD_STATUS_HEADER_FIELD]) !== "final") {
          throw new Error("Failed to upload file: Upload status is not finalized.");
        }
        const resp = uploadToFileSearchStoreOperationFromMldev(responseJson);
        const typedResp = new UploadToFileSearchStoreOperation();
        Object.assign(typedResp, resp);
        return typedResp;
      }
      async uploadFileFromPathInternal(file, uploadUrl, apiClient) {
        var _a7, _b2;
        let fileSize = 0;
        let offset = 0;
        let response = new HttpResponse(new Response());
        let uploadCommand = "upload";
        let fileHandle;
        const fileName = path3.basename(file);
        try {
          fileHandle = await fs5.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),
                    "X-Goog-Upload-File-Name": fileName
                  }
                }
              });
              if ((_a7 = response === null || response === void 0 ? void 0 : response.headers) === null || _a7 === void 0 ? void 0 : _a7[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.");
            }
          }
          return response;
        } finally {
          if (fileHandle) {
            await fileHandle.close();
          }
        }
      }
    };
    LANGUAGE_LABEL_PREFIX = "gl-node/";
    GoogleGenAI = class {
      static {
        __name(this, "GoogleGenAI");
      }
      constructor(options2) {
        var _a7, _b2, _c2, _d, _e2, _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 = (_a7 = options2.vertexai) !== null && _a7 !== void 0 ? _a7 : 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 = (_e2 = options2.location) !== null && _e2 !== void 0 ? _e2 : 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;
          }
          if (!this.location && !this.apiKey) {
            this.location = "global";
          }
        }
        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);
        this.fileSearchStores = new FileSearchStores(this.apiClient);
      }
    };
    __name(getEnv, "getEnv");
    __name(getBooleanEnv, "getBooleanEnv");
    __name(stringToBoolean, "stringToBoolean");
    __name(getApiKeyFromEnv, "getApiKeyFromEnv");
  }
});

// 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["EXECUTION_DENIED"] = "execution_denied";
      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["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(s5) {
        super();
        if (!exports2.IDENTIFIER.test(s5))
          throw new Error("CodeGen: name must be a valid identifier");
        this.str = s5;
      }
      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 _a7;
        return (_a7 = this._str) !== null && _a7 !== void 0 ? _a7 : this._str = this._items.reduce((s5, c4) => `${s5}${c4}`, "");
      }
      get names() {
        var _a7;
        return (_a7 = this._names) !== null && _a7 !== void 0 ? _a7 : this._names = this._items.reduce((names, c4) => {
          if (c4 instanceof Name)
            names[c4.str] = (names[c4.str] || 0) + 1;
          return names;
        }, {});
      }
    };
    exports2._Code = _Code;
    exports2.nil = new _Code("");
    function _2(strs, ...args) {
      const code2 = [strs[0]];
      let i3 = 0;
      while (i3 < args.length) {
        addCodeArg(code2, args[i3]);
        code2.push(strs[++i3]);
      }
      return new _Code(code2);
    }
    __name(_2, "_");
    exports2._ = _2;
    var plus = new _Code("+");
    function str2(strs, ...args) {
      const expr = [safeStringify(strs[0])];
      let i3 = 0;
      while (i3 < args.length) {
        expr.push(plus);
        addCodeArg(expr, args[i3]);
        expr.push(plus, safeStringify(strs[++i3]));
      }
      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(interpolate2(arg));
    }
    __name(addCodeArg, "addCodeArg");
    exports2.addCodeArg = addCodeArg;
    function optimize(expr) {
      let i3 = 1;
      while (i3 < expr.length - 1) {
        if (expr[i3] === plus) {
          const res = mergeExprItems(expr[i3 - 1], expr[i3 + 1]);
          if (res !== void 0) {
            expr.splice(i3 - 1, 3, res);
            continue;
          }
          expr[i3++] = "+";
        }
        i3++;
      }
    }
    __name(optimize, "optimize");
    function mergeExprItems(a2, b2) {
      if (b2 === '""')
        return a2;
      if (a2 === '""')
        return b2;
      if (typeof a2 == "string") {
        if (b2 instanceof Name || a2[a2.length - 1] !== '"')
          return;
        if (typeof b2 != "string")
          return `${a2.slice(0, -1)}${b2}"`;
        if (b2[0] === '"')
          return a2.slice(0, -1) + b2.slice(1);
        return;
      }
      if (typeof b2 == "string" && b2[0] === '"' && !(a2 instanceof Name))
        return `"${a2}${b2.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 interpolate2(x3) {
      return typeof x3 == "number" || typeof x3 == "boolean" || x3 === null ? x3 : safeStringify(Array.isArray(x3) ? x3.join(",") : x3);
    }
    __name(interpolate2, "interpolate");
    function stringify4(x3) {
      return new _Code(safeStringify(x3));
    }
    __name(stringify4, "stringify");
    exports2.stringify = stringify4;
    function safeStringify(x3) {
      return JSON.stringify(x3).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}`) : _2`[${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 _a7, _b2;
        if (((_b2 = (_a7 = this._parent) === null || _a7 === void 0 ? void 0 : _a7._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 _a7;
        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 = (_a7 = value.key) !== null && _a7 !== void 0 ? _a7 : 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 s5 = this._scope[prefix] || (this._scope[prefix] = []);
        const itemIndex = s5.length;
        s5[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 c4 = valueCode(name3);
            if (c4) {
              const def2 = this.opts.es5 ? exports2.varKinds.var : exports2.varKinds.const;
              code2 = (0, code_1._)`${code2}${def2} ${name3} = ${c4};${this.opts._n}`;
            } else if (c4 = getCode === null || getCode === void 0 ? void 0 : getCode(name3)) {
              code2 = (0, code_1._)`${code2}${c4}${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 Node5 = class {
      static {
        __name(this, "Node");
      }
      optimizeNodes() {
        return this;
      }
      optimizeNames(_names, _constants) {
        return this;
      }
    };
    var Def = class extends Node5 {
      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 Node5 {
      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 Node5 {
      static {
        __name(this, "Label");
      }
      constructor(label) {
        super();
        this.label = label;
        this.names = {};
      }
      render({ _n }) {
        return `${this.label}:` + _n;
      }
    };
    var Break = class extends Node5 {
      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 Node5 {
      static {
        __name(this, "Throw");
      }
      constructor(error2) {
        super();
        this.error = error2;
      }
      render({ _n }) {
        return `throw ${this.error};` + _n;
      }
      get names() {
        return this.error.names;
      }
    };
    var AnyCode = class extends Node5 {
      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 Node5 {
      static {
        __name(this, "ParentNode");
      }
      constructor(nodes = []) {
        super();
        this.nodes = nodes;
      }
      render(opts) {
        return this.nodes.reduce((code2, n3) => code2 + n3.render(opts), "");
      }
      optimizeNodes() {
        const { nodes } = this;
        let i3 = nodes.length;
        while (i3--) {
          const n3 = nodes[i3].optimizeNodes();
          if (Array.isArray(n3))
            nodes.splice(i3, 1, ...n3);
          else if (n3)
            nodes[i3] = n3;
          else
            nodes.splice(i3, 1);
        }
        return nodes.length > 0 ? this : void 0;
      }
      optimizeNames(names, constants4) {
        const { nodes } = this;
        let i3 = nodes.length;
        while (i3--) {
          const n3 = nodes[i3];
          if (n3.optimizeNames(names, constants4))
            continue;
          subtractNames(names, n3.names);
          nodes.splice(i3, 1);
        }
        return nodes.length > 0 ? this : void 0;
      }
      get names() {
        return this.nodes.reduce((names, n3) => addNames(names, n3.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 e4 = this.else;
        if (e4) {
          const ns = e4.optimizeNodes();
          e4 = this.else = Array.isArray(ns) ? new Else(ns) : ns;
        }
        if (e4) {
          if (cond === false)
            return e4 instanceof _If ? e4 : e4.nodes;
          if (this.nodes.length)
            return this;
          return new _If(not(cond), e4 instanceof _If ? [e4] : e4.nodes);
        }
        if (cond === false || !this.nodes.length)
          return void 0;
        return this;
      }
      optimizeNames(names, constants4) {
        var _a7;
        this.else = (_a7 = this.else) === null || _a7 === void 0 ? void 0 : _a7.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 _a7, _b2;
        super.optimizeNodes();
        (_a7 = this.catch) === null || _a7 === void 0 ? void 0 : _a7.optimizeNodes();
        (_b2 = this.finally) === null || _b2 === void 0 ? void 0 : _b2.optimizeNodes();
        return this;
      }
      optimizeNames(names, constants4) {
        var _a7, _b2;
        super.optimizeNames(names, constants4);
        (_a7 = this.catch) === null || _a7 === void 0 ? void 0 : _a7.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(error2) {
        super();
        this.error = error2;
      }
      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(c4) {
        if (typeof c4 == "function")
          c4();
        else if (c4 !== code_1.nil)
          this._leafNode(new AnyCode(c4));
        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`, (i3) => {
            this.var(name3, (0, code_1._)`${arr}[${i3}]`);
            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 error2 = this.name("e");
          this._currNode = node.catch = new Catch(error2);
          catchCode(error2);
        }
        if (finallyCode) {
          this._currNode = node.finally = new Finally();
          this.code(finallyCode);
        }
        return this._endBlockNode(Catch, Finally);
      }
      // `throw` statement
      throw(error2) {
        return this._leafNode(new Throw(error2));
      }
      // start self-balancing block
      block(body, nodeCount) {
        this._blockStarts.push(this._nodes.length);
        if (body)
          this.code(body).endBlock(nodeCount);
        return this;
      }
      // end the current self-balancing block
      endBlock(nodeCount) {
        const 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(n3 = 1) {
        while (n3-- > 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 n3 = this._currNode;
        if (n3 instanceof N1 || N2 && n3 instanceof N2) {
          this._nodes.pop();
          return this;
        }
        throw new Error(`CodeGen: not in block "${N2 ? `${N1.kind}/${N2.kind}` : N1.kind}"`);
      }
      _elseNode(node) {
        const n3 = this._currNode;
        if (!(n3 instanceof If)) {
          throw new Error('CodeGen: "else" without "if"');
        }
        this._currNode = n3.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 n3 in from)
        names[n3] = (names[n3] || 0) + (from[n3] || 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, c4) => {
        if (c4 instanceof code_1.Name)
          c4 = replaceName(c4);
        if (c4 instanceof code_1._Code)
          items.push(...c4._items);
        else
          items.push(c4);
        return items;
      }, []));
      function replaceName(n3) {
        const c4 = constants4[n3.str];
        if (c4 === void 0 || names[n3.str] !== 1)
          return n3;
        delete names[n3.str];
        return c4;
      }
      __name(replaceName, "replaceName");
      function canOptimize(e4) {
        return e4 instanceof code_1._Code && e4._items.some((c4) => c4 instanceof code_1.Name && names[c4.str] === 1 && constants4[c4.str] !== void 0);
      }
      __name(canOptimize, "canOptimize");
    }
    __name(optimizeExpr, "optimizeExpr");
    function subtractNames(names, from) {
      for (const n3 in from)
        names[n3] = (names[n3] || 0) - (from[n3] || 0);
    }
    __name(subtractNames, "subtractNames");
    function not(x3) {
      return typeof x3 == "boolean" || typeof x3 == "number" || x3 === null ? !x3 : (0, code_1._)`!${par(x3)}`;
    }
    __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 or2(...args) {
      return args.reduce(orCode);
    }
    __name(or2, "or");
    exports2.or = or2;
    function mappend(op) {
      return (x3, y2) => x3 === code_1.nil ? y2 : y2 === code_1.nil ? x3 : (0, code_1._)`${par(x3)} ${op} ${par(y2)}`;
    }
    __name(mappend, "mappend");
    function par(x3) {
      return x3 instanceof code_1.Name ? x3 : (0, code_1._)`(${x3})`;
    }
    __name(par, "par");
  }
});

// packages/core/node_modules/ajv/dist/compile/util.js
var require_util11 = __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(it2, schema) {
      if (typeof schema == "boolean")
        return schema;
      if (Object.keys(schema).length === 0)
        return true;
      checkUnknownRules(it2, schema);
      return !schemaHasRules(schema, it2.self.RULES.all);
    }
    __name(alwaysValidSchema, "alwaysValidSchema");
    exports2.alwaysValidSchema = alwaysValidSchema;
    function checkUnknownRules(it2, schema = it2.schema) {
      const { opts, self: self2 } = it2;
      if (!opts.strictSchema)
        return;
      if (typeof schema === "boolean")
        return;
      const rules = self2.RULES.keywords;
      for (const key in schema) {
        if (!rules[key])
          checkStrictMode(it2, `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, f5) {
      if (Array.isArray(xs)) {
        for (const x3 of xs)
          f5(x3);
      } else {
        f5(xs);
      }
    }
    __name(eachItem, "eachItem");
    exports2.eachItem = eachItem;
    function makeMergeEvaluated({ mergeNames, mergeToName, mergeValues: mergeValues3, 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) : mergeValues3(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((p2) => gen.assign((0, codegen_1._)`${props}${(0, codegen_1.getProperty)(p2)}`, true));
    }
    __name(setEvaluated, "setEvaluated");
    exports2.setEvaluated = setEvaluated;
    var snippets = {};
    function useFunc(gen, f5) {
      return gen.scopeValue("func", {
        ref: f5,
        code: snippets[f5.code] || (snippets[f5.code] = new code_1._Code(f5.code))
      });
    }
    __name(useFunc, "useFunc");
    exports2.useFunc = useFunc;
    var Type3;
    (function(Type4) {
      Type4[Type4["Num"] = 0] = "Num";
      Type4[Type4["Str"] = 1] = "Str";
    })(Type3 || (exports2.Type = Type3 = {}));
    function getErrorPath(dataProp, dataPropType, jsPropertySyntax) {
      if (dataProp instanceof codegen_1.Name) {
        const isNumber3 = dataPropType === Type3.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(it2, msg, mode = it2.opts.strictSchema) {
      if (!mode)
        return;
      msg = `strict mode: ${msg}`;
      if (mode === true)
        throw new Error(msg);
      it2.self.logger.warn(msg);
    }
    __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_util11();
    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, error2 = exports2.keywordError, errorPaths, overrideAllErrors) {
      const { it: it2 } = cxt;
      const { gen, compositeRule, allErrors } = it2;
      const errObj = errorObjectCode(cxt, error2, errorPaths);
      if (overrideAllErrors !== null && overrideAllErrors !== void 0 ? overrideAllErrors : compositeRule || allErrors) {
        addError(gen, errObj);
      } else {
        returnErrors(it2, (0, codegen_1._)`[${errObj}]`);
      }
    }
    __name(reportError3, "reportError");
    exports2.reportError = reportError3;
    function reportExtraError(cxt, error2 = exports2.keywordError, errorPaths) {
      const { it: it2 } = cxt;
      const { gen, compositeRule, allErrors } = it2;
      const errObj = errorObjectCode(cxt, error2, errorPaths);
      addError(gen, errObj);
      if (!(compositeRule || allErrors)) {
        returnErrors(it2, names_1.default.vErrors);
      }
    }
    __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: it2 }) {
      if (errsCount === void 0)
        throw new Error("ajv implementation error");
      const err = gen.name("err");
      gen.forRange("i", errsCount, names_1.default.errors, (i3) => {
        gen.const(err, (0, codegen_1._)`${names_1.default.vErrors}[${i3}]`);
        gen.if((0, codegen_1._)`${err}.instancePath === undefined`, () => gen.assign((0, codegen_1._)`${err}.instancePath`, (0, codegen_1.strConcat)(names_1.default.instancePath, it2.errorPath)));
        gen.assign((0, codegen_1._)`${err}.schemaPath`, (0, codegen_1.str)`${it2.errSchemaPath}/${keyword}`);
        if (it2.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(it2, errs) {
      const { gen, validateName: validateName2, schemaEnv } = it2;
      if (schemaEnv.$async) {
        gen.throw((0, codegen_1._)`new ${it2.ValidationError}(${errs})`);
      } else {
        gen.assign((0, codegen_1._)`${validateName2}.errors`, errs);
        gen.return(false);
      }
    }
    __name(returnErrors, "returnErrors");
    var E2 = {
      keyword: new codegen_1.Name("keyword"),
      schemaPath: new codegen_1.Name("schemaPath"),
      // also used in JTD errors
      params: new codegen_1.Name("params"),
      propertyName: new codegen_1.Name("propertyName"),
      message: new codegen_1.Name("message"),
      schema: new codegen_1.Name("schema"),
      parentSchema: new codegen_1.Name("parentSchema")
    };
    function errorObjectCode(cxt, error2, errorPaths) {
      const { createErrors } = cxt.it;
      if (createErrors === false)
        return (0, codegen_1._)`{}`;
      return errorObject(cxt, error2, errorPaths);
    }
    __name(errorObjectCode, "errorObjectCode");
    function errorObject(cxt, error2, errorPaths = {}) {
      const { gen, it: it2 } = cxt;
      const keyValues = [
        errorInstancePath(it2, errorPaths),
        errorSchemaPath(cxt, errorPaths)
      ];
      extraErrorProps(cxt, error2, keyValues);
      return gen.object(...keyValues);
    }
    __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 [E2.schemaPath, schPath];
    }
    __name(errorSchemaPath, "errorSchemaPath");
    function extraErrorProps(cxt, { params, message }, keyValues) {
      const { keyword, data, schemaValue, it: it2 } = cxt;
      const { opts, propertyName, topSchemaRef, schemaPath } = it2;
      keyValues.push([E2.keyword, keyword], [E2.params, typeof params == "function" ? params(cxt) : params || (0, codegen_1._)`{}`]);
      if (opts.messages) {
        keyValues.push([E2.message, typeof message == "function" ? message(cxt) : message]);
      }
      if (opts.verbose) {
        keyValues.push([E2.schema, schemaValue], [E2.parentSchema, (0, codegen_1._)`${topSchemaRef}${schemaPath}`], [names_1.default.data, data]);
      }
      if (propertyName)
        keyValues.push([E2.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(it2) {
      const { gen, schema, validateName: validateName2 } = it2;
      if (schema === false) {
        falseSchemaError(it2, false);
      } else if (typeof schema == "object" && schema.$async === true) {
        gen.return(names_1.default.data);
      } else {
        gen.assign((0, codegen_1._)`${validateName2}.errors`, null);
        gen.return(true);
      }
    }
    __name(topBoolOrEmptySchema, "topBoolOrEmptySchema");
    exports2.topBoolOrEmptySchema = topBoolOrEmptySchema;
    function boolOrEmptySchema(it2, valid) {
      const { gen, schema } = it2;
      if (schema === false) {
        gen.var(valid, false);
        falseSchemaError(it2);
      } else {
        gen.var(valid, true);
      }
    }
    __name(boolOrEmptySchema, "boolOrEmptySchema");
    exports2.boolOrEmptySchema = boolOrEmptySchema;
    function falseSchemaError(it2, overrideAllErrors) {
      const { gen, data } = it2;
      const cxt = {
        gen,
        keyword: "false schema",
        data,
        schema: false,
        schemaCode: false,
        schemaValue: false,
        params: {},
        it: it2
      };
      (0, errors_1.reportError)(cxt, boolError, void 0, overrideAllErrors);
    }
    __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(x3) {
      return typeof x3 == "string" && jsonTypes.has(x3);
    }
    __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 _a7;
      return schema[rule.keyword] !== void 0 || ((_a7 = rule.definition.implements) === null || _a7 === void 0 ? void 0 : _a7.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_util11();
    var DataType;
    (function(DataType2) {
      DataType2[DataType2["Correct"] = 0] = "Correct";
      DataType2[DataType2["Wrong"] = 1] = "Wrong";
    })(DataType || (exports2.DataType = DataType = {}));
    function getSchemaTypes(schema) {
      const types7 = getJSONTypes(schema.type);
      const hasNull = types7.includes("null");
      if (hasNull) {
        if (schema.nullable === false)
          throw new Error("type: null contradicts nullable: false");
      } else {
        if (!types7.length && schema.nullable !== void 0) {
          throw new Error('"nullable" cannot be used without "type"');
        }
        if (schema.nullable === true)
          types7.push("null");
      }
      return types7;
    }
    __name(getSchemaTypes, "getSchemaTypes");
    exports2.getSchemaTypes = getSchemaTypes;
    function getJSONTypes(ts) {
      const types7 = Array.isArray(ts) ? ts : ts ? [ts] : [];
      if (types7.every(rules_1.isJSONType))
        return types7;
      throw new Error("type must be JSONType or JSONType[]: " + types7.join(","));
    }
    __name(getJSONTypes, "getJSONTypes");
    exports2.getJSONTypes = getJSONTypes;
    function coerceAndCheckDataType(it2, types7) {
      const { gen, data, opts } = it2;
      const coerceTo = coerceToTypes(types7, opts.coerceTypes);
      const checkTypes = types7.length > 0 && !(coerceTo.length === 0 && types7.length === 1 && (0, applicability_1.schemaHasRulesForType)(it2, types7[0]));
      if (checkTypes) {
        const wrongType = checkDataTypes(types7, data, opts.strictNumbers, DataType.Wrong);
        gen.if(wrongType, () => {
          if (coerceTo.length)
            coerceData(it2, types7, coerceTo);
          else
            reportTypeError(it2);
        });
      }
      return checkTypes;
    }
    __name(coerceAndCheckDataType, "coerceAndCheckDataType");
    exports2.coerceAndCheckDataType = coerceAndCheckDataType;
    var COERCIBLE = /* @__PURE__ */ new Set(["string", "number", "integer", "boolean", "null"]);
    function coerceToTypes(types7, coerceTypes) {
      return coerceTypes ? types7.filter((t5) => COERCIBLE.has(t5) || coerceTypes === "array" && t5 === "array") : [];
    }
    __name(coerceToTypes, "coerceToTypes");
    function coerceData(it2, types7, coerceTo) {
      const { gen, data, opts } = it2;
      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(types7, data, opts.strictNumbers), () => gen.assign(coerced, data)));
      }
      gen.if((0, codegen_1._)`${coerced} !== undefined`);
      for (const t5 of coerceTo) {
        if (COERCIBLE.has(t5) || t5 === "array" && opts.coerceTypes === "array") {
          coerceSpecificType(t5);
        }
      }
      gen.else();
      reportTypeError(it2);
      gen.endIf();
      gen.if((0, codegen_1._)`${coerced} !== undefined`, () => {
        gen.assign(data, coerced);
        assignParentData(it2, coerced);
      });
      function coerceSpecificType(t5) {
        switch (t5) {
          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 types7 = (0, util_1.toHash)(dataTypes);
      if (types7.array && types7.object) {
        const notObj = (0, codegen_1._)`typeof ${data} != "object"`;
        cond = types7.null ? notObj : (0, codegen_1._)`!${data} || ${notObj}`;
        delete types7.null;
        delete types7.array;
        delete types7.object;
      } else {
        cond = codegen_1.nil;
      }
      if (types7.number)
        delete types7.integer;
      for (const t5 in types7)
        cond = (0, codegen_1.and)(cond, checkDataType(t5, 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(it2) {
      const cxt = getTypeErrorContext(it2);
      (0, errors_1.reportError)(cxt, typeError);
    }
    __name(reportTypeError, "reportTypeError");
    exports2.reportTypeError = reportTypeError;
    function getTypeErrorContext(it2) {
      const { gen, data, schema } = it2;
      const schemaCode = (0, util_1.schemaRefOrVal)(it2, schema, "type");
      return {
        gen,
        keyword: "type",
        data,
        schema: schema.type,
        schemaCode,
        schemaValue: schemaCode,
        parentSchema: schema,
        params: {},
        it: it2
      };
    }
    __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_util11();
    function assignDefaults(it2, ty) {
      const { properties, items } = it2.schema;
      if (ty === "object" && properties) {
        for (const key in properties) {
          assignDefault(it2, key, properties[key].default);
        }
      } else if (ty === "array" && Array.isArray(items)) {
        items.forEach((sch, i3) => assignDefault(it2, i3, sch.default));
      }
    }
    __name(assignDefaults, "assignDefaults");
    exports2.assignDefaults = assignDefaults;
    function assignDefault(it2, prop, defaultValue) {
      const { gen, compositeRule, data, opts } = it2;
      if (defaultValue === void 0)
        return;
      const childData = (0, codegen_1._)`${data}${(0, codegen_1.getProperty)(prop)}`;
      if (compositeRule) {
        (0, util_1.checkStrictMode)(it2, `default is ignored for: ${childData}`);
        return;
      }
      let condition = (0, codegen_1._)`${childData} === undefined`;
      if (opts.useDefaults === "empty") {
        condition = (0, codegen_1._)`${condition} || ${childData} === null || ${childData} === ""`;
      }
      gen.if(condition, (0, codegen_1._)`${childData} = ${(0, codegen_1.stringify)(defaultValue)}`);
    }
    __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_util11();
    var names_1 = require_names();
    var util_2 = require_util11();
    function checkReportMissingProp(cxt, prop) {
      const { gen, data, it: it2 } = cxt;
      gen.if(noPropertyInData(gen, data, prop, it2.opts.ownProperties), () => {
        cxt.setParams({ missingProperty: (0, codegen_1._)`${prop}` }, true);
        cxt.error();
      });
    }
    __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((p2) => p2 !== "__proto__") : [];
    }
    __name(allSchemaProperties, "allSchemaProperties");
    exports2.allSchemaProperties = allSchemaProperties;
    function schemaProperties(it2, schemaMap) {
      return allSchemaProperties(schemaMap).filter((p2) => !(0, util_1.alwaysValidSchema)(it2, schemaMap[p2]));
    }
    __name(schemaProperties, "schemaProperties");
    exports2.schemaProperties = schemaProperties;
    function callValidateCode({ schemaCode, data, it: { gen, topSchemaRef, schemaPath, errorPath }, it: it2 }, 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, it2.parentData],
        [names_1.default.parentDataProperty, it2.parentDataProperty],
        [names_1.default.rootData, names_1.default.rootData]
      ];
      if (it2.opts.dynamicRef)
        valCxt.push([names_1.default.dynamicAnchors, names_1.default.dynamicAnchors]);
      const args = (0, codegen_1._)`${dataAndSchema}, ${gen.object(...valCxt)}`;
      return 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 u2 = opts.unicodeRegExp ? "u" : "";
      const { regExp } = opts.code;
      const rx = regExp(pattern, u2);
      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}, ${u2})`
      });
    }
    __name(usePattern, "usePattern");
    exports2.usePattern = usePattern;
    function validateArray(cxt) {
      const { gen, data, keyword, it: it2 } = cxt;
      const valid = gen.name("valid");
      if (it2.allErrors) {
        const validArr = gen.let("valid", true);
        validateItems(() => gen.assign(validArr, false));
        return validArr;
      }
      gen.var(valid, true);
      validateItems(() => gen.break());
      return valid;
      function validateItems(notValid) {
        const len = gen.const("len", (0, codegen_1._)`${data}.length`);
        gen.forRange("i", 0, len, (i3) => {
          cxt.subschema({
            keyword,
            dataProp: i3,
            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: it2 } = cxt;
      if (!Array.isArray(schema))
        throw new Error("ajv implementation error");
      const alwaysValid = schema.some((sch) => (0, util_1.alwaysValidSchema)(it2, sch));
      if (alwaysValid && !it2.opts.unevaluated)
        return;
      const valid = gen.let("valid", false);
      const schValid = gen.name("_valid");
      gen.block(() => schema.forEach((_sch, i3) => {
        const schCxt = cxt.subschema({
          keyword,
          schemaProp: i3,
          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: it2 } = cxt;
      const macroSchema = def2.macro.call(it2.self, schema, parentSchema, it2);
      const schemaRef = useKeyword(gen, keyword, macroSchema);
      if (it2.opts.validateSchema !== false)
        it2.self.validateSchema(macroSchema, true);
      const valid = gen.name("valid");
      cxt.subschema({
        schema: macroSchema,
        schemaPath: codegen_1.nil,
        errSchemaPath: `${it2.errSchemaPath}/${keyword}`,
        topSchemaRef: schemaRef,
        compositeRule: true
      }, valid);
      cxt.pass(valid, () => cxt.error(true));
    }
    __name(macroKeywordCode, "macroKeywordCode");
    exports2.macroKeywordCode = macroKeywordCode;
    function funcKeywordCode(cxt, def2) {
      var _a7;
      const { gen, keyword, schema, parentSchema, $data, it: it2 } = cxt;
      checkAsyncKeyword(it2, def2);
      const validate3 = !$data && def2.compile ? def2.compile.call(it2.self, schema, parentSchema, it2) : def2.validate;
      const validateRef = useKeyword(gen, keyword, validate3);
      const valid = gen.let("valid");
      cxt.block$data(valid, validateKeyword);
      cxt.ok((_a7 = def2.valid) !== null && _a7 !== void 0 ? _a7 : 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 `), (e4) => gen.assign(valid, false).if((0, codegen_1._)`${e4} instanceof ${it2.ValidationError}`, () => gen.assign(ruleErrs, (0, codegen_1._)`${e4}.errors`), () => gen.throw(e4)));
        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 = it2.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 _a8;
        gen.if((0, codegen_1.not)((_a8 = def2.valid) !== null && _a8 !== void 0 ? _a8 : valid), errors);
      }
      __name(reportErrs, "reportErrs");
    }
    __name(funcKeywordCode, "funcKeywordCode");
    exports2.funcKeywordCode = funcKeywordCode;
    function modifyData(cxt) {
      const { gen, data, it: it2 } = cxt;
      gen.if(it2.parentData, () => gen.assign(data, (0, codegen_1._)`${it2.parentData}[${it2.parentDataProperty}]`));
    }
    __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((st2) => st2 === "array" ? Array.isArray(schema) : st2 === "object" ? schema && typeof schema == "object" && !Array.isArray(schema) : typeof schema == st2 || 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_util11();
    function getSubschema(it2, { 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 = it2.schema[keyword];
        return schemaProp === void 0 ? {
          schema: sch,
          schemaPath: (0, codegen_1._)`${it2.schemaPath}${(0, codegen_1.getProperty)(keyword)}`,
          errSchemaPath: `${it2.errSchemaPath}/${keyword}`
        } : {
          schema: sch[schemaProp],
          schemaPath: (0, codegen_1._)`${it2.schemaPath}${(0, codegen_1.getProperty)(keyword)}${(0, codegen_1.getProperty)(schemaProp)}`,
          errSchemaPath: `${it2.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, it2, { dataProp, dataPropType: dpType, data, dataTypes, propertyName }) {
      if (data !== void 0 && dataProp !== void 0) {
        throw new Error('both "data" and "dataProp" passed, only one allowed');
      }
      const { gen } = it2;
      if (dataProp !== void 0) {
        const { errorPath, dataPathArr, opts } = it2;
        const nextData = gen.let("data", (0, codegen_1._)`${it2.data}${(0, codegen_1.getProperty)(dataProp)}`, true);
        dataContextProps(nextData);
        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 = it2.dataLevel + 1;
        subschema.dataTypes = [];
        it2.definedProperties = /* @__PURE__ */ new Set();
        subschema.parentData = it2.data;
        subschema.dataNames = [...it2.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(a2, b2) {
      if (a2 === b2) return true;
      if (a2 && b2 && typeof a2 == "object" && typeof b2 == "object") {
        if (a2.constructor !== b2.constructor) return false;
        var length, i3, keys;
        if (Array.isArray(a2)) {
          length = a2.length;
          if (length != b2.length) return false;
          for (i3 = length; i3-- !== 0; )
            if (!equal(a2[i3], b2[i3])) return false;
          return true;
        }
        if (a2.constructor === RegExp) return a2.source === b2.source && a2.flags === b2.flags;
        if (a2.valueOf !== Object.prototype.valueOf) return a2.valueOf() === b2.valueOf();
        if (a2.toString !== Object.prototype.toString) return a2.toString() === b2.toString();
        keys = Object.keys(a2);
        length = keys.length;
        if (length !== Object.keys(b2).length) return false;
        for (i3 = length; i3-- !== 0; )
          if (!Object.prototype.hasOwnProperty.call(b2, keys[i3])) return false;
        for (i3 = length; i3-- !== 0; ) {
          var key = keys[i3];
          if (!equal(a2[key], b2[key])) return false;
        }
        return true;
      }
      return a2 !== a2 && b2 !== b2;
    }, "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 i3 = 0; i3 < sch.length; i3++)
                _traverse(opts, pre, post, sch[i3], jsonPtr + "/" + key + "/" + i3, rootSchema, jsonPtr, key, schema, i3);
            }
          } 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_util11();
    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 = "", normalize12) {
      if (normalize12 !== false)
        id = normalizeId(id);
      const p2 = resolver.parse(id);
      return _getFullPath(resolver, p2);
    }
    __name(getFullPath, "getFullPath");
    exports2.getFullPath = getFullPath;
    function _getFullPath(resolver, p2) {
      const serialized = resolver.serialize(p2);
      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, _2, 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_util11();
    var errors_1 = require_errors2();
    function validateFunctionCode(it2) {
      if (isSchemaObj(it2)) {
        checkKeywords(it2);
        if (schemaCxtHasRules(it2)) {
          topSchemaObjCode(it2);
          return;
        }
      }
      validateFunction(it2, () => (0, boolSchema_1.topBoolOrEmptySchema)(it2));
    }
    __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(it2) {
      const { schema, opts, gen } = it2;
      validateFunction(it2, () => {
        if (opts.$comment && schema.$comment)
          commentKeyword(it2);
        checkNoDefault(it2);
        gen.let(names_1.default.vErrors, null);
        gen.let(names_1.default.errors, 0);
        if (opts.unevaluated)
          resetEvaluated(it2);
        typeAndKeywords(it2);
        returnResults(it2);
      });
      return;
    }
    __name(topSchemaObjCode, "topSchemaObjCode");
    function resetEvaluated(it2) {
      const { gen, validateName: validateName2 } = it2;
      it2.evaluated = gen.const("evaluated", (0, codegen_1._)`${validateName2}.evaluated`);
      gen.if((0, codegen_1._)`${it2.evaluated}.dynamicProps`, () => gen.assign((0, codegen_1._)`${it2.evaluated}.props`, (0, codegen_1._)`undefined`));
      gen.if((0, codegen_1._)`${it2.evaluated}.dynamicItems`, () => gen.assign((0, codegen_1._)`${it2.evaluated}.items`, (0, codegen_1._)`undefined`));
    }
    __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(it2, valid) {
      if (isSchemaObj(it2)) {
        checkKeywords(it2);
        if (schemaCxtHasRules(it2)) {
          subSchemaObjCode(it2, valid);
          return;
        }
      }
      (0, boolSchema_1.boolOrEmptySchema)(it2, 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(it2) {
      return typeof it2.schema != "boolean";
    }
    __name(isSchemaObj, "isSchemaObj");
    function subSchemaObjCode(it2, valid) {
      const { schema, gen, opts } = it2;
      if (opts.$comment && schema.$comment)
        commentKeyword(it2);
      updateContext(it2);
      checkAsyncSchema(it2);
      const errsCount = gen.const("_errs", names_1.default.errors);
      typeAndKeywords(it2, errsCount);
      gen.var(valid, (0, codegen_1._)`${errsCount} === ${names_1.default.errors}`);
    }
    __name(subSchemaObjCode, "subSchemaObjCode");
    function checkKeywords(it2) {
      (0, util_1.checkUnknownRules)(it2);
      checkRefsAndKeywords(it2);
    }
    __name(checkKeywords, "checkKeywords");
    function typeAndKeywords(it2, errsCount) {
      if (it2.opts.jtd)
        return schemaKeywords(it2, [], false, errsCount);
      const types7 = (0, dataType_1.getSchemaTypes)(it2.schema);
      const checkedTypes = (0, dataType_1.coerceAndCheckDataType)(it2, types7);
      schemaKeywords(it2, types7, !checkedTypes, errsCount);
    }
    __name(typeAndKeywords, "typeAndKeywords");
    function checkRefsAndKeywords(it2) {
      const { schema, errSchemaPath, opts, self: self2 } = it2;
      if (schema.$ref && opts.ignoreKeywordsWithRef && (0, util_1.schemaHasRulesButRef)(schema, self2.RULES)) {
        self2.logger.warn(`$ref: keywords ignored in schema at path "${errSchemaPath}"`);
      }
    }
    __name(checkRefsAndKeywords, "checkRefsAndKeywords");
    function checkNoDefault(it2) {
      const { schema, opts } = it2;
      if (schema.default !== void 0 && opts.useDefaults && opts.strictSchema) {
        (0, util_1.checkStrictMode)(it2, "default is ignored in the schema root");
      }
    }
    __name(checkNoDefault, "checkNoDefault");
    function updateContext(it2) {
      const schId = it2.schema[it2.opts.schemaId];
      if (schId)
        it2.baseId = (0, resolve_1.resolveUrl)(it2.opts.uriResolver, it2.baseId, schId);
    }
    __name(updateContext, "updateContext");
    function checkAsyncSchema(it2) {
      if (it2.schema.$async && !it2.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(it2) {
      const { gen, schemaEnv, validateName: validateName2, ValidationError, opts } = it2;
      if (schemaEnv.$async) {
        gen.if((0, codegen_1._)`${names_1.default.errors} === 0`, () => gen.return(names_1.default.data), () => gen.throw((0, codegen_1._)`new ${ValidationError}(${names_1.default.vErrors})`));
      } else {
        gen.assign((0, codegen_1._)`${validateName2}.errors`, names_1.default.vErrors);
        if (opts.unevaluated)
          assignEvaluated(it2);
        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(it2, types7, typeErrors, errsCount) {
      const { gen, schema, data, allErrors, opts, self: self2 } = it2;
      const { RULES } = self2;
      if (schema.$ref && (opts.ignoreKeywordsWithRef || !(0, util_1.schemaHasRulesButRef)(schema, RULES))) {
        gen.block(() => keywordCode(it2, "$ref", RULES.all.$ref.definition));
        return;
      }
      if (!opts.jtd)
        checkStrictTypes(it2, types7);
      gen.block(() => {
        for (const group of RULES.rules)
          groupKeywords(group);
        groupKeywords(RULES.post);
      });
      function groupKeywords(group) {
        if (!(0, applicability_1.shouldUseGroup)(schema, group))
          return;
        if (group.type) {
          gen.if((0, dataType_2.checkDataType)(group.type, data, opts.strictNumbers));
          iterateKeywords(it2, group);
          if (types7.length === 1 && types7[0] === group.type && typeErrors) {
            gen.else();
            (0, dataType_2.reportTypeError)(it2);
          }
          gen.endIf();
        } else {
          iterateKeywords(it2, group);
        }
        if (!allErrors)
          gen.if((0, codegen_1._)`${names_1.default.errors} === ${errsCount || 0}`);
      }
      __name(groupKeywords, "groupKeywords");
    }
    __name(schemaKeywords, "schemaKeywords");
    function iterateKeywords(it2, group) {
      const { gen, schema, opts: { useDefaults } } = it2;
      if (useDefaults)
        (0, defaults_1.assignDefaults)(it2, group.type);
      gen.block(() => {
        for (const rule of group.rules) {
          if ((0, applicability_1.shouldUseRule)(schema, rule)) {
            keywordCode(it2, rule.keyword, rule.definition, group.type);
          }
        }
      });
    }
    __name(iterateKeywords, "iterateKeywords");
    function checkStrictTypes(it2, types7) {
      if (it2.schemaEnv.meta || !it2.opts.strictTypes)
        return;
      checkContextTypes(it2, types7);
      if (!it2.opts.allowUnionTypes)
        checkMultipleTypes(it2, types7);
      checkKeywordTypes(it2, it2.dataTypes);
    }
    __name(checkStrictTypes, "checkStrictTypes");
    function checkContextTypes(it2, types7) {
      if (!types7.length)
        return;
      if (!it2.dataTypes.length) {
        it2.dataTypes = types7;
        return;
      }
      types7.forEach((t5) => {
        if (!includesType(it2.dataTypes, t5)) {
          strictTypesError(it2, `type "${t5}" not allowed by context "${it2.dataTypes.join(",")}"`);
        }
      });
      narrowSchemaTypes(it2, types7);
    }
    __name(checkContextTypes, "checkContextTypes");
    function checkMultipleTypes(it2, ts) {
      if (ts.length > 1 && !(ts.length === 2 && ts.includes("null"))) {
        strictTypesError(it2, "use allowUnionTypes to allow union type keyword");
      }
    }
    __name(checkMultipleTypes, "checkMultipleTypes");
    function checkKeywordTypes(it2, ts) {
      const rules = it2.self.RULES.all;
      for (const keyword in rules) {
        const rule = rules[keyword];
        if (typeof rule == "object" && (0, applicability_1.shouldUseRule)(it2.schema, rule)) {
          const { type } = rule.definition;
          if (type.length && !type.some((t5) => hasApplicableType(ts, t5))) {
            strictTypesError(it2, `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, t5) {
      return ts.includes(t5) || t5 === "integer" && ts.includes("number");
    }
    __name(includesType, "includesType");
    function narrowSchemaTypes(it2, withTypes) {
      const ts = [];
      for (const t5 of it2.dataTypes) {
        if (includesType(withTypes, t5))
          ts.push(t5);
        else if (withTypes.includes("integer") && t5 === "number")
          ts.push("integer");
      }
      it2.dataTypes = ts;
    }
    __name(narrowSchemaTypes, "narrowSchemaTypes");
    function strictTypesError(it2, msg) {
      const schemaPath = it2.schemaEnv.baseId + it2.errSchemaPath;
      msg += ` at "${schemaPath}" (strictTypes)`;
      (0, util_1.checkStrictMode)(it2, msg, it2.opts.strictTypes);
    }
    __name(strictTypesError, "strictTypesError");
    var KeywordCxt = class {
      static {
        __name(this, "KeywordCxt");
      }
      constructor(it2, def2, keyword) {
        (0, keyword_1.validateKeywordUsage)(it2, def2, keyword);
        this.gen = it2.gen;
        this.allErrors = it2.allErrors;
        this.keyword = keyword;
        this.data = it2.data;
        this.schema = it2.schema[keyword];
        this.$data = def2.$data && it2.opts.$data && this.schema && this.schema.$data;
        this.schemaValue = (0, util_1.schemaRefOrVal)(it2, this.schema, keyword, this.$data);
        this.schemaType = def2.schemaType;
        this.parentSchema = it2.schema;
        this.params = {};
        this.it = it2;
        this.def = def2;
        if (this.$data) {
          this.schemaCode = it2.gen.const("vSchema", getData(this.$data, it2));
        } else {
          this.schemaCode = this.schemaValue;
          if (!(0, keyword_1.validSchemaType)(this.schema, 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 = it2.gen.const("_errs", names_1.default.errors);
        }
      }
      result(condition, successAction, failAction) {
        this.failResult((0, codegen_1.not)(condition), successAction, failAction);
      }
      failResult(condition, successAction, failAction) {
        this.gen.if(condition);
        if (failAction)
          failAction();
        else
          this.error();
        if (successAction) {
          this.gen.else();
          successAction();
          if (this.allErrors)
            this.gen.endIf();
        } else {
          if (this.allErrors)
            this.gen.endIf();
          else
            this.gen.else();
        }
      }
      pass(condition, failAction) {
        this.failResult((0, codegen_1.not)(condition), void 0, failAction);
      }
      fail(condition) {
        if (condition === void 0) {
          this.error();
          if (!this.allErrors)
            this.gen.if(false);
          return;
        }
        this.gen.if(condition);
        this.error();
        if (this.allErrors)
          this.gen.endIf();
        else
          this.gen.else();
      }
      fail$data(condition) {
        if (!this.$data)
          return this.fail(condition);
        const { schemaCode } = this;
        this.fail((0, codegen_1._)`${schemaCode} !== undefined && (${(0, codegen_1.or)(this.invalid$data(), condition)})`);
      }
      error(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: it2 } = this;
        return (0, codegen_1.or)(wrong$DataType(), invalid$DataSchema());
        function wrong$DataType() {
          if (schemaType.length) {
            if (!(schemaCode instanceof codegen_1.Name))
              throw new Error("ajv implementation error");
            const st2 = Array.isArray(schemaType) ? schemaType : [schemaType];
            return (0, codegen_1._)`${(0, dataType_2.checkDataTypes)(st2, schemaCode, it2.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: it2, gen } = this;
        if (!it2.opts.unevaluated)
          return;
        if (it2.props !== true && schemaCxt.props !== void 0) {
          it2.props = util_1.mergeEvaluated.props(gen, schemaCxt.props, it2.props, toName);
        }
        if (it2.items !== true && schemaCxt.items !== void 0) {
          it2.items = util_1.mergeEvaluated.items(gen, schemaCxt.items, it2.items, toName);
        }
      }
      mergeValidEvaluated(schemaCxt, valid) {
        const { it: it2, gen } = this;
        if (it2.opts.unevaluated && (it2.props !== true || it2.items !== true)) {
          gen.if(valid, () => this.mergeEvaluated(schemaCxt, codegen_1.Name));
          return true;
        }
      }
    };
    exports2.KeywordCxt = KeywordCxt;
    function keywordCode(it2, keyword, def2, ruleType) {
      const cxt = new KeywordCxt(it2, 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_util11();
    var validate_1 = require_validate();
    var SchemaEnv = class {
      static {
        __name(this, "SchemaEnv");
      }
      constructor(env7) {
        var _a7;
        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 = (_a7 = env7.baseId) !== null && _a7 !== void 0 ? _a7 : (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 validate3 = makeValidate(this, this.scope.get());
        this.scope.value(validateName2, { ref: validate3 });
        validate3.errors = null;
        validate3.schema = sch.schema;
        validate3.schemaEnv = sch;
        if (sch.$async)
          validate3.$async = true;
        if (this.opts.code.source === true) {
          validate3.source = { validateName: validateName2, validateCode, scopeValues: gen._values };
        }
        if (this.opts.unevaluated) {
          const { props, items } = schemaCxt;
          validate3.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 (validate3.source)
            validate3.source.evaluated = (0, codegen_1.stringify)(validate3.evaluated);
        }
        sch.validate = validate3;
        return sch;
      } catch (e4) {
        delete sch.validate;
        delete sch.validateName;
        if (sourceCode)
          this.logger.error("Error compiling schema, function code:", sourceCode);
        throw e4;
      } finally {
        this._compilations.delete(sch);
      }
    }
    __name(compileSchema, "compileSchema");
    exports2.compileSchema = compileSchema;
    function resolveRef(root, baseId, ref) {
      var _a7;
      ref = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, ref);
      const schOrFunc = root.refs[ref];
      if (schOrFunc)
        return schOrFunc;
      let _sch = resolve30.call(this, root, ref);
      if (_sch === void 0) {
        const schema = (_a7 = root.localRefs) === null || _a7 === void 0 ? void 0 : _a7[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, s22) {
      return s1.schema === s22.schema && s1.root === s22.root && s1.baseId === s22.baseId;
    }
    __name(sameSchemaEnv, "sameSchemaEnv");
    function resolve30(root, ref) {
      let sch;
      while (typeof (sch = this.refs[ref]) == "string")
        ref = sch;
      return sch || this.schemas[ref] || resolveSchema.call(this, root, ref);
    }
    __name(resolve30, "resolve");
    function resolveSchema(root, ref) {
      const p2 = this.opts.uriResolver.parse(ref);
      const refPath = (0, resolve_1._getFullPath)(this.opts.uriResolver, p2);
      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, p2, 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, p2, 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, p2, 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 _a7;
      if (((_a7 = parsedRef.fragment) === null || _a7 === void 0 ? void 0 : _a7[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_utils2 = __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 strip2 = true;
      for (const c4 of input) {
        if (HEX[c4] === void 0) return void 0;
        if (c4 !== "0" && strip2 === true) strip2 = false;
        if (!strip2) acc += c4;
      }
      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 i3 = 0; i3 < input.length; i3++) {
        const cursor = input[i3];
        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 (i3 - 1 >= 0 && input[i3 - 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 ipv62 = getIPV6(host);
      if (!ipv62.error) {
        let newHost = ipv62.address;
        let escapedHost = ipv62.address;
        if (ipv62.zone) {
          newHost += "%" + ipv62.zone;
          escapedHost += "%25" + ipv62.zone;
        }
        return { host: newHost, escapedHost, isIPV6: true };
      } else {
        return { host, isIPV6: false };
      }
    }
    __name(normalizeIPv6, "normalizeIPv6");
    function stripLeadingZeros(str2, token2) {
      let out = "";
      let skip = true;
      const l3 = str2.length;
      for (let i3 = 0; i3 < l3; i3++) {
        const c4 = str2[i3];
        if (c4 === "0" && skip) {
          if (i3 + 1 <= l3 && str2[i3 + 1] === token2 || i3 + 1 === l3) {
            out += c4;
            skip = false;
          }
        } else {
          if (c4 === token2) {
            skip = true;
          } else {
            skip = false;
          }
          out += c4;
        }
      }
      return out;
    }
    __name(stripLeadingZeros, "stripLeadingZeros");
    function findToken(str2, token2) {
      let ind = 0;
      for (let i3 = 0; i3 < str2.length; i3++) {
        if (str2[i3] === 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 s5 = im[0];
            input = input.slice(s5.length);
            output.push(s5);
          } else {
            throw new Error("Unexpected dot segment condition");
          }
        }
      }
      return output.join("");
    }
    __name(removeDotSegments, "removeDotSegments");
    function normalizeComponentEncoding(components, esc2) {
      const func = esc2 !== 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 [path125, query] = wsComponents.resourceName.split("?");
        wsComponents.path = path125 && path125 !== "/" ? path125 : 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 http7 = {
      scheme: "http",
      domainHost: true,
      parse: httpParse,
      serialize: httpSerialize
    };
    var https7 = {
      scheme: "https",
      domainHost: http7.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: http7,
      https: https7,
      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_utils2();
    var SCHEMES = require_schemes();
    function normalize12(uri, options2) {
      if (typeof uri === "string") {
        uri = serialize2(parse14(uri, options2), options2);
      } else if (typeof uri === "object") {
        uri = parse14(serialize2(uri, options2), options2);
      }
      return uri;
    }
    __name(normalize12, "normalize");
    function resolve30(baseURI, relativeURI, options2) {
      const schemelessOptions = Object.assign({ scheme: "null" }, options2);
      const resolved = resolveComponents(parse14(baseURI, schemelessOptions), parse14(relativeURI, schemelessOptions), schemelessOptions, true);
      return serialize2(resolved, { ...schemelessOptions, skipEscape: true });
    }
    __name(resolve30, "resolve");
    function resolveComponents(base, relative11, options2, skipNormalization) {
      const target = {};
      if (!skipNormalization) {
        base = parse14(serialize2(base, options2), options2);
        relative11 = parse14(serialize2(relative11, options2), options2);
      }
      options2 = options2 || {};
      if (!options2.tolerant && relative11.scheme) {
        target.scheme = relative11.scheme;
        target.userinfo = relative11.userinfo;
        target.host = relative11.host;
        target.port = relative11.port;
        target.path = removeDotSegments(relative11.path || "");
        target.query = relative11.query;
      } else {
        if (relative11.userinfo !== void 0 || relative11.host !== void 0 || relative11.port !== void 0) {
          target.userinfo = relative11.userinfo;
          target.host = relative11.host;
          target.port = relative11.port;
          target.path = removeDotSegments(relative11.path || "");
          target.query = relative11.query;
        } else {
          if (!relative11.path) {
            target.path = base.path;
            if (relative11.query !== void 0) {
              target.query = relative11.query;
            } else {
              target.query = base.query;
            }
          } else {
            if (relative11.path.charAt(0) === "/") {
              target.path = removeDotSegments(relative11.path);
            } else {
              if ((base.userinfo !== void 0 || base.host !== void 0 || base.port !== void 0) && !base.path) {
                target.path = "/" + relative11.path;
              } else if (!base.path) {
                target.path = relative11.path;
              } else {
                target.path = base.path.slice(0, base.path.lastIndexOf("/") + 1) + relative11.path;
              }
              target.path = removeDotSegments(target.path);
            }
            target.query = relative11.query;
          }
          target.userinfo = base.userinfo;
          target.host = base.host;
          target.port = base.port;
        }
        target.scheme = base.scheme;
      }
      target.fragment = relative11.fragment;
      return target;
    }
    __name(resolveComponents, "resolveComponents");
    function equal(uriA, uriB, options2) {
      if (typeof uriA === "string") {
        uriA = unescape(uriA);
        uriA = serialize2(normalizeComponentEncoding(parse14(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(parse14(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 s5 = components.path;
        if (!options2.absolutePath && (!schemeHandler || !schemeHandler.absolutePath)) {
          s5 = removeDotSegments(s5);
        }
        if (authority === void 0) {
          s5 = s5.replace(/^\/\//u, "/%2F");
        }
        uriTokens.push(s5);
      }
      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, k2) => /[^!"$&'()*+,\-.;=_`a-z{}~]/u.test(String.fromCharCode(k2)));
    function nonSimpleDomain(value) {
      let code2 = 0;
      for (let i3 = 0, len = value.length; i3 < len; ++i3) {
        code2 = value.charCodeAt(i3);
        if (code2 > 126 || hexLookUp[code2]) {
          return true;
        }
      }
      return false;
    }
    __name(nonSimpleDomain, "nonSimpleDomain");
    var URI_PARSE = /^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;
    function parse14(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 isIP3 = 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();
            isIP3 = ipv6result.isIPV6;
          } else {
            parsed.host = ipv4result.host;
            isIP3 = 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) && isIP3 === false && nonSimpleDomain(parsed.host)) {
            try {
              parsed.host = URL.domainToASCII(parsed.host.toLowerCase());
            } catch (e4) {
              parsed.error = parsed.error || "Host's domain name can not be converted to ASCII: " + e4;
            }
          }
        }
        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(parse14, "parse");
    var fastUri = {
      SCHEMES,
      normalize: normalize12,
      resolve: resolve30,
      resolveComponents,
      equal,
      serialize: serialize2,
      parse: parse14
    };
    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_util11();
    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(o3) {
      var _a7, _b2, _c2, _d, _e2, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r2, _s, _t2, _u, _v, _w, _x, _y, _z, _0;
      const s5 = o3.strict;
      const _optz = (_a7 = o3.code) === null || _a7 === void 0 ? void 0 : _a7.optimize;
      const optimize = _optz === true || _optz === void 0 ? 1 : _optz || 0;
      const regExp = (_c2 = (_b2 = o3.code) === null || _b2 === void 0 ? void 0 : _b2.regExp) !== null && _c2 !== void 0 ? _c2 : defaultRegExp;
      const uriResolver = (_d = o3.uriResolver) !== null && _d !== void 0 ? _d : uri_1.default;
      return {
        strictSchema: (_f = (_e2 = o3.strictSchema) !== null && _e2 !== void 0 ? _e2 : s5) !== null && _f !== void 0 ? _f : true,
        strictNumbers: (_h = (_g = o3.strictNumbers) !== null && _g !== void 0 ? _g : s5) !== null && _h !== void 0 ? _h : true,
        strictTypes: (_k = (_j = o3.strictTypes) !== null && _j !== void 0 ? _j : s5) !== null && _k !== void 0 ? _k : "log",
        strictTuples: (_m = (_l = o3.strictTuples) !== null && _l !== void 0 ? _l : s5) !== null && _m !== void 0 ? _m : "log",
        strictRequired: (_p = (_o = o3.strictRequired) !== null && _o !== void 0 ? _o : s5) !== null && _p !== void 0 ? _p : false,
        code: o3.code ? { ...o3.code, optimize, regExp } : { optimize, regExp },
        loopRequired: (_q = o3.loopRequired) !== null && _q !== void 0 ? _q : MAX_EXPRESSION,
        loopEnum: (_r2 = o3.loopEnum) !== null && _r2 !== void 0 ? _r2 : MAX_EXPRESSION,
        meta: (_s = o3.meta) !== null && _s !== void 0 ? _s : true,
        messages: (_t2 = o3.messages) !== null && _t2 !== void 0 ? _t2 : true,
        inlineRefs: (_u = o3.inlineRefs) !== null && _u !== void 0 ? _u : true,
        schemaId: (_v = o3.schemaId) !== null && _v !== void 0 ? _v : "$id",
        addUsedSchema: (_w = o3.addUsedSchema) !== null && _w !== void 0 ? _w : true,
        validateSchema: (_x = o3.validateSchema) !== null && _x !== void 0 ? _x : true,
        validateFormats: (_y = o3.validateFormats) !== null && _y !== void 0 ? _y : true,
        unicodeRegExp: (_z = o3.unicodeRegExp) !== null && _z !== void 0 ? _z : true,
        int32range: (_0 = o3.int32range) !== null && _0 !== void 0 ? _0 : true,
        uriResolver
      };
    }
    __name(requiredOptions, "requiredOptions");
    var Ajv3 = 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 v2;
        if (typeof schemaKeyRef == "string") {
          v2 = this.getSchema(schemaKeyRef);
          if (!v2)
            throw new Error(`no schema with key or ref "${schemaKeyRef}"`);
        } else {
          v2 = this.compile(schemaKeyRef);
        }
        const valid = v2(data);
        if (!("$async" in v2))
          this.errors = v2.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 (e4) {
            if (!(e4 instanceof ref_error_1.default))
              throw e4;
            checkLoaded.call(this, e4);
            await loadMissingSchema.call(this, e4.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 p2 = this._loading[ref];
          if (p2)
            return p2;
          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 ? (k2) => addRule.call(this, k2, definition) : (k2) => definition.type.forEach((t5) => addRule.call(this, k2, definition, t5)));
        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 i3 = group.rules.findIndex((rule) => rule.keyword === keyword);
          if (i3 >= 0)
            group.rules.splice(i3, 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((e4) => `${dataVar}${e4.instancePath} ${e4.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;
        }
      }
    };
    Ajv3.ValidationError = validation_error_1.default;
    Ajv3.MissingRefError = ref_error_1.default;
    exports2.default = Ajv3;
    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 _a7;
      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: t5 }) => t5 === 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;
      (_a7 = definition.implements) === null || _a7 === void 0 ? void 0 : _a7.forEach((kwd) => this.addKeyword(kwd));
    }
    __name(addRule, "addRule");
    function addBeforeRule(ruleGroup, rule, before) {
      const i3 = ruleGroup.rules.findIndex((_rule) => _rule.keyword === before);
      if (i3 >= 0) {
        ruleGroup.rules.splice(i3, 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_util11();
    var def2 = {
      keyword: "$ref",
      schemaType: "string",
      code(cxt) {
        const { gen, schema: $ref, it: it2 } = cxt;
        const { baseId, schemaEnv: env7, validateName: validateName2, opts, self: self2 } = it2;
        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(it2.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 v2 = getValidate(cxt, sch);
          callRef(cxt, v2, 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, v2, sch, $async) {
      const { gen, it: it2 } = cxt;
      const { allErrors, schemaEnv: env7, opts } = it2;
      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, v2, passCxt)}`);
          addEvaluatedFrom(v2);
          if (!allErrors)
            gen.assign(valid, true);
        }, (e4) => {
          gen.if((0, codegen_1._)`!(${e4} instanceof ${it2.ValidationError})`, () => gen.throw(e4));
          addErrorsFrom(e4);
          if (!allErrors)
            gen.assign(valid, false);
        });
        cxt.ok(valid);
      }
      __name(callAsyncRef, "callAsyncRef");
      function callSyncRef() {
        cxt.result((0, code_1.callValidateCode)(cxt, v2, passCxt), () => addEvaluatedFrom(v2), () => addErrorsFrom(v2));
      }
      __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 _a7;
        if (!it2.opts.unevaluated)
          return;
        const schEvaluated = (_a7 = sch === null || sch === void 0 ? void 0 : sch.validate) === null || _a7 === void 0 ? void 0 : _a7.evaluated;
        if (it2.props !== true) {
          if (schEvaluated && !schEvaluated.dynamicProps) {
            if (schEvaluated.props !== void 0) {
              it2.props = util_1.mergeEvaluated.props(gen, schEvaluated.props, it2.props);
            }
          } else {
            const props = gen.var("props", (0, codegen_1._)`${source2}.evaluated.props`);
            it2.props = util_1.mergeEvaluated.props(gen, props, it2.props, codegen_1.Name);
          }
        }
        if (it2.items !== true) {
          if (schEvaluated && !schEvaluated.dynamicItems) {
            if (schEvaluated.items !== void 0) {
              it2.items = util_1.mergeEvaluated.items(gen, schEvaluated.items, it2.items);
            }
          } else {
            const items = gen.var("items", (0, codegen_1._)`${source2}.evaluated.items`);
            it2.items = util_1.mergeEvaluated.items(gen, items, it2.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 error2 = {
      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: error2,
      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 error2 = {
      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: error2,
      code(cxt) {
        const { gen, data, schemaCode, it: it2 } = cxt;
        const prec = it2.opts.multipleOfPrecision;
        const res = gen.let("res");
        const invalid = prec ? (0, codegen_1._)`Math.abs(Math.round(${res}) - ${res}) > 1e-${prec}` : (0, codegen_1._)`${res} !== parseInt(${res})`;
        cxt.fail$data((0, codegen_1._)`(${schemaCode} === 0 || (${res} = ${data}/${schemaCode}, ${invalid}))`);
      }
    };
    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_util11();
    var ucs2length_1 = require_ucs2length();
    var error2 = {
      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: error2,
      code(cxt) {
        const { keyword, data, schemaCode, it: it2 } = cxt;
        const op = keyword === "maxLength" ? codegen_1.operators.GT : codegen_1.operators.LT;
        const len = it2.opts.unicode === false ? (0, codegen_1._)`${data}.length` : (0, codegen_1._)`${(0, util_1.useFunc)(cxt.gen, ucs2length_1.default)}(${data})`;
        cxt.fail$data((0, codegen_1._)`${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 error2 = {
      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: error2,
      code(cxt) {
        const { data, $data, schema, schemaCode, it: it2 } = cxt;
        const u2 = it2.opts.unicodeRegExp ? "u" : "";
        const regExp = $data ? (0, codegen_1._)`(new RegExp(${schemaCode}, ${u2}))` : (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 error2 = {
      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: error2,
      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_util11();
    var error2 = {
      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: error2,
      code(cxt) {
        const { gen, schema, schemaCode, data, $data, it: it2 } = cxt;
        const { opts } = it2;
        if (!$data && schema.length === 0)
          return;
        const useLoop = schema.length >= opts.loopRequired;
        if (it2.allErrors)
          allErrorsMode();
        else
          exitOnErrorMode();
        if (opts.strictRequired) {
          const props = cxt.parentSchema.properties;
          const { definedProperties } = cxt.it;
          for (const requiredKey of schema) {
            if ((props === null || props === void 0 ? void 0 : props[requiredKey]) === void 0 && !definedProperties.has(requiredKey)) {
              const schemaPath = it2.schemaEnv.baseId + it2.errSchemaPath;
              const msg = `required property "${requiredKey}" is not defined at "${schemaPath}" (strictRequired)`;
              (0, util_1.checkStrictMode)(it2, msg, it2.opts.strictRequired);
            }
          }
        }
        function allErrorsMode() {
          if (useLoop || $data) {
            cxt.block$data(codegen_1.nil, loopAllRequired);
          } else {
            for (const prop of schema) {
              (0, code_1.checkReportMissingProp)(cxt, prop);
            }
          }
        }
        __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 error2 = {
      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: error2,
      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_util11();
    var equal_1 = require_equal();
    var error2 = {
      message: /* @__PURE__ */ __name(({ params: { i: i3, j: j2 } }) => (0, codegen_1.str)`must NOT have duplicate items (items ## ${j2} and ${i3} are identical)`, "message"),
      params: /* @__PURE__ */ __name(({ params: { i: i3, j: j2 } }) => (0, codegen_1._)`{i: ${i3}, j: ${j2}}`, "params")
    };
    var def2 = {
      keyword: "uniqueItems",
      type: "array",
      schemaType: "boolean",
      $data: true,
      error: error2,
      code(cxt) {
        const { gen, data, $data, schema, parentSchema, schemaCode, it: it2 } = cxt;
        if (!$data && !schema)
          return;
        const valid = gen.let("valid");
        const itemTypes = parentSchema.items ? (0, dataType_1.getSchemaTypes)(parentSchema.items) : [];
        cxt.block$data(valid, validateUniqueItems, (0, codegen_1._)`${schemaCode} === false`);
        cxt.ok(valid);
        function validateUniqueItems() {
          const i3 = gen.let("i", (0, codegen_1._)`${data}.length`);
          const j2 = gen.let("j");
          cxt.setParams({ i: i3, j: j2 });
          gen.assign(valid, true);
          gen.if((0, codegen_1._)`${i3} > 1`, () => (canOptimize() ? loopN : loopN2)(i3, j2));
        }
        __name(validateUniqueItems, "validateUniqueItems");
        function canOptimize() {
          return itemTypes.length > 0 && !itemTypes.some((t5) => t5 === "object" || t5 === "array");
        }
        __name(canOptimize, "canOptimize");
        function loopN(i3, j2) {
          const item = gen.name("item");
          const wrongType = (0, dataType_1.checkDataTypes)(itemTypes, item, it2.opts.strictNumbers, dataType_1.DataType.Wrong);
          const indices = gen.const("indices", (0, codegen_1._)`{}`);
          gen.for((0, codegen_1._)`;${i3}--;`, () => {
            gen.let(item, (0, codegen_1._)`${data}[${i3}]`);
            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(j2, (0, codegen_1._)`${indices}[${item}]`);
              cxt.error();
              gen.assign(valid, false).break();
            }).code((0, codegen_1._)`${indices}[${item}] = ${i3}`);
          });
        }
        __name(loopN, "loopN");
        function loopN2(i3, j2) {
          const eql = (0, util_1.useFunc)(gen, equal_1.default);
          const outer = gen.name("outer");
          gen.label(outer).for((0, codegen_1._)`;${i3}--;`, () => gen.for((0, codegen_1._)`${j2} = ${i3}; ${j2}--;`, () => gen.if((0, codegen_1._)`${eql}(${data}[${i3}], ${data}[${j2}])`, () => {
            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_util11();
    var equal_1 = require_equal();
    var error2 = {
      message: "must be equal to constant",
      params: /* @__PURE__ */ __name(({ schemaCode }) => (0, codegen_1._)`{allowedValue: ${schemaCode}}`, "params")
    };
    var def2 = {
      keyword: "const",
      $data: true,
      error: error2,
      code(cxt) {
        const { gen, data, $data, schemaCode, schema } = cxt;
        if ($data || schema && typeof schema == "object") {
          cxt.fail$data((0, codegen_1._)`!${(0, util_1.useFunc)(gen, equal_1.default)}(${data}, ${schemaCode})`);
        } else {
          cxt.fail((0, codegen_1._)`${schema} !== ${data}`);
        }
      }
    };
    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_util11();
    var equal_1 = require_equal();
    var error2 = {
      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: error2,
      code(cxt) {
        const { gen, data, $data, schema, schemaCode, it: it2 } = cxt;
        if (!$data && schema.length === 0)
          throw new Error("enum must have non-empty array");
        const useLoop = schema.length >= it2.opts.loopEnum;
        let eql;
        const getEql = /* @__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, i3) => equalCode(vSchema, i3)));
        }
        cxt.pass(valid);
        function loopEnum() {
          gen.assign(valid, false);
          gen.forOf("v", schemaCode, (v2) => gen.if((0, codegen_1._)`${getEql()}(${data}, ${v2})`, () => gen.assign(valid, true).break()));
        }
        __name(loopEnum, "loopEnum");
        function equalCode(vSchema, i3) {
          const sch = schema[i3];
          return typeof sch === "object" && sch !== null ? (0, codegen_1._)`${getEql()}(${data}, ${vSchema}[${i3}])` : (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_util11();
    var error2 = {
      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: error2,
      code(cxt) {
        const { parentSchema, it: it2 } = cxt;
        const { items } = parentSchema;
        if (!Array.isArray(items)) {
          (0, util_1.checkStrictMode)(it2, '"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: it2 } = cxt;
      it2.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)(it2, 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, (i3) => {
          cxt.subschema({ keyword, dataProp: i3, dataPropType: util_1.Type.Num }, valid);
          if (!it2.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_util11();
    var code_1 = require_code2();
    var def2 = {
      keyword: "items",
      type: "array",
      schemaType: ["object", "array", "boolean"],
      before: "uniqueItems",
      code(cxt) {
        const { schema, it: it2 } = cxt;
        if (Array.isArray(schema))
          return validateTuple(cxt, "additionalItems", schema);
        it2.items = true;
        if ((0, util_1.alwaysValidSchema)(it2, schema))
          return;
        cxt.ok((0, code_1.validateArray)(cxt));
      }
    };
    function validateTuple(cxt, extraItems, schArr = cxt.schema) {
      const { gen, parentSchema, data, keyword, it: it2 } = cxt;
      checkStrictTuple(parentSchema);
      if (it2.opts.unevaluated && schArr.length && it2.items !== true) {
        it2.items = util_1.mergeEvaluated.items(gen, schArr.length, it2.items);
      }
      const valid = gen.name("valid");
      const len = gen.const("len", (0, codegen_1._)`${data}.length`);
      schArr.forEach((sch, i3) => {
        if ((0, util_1.alwaysValidSchema)(it2, sch))
          return;
        gen.if((0, codegen_1._)`${len} > ${i3}`, () => cxt.subschema({
          keyword,
          schemaProp: i3,
          dataProp: i3
        }, valid));
        cxt.ok(valid);
      });
      function checkStrictTuple(sch) {
        const { opts, errSchemaPath } = it2;
        const l3 = schArr.length;
        const fullTuple = l3 === sch.minItems && (l3 === sch.maxItems || sch[extraItems] === false);
        if (opts.strictTuples && !fullTuple) {
          const msg = `"${keyword}" is ${l3}-tuple, but minItems or maxItems/${extraItems} are not specified or different at path "${errSchemaPath}"`;
          (0, util_1.checkStrictMode)(it2, 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_util11();
    var code_1 = require_code2();
    var additionalItems_1 = require_additionalItems();
    var error2 = {
      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: error2,
      code(cxt) {
        const { schema, parentSchema, it: it2 } = cxt;
        const { prefixItems } = parentSchema;
        it2.items = true;
        if ((0, util_1.alwaysValidSchema)(it2, 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_util11();
    var error2 = {
      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: error2,
      code(cxt) {
        const { gen, schema, parentSchema, data, it: it2 } = cxt;
        let min;
        let max;
        const { minContains, maxContains } = parentSchema;
        if (it2.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)(it2, `"minContains" == 0 without "maxContains": "contains" keyword ignored`);
          return;
        }
        if (max !== void 0 && min > max) {
          (0, util_1.checkStrictMode)(it2, `"minContains" > "maxContains" is always invalid`);
          cxt.fail();
          return;
        }
        if ((0, util_1.alwaysValidSchema)(it2, schema)) {
          let cond = (0, codegen_1._)`${len} >= ${min}`;
          if (max !== void 0)
            cond = (0, codegen_1._)`${cond} && ${len} <= ${max}`;
          cxt.pass(cond);
          return;
        }
        it2.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, (i3) => {
            cxt.subschema({
              keyword: "contains",
              dataProp: i3,
              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_util11();
    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: it2 } = cxt;
      if (Object.keys(propertyDeps).length === 0)
        return;
      const missing = gen.let("missing");
      for (const prop in propertyDeps) {
        const deps = propertyDeps[prop];
        if (deps.length === 0)
          continue;
        const hasProperty2 = (0, code_1.propertyInData)(gen, data, prop, it2.opts.ownProperties);
        cxt.setParams({
          property: prop,
          depsCount: deps.length,
          deps: deps.join(", ")
        });
        if (it2.allErrors) {
          gen.if(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: it2 } = cxt;
      const valid = gen.name("valid");
      for (const prop in schemaDeps) {
        if ((0, util_1.alwaysValidSchema)(it2, schemaDeps[prop]))
          continue;
        gen.if(
          (0, code_1.propertyInData)(gen, data, prop, it2.opts.ownProperties),
          () => {
            const schCxt = cxt.subschema({ keyword, 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_util11();
    var error2 = {
      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: error2,
      code(cxt) {
        const { gen, schema, data, it: it2 } = cxt;
        if ((0, util_1.alwaysValidSchema)(it2, schema))
          return;
        const valid = gen.name("valid");
        gen.forIn("key", data, (key) => {
          cxt.setParams({ propertyName: key });
          cxt.subschema({
            keyword: "propertyNames",
            data: key,
            dataTypes: ["string"],
            propertyName: key,
            compositeRule: true
          }, valid);
          gen.if((0, codegen_1.not)(valid), () => {
            cxt.error(true);
            if (!it2.allErrors)
              gen.break();
          });
        });
        cxt.ok(valid);
      }
    };
    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_util11();
    var error2 = {
      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: error2,
      code(cxt) {
        const { gen, schema, parentSchema, data, errsCount, it: it2 } = cxt;
        if (!errsCount)
          throw new Error("ajv implementation error");
        const { allErrors, opts } = it2;
        it2.props = true;
        if (opts.removeAdditional !== "all" && (0, util_1.alwaysValidSchema)(it2, schema))
          return;
        const props = (0, code_1.allSchemaProperties)(parentSchema.properties);
        const patProps = (0, code_1.allSchemaProperties)(parentSchema.patternProperties);
        checkAdditionalProperties();
        cxt.ok((0, codegen_1._)`${errsCount} === ${names_1.default.errors}`);
        function checkAdditionalProperties() {
          gen.forIn("key", data, (key) => {
            if (!props.length && !patProps.length)
              additionalPropertyCode(key);
            else
              gen.if(isAdditional(key), () => additionalPropertyCode(key));
          });
        }
        __name(checkAdditionalProperties, "checkAdditionalProperties");
        function isAdditional(key) {
          let definedProp;
          if (props.length > 8) {
            const propsSchema = (0, util_1.schemaRefOrVal)(it2, parentSchema.properties, "properties");
            definedProp = (0, code_1.isOwnProperty)(gen, propsSchema, key);
          } else if (props.length) {
            definedProp = (0, codegen_1.or)(...props.map((p2) => (0, codegen_1._)`${key} === ${p2}`));
          } else {
            definedProp = codegen_1.nil;
          }
          if (patProps.length) {
            definedProp = (0, codegen_1.or)(definedProp, ...patProps.map((p2) => (0, codegen_1._)`${(0, code_1.usePattern)(cxt, p2)}.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)(it2, schema)) {
            const valid = gen.name("valid");
            if (opts.removeAdditional === "failing") {
              applyAdditionalSchema(key, valid, false);
              gen.if((0, codegen_1.not)(valid), () => {
                cxt.reset();
                deleteAdditional(key);
              });
            } else {
              applyAdditionalSchema(key, valid);
              if (!allErrors)
                gen.if((0, codegen_1.not)(valid), () => gen.break());
            }
          }
        }
        __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_util11();
    var additionalProperties_1 = require_additionalProperties();
    var def2 = {
      keyword: "properties",
      type: "object",
      schemaType: "object",
      code(cxt) {
        const { gen, schema, parentSchema, data, it: it2 } = cxt;
        if (it2.opts.removeAdditional === "all" && parentSchema.additionalProperties === void 0) {
          additionalProperties_1.default.code(new validate_1.KeywordCxt(it2, additionalProperties_1.default, "additionalProperties"));
        }
        const allProps = (0, code_1.allSchemaProperties)(schema);
        for (const prop of allProps) {
          it2.definedProperties.add(prop);
        }
        if (it2.opts.unevaluated && allProps.length && it2.props !== true) {
          it2.props = util_1.mergeEvaluated.props(gen, (0, util_1.toHash)(allProps), it2.props);
        }
        const properties = allProps.filter((p2) => !(0, util_1.alwaysValidSchema)(it2, schema[p2]));
        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, it2.opts.ownProperties));
            applyPropertySchema(prop);
            if (!it2.allErrors)
              gen.else().var(valid, true);
            gen.endIf();
          }
          cxt.it.definedProperties.add(prop);
          cxt.ok(valid);
        }
        function hasDefault(prop) {
          return it2.opts.useDefaults && !it2.compositeRule && schema[prop].default !== void 0;
        }
        __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_util11();
    var util_2 = require_util11();
    var def2 = {
      keyword: "patternProperties",
      type: "object",
      schemaType: "object",
      code(cxt) {
        const { gen, schema, data, parentSchema, it: it2 } = cxt;
        const { opts } = it2;
        const patterns = (0, code_1.allSchemaProperties)(schema);
        const alwaysValidPatterns = patterns.filter((p2) => (0, util_1.alwaysValidSchema)(it2, schema[p2]));
        if (patterns.length === 0 || alwaysValidPatterns.length === patterns.length && (!it2.opts.unevaluated || it2.props === true)) {
          return;
        }
        const checkProperties = opts.strictSchema && !opts.allowMatchingProperties && parentSchema.properties;
        const valid = gen.name("valid");
        if (it2.props !== true && !(it2.props instanceof codegen_1.Name)) {
          it2.props = (0, util_2.evaluatedPropsToName)(gen, it2.props);
        }
        const { props } = it2;
        validatePatternProperties();
        function validatePatternProperties() {
          for (const pat of patterns) {
            if (checkProperties)
              checkMatchingProperties(pat);
            if (it2.allErrors) {
              validateProperties(pat);
            } else {
              gen.var(valid, true);
              validateProperties(pat);
              gen.if(valid);
            }
          }
        }
        __name(validatePatternProperties, "validatePatternProperties");
        function checkMatchingProperties(pat) {
          for (const prop in checkProperties) {
            if (new RegExp(pat).test(prop)) {
              (0, util_1.checkStrictMode)(it2, `property ${prop} matches pattern ${pat} (use allowMatchingProperties)`);
            }
          }
        }
        __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 (it2.opts.unevaluated && props !== true) {
                gen.assign((0, codegen_1._)`${props}[${key}]`, true);
              } else if (!alwaysValid && !it2.allErrors) {
                gen.if((0, codegen_1.not)(valid), () => gen.break());
              }
            });
          });
        }
        __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_util11();
    var def2 = {
      keyword: "not",
      schemaType: ["object", "boolean"],
      trackErrors: true,
      code(cxt) {
        const { gen, schema, it: it2 } = cxt;
        if ((0, util_1.alwaysValidSchema)(it2, schema)) {
          cxt.fail();
          return;
        }
        const valid = gen.name("valid");
        cxt.subschema({
          keyword: "not",
          compositeRule: true,
          createErrors: false,
          allErrors: false
        }, valid);
        cxt.failResult(valid, () => cxt.reset(), () => cxt.error());
      },
      error: { message: "must NOT be valid" }
    };
    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_util11();
    var error2 = {
      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: error2,
      code(cxt) {
        const { gen, schema, parentSchema, it: it2 } = cxt;
        if (!Array.isArray(schema))
          throw new Error("ajv implementation error");
        if (it2.opts.discriminator && parentSchema.discriminator)
          return;
        const schArr = schema;
        const valid = gen.let("valid", false);
        const passing = gen.let("passing", null);
        const schValid = gen.name("_valid");
        cxt.setParams({ passing });
        gen.block(validateOneOf);
        cxt.result(valid, () => cxt.reset(), () => cxt.error(true));
        function validateOneOf() {
          schArr.forEach((sch, i3) => {
            let schCxt;
            if ((0, util_1.alwaysValidSchema)(it2, sch)) {
              gen.var(schValid, true);
            } else {
              schCxt = cxt.subschema({
                keyword: "oneOf",
                schemaProp: i3,
                compositeRule: true
              }, schValid);
            }
            if (i3 > 0) {
              gen.if((0, codegen_1._)`${schValid} && ${valid}`).assign(valid, false).assign(passing, (0, codegen_1._)`[${passing}, ${i3}]`).else();
            }
            gen.if(schValid, () => {
              gen.assign(valid, true);
              gen.assign(passing, i3);
              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_util11();
    var def2 = {
      keyword: "allOf",
      schemaType: "array",
      code(cxt) {
        const { gen, schema, it: it2 } = cxt;
        if (!Array.isArray(schema))
          throw new Error("ajv implementation error");
        const valid = gen.name("valid");
        schema.forEach((sch, i3) => {
          if ((0, util_1.alwaysValidSchema)(it2, sch))
            return;
          const schCxt = cxt.subschema({ keyword: "allOf", schemaProp: i3 }, 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_util11();
    var error2 = {
      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: error2,
      code(cxt) {
        const { gen, parentSchema, it: it2 } = cxt;
        if (parentSchema.then === void 0 && parentSchema.else === void 0) {
          (0, util_1.checkStrictMode)(it2, '"if" without "then" and "else" is ignored');
        }
        const hasThen = hasSchema(it2, "then");
        const hasElse = hasSchema(it2, "else");
        if (!hasThen && !hasElse)
          return;
        const valid = gen.let("valid", true);
        const schValid = gen.name("_valid");
        validateIf();
        cxt.reset();
        if (hasThen && hasElse) {
          const ifClause = gen.let("ifClause");
          cxt.setParams({ ifClause });
          gen.if(schValid, validateClause("then", ifClause), validateClause("else", ifClause));
        } else if (hasThen) {
          gen.if(schValid, validateClause("then"));
        } else {
          gen.if((0, codegen_1.not)(schValid), validateClause("else"));
        }
        cxt.pass(valid, () => cxt.error(true));
        function validateIf() {
          const schCxt = cxt.subschema({
            keyword: "if",
            compositeRule: true,
            createErrors: false,
            allErrors: false
          }, schValid);
          cxt.mergeEvaluated(schCxt);
        }
        __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(it2, keyword) {
      const schema = it2.schema[keyword];
      return schema !== void 0 && !(0, util_1.alwaysValidSchema)(it2, 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_util11();
    var def2 = {
      keyword: ["then", "else"],
      schemaType: ["object", "boolean"],
      code({ keyword, parentSchema, it: it2 }) {
        if (parentSchema.if === void 0)
          (0, util_1.checkStrictMode)(it2, `"${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 error2 = {
      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: error2,
      code(cxt, ruleType) {
        const { gen, data, $data, schema, schemaCode, it: it2 } = cxt;
        const { opts, errSchemaPath, schemaEnv, self: self2 } = it2;
        if (!opts.validateFormats)
          return;
        if ($data)
          validate$DataFormat();
        else
          validateFormat();
        function validate$DataFormat() {
          const fmts = gen.scopeValue("formats", {
            ref: self2.formats,
            code: opts.code.formats
          });
          const fDef = gen.const("fDef", (0, codegen_1._)`${fmts}[${schemaCode}]`);
          const fType = gen.let("fType");
          const 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_util11();
    var error2 = {
      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: error2,
      code(cxt) {
        const { gen, data, schema, parentSchema, it: it2 } = cxt;
        const { oneOf } = parentSchema;
        if (!it2.opts.discriminator) {
          throw new Error("discriminator: requires discriminator option");
        }
        const tagName = schema.propertyName;
        if (typeof tagName != "string")
          throw new Error("discriminator: requires propertyName");
        if (schema.mapping)
          throw new Error("discriminator: mapping is not supported");
        if (!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 _a7;
          const oneOfMapping = {};
          const topRequired = hasRequired(parentSchema);
          let tagRequired = true;
          for (let i3 = 0; i3 < oneOf.length; i3++) {
            let sch = oneOf[i3];
            if ((sch === null || sch === void 0 ? void 0 : sch.$ref) && !(0, util_1.schemaHasRulesButRef)(sch, it2.self.RULES)) {
              const ref = sch.$ref;
              sch = compile_1.resolveRef.call(it2.self, it2.schemaEnv.root, it2.baseId, ref);
              if (sch instanceof compile_1.SchemaEnv)
                sch = sch.schema;
              if (sch === void 0)
                throw new ref_error_1.default(it2.opts.uriResolver, it2.baseId, ref);
            }
            const propSch = (_a7 = sch === null || sch === void 0 ? void 0 : sch.properties) === null || _a7 === void 0 ? void 0 : _a7[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, i3);
          }
          if (!tagRequired)
            throw new Error(`discriminator: "${tagName}" must be required`);
          return oneOfMapping;
          function hasRequired({ required: required2 }) {
            return Array.isArray(required2) && required2.includes(tagName);
          }
          __name(hasRequired, "hasRequired");
          function addMappings(sch, i3) {
            if (sch.const) {
              addMapping(sch.const, i3);
            } else if (sch.enum) {
              for (const tagValue of sch.enum) {
                addMapping(tagValue, i3);
              }
            } else {
              throw new Error(`discriminator: "properties/${tagName}" must have "const" or "enum"`);
            }
          }
          __name(addMappings, "addMappings");
          function addMapping(tagValue, i3) {
            if (typeof tagValue != "string" || tagValue in oneOfMapping) {
              throw new Error(`discriminator: "${tagName}" values must be unique strings`);
            }
            oneOfMapping[tagValue] = i3;
          }
          __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 Ajv3 = class extends core_1.default {
      static {
        __name(this, "Ajv");
      }
      _addVocabularies() {
        super._addVocabularies();
        draft7_1.default.forEach((v2) => this.addVocabulary(v2));
        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 = Ajv3;
    module2.exports = exports2 = Ajv3;
    module2.exports.Ajv = Ajv3;
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.default = Ajv3;
    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") });
  }
});

// packages/core/node_modules/ajv/dist/vocabularies/dynamic/dynamicAnchor.js
var require_dynamicAnchor = __commonJS({
  "packages/core/node_modules/ajv/dist/vocabularies/dynamic/dynamicAnchor.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.dynamicAnchor = void 0;
    var codegen_1 = require_codegen();
    var names_1 = require_names();
    var compile_1 = require_compile();
    var ref_1 = require_ref();
    var def2 = {
      keyword: "$dynamicAnchor",
      schemaType: "string",
      code: /* @__PURE__ */ __name((cxt) => dynamicAnchor(cxt, cxt.schema), "code")
    };
    function dynamicAnchor(cxt, anchor) {
      const { gen, it: it2 } = cxt;
      it2.schemaEnv.root.dynamicAnchors[anchor] = true;
      const v2 = (0, codegen_1._)`${names_1.default.dynamicAnchors}${(0, codegen_1.getProperty)(anchor)}`;
      const validate3 = it2.errSchemaPath === "#" ? it2.validateName : _getValidate(cxt);
      gen.if((0, codegen_1._)`!${v2}`, () => gen.assign(v2, validate3));
    }
    __name(dynamicAnchor, "dynamicAnchor");
    exports2.dynamicAnchor = dynamicAnchor;
    function _getValidate(cxt) {
      const { schemaEnv, schema, self: self2 } = cxt.it;
      const { root, baseId, localRefs, meta } = schemaEnv.root;
      const { schemaId } = self2.opts;
      const sch = new compile_1.SchemaEnv({ schema, schemaId, root, baseId, localRefs, meta });
      compile_1.compileSchema.call(self2, sch);
      return (0, ref_1.getValidate)(cxt, sch);
    }
    __name(_getValidate, "_getValidate");
    exports2.default = def2;
  }
});

// packages/core/node_modules/ajv/dist/vocabularies/dynamic/dynamicRef.js
var require_dynamicRef = __commonJS({
  "packages/core/node_modules/ajv/dist/vocabularies/dynamic/dynamicRef.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.dynamicRef = void 0;
    var codegen_1 = require_codegen();
    var names_1 = require_names();
    var ref_1 = require_ref();
    var def2 = {
      keyword: "$dynamicRef",
      schemaType: "string",
      code: /* @__PURE__ */ __name((cxt) => dynamicRef(cxt, cxt.schema), "code")
    };
    function dynamicRef(cxt, ref) {
      const { gen, keyword, it: it2 } = cxt;
      if (ref[0] !== "#")
        throw new Error(`"${keyword}" only supports hash fragment reference`);
      const anchor = ref.slice(1);
      if (it2.allErrors) {
        _dynamicRef();
      } else {
        const valid = gen.let("valid", false);
        _dynamicRef(valid);
        cxt.ok(valid);
      }
      function _dynamicRef(valid) {
        if (it2.schemaEnv.root.dynamicAnchors[anchor]) {
          const v2 = gen.let("_v", (0, codegen_1._)`${names_1.default.dynamicAnchors}${(0, codegen_1.getProperty)(anchor)}`);
          gen.if(v2, _callRef(v2, valid), _callRef(it2.validateName, valid));
        } else {
          _callRef(it2.validateName, valid)();
        }
      }
      __name(_dynamicRef, "_dynamicRef");
      function _callRef(validate3, valid) {
        return valid ? () => gen.block(() => {
          (0, ref_1.callRef)(cxt, validate3);
          gen.let(valid, true);
        }) : () => (0, ref_1.callRef)(cxt, validate3);
      }
      __name(_callRef, "_callRef");
    }
    __name(dynamicRef, "dynamicRef");
    exports2.dynamicRef = dynamicRef;
    exports2.default = def2;
  }
});

// packages/core/node_modules/ajv/dist/vocabularies/dynamic/recursiveAnchor.js
var require_recursiveAnchor = __commonJS({
  "packages/core/node_modules/ajv/dist/vocabularies/dynamic/recursiveAnchor.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    var dynamicAnchor_1 = require_dynamicAnchor();
    var util_1 = require_util11();
    var def2 = {
      keyword: "$recursiveAnchor",
      schemaType: "boolean",
      code(cxt) {
        if (cxt.schema)
          (0, dynamicAnchor_1.dynamicAnchor)(cxt, "");
        else
          (0, util_1.checkStrictMode)(cxt.it, "$recursiveAnchor: false is ignored");
      }
    };
    exports2.default = def2;
  }
});

// packages/core/node_modules/ajv/dist/vocabularies/dynamic/recursiveRef.js
var require_recursiveRef = __commonJS({
  "packages/core/node_modules/ajv/dist/vocabularies/dynamic/recursiveRef.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    var dynamicRef_1 = require_dynamicRef();
    var def2 = {
      keyword: "$recursiveRef",
      schemaType: "string",
      code: /* @__PURE__ */ __name((cxt) => (0, dynamicRef_1.dynamicRef)(cxt, cxt.schema), "code")
    };
    exports2.default = def2;
  }
});

// packages/core/node_modules/ajv/dist/vocabularies/dynamic/index.js
var require_dynamic = __commonJS({
  "packages/core/node_modules/ajv/dist/vocabularies/dynamic/index.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    var dynamicAnchor_1 = require_dynamicAnchor();
    var dynamicRef_1 = require_dynamicRef();
    var recursiveAnchor_1 = require_recursiveAnchor();
    var recursiveRef_1 = require_recursiveRef();
    var dynamic = [dynamicAnchor_1.default, dynamicRef_1.default, recursiveAnchor_1.default, recursiveRef_1.default];
    exports2.default = dynamic;
  }
});

// packages/core/node_modules/ajv/dist/vocabularies/validation/dependentRequired.js
var require_dependentRequired = __commonJS({
  "packages/core/node_modules/ajv/dist/vocabularies/validation/dependentRequired.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    var dependencies_1 = require_dependencies();
    var def2 = {
      keyword: "dependentRequired",
      type: "object",
      schemaType: "object",
      error: dependencies_1.error,
      code: /* @__PURE__ */ __name((cxt) => (0, dependencies_1.validatePropertyDeps)(cxt), "code")
    };
    exports2.default = def2;
  }
});

// packages/core/node_modules/ajv/dist/vocabularies/applicator/dependentSchemas.js
var require_dependentSchemas = __commonJS({
  "packages/core/node_modules/ajv/dist/vocabularies/applicator/dependentSchemas.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    var dependencies_1 = require_dependencies();
    var def2 = {
      keyword: "dependentSchemas",
      type: "object",
      schemaType: "object",
      code: /* @__PURE__ */ __name((cxt) => (0, dependencies_1.validateSchemaDeps)(cxt), "code")
    };
    exports2.default = def2;
  }
});

// packages/core/node_modules/ajv/dist/vocabularies/validation/limitContains.js
var require_limitContains = __commonJS({
  "packages/core/node_modules/ajv/dist/vocabularies/validation/limitContains.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    var util_1 = require_util11();
    var def2 = {
      keyword: ["maxContains", "minContains"],
      type: "array",
      schemaType: "number",
      code({ keyword, parentSchema, it: it2 }) {
        if (parentSchema.contains === void 0) {
          (0, util_1.checkStrictMode)(it2, `"${keyword}" without "contains" is ignored`);
        }
      }
    };
    exports2.default = def2;
  }
});

// packages/core/node_modules/ajv/dist/vocabularies/next.js
var require_next = __commonJS({
  "packages/core/node_modules/ajv/dist/vocabularies/next.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    var dependentRequired_1 = require_dependentRequired();
    var dependentSchemas_1 = require_dependentSchemas();
    var limitContains_1 = require_limitContains();
    var next = [dependentRequired_1.default, dependentSchemas_1.default, limitContains_1.default];
    exports2.default = next;
  }
});

// packages/core/node_modules/ajv/dist/vocabularies/unevaluated/unevaluatedProperties.js
var require_unevaluatedProperties = __commonJS({
  "packages/core/node_modules/ajv/dist/vocabularies/unevaluated/unevaluatedProperties.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    var codegen_1 = require_codegen();
    var util_1 = require_util11();
    var names_1 = require_names();
    var error2 = {
      message: "must NOT have unevaluated properties",
      params: /* @__PURE__ */ __name(({ params }) => (0, codegen_1._)`{unevaluatedProperty: ${params.unevaluatedProperty}}`, "params")
    };
    var def2 = {
      keyword: "unevaluatedProperties",
      type: "object",
      schemaType: ["boolean", "object"],
      trackErrors: true,
      error: error2,
      code(cxt) {
        const { gen, schema, data, errsCount, it: it2 } = cxt;
        if (!errsCount)
          throw new Error("ajv implementation error");
        const { allErrors, props } = it2;
        if (props instanceof codegen_1.Name) {
          gen.if((0, codegen_1._)`${props} !== true`, () => gen.forIn("key", data, (key) => gen.if(unevaluatedDynamic(props, key), () => unevaluatedPropCode(key))));
        } else if (props !== true) {
          gen.forIn("key", data, (key) => props === void 0 ? unevaluatedPropCode(key) : gen.if(unevaluatedStatic(props, key), () => unevaluatedPropCode(key)));
        }
        it2.props = true;
        cxt.ok((0, codegen_1._)`${errsCount} === ${names_1.default.errors}`);
        function unevaluatedPropCode(key) {
          if (schema === false) {
            cxt.setParams({ unevaluatedProperty: key });
            cxt.error();
            if (!allErrors)
              gen.break();
            return;
          }
          if (!(0, util_1.alwaysValidSchema)(it2, schema)) {
            const valid = gen.name("valid");
            cxt.subschema({
              keyword: "unevaluatedProperties",
              dataProp: key,
              dataPropType: util_1.Type.Str
            }, valid);
            if (!allErrors)
              gen.if((0, codegen_1.not)(valid), () => gen.break());
          }
        }
        __name(unevaluatedPropCode, "unevaluatedPropCode");
        function unevaluatedDynamic(evaluatedProps, key) {
          return (0, codegen_1._)`!${evaluatedProps} || !${evaluatedProps}[${key}]`;
        }
        __name(unevaluatedDynamic, "unevaluatedDynamic");
        function unevaluatedStatic(evaluatedProps, key) {
          const ps = [];
          for (const p2 in evaluatedProps) {
            if (evaluatedProps[p2] === true)
              ps.push((0, codegen_1._)`${key} !== ${p2}`);
          }
          return (0, codegen_1.and)(...ps);
        }
        __name(unevaluatedStatic, "unevaluatedStatic");
      }
    };
    exports2.default = def2;
  }
});

// packages/core/node_modules/ajv/dist/vocabularies/unevaluated/unevaluatedItems.js
var require_unevaluatedItems = __commonJS({
  "packages/core/node_modules/ajv/dist/vocabularies/unevaluated/unevaluatedItems.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    var codegen_1 = require_codegen();
    var util_1 = require_util11();
    var error2 = {
      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: "unevaluatedItems",
      type: "array",
      schemaType: ["boolean", "object"],
      error: error2,
      code(cxt) {
        const { gen, schema, data, it: it2 } = cxt;
        const items = it2.items || 0;
        if (items === true)
          return;
        const len = gen.const("len", (0, codegen_1._)`${data}.length`);
        if (schema === false) {
          cxt.setParams({ len: items });
          cxt.fail((0, codegen_1._)`${len} > ${items}`);
        } else if (typeof schema == "object" && !(0, util_1.alwaysValidSchema)(it2, schema)) {
          const valid = gen.var("valid", (0, codegen_1._)`${len} <= ${items}`);
          gen.if((0, codegen_1.not)(valid), () => validateItems(valid, items));
          cxt.ok(valid);
        }
        it2.items = true;
        function validateItems(valid, from) {
          gen.forRange("i", from, len, (i3) => {
            cxt.subschema({ keyword: "unevaluatedItems", dataProp: i3, dataPropType: util_1.Type.Num }, valid);
            if (!it2.allErrors)
              gen.if((0, codegen_1.not)(valid), () => gen.break());
          });
        }
        __name(validateItems, "validateItems");
      }
    };
    exports2.default = def2;
  }
});

// packages/core/node_modules/ajv/dist/vocabularies/unevaluated/index.js
var require_unevaluated = __commonJS({
  "packages/core/node_modules/ajv/dist/vocabularies/unevaluated/index.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    var unevaluatedProperties_1 = require_unevaluatedProperties();
    var unevaluatedItems_1 = require_unevaluatedItems();
    var unevaluated = [unevaluatedProperties_1.default, unevaluatedItems_1.default];
    exports2.default = unevaluated;
  }
});

// packages/core/node_modules/ajv/dist/vocabularies/draft2020.js
var require_draft2020 = __commonJS({
  "packages/core/node_modules/ajv/dist/vocabularies/draft2020.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 dynamic_1 = require_dynamic();
    var next_1 = require_next();
    var unevaluated_1 = require_unevaluated();
    var format_1 = require_format2();
    var metadata_1 = require_metadata();
    var draft2020Vocabularies = [
      dynamic_1.default,
      core_1.default,
      validation_1.default,
      (0, applicator_1.default)(true),
      format_1.default,
      metadata_1.metadataVocabulary,
      metadata_1.contentVocabulary,
      next_1.default,
      unevaluated_1.default
    ];
    exports2.default = draft2020Vocabularies;
  }
});

// packages/core/node_modules/ajv/dist/refs/json-schema-2020-12/schema.json
var require_schema = __commonJS({
  "packages/core/node_modules/ajv/dist/refs/json-schema-2020-12/schema.json"(exports2, module2) {
    module2.exports = {
      $schema: "https://json-schema.org/draft/2020-12/schema",
      $id: "https://json-schema.org/draft/2020-12/schema",
      $vocabulary: {
        "https://json-schema.org/draft/2020-12/vocab/core": true,
        "https://json-schema.org/draft/2020-12/vocab/applicator": true,
        "https://json-schema.org/draft/2020-12/vocab/unevaluated": true,
        "https://json-schema.org/draft/2020-12/vocab/validation": true,
        "https://json-schema.org/draft/2020-12/vocab/meta-data": true,
        "https://json-schema.org/draft/2020-12/vocab/format-annotation": true,
        "https://json-schema.org/draft/2020-12/vocab/content": true
      },
      $dynamicAnchor: "meta",
      title: "Core and Validation specifications meta-schema",
      allOf: [
        { $ref: "meta/core" },
        { $ref: "meta/applicator" },
        { $ref: "meta/unevaluated" },
        { $ref: "meta/validation" },
        { $ref: "meta/meta-data" },
        { $ref: "meta/format-annotation" },
        { $ref: "meta/content" }
      ],
      type: ["object", "boolean"],
      $comment: "This meta-schema also defines keywords that have appeared in previous drafts in order to prevent incompatible extensions as they remain in common use.",
      properties: {
        definitions: {
          $comment: '"definitions" has been replaced by "$defs".',
          type: "object",
          additionalProperties: { $dynamicRef: "#meta" },
          deprecated: true,
          default: {}
        },
        dependencies: {
          $comment: '"dependencies" has been split and replaced by "dependentSchemas" and "dependentRequired" in order to serve their differing semantics.',
          type: "object",
          additionalProperties: {
            anyOf: [{ $dynamicRef: "#meta" }, { $ref: "meta/validation#/$defs/stringArray" }]
          },
          deprecated: true,
          default: {}
        },
        $recursiveAnchor: {
          $comment: '"$recursiveAnchor" has been replaced by "$dynamicAnchor".',
          $ref: "meta/core#/$defs/anchorString",
          deprecated: true
        },
        $recursiveRef: {
          $comment: '"$recursiveRef" has been replaced by "$dynamicRef".',
          $ref: "meta/core#/$defs/uriReferenceString",
          deprecated: true
        }
      }
    };
  }
});

// packages/core/node_modules/ajv/dist/refs/json-schema-2020-12/meta/applicator.json
var require_applicator2 = __commonJS({
  "packages/core/node_modules/ajv/dist/refs/json-schema-2020-12/meta/applicator.json"(exports2, module2) {
    module2.exports = {
      $schema: "https://json-schema.org/draft/2020-12/schema",
      $id: "https://json-schema.org/draft/2020-12/meta/applicator",
      $vocabulary: {
        "https://json-schema.org/draft/2020-12/vocab/applicator": true
      },
      $dynamicAnchor: "meta",
      title: "Applicator vocabulary meta-schema",
      type: ["object", "boolean"],
      properties: {
        prefixItems: { $ref: "#/$defs/schemaArray" },
        items: { $dynamicRef: "#meta" },
        contains: { $dynamicRef: "#meta" },
        additionalProperties: { $dynamicRef: "#meta" },
        properties: {
          type: "object",
          additionalProperties: { $dynamicRef: "#meta" },
          default: {}
        },
        patternProperties: {
          type: "object",
          additionalProperties: { $dynamicRef: "#meta" },
          propertyNames: { format: "regex" },
          default: {}
        },
        dependentSchemas: {
          type: "object",
          additionalProperties: { $dynamicRef: "#meta" },
          default: {}
        },
        propertyNames: { $dynamicRef: "#meta" },
        if: { $dynamicRef: "#meta" },
        then: { $dynamicRef: "#meta" },
        else: { $dynamicRef: "#meta" },
        allOf: { $ref: "#/$defs/schemaArray" },
        anyOf: { $ref: "#/$defs/schemaArray" },
        oneOf: { $ref: "#/$defs/schemaArray" },
        not: { $dynamicRef: "#meta" }
      },
      $defs: {
        schemaArray: {
          type: "array",
          minItems: 1,
          items: { $dynamicRef: "#meta" }
        }
      }
    };
  }
});

// packages/core/node_modules/ajv/dist/refs/json-schema-2020-12/meta/unevaluated.json
var require_unevaluated2 = __commonJS({
  "packages/core/node_modules/ajv/dist/refs/json-schema-2020-12/meta/unevaluated.json"(exports2, module2) {
    module2.exports = {
      $schema: "https://json-schema.org/draft/2020-12/schema",
      $id: "https://json-schema.org/draft/2020-12/meta/unevaluated",
      $vocabulary: {
        "https://json-schema.org/draft/2020-12/vocab/unevaluated": true
      },
      $dynamicAnchor: "meta",
      title: "Unevaluated applicator vocabulary meta-schema",
      type: ["object", "boolean"],
      properties: {
        unevaluatedItems: { $dynamicRef: "#meta" },
        unevaluatedProperties: { $dynamicRef: "#meta" }
      }
    };
  }
});

// packages/core/node_modules/ajv/dist/refs/json-schema-2020-12/meta/content.json
var require_content = __commonJS({
  "packages/core/node_modules/ajv/dist/refs/json-schema-2020-12/meta/content.json"(exports2, module2) {
    module2.exports = {
      $schema: "https://json-schema.org/draft/2020-12/schema",
      $id: "https://json-schema.org/draft/2020-12/meta/content",
      $vocabulary: {
        "https://json-schema.org/draft/2020-12/vocab/content": true
      },
      $dynamicAnchor: "meta",
      title: "Content vocabulary meta-schema",
      type: ["object", "boolean"],
      properties: {
        contentEncoding: { type: "string" },
        contentMediaType: { type: "string" },
        contentSchema: { $dynamicRef: "#meta" }
      }
    };
  }
});

// packages/core/node_modules/ajv/dist/refs/json-schema-2020-12/meta/core.json
var require_core3 = __commonJS({
  "packages/core/node_modules/ajv/dist/refs/json-schema-2020-12/meta/core.json"(exports2, module2) {
    module2.exports = {
      $schema: "https://json-schema.org/draft/2020-12/schema",
      $id: "https://json-schema.org/draft/2020-12/meta/core",
      $vocabulary: {
        "https://json-schema.org/draft/2020-12/vocab/core": true
      },
      $dynamicAnchor: "meta",
      title: "Core vocabulary meta-schema",
      type: ["object", "boolean"],
      properties: {
        $id: {
          $ref: "#/$defs/uriReferenceString",
          $comment: "Non-empty fragments not allowed.",
          pattern: "^[^#]*#?$"
        },
        $schema: { $ref: "#/$defs/uriString" },
        $ref: { $ref: "#/$defs/uriReferenceString" },
        $anchor: { $ref: "#/$defs/anchorString" },
        $dynamicRef: { $ref: "#/$defs/uriReferenceString" },
        $dynamicAnchor: { $ref: "#/$defs/anchorString" },
        $vocabulary: {
          type: "object",
          propertyNames: { $ref: "#/$defs/uriString" },
          additionalProperties: {
            type: "boolean"
          }
        },
        $comment: {
          type: "string"
        },
        $defs: {
          type: "object",
          additionalProperties: { $dynamicRef: "#meta" }
        }
      },
      $defs: {
        anchorString: {
          type: "string",
          pattern: "^[A-Za-z_][-A-Za-z0-9._]*$"
        },
        uriString: {
          type: "string",
          format: "uri"
        },
        uriReferenceString: {
          type: "string",
          format: "uri-reference"
        }
      }
    };
  }
});

// packages/core/node_modules/ajv/dist/refs/json-schema-2020-12/meta/format-annotation.json
var require_format_annotation = __commonJS({
  "packages/core/node_modules/ajv/dist/refs/json-schema-2020-12/meta/format-annotation.json"(exports2, module2) {
    module2.exports = {
      $schema: "https://json-schema.org/draft/2020-12/schema",
      $id: "https://json-schema.org/draft/2020-12/meta/format-annotation",
      $vocabulary: {
        "https://json-schema.org/draft/2020-12/vocab/format-annotation": true
      },
      $dynamicAnchor: "meta",
      title: "Format vocabulary meta-schema for annotation results",
      type: ["object", "boolean"],
      properties: {
        format: { type: "string" }
      }
    };
  }
});

// packages/core/node_modules/ajv/dist/refs/json-schema-2020-12/meta/meta-data.json
var require_meta_data = __commonJS({
  "packages/core/node_modules/ajv/dist/refs/json-schema-2020-12/meta/meta-data.json"(exports2, module2) {
    module2.exports = {
      $schema: "https://json-schema.org/draft/2020-12/schema",
      $id: "https://json-schema.org/draft/2020-12/meta/meta-data",
      $vocabulary: {
        "https://json-schema.org/draft/2020-12/vocab/meta-data": true
      },
      $dynamicAnchor: "meta",
      title: "Meta-data vocabulary meta-schema",
      type: ["object", "boolean"],
      properties: {
        title: {
          type: "string"
        },
        description: {
          type: "string"
        },
        default: true,
        deprecated: {
          type: "boolean",
          default: false
        },
        readOnly: {
          type: "boolean",
          default: false
        },
        writeOnly: {
          type: "boolean",
          default: false
        },
        examples: {
          type: "array",
          items: true
        }
      }
    };
  }
});

// packages/core/node_modules/ajv/dist/refs/json-schema-2020-12/meta/validation.json
var require_validation3 = __commonJS({
  "packages/core/node_modules/ajv/dist/refs/json-schema-2020-12/meta/validation.json"(exports2, module2) {
    module2.exports = {
      $schema: "https://json-schema.org/draft/2020-12/schema",
      $id: "https://json-schema.org/draft/2020-12/meta/validation",
      $vocabulary: {
        "https://json-schema.org/draft/2020-12/vocab/validation": true
      },
      $dynamicAnchor: "meta",
      title: "Validation vocabulary meta-schema",
      type: ["object", "boolean"],
      properties: {
        type: {
          anyOf: [
            { $ref: "#/$defs/simpleTypes" },
            {
              type: "array",
              items: { $ref: "#/$defs/simpleTypes" },
              minItems: 1,
              uniqueItems: true
            }
          ]
        },
        const: true,
        enum: {
          type: "array",
          items: true
        },
        multipleOf: {
          type: "number",
          exclusiveMinimum: 0
        },
        maximum: {
          type: "number"
        },
        exclusiveMaximum: {
          type: "number"
        },
        minimum: {
          type: "number"
        },
        exclusiveMinimum: {
          type: "number"
        },
        maxLength: { $ref: "#/$defs/nonNegativeInteger" },
        minLength: { $ref: "#/$defs/nonNegativeIntegerDefault0" },
        pattern: {
          type: "string",
          format: "regex"
        },
        maxItems: { $ref: "#/$defs/nonNegativeInteger" },
        minItems: { $ref: "#/$defs/nonNegativeIntegerDefault0" },
        uniqueItems: {
          type: "boolean",
          default: false
        },
        maxContains: { $ref: "#/$defs/nonNegativeInteger" },
        minContains: {
          $ref: "#/$defs/nonNegativeInteger",
          default: 1
        },
        maxProperties: { $ref: "#/$defs/nonNegativeInteger" },
        minProperties: { $ref: "#/$defs/nonNegativeIntegerDefault0" },
        required: { $ref: "#/$defs/stringArray" },
        dependentRequired: {
          type: "object",
          additionalProperties: {
            $ref: "#/$defs/stringArray"
          }
        }
      },
      $defs: {
        nonNegativeInteger: {
          type: "integer",
          minimum: 0
        },
        nonNegativeIntegerDefault0: {
          $ref: "#/$defs/nonNegativeInteger",
          default: 0
        },
        simpleTypes: {
          enum: ["array", "boolean", "integer", "null", "number", "object", "string"]
        },
        stringArray: {
          type: "array",
          items: { type: "string" },
          uniqueItems: true,
          default: []
        }
      }
    };
  }
});

// packages/core/node_modules/ajv/dist/refs/json-schema-2020-12/index.js
var require_json_schema_2020_12 = __commonJS({
  "packages/core/node_modules/ajv/dist/refs/json-schema-2020-12/index.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    var metaSchema = require_schema();
    var applicator = require_applicator2();
    var unevaluated = require_unevaluated2();
    var content = require_content();
    var core = require_core3();
    var format4 = require_format_annotation();
    var metadata = require_meta_data();
    var validation2 = require_validation3();
    var META_SUPPORT_DATA = ["/properties"];
    function addMetaSchema2020($data) {
      ;
      [
        metaSchema,
        applicator,
        unevaluated,
        content,
        core,
        with$data(this, format4),
        metadata,
        with$data(this, validation2)
      ].forEach((sch) => this.addMetaSchema(sch, void 0, false));
      return this;
      function with$data(ajv, sch) {
        return $data ? ajv.$dataMetaSchema(sch, META_SUPPORT_DATA) : sch;
      }
      __name(with$data, "with$data");
    }
    __name(addMetaSchema2020, "addMetaSchema2020");
    exports2.default = addMetaSchema2020;
  }
});

// packages/core/node_modules/ajv/dist/2020.js
var require__ = __commonJS({
  "packages/core/node_modules/ajv/dist/2020.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.Ajv2020 = void 0;
    var core_1 = require_core();
    var draft2020_1 = require_draft2020();
    var discriminator_1 = require_discriminator();
    var json_schema_2020_12_1 = require_json_schema_2020_12();
    var META_SCHEMA_ID = "https://json-schema.org/draft/2020-12/schema";
    var Ajv2020 = class extends core_1.default {
      static {
        __name(this, "Ajv2020");
      }
      constructor(opts = {}) {
        super({
          ...opts,
          dynamicRef: true,
          next: true,
          unevaluated: true
        });
      }
      _addVocabularies() {
        super._addVocabularies();
        draft2020_1.default.forEach((v2) => this.addVocabulary(v2));
        if (this.opts.discriminator)
          this.addKeyword(discriminator_1.default);
      }
      _addDefaultMetaSchema() {
        super._addDefaultMetaSchema();
        const { $data, meta } = this.opts;
        if (!meta)
          return;
        json_schema_2020_12_1.default.call(this, $data);
        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.Ajv2020 = Ajv2020;
    module2.exports = exports2 = Ajv2020;
    module2.exports.Ajv2020 = Ajv2020;
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.default = Ajv2020;
    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(validate3, compare) {
      return { validate: validate3, compare };
    }
    __name(fmtDef, "fmtDef");
    exports2.fullFormats = {
      // date: http://tools.ietf.org/html/rfc3339#section-5.6
      date: fmtDef(date4, 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 date4(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(date4, "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 time3(str2) {
        const matches = TIME.exec(str2);
        if (!matches)
          return false;
        const hr3 = +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 (hr3 <= 23 && min <= 59 && sec < 60)
          return true;
        const utcMin = min - tzM * tzSign;
        const utcHr = hr3 - tzH * tzSign - (utcMin < 0 ? 1 : 0);
        return (utcHr === 23 || utcHr === -1) && (utcMin === 59 || utcMin === -1) && sec < 61;
      }, "time");
    }
    __name(getTime, "getTime");
    function compareTime(s1, s22) {
      if (!(s1 && s22))
        return void 0;
      const t1 = (/* @__PURE__ */ new Date("2020-01-01T" + s1)).valueOf();
      const t22 = (/* @__PURE__ */ new Date("2020-01-01T" + s22)).valueOf();
      if (!(t1 && t22))
        return void 0;
      return t1 - t22;
    }
    __name(compareTime, "compareTime");
    function compareIsoTime(t1, t22) {
      if (!(t1 && t22))
        return void 0;
      const a1 = TIME.exec(t1);
      const a2 = TIME.exec(t22);
      if (!(a1 && a2))
        return void 0;
      t1 = a1[1] + a1[2] + a1[3];
      t22 = a2[1] + a2[2] + a2[3];
      if (t1 > t22)
        return 1;
      if (t1 < t22)
        return -1;
      return 0;
    }
    __name(compareIsoTime, "compareIsoTime");
    var DATE_TIME_SEPARATOR = /t|\s/i;
    function getDateTime(strictTimeZone) {
      const time3 = getTime(strictTimeZone);
      return /* @__PURE__ */ __name(function date_time(str2) {
        const dateTime = str2.split(DATE_TIME_SEPARATOR);
        return dateTime.length === 2 && date4(dateTime[0]) && time3(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, t22] = dt2.split(DATE_TIME_SEPARATOR);
      const res = compareDate(d1, d2);
      if (res === void 0)
        return void 0;
      return res || compareTime(t1, t22);
    }
    __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 (e4) {
        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(s5) {
        super();
        if (!exports2.IDENTIFIER.test(s5))
          throw new Error("CodeGen: name must be a valid identifier");
        this.str = s5;
      }
      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 _a7;
        return (_a7 = this._str) !== null && _a7 !== void 0 ? _a7 : this._str = this._items.reduce((s5, c4) => `${s5}${c4}`, "");
      }
      get names() {
        var _a7;
        return (_a7 = this._names) !== null && _a7 !== void 0 ? _a7 : this._names = this._items.reduce((names, c4) => {
          if (c4 instanceof Name)
            names[c4.str] = (names[c4.str] || 0) + 1;
          return names;
        }, {});
      }
    };
    exports2._Code = _Code;
    exports2.nil = new _Code("");
    function _2(strs, ...args) {
      const code2 = [strs[0]];
      let i3 = 0;
      while (i3 < args.length) {
        addCodeArg(code2, args[i3]);
        code2.push(strs[++i3]);
      }
      return new _Code(code2);
    }
    __name(_2, "_");
    exports2._ = _2;
    var plus = new _Code("+");
    function str2(strs, ...args) {
      const expr = [safeStringify(strs[0])];
      let i3 = 0;
      while (i3 < args.length) {
        expr.push(plus);
        addCodeArg(expr, args[i3]);
        expr.push(plus, safeStringify(strs[++i3]));
      }
      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(interpolate2(arg));
    }
    __name(addCodeArg, "addCodeArg");
    exports2.addCodeArg = addCodeArg;
    function optimize(expr) {
      let i3 = 1;
      while (i3 < expr.length - 1) {
        if (expr[i3] === plus) {
          const res = mergeExprItems(expr[i3 - 1], expr[i3 + 1]);
          if (res !== void 0) {
            expr.splice(i3 - 1, 3, res);
            continue;
          }
          expr[i3++] = "+";
        }
        i3++;
      }
    }
    __name(optimize, "optimize");
    function mergeExprItems(a2, b2) {
      if (b2 === '""')
        return a2;
      if (a2 === '""')
        return b2;
      if (typeof a2 == "string") {
        if (b2 instanceof Name || a2[a2.length - 1] !== '"')
          return;
        if (typeof b2 != "string")
          return `${a2.slice(0, -1)}${b2}"`;
        if (b2[0] === '"')
          return a2.slice(0, -1) + b2.slice(1);
        return;
      }
      if (typeof b2 == "string" && b2[0] === '"' && !(a2 instanceof Name))
        return `"${a2}${b2.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 interpolate2(x3) {
      return typeof x3 == "number" || typeof x3 == "boolean" || x3 === null ? x3 : safeStringify(Array.isArray(x3) ? x3.join(",") : x3);
    }
    __name(interpolate2, "interpolate");
    function stringify4(x3) {
      return new _Code(safeStringify(x3));
    }
    __name(stringify4, "stringify");
    exports2.stringify = stringify4;
    function safeStringify(x3) {
      return JSON.stringify(x3).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}`) : _2`[${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 _a7, _b2;
        if (((_b2 = (_a7 = this._parent) === null || _a7 === void 0 ? void 0 : _a7._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 _a7;
        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 = (_a7 = value.key) !== null && _a7 !== void 0 ? _a7 : 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 s5 = this._scope[prefix] || (this._scope[prefix] = []);
        const itemIndex = s5.length;
        s5[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 c4 = valueCode(name3);
            if (c4) {
              const def2 = this.opts.es5 ? exports2.varKinds.var : exports2.varKinds.const;
              code2 = (0, code_1._)`${code2}${def2} ${name3} = ${c4};${this.opts._n}`;
            } else if (c4 = getCode === null || getCode === void 0 ? void 0 : getCode(name3)) {
              code2 = (0, code_1._)`${code2}${c4}${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 Node5 = class {
      static {
        __name(this, "Node");
      }
      optimizeNodes() {
        return this;
      }
      optimizeNames(_names, _constants) {
        return this;
      }
    };
    var Def = class extends Node5 {
      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 Node5 {
      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 Node5 {
      static {
        __name(this, "Label");
      }
      constructor(label) {
        super();
        this.label = label;
        this.names = {};
      }
      render({ _n }) {
        return `${this.label}:` + _n;
      }
    };
    var Break = class extends Node5 {
      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 Node5 {
      static {
        __name(this, "Throw");
      }
      constructor(error2) {
        super();
        this.error = error2;
      }
      render({ _n }) {
        return `throw ${this.error};` + _n;
      }
      get names() {
        return this.error.names;
      }
    };
    var AnyCode = class extends Node5 {
      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 Node5 {
      static {
        __name(this, "ParentNode");
      }
      constructor(nodes = []) {
        super();
        this.nodes = nodes;
      }
      render(opts) {
        return this.nodes.reduce((code2, n3) => code2 + n3.render(opts), "");
      }
      optimizeNodes() {
        const { nodes } = this;
        let i3 = nodes.length;
        while (i3--) {
          const n3 = nodes[i3].optimizeNodes();
          if (Array.isArray(n3))
            nodes.splice(i3, 1, ...n3);
          else if (n3)
            nodes[i3] = n3;
          else
            nodes.splice(i3, 1);
        }
        return nodes.length > 0 ? this : void 0;
      }
      optimizeNames(names, constants4) {
        const { nodes } = this;
        let i3 = nodes.length;
        while (i3--) {
          const n3 = nodes[i3];
          if (n3.optimizeNames(names, constants4))
            continue;
          subtractNames(names, n3.names);
          nodes.splice(i3, 1);
        }
        return nodes.length > 0 ? this : void 0;
      }
      get names() {
        return this.nodes.reduce((names, n3) => addNames(names, n3.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 e4 = this.else;
        if (e4) {
          const ns = e4.optimizeNodes();
          e4 = this.else = Array.isArray(ns) ? new Else(ns) : ns;
        }
        if (e4) {
          if (cond === false)
            return e4 instanceof _If ? e4 : e4.nodes;
          if (this.nodes.length)
            return this;
          return new _If(not(cond), e4 instanceof _If ? [e4] : e4.nodes);
        }
        if (cond === false || !this.nodes.length)
          return void 0;
        return this;
      }
      optimizeNames(names, constants4) {
        var _a7;
        this.else = (_a7 = this.else) === null || _a7 === void 0 ? void 0 : _a7.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 _a7, _b2;
        super.optimizeNodes();
        (_a7 = this.catch) === null || _a7 === void 0 ? void 0 : _a7.optimizeNodes();
        (_b2 = this.finally) === null || _b2 === void 0 ? void 0 : _b2.optimizeNodes();
        return this;
      }
      optimizeNames(names, constants4) {
        var _a7, _b2;
        super.optimizeNames(names, constants4);
        (_a7 = this.catch) === null || _a7 === void 0 ? void 0 : _a7.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(error2) {
        super();
        this.error = error2;
      }
      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(c4) {
        if (typeof c4 == "function")
          c4();
        else if (c4 !== code_1.nil)
          this._leafNode(new AnyCode(c4));
        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`, (i3) => {
            this.var(name3, (0, code_1._)`${arr}[${i3}]`);
            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 error2 = this.name("e");
          this._currNode = node.catch = new Catch(error2);
          catchCode(error2);
        }
        if (finallyCode) {
          this._currNode = node.finally = new Finally();
          this.code(finallyCode);
        }
        return this._endBlockNode(Catch, Finally);
      }
      // `throw` statement
      throw(error2) {
        return this._leafNode(new Throw(error2));
      }
      // start self-balancing block
      block(body, nodeCount) {
        this._blockStarts.push(this._nodes.length);
        if (body)
          this.code(body).endBlock(nodeCount);
        return this;
      }
      // end the current self-balancing block
      endBlock(nodeCount) {
        const 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(n3 = 1) {
        while (n3-- > 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 n3 = this._currNode;
        if (n3 instanceof N1 || N2 && n3 instanceof N2) {
          this._nodes.pop();
          return this;
        }
        throw new Error(`CodeGen: not in block "${N2 ? `${N1.kind}/${N2.kind}` : N1.kind}"`);
      }
      _elseNode(node) {
        const n3 = this._currNode;
        if (!(n3 instanceof If)) {
          throw new Error('CodeGen: "else" without "if"');
        }
        this._currNode = n3.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 n3 in from)
        names[n3] = (names[n3] || 0) + (from[n3] || 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, c4) => {
        if (c4 instanceof code_1.Name)
          c4 = replaceName(c4);
        if (c4 instanceof code_1._Code)
          items.push(...c4._items);
        else
          items.push(c4);
        return items;
      }, []));
      function replaceName(n3) {
        const c4 = constants4[n3.str];
        if (c4 === void 0 || names[n3.str] !== 1)
          return n3;
        delete names[n3.str];
        return c4;
      }
      __name(replaceName, "replaceName");
      function canOptimize(e4) {
        return e4 instanceof code_1._Code && e4._items.some((c4) => c4 instanceof code_1.Name && names[c4.str] === 1 && constants4[c4.str] !== void 0);
      }
      __name(canOptimize, "canOptimize");
    }
    __name(optimizeExpr, "optimizeExpr");
    function subtractNames(names, from) {
      for (const n3 in from)
        names[n3] = (names[n3] || 0) - (from[n3] || 0);
    }
    __name(subtractNames, "subtractNames");
    function not(x3) {
      return typeof x3 == "boolean" || typeof x3 == "number" || x3 === null ? !x3 : (0, code_1._)`!${par(x3)}`;
    }
    __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 or2(...args) {
      return args.reduce(orCode);
    }
    __name(or2, "or");
    exports2.or = or2;
    function mappend(op) {
      return (x3, y2) => x3 === code_1.nil ? y2 : y2 === code_1.nil ? x3 : (0, code_1._)`${par(x3)} ${op} ${par(y2)}`;
    }
    __name(mappend, "mappend");
    function par(x3) {
      return x3 instanceof code_1.Name ? x3 : (0, code_1._)`(${x3})`;
    }
    __name(par, "par");
  }
});

// node_modules/ajv-formats/node_modules/ajv/dist/compile/util.js
var require_util12 = __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(it2, schema) {
      if (typeof schema == "boolean")
        return schema;
      if (Object.keys(schema).length === 0)
        return true;
      checkUnknownRules(it2, schema);
      return !schemaHasRules(schema, it2.self.RULES.all);
    }
    __name(alwaysValidSchema, "alwaysValidSchema");
    exports2.alwaysValidSchema = alwaysValidSchema;
    function checkUnknownRules(it2, schema = it2.schema) {
      const { opts, self: self2 } = it2;
      if (!opts.strictSchema)
        return;
      if (typeof schema === "boolean")
        return;
      const rules = self2.RULES.keywords;
      for (const key in schema) {
        if (!rules[key])
          checkStrictMode(it2, `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, f5) {
      if (Array.isArray(xs)) {
        for (const x3 of xs)
          f5(x3);
      } else {
        f5(xs);
      }
    }
    __name(eachItem, "eachItem");
    exports2.eachItem = eachItem;
    function makeMergeEvaluated({ mergeNames, mergeToName, mergeValues: mergeValues3, 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) : mergeValues3(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((p2) => gen.assign((0, codegen_1._)`${props}${(0, codegen_1.getProperty)(p2)}`, true));
    }
    __name(setEvaluated, "setEvaluated");
    exports2.setEvaluated = setEvaluated;
    var snippets = {};
    function useFunc(gen, f5) {
      return gen.scopeValue("func", {
        ref: f5,
        code: snippets[f5.code] || (snippets[f5.code] = new code_1._Code(f5.code))
      });
    }
    __name(useFunc, "useFunc");
    exports2.useFunc = useFunc;
    var Type3;
    (function(Type4) {
      Type4[Type4["Num"] = 0] = "Num";
      Type4[Type4["Str"] = 1] = "Str";
    })(Type3 || (exports2.Type = Type3 = {}));
    function getErrorPath(dataProp, dataPropType, jsPropertySyntax) {
      if (dataProp instanceof codegen_1.Name) {
        const isNumber3 = dataPropType === Type3.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(it2, msg, mode = it2.opts.strictSchema) {
      if (!mode)
        return;
      msg = `strict mode: ${msg}`;
      if (mode === true)
        throw new Error(msg);
      it2.self.logger.warn(msg);
    }
    __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_util12();
    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, error2 = exports2.keywordError, errorPaths, overrideAllErrors) {
      const { it: it2 } = cxt;
      const { gen, compositeRule, allErrors } = it2;
      const errObj = errorObjectCode(cxt, error2, errorPaths);
      if (overrideAllErrors !== null && overrideAllErrors !== void 0 ? overrideAllErrors : compositeRule || allErrors) {
        addError(gen, errObj);
      } else {
        returnErrors(it2, (0, codegen_1._)`[${errObj}]`);
      }
    }
    __name(reportError3, "reportError");
    exports2.reportError = reportError3;
    function reportExtraError(cxt, error2 = exports2.keywordError, errorPaths) {
      const { it: it2 } = cxt;
      const { gen, compositeRule, allErrors } = it2;
      const errObj = errorObjectCode(cxt, error2, errorPaths);
      addError(gen, errObj);
      if (!(compositeRule || allErrors)) {
        returnErrors(it2, names_1.default.vErrors);
      }
    }
    __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: it2 }) {
      if (errsCount === void 0)
        throw new Error("ajv implementation error");
      const err = gen.name("err");
      gen.forRange("i", errsCount, names_1.default.errors, (i3) => {
        gen.const(err, (0, codegen_1._)`${names_1.default.vErrors}[${i3}]`);
        gen.if((0, codegen_1._)`${err}.instancePath === undefined`, () => gen.assign((0, codegen_1._)`${err}.instancePath`, (0, codegen_1.strConcat)(names_1.default.instancePath, it2.errorPath)));
        gen.assign((0, codegen_1._)`${err}.schemaPath`, (0, codegen_1.str)`${it2.errSchemaPath}/${keyword}`);
        if (it2.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(it2, errs) {
      const { gen, validateName: validateName2, schemaEnv } = it2;
      if (schemaEnv.$async) {
        gen.throw((0, codegen_1._)`new ${it2.ValidationError}(${errs})`);
      } else {
        gen.assign((0, codegen_1._)`${validateName2}.errors`, errs);
        gen.return(false);
      }
    }
    __name(returnErrors, "returnErrors");
    var E2 = {
      keyword: new codegen_1.Name("keyword"),
      schemaPath: new codegen_1.Name("schemaPath"),
      // also used in JTD errors
      params: new codegen_1.Name("params"),
      propertyName: new codegen_1.Name("propertyName"),
      message: new codegen_1.Name("message"),
      schema: new codegen_1.Name("schema"),
      parentSchema: new codegen_1.Name("parentSchema")
    };
    function errorObjectCode(cxt, error2, errorPaths) {
      const { createErrors } = cxt.it;
      if (createErrors === false)
        return (0, codegen_1._)`{}`;
      return errorObject(cxt, error2, errorPaths);
    }
    __name(errorObjectCode, "errorObjectCode");
    function errorObject(cxt, error2, errorPaths = {}) {
      const { gen, it: it2 } = cxt;
      const keyValues = [
        errorInstancePath(it2, errorPaths),
        errorSchemaPath(cxt, errorPaths)
      ];
      extraErrorProps(cxt, error2, keyValues);
      return gen.object(...keyValues);
    }
    __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 [E2.schemaPath, schPath];
    }
    __name(errorSchemaPath, "errorSchemaPath");
    function extraErrorProps(cxt, { params, message }, keyValues) {
      const { keyword, data, schemaValue, it: it2 } = cxt;
      const { opts, propertyName, topSchemaRef, schemaPath } = it2;
      keyValues.push([E2.keyword, keyword], [E2.params, typeof params == "function" ? params(cxt) : params || (0, codegen_1._)`{}`]);
      if (opts.messages) {
        keyValues.push([E2.message, typeof message == "function" ? message(cxt) : message]);
      }
      if (opts.verbose) {
        keyValues.push([E2.schema, schemaValue], [E2.parentSchema, (0, codegen_1._)`${topSchemaRef}${schemaPath}`], [names_1.default.data, data]);
      }
      if (propertyName)
        keyValues.push([E2.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(it2) {
      const { gen, schema, validateName: validateName2 } = it2;
      if (schema === false) {
        falseSchemaError(it2, false);
      } else if (typeof schema == "object" && schema.$async === true) {
        gen.return(names_1.default.data);
      } else {
        gen.assign((0, codegen_1._)`${validateName2}.errors`, null);
        gen.return(true);
      }
    }
    __name(topBoolOrEmptySchema, "topBoolOrEmptySchema");
    exports2.topBoolOrEmptySchema = topBoolOrEmptySchema;
    function boolOrEmptySchema(it2, valid) {
      const { gen, schema } = it2;
      if (schema === false) {
        gen.var(valid, false);
        falseSchemaError(it2);
      } else {
        gen.var(valid, true);
      }
    }
    __name(boolOrEmptySchema, "boolOrEmptySchema");
    exports2.boolOrEmptySchema = boolOrEmptySchema;
    function falseSchemaError(it2, overrideAllErrors) {
      const { gen, data } = it2;
      const cxt = {
        gen,
        keyword: "false schema",
        data,
        schema: false,
        schemaCode: false,
        schemaValue: false,
        params: {},
        it: it2
      };
      (0, errors_1.reportError)(cxt, boolError, void 0, overrideAllErrors);
    }
    __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(x3) {
      return typeof x3 == "string" && jsonTypes.has(x3);
    }
    __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 _a7;
      return schema[rule.keyword] !== void 0 || ((_a7 = rule.definition.implements) === null || _a7 === void 0 ? void 0 : _a7.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_util12();
    var DataType;
    (function(DataType2) {
      DataType2[DataType2["Correct"] = 0] = "Correct";
      DataType2[DataType2["Wrong"] = 1] = "Wrong";
    })(DataType || (exports2.DataType = DataType = {}));
    function getSchemaTypes(schema) {
      const types7 = getJSONTypes(schema.type);
      const hasNull = types7.includes("null");
      if (hasNull) {
        if (schema.nullable === false)
          throw new Error("type: null contradicts nullable: false");
      } else {
        if (!types7.length && schema.nullable !== void 0) {
          throw new Error('"nullable" cannot be used without "type"');
        }
        if (schema.nullable === true)
          types7.push("null");
      }
      return types7;
    }
    __name(getSchemaTypes, "getSchemaTypes");
    exports2.getSchemaTypes = getSchemaTypes;
    function getJSONTypes(ts) {
      const types7 = Array.isArray(ts) ? ts : ts ? [ts] : [];
      if (types7.every(rules_1.isJSONType))
        return types7;
      throw new Error("type must be JSONType or JSONType[]: " + types7.join(","));
    }
    __name(getJSONTypes, "getJSONTypes");
    exports2.getJSONTypes = getJSONTypes;
    function coerceAndCheckDataType(it2, types7) {
      const { gen, data, opts } = it2;
      const coerceTo = coerceToTypes(types7, opts.coerceTypes);
      const checkTypes = types7.length > 0 && !(coerceTo.length === 0 && types7.length === 1 && (0, applicability_1.schemaHasRulesForType)(it2, types7[0]));
      if (checkTypes) {
        const wrongType = checkDataTypes(types7, data, opts.strictNumbers, DataType.Wrong);
        gen.if(wrongType, () => {
          if (coerceTo.length)
            coerceData(it2, types7, coerceTo);
          else
            reportTypeError(it2);
        });
      }
      return checkTypes;
    }
    __name(coerceAndCheckDataType, "coerceAndCheckDataType");
    exports2.coerceAndCheckDataType = coerceAndCheckDataType;
    var COERCIBLE = /* @__PURE__ */ new Set(["string", "number", "integer", "boolean", "null"]);
    function coerceToTypes(types7, coerceTypes) {
      return coerceTypes ? types7.filter((t5) => COERCIBLE.has(t5) || coerceTypes === "array" && t5 === "array") : [];
    }
    __name(coerceToTypes, "coerceToTypes");
    function coerceData(it2, types7, coerceTo) {
      const { gen, data, opts } = it2;
      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(types7, data, opts.strictNumbers), () => gen.assign(coerced, data)));
      }
      gen.if((0, codegen_1._)`${coerced} !== undefined`);
      for (const t5 of coerceTo) {
        if (COERCIBLE.has(t5) || t5 === "array" && opts.coerceTypes === "array") {
          coerceSpecificType(t5);
        }
      }
      gen.else();
      reportTypeError(it2);
      gen.endIf();
      gen.if((0, codegen_1._)`${coerced} !== undefined`, () => {
        gen.assign(data, coerced);
        assignParentData(it2, coerced);
      });
      function coerceSpecificType(t5) {
        switch (t5) {
          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 types7 = (0, util_1.toHash)(dataTypes);
      if (types7.array && types7.object) {
        const notObj = (0, codegen_1._)`typeof ${data} != "object"`;
        cond = types7.null ? notObj : (0, codegen_1._)`!${data} || ${notObj}`;
        delete types7.null;
        delete types7.array;
        delete types7.object;
      } else {
        cond = codegen_1.nil;
      }
      if (types7.number)
        delete types7.integer;
      for (const t5 in types7)
        cond = (0, codegen_1.and)(cond, checkDataType(t5, 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(it2) {
      const cxt = getTypeErrorContext(it2);
      (0, errors_1.reportError)(cxt, typeError);
    }
    __name(reportTypeError, "reportTypeError");
    exports2.reportTypeError = reportTypeError;
    function getTypeErrorContext(it2) {
      const { gen, data, schema } = it2;
      const schemaCode = (0, util_1.schemaRefOrVal)(it2, schema, "type");
      return {
        gen,
        keyword: "type",
        data,
        schema: schema.type,
        schemaCode,
        schemaValue: schemaCode,
        parentSchema: schema,
        params: {},
        it: it2
      };
    }
    __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_util12();
    function assignDefaults(it2, ty) {
      const { properties, items } = it2.schema;
      if (ty === "object" && properties) {
        for (const key in properties) {
          assignDefault(it2, key, properties[key].default);
        }
      } else if (ty === "array" && Array.isArray(items)) {
        items.forEach((sch, i3) => assignDefault(it2, i3, sch.default));
      }
    }
    __name(assignDefaults, "assignDefaults");
    exports2.assignDefaults = assignDefaults;
    function assignDefault(it2, prop, defaultValue) {
      const { gen, compositeRule, data, opts } = it2;
      if (defaultValue === void 0)
        return;
      const childData = (0, codegen_1._)`${data}${(0, codegen_1.getProperty)(prop)}`;
      if (compositeRule) {
        (0, util_1.checkStrictMode)(it2, `default is ignored for: ${childData}`);
        return;
      }
      let condition = (0, codegen_1._)`${childData} === undefined`;
      if (opts.useDefaults === "empty") {
        condition = (0, codegen_1._)`${condition} || ${childData} === null || ${childData} === ""`;
      }
      gen.if(condition, (0, codegen_1._)`${childData} = ${(0, codegen_1.stringify)(defaultValue)}`);
    }
    __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_util12();
    var names_1 = require_names2();
    var util_2 = require_util12();
    function checkReportMissingProp(cxt, prop) {
      const { gen, data, it: it2 } = cxt;
      gen.if(noPropertyInData(gen, data, prop, it2.opts.ownProperties), () => {
        cxt.setParams({ missingProperty: (0, codegen_1._)`${prop}` }, true);
        cxt.error();
      });
    }
    __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((p2) => p2 !== "__proto__") : [];
    }
    __name(allSchemaProperties, "allSchemaProperties");
    exports2.allSchemaProperties = allSchemaProperties;
    function schemaProperties(it2, schemaMap) {
      return allSchemaProperties(schemaMap).filter((p2) => !(0, util_1.alwaysValidSchema)(it2, schemaMap[p2]));
    }
    __name(schemaProperties, "schemaProperties");
    exports2.schemaProperties = schemaProperties;
    function callValidateCode({ schemaCode, data, it: { gen, topSchemaRef, schemaPath, errorPath }, it: it2 }, 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, it2.parentData],
        [names_1.default.parentDataProperty, it2.parentDataProperty],
        [names_1.default.rootData, names_1.default.rootData]
      ];
      if (it2.opts.dynamicRef)
        valCxt.push([names_1.default.dynamicAnchors, names_1.default.dynamicAnchors]);
      const args = (0, codegen_1._)`${dataAndSchema}, ${gen.object(...valCxt)}`;
      return 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 u2 = opts.unicodeRegExp ? "u" : "";
      const { regExp } = opts.code;
      const rx = regExp(pattern, u2);
      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}, ${u2})`
      });
    }
    __name(usePattern, "usePattern");
    exports2.usePattern = usePattern;
    function validateArray(cxt) {
      const { gen, data, keyword, it: it2 } = cxt;
      const valid = gen.name("valid");
      if (it2.allErrors) {
        const validArr = gen.let("valid", true);
        validateItems(() => gen.assign(validArr, false));
        return validArr;
      }
      gen.var(valid, true);
      validateItems(() => gen.break());
      return valid;
      function validateItems(notValid) {
        const len = gen.const("len", (0, codegen_1._)`${data}.length`);
        gen.forRange("i", 0, len, (i3) => {
          cxt.subschema({
            keyword,
            dataProp: i3,
            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: it2 } = cxt;
      if (!Array.isArray(schema))
        throw new Error("ajv implementation error");
      const alwaysValid = schema.some((sch) => (0, util_1.alwaysValidSchema)(it2, sch));
      if (alwaysValid && !it2.opts.unevaluated)
        return;
      const valid = gen.let("valid", false);
      const schValid = gen.name("_valid");
      gen.block(() => schema.forEach((_sch, i3) => {
        const schCxt = cxt.subschema({
          keyword,
          schemaProp: i3,
          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: it2 } = cxt;
      const macroSchema = def2.macro.call(it2.self, schema, parentSchema, it2);
      const schemaRef = useKeyword(gen, keyword, macroSchema);
      if (it2.opts.validateSchema !== false)
        it2.self.validateSchema(macroSchema, true);
      const valid = gen.name("valid");
      cxt.subschema({
        schema: macroSchema,
        schemaPath: codegen_1.nil,
        errSchemaPath: `${it2.errSchemaPath}/${keyword}`,
        topSchemaRef: schemaRef,
        compositeRule: true
      }, valid);
      cxt.pass(valid, () => cxt.error(true));
    }
    __name(macroKeywordCode, "macroKeywordCode");
    exports2.macroKeywordCode = macroKeywordCode;
    function funcKeywordCode(cxt, def2) {
      var _a7;
      const { gen, keyword, schema, parentSchema, $data, it: it2 } = cxt;
      checkAsyncKeyword(it2, def2);
      const validate3 = !$data && def2.compile ? def2.compile.call(it2.self, schema, parentSchema, it2) : def2.validate;
      const validateRef = useKeyword(gen, keyword, validate3);
      const valid = gen.let("valid");
      cxt.block$data(valid, validateKeyword);
      cxt.ok((_a7 = def2.valid) !== null && _a7 !== void 0 ? _a7 : 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 `), (e4) => gen.assign(valid, false).if((0, codegen_1._)`${e4} instanceof ${it2.ValidationError}`, () => gen.assign(ruleErrs, (0, codegen_1._)`${e4}.errors`), () => gen.throw(e4)));
        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 = it2.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 _a8;
        gen.if((0, codegen_1.not)((_a8 = def2.valid) !== null && _a8 !== void 0 ? _a8 : valid), errors);
      }
      __name(reportErrs, "reportErrs");
    }
    __name(funcKeywordCode, "funcKeywordCode");
    exports2.funcKeywordCode = funcKeywordCode;
    function modifyData(cxt) {
      const { gen, data, it: it2 } = cxt;
      gen.if(it2.parentData, () => gen.assign(data, (0, codegen_1._)`${it2.parentData}[${it2.parentDataProperty}]`));
    }
    __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((st2) => st2 === "array" ? Array.isArray(schema) : st2 === "object" ? schema && typeof schema == "object" && !Array.isArray(schema) : typeof schema == st2 || 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_util12();
    function getSubschema(it2, { 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 = it2.schema[keyword];
        return schemaProp === void 0 ? {
          schema: sch,
          schemaPath: (0, codegen_1._)`${it2.schemaPath}${(0, codegen_1.getProperty)(keyword)}`,
          errSchemaPath: `${it2.errSchemaPath}/${keyword}`
        } : {
          schema: sch[schemaProp],
          schemaPath: (0, codegen_1._)`${it2.schemaPath}${(0, codegen_1.getProperty)(keyword)}${(0, codegen_1.getProperty)(schemaProp)}`,
          errSchemaPath: `${it2.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, it2, { dataProp, dataPropType: dpType, data, dataTypes, propertyName }) {
      if (data !== void 0 && dataProp !== void 0) {
        throw new Error('both "data" and "dataProp" passed, only one allowed');
      }
      const { gen } = it2;
      if (dataProp !== void 0) {
        const { errorPath, dataPathArr, opts } = it2;
        const nextData = gen.let("data", (0, codegen_1._)`${it2.data}${(0, codegen_1.getProperty)(dataProp)}`, true);
        dataContextProps(nextData);
        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 = it2.dataLevel + 1;
        subschema.dataTypes = [];
        it2.definedProperties = /* @__PURE__ */ new Set();
        subschema.parentData = it2.data;
        subschema.dataNames = [...it2.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 i3 = 0; i3 < sch.length; i3++)
                _traverse(opts, pre, post, sch[i3], jsonPtr + "/" + key + "/" + i3, rootSchema, jsonPtr, key, schema, i3);
            }
          } 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_util12();
    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 = "", normalize12) {
      if (normalize12 !== false)
        id = normalizeId(id);
      const p2 = resolver.parse(id);
      return _getFullPath(resolver, p2);
    }
    __name(getFullPath, "getFullPath");
    exports2.getFullPath = getFullPath;
    function _getFullPath(resolver, p2) {
      const serialized = resolver.serialize(p2);
      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, _2, 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_util12();
    var errors_1 = require_errors3();
    function validateFunctionCode(it2) {
      if (isSchemaObj(it2)) {
        checkKeywords(it2);
        if (schemaCxtHasRules(it2)) {
          topSchemaObjCode(it2);
          return;
        }
      }
      validateFunction(it2, () => (0, boolSchema_1.topBoolOrEmptySchema)(it2));
    }
    __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(it2) {
      const { schema, opts, gen } = it2;
      validateFunction(it2, () => {
        if (opts.$comment && schema.$comment)
          commentKeyword(it2);
        checkNoDefault(it2);
        gen.let(names_1.default.vErrors, null);
        gen.let(names_1.default.errors, 0);
        if (opts.unevaluated)
          resetEvaluated(it2);
        typeAndKeywords(it2);
        returnResults(it2);
      });
      return;
    }
    __name(topSchemaObjCode, "topSchemaObjCode");
    function resetEvaluated(it2) {
      const { gen, validateName: validateName2 } = it2;
      it2.evaluated = gen.const("evaluated", (0, codegen_1._)`${validateName2}.evaluated`);
      gen.if((0, codegen_1._)`${it2.evaluated}.dynamicProps`, () => gen.assign((0, codegen_1._)`${it2.evaluated}.props`, (0, codegen_1._)`undefined`));
      gen.if((0, codegen_1._)`${it2.evaluated}.dynamicItems`, () => gen.assign((0, codegen_1._)`${it2.evaluated}.items`, (0, codegen_1._)`undefined`));
    }
    __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(it2, valid) {
      if (isSchemaObj(it2)) {
        checkKeywords(it2);
        if (schemaCxtHasRules(it2)) {
          subSchemaObjCode(it2, valid);
          return;
        }
      }
      (0, boolSchema_1.boolOrEmptySchema)(it2, 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(it2) {
      return typeof it2.schema != "boolean";
    }
    __name(isSchemaObj, "isSchemaObj");
    function subSchemaObjCode(it2, valid) {
      const { schema, gen, opts } = it2;
      if (opts.$comment && schema.$comment)
        commentKeyword(it2);
      updateContext(it2);
      checkAsyncSchema(it2);
      const errsCount = gen.const("_errs", names_1.default.errors);
      typeAndKeywords(it2, errsCount);
      gen.var(valid, (0, codegen_1._)`${errsCount} === ${names_1.default.errors}`);
    }
    __name(subSchemaObjCode, "subSchemaObjCode");
    function checkKeywords(it2) {
      (0, util_1.checkUnknownRules)(it2);
      checkRefsAndKeywords(it2);
    }
    __name(checkKeywords, "checkKeywords");
    function typeAndKeywords(it2, errsCount) {
      if (it2.opts.jtd)
        return schemaKeywords(it2, [], false, errsCount);
      const types7 = (0, dataType_1.getSchemaTypes)(it2.schema);
      const checkedTypes = (0, dataType_1.coerceAndCheckDataType)(it2, types7);
      schemaKeywords(it2, types7, !checkedTypes, errsCount);
    }
    __name(typeAndKeywords, "typeAndKeywords");
    function checkRefsAndKeywords(it2) {
      const { schema, errSchemaPath, opts, self: self2 } = it2;
      if (schema.$ref && opts.ignoreKeywordsWithRef && (0, util_1.schemaHasRulesButRef)(schema, self2.RULES)) {
        self2.logger.warn(`$ref: keywords ignored in schema at path "${errSchemaPath}"`);
      }
    }
    __name(checkRefsAndKeywords, "checkRefsAndKeywords");
    function checkNoDefault(it2) {
      const { schema, opts } = it2;
      if (schema.default !== void 0 && opts.useDefaults && opts.strictSchema) {
        (0, util_1.checkStrictMode)(it2, "default is ignored in the schema root");
      }
    }
    __name(checkNoDefault, "checkNoDefault");
    function updateContext(it2) {
      const schId = it2.schema[it2.opts.schemaId];
      if (schId)
        it2.baseId = (0, resolve_1.resolveUrl)(it2.opts.uriResolver, it2.baseId, schId);
    }
    __name(updateContext, "updateContext");
    function checkAsyncSchema(it2) {
      if (it2.schema.$async && !it2.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(it2) {
      const { gen, schemaEnv, validateName: validateName2, ValidationError, opts } = it2;
      if (schemaEnv.$async) {
        gen.if((0, codegen_1._)`${names_1.default.errors} === 0`, () => gen.return(names_1.default.data), () => gen.throw((0, codegen_1._)`new ${ValidationError}(${names_1.default.vErrors})`));
      } else {
        gen.assign((0, codegen_1._)`${validateName2}.errors`, names_1.default.vErrors);
        if (opts.unevaluated)
          assignEvaluated(it2);
        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(it2, types7, typeErrors, errsCount) {
      const { gen, schema, data, allErrors, opts, self: self2 } = it2;
      const { RULES } = self2;
      if (schema.$ref && (opts.ignoreKeywordsWithRef || !(0, util_1.schemaHasRulesButRef)(schema, RULES))) {
        gen.block(() => keywordCode(it2, "$ref", RULES.all.$ref.definition));
        return;
      }
      if (!opts.jtd)
        checkStrictTypes(it2, types7);
      gen.block(() => {
        for (const group of RULES.rules)
          groupKeywords(group);
        groupKeywords(RULES.post);
      });
      function groupKeywords(group) {
        if (!(0, applicability_1.shouldUseGroup)(schema, group))
          return;
        if (group.type) {
          gen.if((0, dataType_2.checkDataType)(group.type, data, opts.strictNumbers));
          iterateKeywords(it2, group);
          if (types7.length === 1 && types7[0] === group.type && typeErrors) {
            gen.else();
            (0, dataType_2.reportTypeError)(it2);
          }
          gen.endIf();
        } else {
          iterateKeywords(it2, group);
        }
        if (!allErrors)
          gen.if((0, codegen_1._)`${names_1.default.errors} === ${errsCount || 0}`);
      }
      __name(groupKeywords, "groupKeywords");
    }
    __name(schemaKeywords, "schemaKeywords");
    function iterateKeywords(it2, group) {
      const { gen, schema, opts: { useDefaults } } = it2;
      if (useDefaults)
        (0, defaults_1.assignDefaults)(it2, group.type);
      gen.block(() => {
        for (const rule of group.rules) {
          if ((0, applicability_1.shouldUseRule)(schema, rule)) {
            keywordCode(it2, rule.keyword, rule.definition, group.type);
          }
        }
      });
    }
    __name(iterateKeywords, "iterateKeywords");
    function checkStrictTypes(it2, types7) {
      if (it2.schemaEnv.meta || !it2.opts.strictTypes)
        return;
      checkContextTypes(it2, types7);
      if (!it2.opts.allowUnionTypes)
        checkMultipleTypes(it2, types7);
      checkKeywordTypes(it2, it2.dataTypes);
    }
    __name(checkStrictTypes, "checkStrictTypes");
    function checkContextTypes(it2, types7) {
      if (!types7.length)
        return;
      if (!it2.dataTypes.length) {
        it2.dataTypes = types7;
        return;
      }
      types7.forEach((t5) => {
        if (!includesType(it2.dataTypes, t5)) {
          strictTypesError(it2, `type "${t5}" not allowed by context "${it2.dataTypes.join(",")}"`);
        }
      });
      narrowSchemaTypes(it2, types7);
    }
    __name(checkContextTypes, "checkContextTypes");
    function checkMultipleTypes(it2, ts) {
      if (ts.length > 1 && !(ts.length === 2 && ts.includes("null"))) {
        strictTypesError(it2, "use allowUnionTypes to allow union type keyword");
      }
    }
    __name(checkMultipleTypes, "checkMultipleTypes");
    function checkKeywordTypes(it2, ts) {
      const rules = it2.self.RULES.all;
      for (const keyword in rules) {
        const rule = rules[keyword];
        if (typeof rule == "object" && (0, applicability_1.shouldUseRule)(it2.schema, rule)) {
          const { type } = rule.definition;
          if (type.length && !type.some((t5) => hasApplicableType(ts, t5))) {
            strictTypesError(it2, `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, t5) {
      return ts.includes(t5) || t5 === "integer" && ts.includes("number");
    }
    __name(includesType, "includesType");
    function narrowSchemaTypes(it2, withTypes) {
      const ts = [];
      for (const t5 of it2.dataTypes) {
        if (includesType(withTypes, t5))
          ts.push(t5);
        else if (withTypes.includes("integer") && t5 === "number")
          ts.push("integer");
      }
      it2.dataTypes = ts;
    }
    __name(narrowSchemaTypes, "narrowSchemaTypes");
    function strictTypesError(it2, msg) {
      const schemaPath = it2.schemaEnv.baseId + it2.errSchemaPath;
      msg += ` at "${schemaPath}" (strictTypes)`;
      (0, util_1.checkStrictMode)(it2, msg, it2.opts.strictTypes);
    }
    __name(strictTypesError, "strictTypesError");
    var KeywordCxt = class {
      static {
        __name(this, "KeywordCxt");
      }
      constructor(it2, def2, keyword) {
        (0, keyword_1.validateKeywordUsage)(it2, def2, keyword);
        this.gen = it2.gen;
        this.allErrors = it2.allErrors;
        this.keyword = keyword;
        this.data = it2.data;
        this.schema = it2.schema[keyword];
        this.$data = def2.$data && it2.opts.$data && this.schema && this.schema.$data;
        this.schemaValue = (0, util_1.schemaRefOrVal)(it2, this.schema, keyword, this.$data);
        this.schemaType = def2.schemaType;
        this.parentSchema = it2.schema;
        this.params = {};
        this.it = it2;
        this.def = def2;
        if (this.$data) {
          this.schemaCode = it2.gen.const("vSchema", getData(this.$data, it2));
        } else {
          this.schemaCode = this.schemaValue;
          if (!(0, keyword_1.validSchemaType)(this.schema, 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 = it2.gen.const("_errs", names_1.default.errors);
        }
      }
      result(condition, successAction, failAction) {
        this.failResult((0, codegen_1.not)(condition), successAction, failAction);
      }
      failResult(condition, successAction, failAction) {
        this.gen.if(condition);
        if (failAction)
          failAction();
        else
          this.error();
        if (successAction) {
          this.gen.else();
          successAction();
          if (this.allErrors)
            this.gen.endIf();
        } else {
          if (this.allErrors)
            this.gen.endIf();
          else
            this.gen.else();
        }
      }
      pass(condition, failAction) {
        this.failResult((0, codegen_1.not)(condition), void 0, failAction);
      }
      fail(condition) {
        if (condition === void 0) {
          this.error();
          if (!this.allErrors)
            this.gen.if(false);
          return;
        }
        this.gen.if(condition);
        this.error();
        if (this.allErrors)
          this.gen.endIf();
        else
          this.gen.else();
      }
      fail$data(condition) {
        if (!this.$data)
          return this.fail(condition);
        const { schemaCode } = this;
        this.fail((0, codegen_1._)`${schemaCode} !== undefined && (${(0, codegen_1.or)(this.invalid$data(), condition)})`);
      }
      error(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: it2 } = this;
        return (0, codegen_1.or)(wrong$DataType(), invalid$DataSchema());
        function wrong$DataType() {
          if (schemaType.length) {
            if (!(schemaCode instanceof codegen_1.Name))
              throw new Error("ajv implementation error");
            const st2 = Array.isArray(schemaType) ? schemaType : [schemaType];
            return (0, codegen_1._)`${(0, dataType_2.checkDataTypes)(st2, schemaCode, it2.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: it2, gen } = this;
        if (!it2.opts.unevaluated)
          return;
        if (it2.props !== true && schemaCxt.props !== void 0) {
          it2.props = util_1.mergeEvaluated.props(gen, schemaCxt.props, it2.props, toName);
        }
        if (it2.items !== true && schemaCxt.items !== void 0) {
          it2.items = util_1.mergeEvaluated.items(gen, schemaCxt.items, it2.items, toName);
        }
      }
      mergeValidEvaluated(schemaCxt, valid) {
        const { it: it2, gen } = this;
        if (it2.opts.unevaluated && (it2.props !== true || it2.items !== true)) {
          gen.if(valid, () => this.mergeEvaluated(schemaCxt, codegen_1.Name));
          return true;
        }
      }
    };
    exports2.KeywordCxt = KeywordCxt;
    function keywordCode(it2, keyword, def2, ruleType) {
      const cxt = new KeywordCxt(it2, 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_util12();
    var validate_1 = require_validate2();
    var SchemaEnv = class {
      static {
        __name(this, "SchemaEnv");
      }
      constructor(env7) {
        var _a7;
        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 = (_a7 = env7.baseId) !== null && _a7 !== void 0 ? _a7 : (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 validate3 = makeValidate(this, this.scope.get());
        this.scope.value(validateName2, { ref: validate3 });
        validate3.errors = null;
        validate3.schema = sch.schema;
        validate3.schemaEnv = sch;
        if (sch.$async)
          validate3.$async = true;
        if (this.opts.code.source === true) {
          validate3.source = { validateName: validateName2, validateCode, scopeValues: gen._values };
        }
        if (this.opts.unevaluated) {
          const { props, items } = schemaCxt;
          validate3.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 (validate3.source)
            validate3.source.evaluated = (0, codegen_1.stringify)(validate3.evaluated);
        }
        sch.validate = validate3;
        return sch;
      } catch (e4) {
        delete sch.validate;
        delete sch.validateName;
        if (sourceCode)
          this.logger.error("Error compiling schema, function code:", sourceCode);
        throw e4;
      } finally {
        this._compilations.delete(sch);
      }
    }
    __name(compileSchema, "compileSchema");
    exports2.compileSchema = compileSchema;
    function resolveRef(root, baseId, ref) {
      var _a7;
      ref = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, ref);
      const schOrFunc = root.refs[ref];
      if (schOrFunc)
        return schOrFunc;
      let _sch = resolve30.call(this, root, ref);
      if (_sch === void 0) {
        const schema = (_a7 = root.localRefs) === null || _a7 === void 0 ? void 0 : _a7[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, s22) {
      return s1.schema === s22.schema && s1.root === s22.root && s1.baseId === s22.baseId;
    }
    __name(sameSchemaEnv, "sameSchemaEnv");
    function resolve30(root, ref) {
      let sch;
      while (typeof (sch = this.refs[ref]) == "string")
        ref = sch;
      return sch || this.schemas[ref] || resolveSchema.call(this, root, ref);
    }
    __name(resolve30, "resolve");
    function resolveSchema(root, ref) {
      const p2 = this.opts.uriResolver.parse(ref);
      const refPath = (0, resolve_1._getFullPath)(this.opts.uriResolver, p2);
      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, p2, 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, p2, 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, p2, 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 _a7;
      if (((_a7 = parsedRef.fragment) === null || _a7 === void 0 ? void 0 : _a7[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_core4 = __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_util12();
    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(o3) {
      var _a7, _b2, _c2, _d, _e2, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r2, _s, _t2, _u, _v, _w, _x, _y, _z, _0;
      const s5 = o3.strict;
      const _optz = (_a7 = o3.code) === null || _a7 === void 0 ? void 0 : _a7.optimize;
      const optimize = _optz === true || _optz === void 0 ? 1 : _optz || 0;
      const regExp = (_c2 = (_b2 = o3.code) === null || _b2 === void 0 ? void 0 : _b2.regExp) !== null && _c2 !== void 0 ? _c2 : defaultRegExp;
      const uriResolver = (_d = o3.uriResolver) !== null && _d !== void 0 ? _d : uri_1.default;
      return {
        strictSchema: (_f = (_e2 = o3.strictSchema) !== null && _e2 !== void 0 ? _e2 : s5) !== null && _f !== void 0 ? _f : true,
        strictNumbers: (_h = (_g = o3.strictNumbers) !== null && _g !== void 0 ? _g : s5) !== null && _h !== void 0 ? _h : true,
        strictTypes: (_k = (_j = o3.strictTypes) !== null && _j !== void 0 ? _j : s5) !== null && _k !== void 0 ? _k : "log",
        strictTuples: (_m = (_l = o3.strictTuples) !== null && _l !== void 0 ? _l : s5) !== null && _m !== void 0 ? _m : "log",
        strictRequired: (_p = (_o = o3.strictRequired) !== null && _o !== void 0 ? _o : s5) !== null && _p !== void 0 ? _p : false,
        code: o3.code ? { ...o3.code, optimize, regExp } : { optimize, regExp },
        loopRequired: (_q = o3.loopRequired) !== null && _q !== void 0 ? _q : MAX_EXPRESSION,
        loopEnum: (_r2 = o3.loopEnum) !== null && _r2 !== void 0 ? _r2 : MAX_EXPRESSION,
        meta: (_s = o3.meta) !== null && _s !== void 0 ? _s : true,
        messages: (_t2 = o3.messages) !== null && _t2 !== void 0 ? _t2 : true,
        inlineRefs: (_u = o3.inlineRefs) !== null && _u !== void 0 ? _u : true,
        schemaId: (_v = o3.schemaId) !== null && _v !== void 0 ? _v : "$id",
        addUsedSchema: (_w = o3.addUsedSchema) !== null && _w !== void 0 ? _w : true,
        validateSchema: (_x = o3.validateSchema) !== null && _x !== void 0 ? _x : true,
        validateFormats: (_y = o3.validateFormats) !== null && _y !== void 0 ? _y : true,
        unicodeRegExp: (_z = o3.unicodeRegExp) !== null && _z !== void 0 ? _z : true,
        int32range: (_0 = o3.int32range) !== null && _0 !== void 0 ? _0 : true,
        uriResolver
      };
    }
    __name(requiredOptions, "requiredOptions");
    var Ajv3 = 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 v2;
        if (typeof schemaKeyRef == "string") {
          v2 = this.getSchema(schemaKeyRef);
          if (!v2)
            throw new Error(`no schema with key or ref "${schemaKeyRef}"`);
        } else {
          v2 = this.compile(schemaKeyRef);
        }
        const valid = v2(data);
        if (!("$async" in v2))
          this.errors = v2.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 (e4) {
            if (!(e4 instanceof ref_error_1.default))
              throw e4;
            checkLoaded.call(this, e4);
            await loadMissingSchema.call(this, e4.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 p2 = this._loading[ref];
          if (p2)
            return p2;
          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 ? (k2) => addRule.call(this, k2, definition) : (k2) => definition.type.forEach((t5) => addRule.call(this, k2, definition, t5)));
        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 i3 = group.rules.findIndex((rule) => rule.keyword === keyword);
          if (i3 >= 0)
            group.rules.splice(i3, 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((e4) => `${dataVar}${e4.instancePath} ${e4.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;
        }
      }
    };
    Ajv3.ValidationError = validation_error_1.default;
    Ajv3.MissingRefError = ref_error_1.default;
    exports2.default = Ajv3;
    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 _a7;
      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: t5 }) => t5 === 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;
      (_a7 = definition.implements) === null || _a7 === void 0 ? void 0 : _a7.forEach((kwd) => this.addKeyword(kwd));
    }
    __name(addRule, "addRule");
    function addBeforeRule(ruleGroup, rule, before) {
      const i3 = ruleGroup.rules.findIndex((_rule) => _rule.keyword === before);
      if (i3 >= 0) {
        ruleGroup.rules.splice(i3, 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_util12();
    var def2 = {
      keyword: "$ref",
      schemaType: "string",
      code(cxt) {
        const { gen, schema: $ref, it: it2 } = cxt;
        const { baseId, schemaEnv: env7, validateName: validateName2, opts, self: self2 } = it2;
        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(it2.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 v2 = getValidate(cxt, sch);
          callRef(cxt, v2, 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, v2, sch, $async) {
      const { gen, it: it2 } = cxt;
      const { allErrors, schemaEnv: env7, opts } = it2;
      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, v2, passCxt)}`);
          addEvaluatedFrom(v2);
          if (!allErrors)
            gen.assign(valid, true);
        }, (e4) => {
          gen.if((0, codegen_1._)`!(${e4} instanceof ${it2.ValidationError})`, () => gen.throw(e4));
          addErrorsFrom(e4);
          if (!allErrors)
            gen.assign(valid, false);
        });
        cxt.ok(valid);
      }
      __name(callAsyncRef, "callAsyncRef");
      function callSyncRef() {
        cxt.result((0, code_1.callValidateCode)(cxt, v2, passCxt), () => addEvaluatedFrom(v2), () => addErrorsFrom(v2));
      }
      __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 _a7;
        if (!it2.opts.unevaluated)
          return;
        const schEvaluated = (_a7 = sch === null || sch === void 0 ? void 0 : sch.validate) === null || _a7 === void 0 ? void 0 : _a7.evaluated;
        if (it2.props !== true) {
          if (schEvaluated && !schEvaluated.dynamicProps) {
            if (schEvaluated.props !== void 0) {
              it2.props = util_1.mergeEvaluated.props(gen, schEvaluated.props, it2.props);
            }
          } else {
            const props = gen.var("props", (0, codegen_1._)`${source2}.evaluated.props`);
            it2.props = util_1.mergeEvaluated.props(gen, props, it2.props, codegen_1.Name);
          }
        }
        if (it2.items !== true) {
          if (schEvaluated && !schEvaluated.dynamicItems) {
            if (schEvaluated.items !== void 0) {
              it2.items = util_1.mergeEvaluated.items(gen, schEvaluated.items, it2.items);
            }
          } else {
            const items = gen.var("items", (0, codegen_1._)`${source2}.evaluated.items`);
            it2.items = util_1.mergeEvaluated.items(gen, items, it2.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_core5 = __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 error2 = {
      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: error2,
      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 error2 = {
      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: error2,
      code(cxt) {
        const { gen, data, schemaCode, it: it2 } = cxt;
        const prec = it2.opts.multipleOfPrecision;
        const res = gen.let("res");
        const invalid = prec ? (0, codegen_1._)`Math.abs(Math.round(${res}) - ${res}) > 1e-${prec}` : (0, codegen_1._)`${res} !== parseInt(${res})`;
        cxt.fail$data((0, codegen_1._)`(${schemaCode} === 0 || (${res} = ${data}/${schemaCode}, ${invalid}))`);
      }
    };
    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_util12();
    var ucs2length_1 = require_ucs2length2();
    var error2 = {
      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: error2,
      code(cxt) {
        const { keyword, data, schemaCode, it: it2 } = cxt;
        const op = keyword === "maxLength" ? codegen_1.operators.GT : codegen_1.operators.LT;
        const len = it2.opts.unicode === false ? (0, codegen_1._)`${data}.length` : (0, codegen_1._)`${(0, util_1.useFunc)(cxt.gen, ucs2length_1.default)}(${data})`;
        cxt.fail$data((0, codegen_1._)`${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 error2 = {
      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: error2,
      code(cxt) {
        const { data, $data, schema, schemaCode, it: it2 } = cxt;
        const u2 = it2.opts.unicodeRegExp ? "u" : "";
        const regExp = $data ? (0, codegen_1._)`(new RegExp(${schemaCode}, ${u2}))` : (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 error2 = {
      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: error2,
      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_util12();
    var error2 = {
      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: error2,
      code(cxt) {
        const { gen, schema, schemaCode, data, $data, it: it2 } = cxt;
        const { opts } = it2;
        if (!$data && schema.length === 0)
          return;
        const useLoop = schema.length >= opts.loopRequired;
        if (it2.allErrors)
          allErrorsMode();
        else
          exitOnErrorMode();
        if (opts.strictRequired) {
          const props = cxt.parentSchema.properties;
          const { definedProperties } = cxt.it;
          for (const requiredKey of schema) {
            if ((props === null || props === void 0 ? void 0 : props[requiredKey]) === void 0 && !definedProperties.has(requiredKey)) {
              const schemaPath = it2.schemaEnv.baseId + it2.errSchemaPath;
              const msg = `required property "${requiredKey}" is not defined at "${schemaPath}" (strictRequired)`;
              (0, util_1.checkStrictMode)(it2, msg, it2.opts.strictRequired);
            }
          }
        }
        function allErrorsMode() {
          if (useLoop || $data) {
            cxt.block$data(codegen_1.nil, loopAllRequired);
          } else {
            for (const prop of schema) {
              (0, code_1.checkReportMissingProp)(cxt, prop);
            }
          }
        }
        __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 error2 = {
      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: error2,
      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_util12();
    var equal_1 = require_equal2();
    var error2 = {
      message: /* @__PURE__ */ __name(({ params: { i: i3, j: j2 } }) => (0, codegen_1.str)`must NOT have duplicate items (items ## ${j2} and ${i3} are identical)`, "message"),
      params: /* @__PURE__ */ __name(({ params: { i: i3, j: j2 } }) => (0, codegen_1._)`{i: ${i3}, j: ${j2}}`, "params")
    };
    var def2 = {
      keyword: "uniqueItems",
      type: "array",
      schemaType: "boolean",
      $data: true,
      error: error2,
      code(cxt) {
        const { gen, data, $data, schema, parentSchema, schemaCode, it: it2 } = cxt;
        if (!$data && !schema)
          return;
        const valid = gen.let("valid");
        const itemTypes = parentSchema.items ? (0, dataType_1.getSchemaTypes)(parentSchema.items) : [];
        cxt.block$data(valid, validateUniqueItems, (0, codegen_1._)`${schemaCode} === false`);
        cxt.ok(valid);
        function validateUniqueItems() {
          const i3 = gen.let("i", (0, codegen_1._)`${data}.length`);
          const j2 = gen.let("j");
          cxt.setParams({ i: i3, j: j2 });
          gen.assign(valid, true);
          gen.if((0, codegen_1._)`${i3} > 1`, () => (canOptimize() ? loopN : loopN2)(i3, j2));
        }
        __name(validateUniqueItems, "validateUniqueItems");
        function canOptimize() {
          return itemTypes.length > 0 && !itemTypes.some((t5) => t5 === "object" || t5 === "array");
        }
        __name(canOptimize, "canOptimize");
        function loopN(i3, j2) {
          const item = gen.name("item");
          const wrongType = (0, dataType_1.checkDataTypes)(itemTypes, item, it2.opts.strictNumbers, dataType_1.DataType.Wrong);
          const indices = gen.const("indices", (0, codegen_1._)`{}`);
          gen.for((0, codegen_1._)`;${i3}--;`, () => {
            gen.let(item, (0, codegen_1._)`${data}[${i3}]`);
            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(j2, (0, codegen_1._)`${indices}[${item}]`);
              cxt.error();
              gen.assign(valid, false).break();
            }).code((0, codegen_1._)`${indices}[${item}] = ${i3}`);
          });
        }
        __name(loopN, "loopN");
        function loopN2(i3, j2) {
          const eql = (0, util_1.useFunc)(gen, equal_1.default);
          const outer = gen.name("outer");
          gen.label(outer).for((0, codegen_1._)`;${i3}--;`, () => gen.for((0, codegen_1._)`${j2} = ${i3}; ${j2}--;`, () => gen.if((0, codegen_1._)`${eql}(${data}[${i3}], ${data}[${j2}])`, () => {
            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_util12();
    var equal_1 = require_equal2();
    var error2 = {
      message: "must be equal to constant",
      params: /* @__PURE__ */ __name(({ schemaCode }) => (0, codegen_1._)`{allowedValue: ${schemaCode}}`, "params")
    };
    var def2 = {
      keyword: "const",
      $data: true,
      error: error2,
      code(cxt) {
        const { gen, data, $data, schemaCode, schema } = cxt;
        if ($data || schema && typeof schema == "object") {
          cxt.fail$data((0, codegen_1._)`!${(0, util_1.useFunc)(gen, equal_1.default)}(${data}, ${schemaCode})`);
        } else {
          cxt.fail((0, codegen_1._)`${schema} !== ${data}`);
        }
      }
    };
    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_util12();
    var equal_1 = require_equal2();
    var error2 = {
      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: error2,
      code(cxt) {
        const { gen, data, $data, schema, schemaCode, it: it2 } = cxt;
        if (!$data && schema.length === 0)
          throw new Error("enum must have non-empty array");
        const useLoop = schema.length >= it2.opts.loopEnum;
        let eql;
        const getEql = /* @__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, i3) => equalCode(vSchema, i3)));
        }
        cxt.pass(valid);
        function loopEnum() {
          gen.assign(valid, false);
          gen.forOf("v", schemaCode, (v2) => gen.if((0, codegen_1._)`${getEql()}(${data}, ${v2})`, () => gen.assign(valid, true).break()));
        }
        __name(loopEnum, "loopEnum");
        function equalCode(vSchema, i3) {
          const sch = schema[i3];
          return typeof sch === "object" && sch !== null ? (0, codegen_1._)`${getEql()}(${data}, ${vSchema}[${i3}])` : (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_validation4 = __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_util12();
    var error2 = {
      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: error2,
      code(cxt) {
        const { parentSchema, it: it2 } = cxt;
        const { items } = parentSchema;
        if (!Array.isArray(items)) {
          (0, util_1.checkStrictMode)(it2, '"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: it2 } = cxt;
      it2.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)(it2, 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, (i3) => {
          cxt.subschema({ keyword, dataProp: i3, dataPropType: util_1.Type.Num }, valid);
          if (!it2.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_util12();
    var code_1 = require_code4();
    var def2 = {
      keyword: "items",
      type: "array",
      schemaType: ["object", "array", "boolean"],
      before: "uniqueItems",
      code(cxt) {
        const { schema, it: it2 } = cxt;
        if (Array.isArray(schema))
          return validateTuple(cxt, "additionalItems", schema);
        it2.items = true;
        if ((0, util_1.alwaysValidSchema)(it2, schema))
          return;
        cxt.ok((0, code_1.validateArray)(cxt));
      }
    };
    function validateTuple(cxt, extraItems, schArr = cxt.schema) {
      const { gen, parentSchema, data, keyword, it: it2 } = cxt;
      checkStrictTuple(parentSchema);
      if (it2.opts.unevaluated && schArr.length && it2.items !== true) {
        it2.items = util_1.mergeEvaluated.items(gen, schArr.length, it2.items);
      }
      const valid = gen.name("valid");
      const len = gen.const("len", (0, codegen_1._)`${data}.length`);
      schArr.forEach((sch, i3) => {
        if ((0, util_1.alwaysValidSchema)(it2, sch))
          return;
        gen.if((0, codegen_1._)`${len} > ${i3}`, () => cxt.subschema({
          keyword,
          schemaProp: i3,
          dataProp: i3
        }, valid));
        cxt.ok(valid);
      });
      function checkStrictTuple(sch) {
        const { opts, errSchemaPath } = it2;
        const l3 = schArr.length;
        const fullTuple = l3 === sch.minItems && (l3 === sch.maxItems || sch[extraItems] === false);
        if (opts.strictTuples && !fullTuple) {
          const msg = `"${keyword}" is ${l3}-tuple, but minItems or maxItems/${extraItems} are not specified or different at path "${errSchemaPath}"`;
          (0, util_1.checkStrictMode)(it2, 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_util12();
    var code_1 = require_code4();
    var additionalItems_1 = require_additionalItems2();
    var error2 = {
      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: error2,
      code(cxt) {
        const { schema, parentSchema, it: it2 } = cxt;
        const { prefixItems } = parentSchema;
        it2.items = true;
        if ((0, util_1.alwaysValidSchema)(it2, 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_util12();
    var error2 = {
      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: error2,
      code(cxt) {
        const { gen, schema, parentSchema, data, it: it2 } = cxt;
        let min;
        let max;
        const { minContains, maxContains } = parentSchema;
        if (it2.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)(it2, `"minContains" == 0 without "maxContains": "contains" keyword ignored`);
          return;
        }
        if (max !== void 0 && min > max) {
          (0, util_1.checkStrictMode)(it2, `"minContains" > "maxContains" is always invalid`);
          cxt.fail();
          return;
        }
        if ((0, util_1.alwaysValidSchema)(it2, schema)) {
          let cond = (0, codegen_1._)`${len} >= ${min}`;
          if (max !== void 0)
            cond = (0, codegen_1._)`${cond} && ${len} <= ${max}`;
          cxt.pass(cond);
          return;
        }
        it2.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, (i3) => {
            cxt.subschema({
              keyword: "contains",
              dataProp: i3,
              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_util12();
    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: it2 } = cxt;
      if (Object.keys(propertyDeps).length === 0)
        return;
      const missing = gen.let("missing");
      for (const prop in propertyDeps) {
        const deps = propertyDeps[prop];
        if (deps.length === 0)
          continue;
        const hasProperty2 = (0, code_1.propertyInData)(gen, data, prop, it2.opts.ownProperties);
        cxt.setParams({
          property: prop,
          depsCount: deps.length,
          deps: deps.join(", ")
        });
        if (it2.allErrors) {
          gen.if(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: it2 } = cxt;
      const valid = gen.name("valid");
      for (const prop in schemaDeps) {
        if ((0, util_1.alwaysValidSchema)(it2, schemaDeps[prop]))
          continue;
        gen.if(
          (0, code_1.propertyInData)(gen, data, prop, it2.opts.ownProperties),
          () => {
            const schCxt = cxt.subschema({ keyword, 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_util12();
    var error2 = {
      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: error2,
      code(cxt) {
        const { gen, schema, data, it: it2 } = cxt;
        if ((0, util_1.alwaysValidSchema)(it2, schema))
          return;
        const valid = gen.name("valid");
        gen.forIn("key", data, (key) => {
          cxt.setParams({ propertyName: key });
          cxt.subschema({
            keyword: "propertyNames",
            data: key,
            dataTypes: ["string"],
            propertyName: key,
            compositeRule: true
          }, valid);
          gen.if((0, codegen_1.not)(valid), () => {
            cxt.error(true);
            if (!it2.allErrors)
              gen.break();
          });
        });
        cxt.ok(valid);
      }
    };
    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_util12();
    var error2 = {
      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: error2,
      code(cxt) {
        const { gen, schema, parentSchema, data, errsCount, it: it2 } = cxt;
        if (!errsCount)
          throw new Error("ajv implementation error");
        const { allErrors, opts } = it2;
        it2.props = true;
        if (opts.removeAdditional !== "all" && (0, util_1.alwaysValidSchema)(it2, schema))
          return;
        const props = (0, code_1.allSchemaProperties)(parentSchema.properties);
        const patProps = (0, code_1.allSchemaProperties)(parentSchema.patternProperties);
        checkAdditionalProperties();
        cxt.ok((0, codegen_1._)`${errsCount} === ${names_1.default.errors}`);
        function checkAdditionalProperties() {
          gen.forIn("key", data, (key) => {
            if (!props.length && !patProps.length)
              additionalPropertyCode(key);
            else
              gen.if(isAdditional(key), () => additionalPropertyCode(key));
          });
        }
        __name(checkAdditionalProperties, "checkAdditionalProperties");
        function isAdditional(key) {
          let definedProp;
          if (props.length > 8) {
            const propsSchema = (0, util_1.schemaRefOrVal)(it2, parentSchema.properties, "properties");
            definedProp = (0, code_1.isOwnProperty)(gen, propsSchema, key);
          } else if (props.length) {
            definedProp = (0, codegen_1.or)(...props.map((p2) => (0, codegen_1._)`${key} === ${p2}`));
          } else {
            definedProp = codegen_1.nil;
          }
          if (patProps.length) {
            definedProp = (0, codegen_1.or)(definedProp, ...patProps.map((p2) => (0, codegen_1._)`${(0, code_1.usePattern)(cxt, p2)}.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)(it2, schema)) {
            const valid = gen.name("valid");
            if (opts.removeAdditional === "failing") {
              applyAdditionalSchema(key, valid, false);
              gen.if((0, codegen_1.not)(valid), () => {
                cxt.reset();
                deleteAdditional(key);
              });
            } else {
              applyAdditionalSchema(key, valid);
              if (!allErrors)
                gen.if((0, codegen_1.not)(valid), () => gen.break());
            }
          }
        }
        __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_util12();
    var additionalProperties_1 = require_additionalProperties2();
    var def2 = {
      keyword: "properties",
      type: "object",
      schemaType: "object",
      code(cxt) {
        const { gen, schema, parentSchema, data, it: it2 } = cxt;
        if (it2.opts.removeAdditional === "all" && parentSchema.additionalProperties === void 0) {
          additionalProperties_1.default.code(new validate_1.KeywordCxt(it2, additionalProperties_1.default, "additionalProperties"));
        }
        const allProps = (0, code_1.allSchemaProperties)(schema);
        for (const prop of allProps) {
          it2.definedProperties.add(prop);
        }
        if (it2.opts.unevaluated && allProps.length && it2.props !== true) {
          it2.props = util_1.mergeEvaluated.props(gen, (0, util_1.toHash)(allProps), it2.props);
        }
        const properties = allProps.filter((p2) => !(0, util_1.alwaysValidSchema)(it2, schema[p2]));
        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, it2.opts.ownProperties));
            applyPropertySchema(prop);
            if (!it2.allErrors)
              gen.else().var(valid, true);
            gen.endIf();
          }
          cxt.it.definedProperties.add(prop);
          cxt.ok(valid);
        }
        function hasDefault(prop) {
          return it2.opts.useDefaults && !it2.compositeRule && schema[prop].default !== void 0;
        }
        __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_util12();
    var util_2 = require_util12();
    var def2 = {
      keyword: "patternProperties",
      type: "object",
      schemaType: "object",
      code(cxt) {
        const { gen, schema, data, parentSchema, it: it2 } = cxt;
        const { opts } = it2;
        const patterns = (0, code_1.allSchemaProperties)(schema);
        const alwaysValidPatterns = patterns.filter((p2) => (0, util_1.alwaysValidSchema)(it2, schema[p2]));
        if (patterns.length === 0 || alwaysValidPatterns.length === patterns.length && (!it2.opts.unevaluated || it2.props === true)) {
          return;
        }
        const checkProperties = opts.strictSchema && !opts.allowMatchingProperties && parentSchema.properties;
        const valid = gen.name("valid");
        if (it2.props !== true && !(it2.props instanceof codegen_1.Name)) {
          it2.props = (0, util_2.evaluatedPropsToName)(gen, it2.props);
        }
        const { props } = it2;
        validatePatternProperties();
        function validatePatternProperties() {
          for (const pat of patterns) {
            if (checkProperties)
              checkMatchingProperties(pat);
            if (it2.allErrors) {
              validateProperties(pat);
            } else {
              gen.var(valid, true);
              validateProperties(pat);
              gen.if(valid);
            }
          }
        }
        __name(validatePatternProperties, "validatePatternProperties");
        function checkMatchingProperties(pat) {
          for (const prop in checkProperties) {
            if (new RegExp(pat).test(prop)) {
              (0, util_1.checkStrictMode)(it2, `property ${prop} matches pattern ${pat} (use allowMatchingProperties)`);
            }
          }
        }
        __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 (it2.opts.unevaluated && props !== true) {
                gen.assign((0, codegen_1._)`${props}[${key}]`, true);
              } else if (!alwaysValid && !it2.allErrors) {
                gen.if((0, codegen_1.not)(valid), () => gen.break());
              }
            });
          });
        }
        __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_util12();
    var def2 = {
      keyword: "not",
      schemaType: ["object", "boolean"],
      trackErrors: true,
      code(cxt) {
        const { gen, schema, it: it2 } = cxt;
        if ((0, util_1.alwaysValidSchema)(it2, schema)) {
          cxt.fail();
          return;
        }
        const valid = gen.name("valid");
        cxt.subschema({
          keyword: "not",
          compositeRule: true,
          createErrors: false,
          allErrors: false
        }, valid);
        cxt.failResult(valid, () => cxt.reset(), () => cxt.error());
      },
      error: { message: "must NOT be valid" }
    };
    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_util12();
    var error2 = {
      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: error2,
      code(cxt) {
        const { gen, schema, parentSchema, it: it2 } = cxt;
        if (!Array.isArray(schema))
          throw new Error("ajv implementation error");
        if (it2.opts.discriminator && parentSchema.discriminator)
          return;
        const schArr = schema;
        const valid = gen.let("valid", false);
        const passing = gen.let("passing", null);
        const schValid = gen.name("_valid");
        cxt.setParams({ passing });
        gen.block(validateOneOf);
        cxt.result(valid, () => cxt.reset(), () => cxt.error(true));
        function validateOneOf() {
          schArr.forEach((sch, i3) => {
            let schCxt;
            if ((0, util_1.alwaysValidSchema)(it2, sch)) {
              gen.var(schValid, true);
            } else {
              schCxt = cxt.subschema({
                keyword: "oneOf",
                schemaProp: i3,
                compositeRule: true
              }, schValid);
            }
            if (i3 > 0) {
              gen.if((0, codegen_1._)`${schValid} && ${valid}`).assign(valid, false).assign(passing, (0, codegen_1._)`[${passing}, ${i3}]`).else();
            }
            gen.if(schValid, () => {
              gen.assign(valid, true);
              gen.assign(passing, i3);
              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_util12();
    var def2 = {
      keyword: "allOf",
      schemaType: "array",
      code(cxt) {
        const { gen, schema, it: it2 } = cxt;
        if (!Array.isArray(schema))
          throw new Error("ajv implementation error");
        const valid = gen.name("valid");
        schema.forEach((sch, i3) => {
          if ((0, util_1.alwaysValidSchema)(it2, sch))
            return;
          const schCxt = cxt.subschema({ keyword: "allOf", schemaProp: i3 }, 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_util12();
    var error2 = {
      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: error2,
      code(cxt) {
        const { gen, parentSchema, it: it2 } = cxt;
        if (parentSchema.then === void 0 && parentSchema.else === void 0) {
          (0, util_1.checkStrictMode)(it2, '"if" without "then" and "else" is ignored');
        }
        const hasThen = hasSchema(it2, "then");
        const hasElse = hasSchema(it2, "else");
        if (!hasThen && !hasElse)
          return;
        const valid = gen.let("valid", true);
        const schValid = gen.name("_valid");
        validateIf();
        cxt.reset();
        if (hasThen && hasElse) {
          const ifClause = gen.let("ifClause");
          cxt.setParams({ ifClause });
          gen.if(schValid, validateClause("then", ifClause), validateClause("else", ifClause));
        } else if (hasThen) {
          gen.if(schValid, validateClause("then"));
        } else {
          gen.if((0, codegen_1.not)(schValid), validateClause("else"));
        }
        cxt.pass(valid, () => cxt.error(true));
        function validateIf() {
          const schCxt = cxt.subschema({
            keyword: "if",
            compositeRule: true,
            createErrors: false,
            allErrors: false
          }, schValid);
          cxt.mergeEvaluated(schCxt);
        }
        __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(it2, keyword) {
      const schema = it2.schema[keyword];
      return schema !== void 0 && !(0, util_1.alwaysValidSchema)(it2, 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_util12();
    var def2 = {
      keyword: ["then", "else"],
      schemaType: ["object", "boolean"],
      code({ keyword, parentSchema, it: it2 }) {
        if (parentSchema.if === void 0)
          (0, util_1.checkStrictMode)(it2, `"${keyword}" without "if" is ignored`);
      }
    };
    exports2.default = def2;
  }
});

// node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/applicator/index.js
var require_applicator3 = __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 error2 = {
      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: error2,
      code(cxt, ruleType) {
        const { gen, data, $data, schema, schemaCode, it: it2 } = cxt;
        const { opts, errSchemaPath, schemaEnv, self: self2 } = it2;
        if (!opts.validateFormats)
          return;
        if ($data)
          validate$DataFormat();
        else
          validateFormat();
        function validate$DataFormat() {
          const fmts = gen.scopeValue("formats", {
            ref: self2.formats,
            code: opts.code.formats
          });
          const fDef = gen.const("fDef", (0, codegen_1._)`${fmts}[${schemaCode}]`);
          const fType = gen.let("fType");
          const 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_core5();
    var validation_1 = require_validation4();
    var applicator_1 = require_applicator3();
    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_util12();
    var error2 = {
      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: error2,
      code(cxt) {
        const { gen, data, schema, parentSchema, it: it2 } = cxt;
        const { oneOf } = parentSchema;
        if (!it2.opts.discriminator) {
          throw new Error("discriminator: requires discriminator option");
        }
        const tagName = schema.propertyName;
        if (typeof tagName != "string")
          throw new Error("discriminator: requires propertyName");
        if (schema.mapping)
          throw new Error("discriminator: mapping is not supported");
        if (!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 _a7;
          const oneOfMapping = {};
          const topRequired = hasRequired(parentSchema);
          let tagRequired = true;
          for (let i3 = 0; i3 < oneOf.length; i3++) {
            let sch = oneOf[i3];
            if ((sch === null || sch === void 0 ? void 0 : sch.$ref) && !(0, util_1.schemaHasRulesButRef)(sch, it2.self.RULES)) {
              const ref = sch.$ref;
              sch = compile_1.resolveRef.call(it2.self, it2.schemaEnv.root, it2.baseId, ref);
              if (sch instanceof compile_1.SchemaEnv)
                sch = sch.schema;
              if (sch === void 0)
                throw new ref_error_1.default(it2.opts.uriResolver, it2.baseId, ref);
            }
            const propSch = (_a7 = sch === null || sch === void 0 ? void 0 : sch.properties) === null || _a7 === void 0 ? void 0 : _a7[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, i3);
          }
          if (!tagRequired)
            throw new Error(`discriminator: "${tagName}" must be required`);
          return oneOfMapping;
          function hasRequired({ required: required2 }) {
            return Array.isArray(required2) && required2.includes(tagName);
          }
          __name(hasRequired, "hasRequired");
          function addMappings(sch, i3) {
            if (sch.const) {
              addMapping(sch.const, i3);
            } else if (sch.enum) {
              for (const tagValue of sch.enum) {
                addMapping(tagValue, i3);
              }
            } else {
              throw new Error(`discriminator: "properties/${tagName}" must have "const" or "enum"`);
            }
          }
          __name(addMappings, "addMappings");
          function addMapping(tagValue, i3) {
            if (typeof tagValue != "string" || tagValue in oneOfMapping) {
              throw new Error(`discriminator: "${tagName}" values must be unique strings`);
            }
            oneOfMapping[tagValue] = i3;
          }
          __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_core4();
    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 Ajv3 = class extends core_1.default {
      static {
        __name(this, "Ajv");
      }
      _addVocabularies() {
        super._addVocabularies();
        draft7_1.default.forEach((v2) => this.addVocabulary(v2));
        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 = Ajv3;
    module2.exports = exports2 = Ajv3;
    module2.exports.Ajv = Ajv3;
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.default = Ajv3;
    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 error2 = {
      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: error2,
      code(cxt) {
        const { gen, data, schemaCode, keyword, it: it2 } = cxt;
        const { opts, self: self2 } = it2;
        if (!opts.validateFormats)
          return;
        const fCxt = new ajv_1.KeywordCxt(it2, self2.RULES.all.format.definition, "format");
        if (fCxt.$data)
          validate$DataFormat();
        else
          validateFormat();
        function validate$DataFormat() {
          const fmts = gen.scopeValue("formats", {
            ref: self2.formats,
            code: opts.code.formats
          });
          const fmt = gen.const("fmt", (0, codegen_1._)`${fmts}[${fCxt.schemaCode}]`);
          cxt.fail$data((0, codegen_1.or)((0, codegen_1._)`typeof ${fmt} != "object"`, (0, codegen_1._)`${fmt} instanceof RegExp`, (0, codegen_1._)`typeof ${fmt}.compare != "function"`, compareCode(fmt)));
        }
        __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 f5 = formats[name3];
      if (!f5)
        throw new Error(`Unknown format "${name3}"`);
      return f5;
    };
    function addFormats2(ajv, list3, fs113, exportName) {
      var _a7;
      var _b2;
      (_a7 = (_b2 = ajv.opts.code).formats) !== null && _a7 !== void 0 ? _a7 : _b2.formats = (0, codegen_1._)`require("ajv-formats/dist/formats").${exportName}`;
      for (const f5 of list3)
        ajv.addFormat(f5, fs113[f5]);
    }
    __name(addFormats2, "addFormats");
    module2.exports = exports2 = formatsPlugin;
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.default = formatsPlugin;
  }
});

// packages/core/dist/src/utils/schemaValidator.js
function getValidator(schema) {
  if (typeof schema === "object" && schema !== null && "$schema" in schema && schema.$schema === DRAFT_2020_12_SCHEMA) {
    return ajv2020;
  }
  return ajvDefault;
}
function fixBooleanValues(data) {
  for (const key of Object.keys(data)) {
    if (!(key in data))
      continue;
    const value = data[key];
    if (typeof value === "object" && value !== null) {
      fixBooleanValues(value);
    } else if (typeof value === "string") {
      const lower3 = value.toLowerCase();
      if (lower3 === "true") {
        data[key] = true;
      } else if (lower3 === "false") {
        data[key] = false;
      }
    }
  }
}
var import_ajv, import__, addFormats, AjvClass, Ajv2020Class, debugLogger2, ajvOptions, ajvDefault, ajv2020, addFormatsFunc, DRAFT_2020_12_SCHEMA, SchemaValidator;
var init_schemaValidator = __esm({
  "packages/core/dist/src/utils/schemaValidator.js"() {
    "use strict";
    init_esbuild_shims();
    import_ajv = __toESM(require_ajv(), 1);
    import__ = __toESM(require__(), 1);
    addFormats = __toESM(require_dist3(), 1);
    init_debugLogger();
    AjvClass = import_ajv.default.default || import_ajv.default;
    Ajv2020Class = import__.default.default || import__.default;
    debugLogger2 = createDebugLogger("SchemaValidator");
    ajvOptions = {
      // 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
    };
    ajvDefault = new AjvClass(ajvOptions);
    ajv2020 = new Ajv2020Class(ajvOptions);
    addFormatsFunc = addFormats.default || addFormats;
    addFormatsFunc(ajvDefault);
    addFormatsFunc(ajv2020);
    DRAFT_2020_12_SCHEMA = "https://json-schema.org/draft/2020-12/schema";
    __name(getValidator, "getValidator");
    SchemaValidator = class {
      static {
        __name(this, "SchemaValidator");
      }
      /**
       * Returns null if the data conforms 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 anySchema = schema;
        const validator = getValidator(anySchema);
        let validate3;
        try {
          validate3 = validator.compile(anySchema);
        } catch (error2) {
          debugLogger2.warn(`Failed to compile schema (${schema?.["$schema"] ?? "<no $schema>"}): ${error2 instanceof Error ? error2.message : String(error2)}. Skipping parameter validation.`);
          return null;
        }
        let valid = validate3(data);
        if (!valid && validate3.errors) {
          fixBooleanValues(data);
          valid = validate3(data);
          if (!valid && validate3.errors) {
            return validator.errorsText(validate3.errors, { dataVar: "params" });
          }
        }
        return null;
      }
    };
    __name(fixBooleanValues, "fixBooleanValues");
  }
});

// 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;
      thoughtTokens = 0;
      cachedTokens = 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, thought = 0, cached2 = 0) {
        this.inputTokens += Math.max(0, input || 0);
        this.outputTokens += Math.max(0, output || 0);
        this.thoughtTokens += Math.max(0, thought || 0);
        this.cachedTokens += Math.max(0, cached2 || 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 + this.thoughtTokens + this.cachedTokens;
        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,
          thoughtTokens: this.thoughtTokens,
          cachedTokens: this.cachedTokens,
          totalTokens,
          estimatedCost,
          toolUsage: Array.from(this.toolUsage.values())
        };
      }
      formatCompact(taskDesc, now = Date.now()) {
        const stats = this.getSummary(now);
        const sr2 = 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 ? `, ${sr2.toFixed(1)}% success` : ""}`,
          `\u23F1\uFE0F Duration: ${this.fmtDuration(stats.totalDurationMs)} | \u{1F501} Rounds: ${stats.rounds}`
        ];
        if (typeof stats.totalTokens === "number") {
          const parts = [
            `in ${stats.inputTokens ?? 0}`,
            `out ${stats.outputTokens ?? 0}`
          ];
          lines.push(`\u{1F522} Tokens: ${stats.totalTokens.toLocaleString()}${parts.length ? ` (${parts.join(", ")})` : ""}`);
        }
        return lines.join("\n");
      }
      formatDetailed(taskDesc, now = Date.now()) {
        const stats = this.getSummary(now);
        const sr2 = 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 (sr2 >= 95)
          quality = "Excellent execution";
        else if (sr2 >= 85)
          quality = "Good execution";
        else if (sr2 >= 70)
          quality = "Fair execution";
        lines.push(`\u2705 Quality: ${quality} (${sr2.toFixed(1)}% tool success)`);
        const d2 = stats.totalDurationMs;
        let speed = "Long execution - consider breaking down tasks";
        if (d2 < 1e4)
          speed = "Fast completion - under 10 seconds";
        else if (d2 < 6e4)
          speed = "Good speed - under a minute";
        else if (d2 < 3e5)
          speed = "Moderate duration - a few minutes";
        lines.push(`\u{1F680} Speed: ${speed}`);
        lines.push(`\u{1F527} Tools: ${stats.totalToolCalls} calls, ${sr2.toFixed(1)}% success (${stats.successfulToolCalls} ok, ${stats.failedToolCalls} failed)`);
        if (typeof stats.totalTokens === "number") {
          const parts = [
            `in ${stats.inputTokens ?? 0}`,
            `out ${stats.outputTokens ?? 0}`
          ];
          lines.push(`\u{1F522} Tokens: ${stats.totalTokens.toLocaleString()} (${parts.join(", ")})`);
        }
        if (stats.toolUsage && stats.toolUsage.length) {
          const sorted2 = [...stats.toolUsage].sort((a2, b2) => b2.count - a2.count).slice(0, 5);
          lines.push("\nTop tools:");
          for (const t5 of sorted2) {
            const avg = typeof t5.averageDurationMs === "number" ? `, avg ${this.fmtDuration(Math.round(t5.averageDurationMs))}` : "";
            lines.push(` - ${t5.name}: ${t5.count} calls (${t5.success} ok, ${t5.failure} fail${avg}${t5.lastError ? `, last error: ${t5.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 m4 = Math.floor(ms / 6e4);
          const s5 = Math.floor(ms % 6e4 / 1e3);
          return `${m4}m ${s5}s`;
        }
        const h3 = Math.floor(ms / 36e5);
        const m3 = Math.floor(ms % 36e5 / 6e4);
        return `${h3}h ${m3}m`;
      }
      generatePerformanceTips(stats) {
        const tips = [];
        const totalCalls = stats.totalToolCalls;
        const sr2 = stats.totalToolCalls > 0 ? stats.successRate ?? stats.successfulToolCalls / stats.totalToolCalls * 100 : 0;
        if (sr2 < 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((t5) => isNetworkTool(t5.name) && t5.lastError && /timeout|network/i.test(t5.lastError));
        if (hadNetworkFailure)
          tips.push("Network operations had failures - consider increasing timeout or checking connectivity");
        const slow = (stats.toolUsage || []).filter((t5) => (t5.averageDurationMs ?? 0) > 1e4).sort((a2, b2) => (b2.averageDurationMs ?? 0) - (a2.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 path125 = ref.substring(2).split("/");
    let current = schema;
    for (const segment of path125) {
      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, kind2, parameterSchema, isOutputMarkdown = true, canUpdateOutput = false) {
        this.name = name3;
        this.displayName = displayName;
        this.description = description;
        this.kind = kind2;
        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 (e4) {
          if (e4 instanceof Error) {
            return e4;
          }
          return new Error(String(e4));
        }
      }
      /**
       * 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 (error2) {
          const errorMessage = error2 instanceof Error ? error2.message : String(error2);
          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 wrapMcpCallToolResultAsParts(toolName, result) {
  const response = result.isError ? { error: result, content: result.content } : result;
  return [
    {
      functionResponse: {
        name: toolName,
        response
      }
    }
  ];
}
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;
      mcpClient;
      mcpTimeout;
      annotations;
      static allowlist = /* @__PURE__ */ new Set();
      constructor(mcpTool, serverName, serverToolName, displayName, trust, params = {}, cliConfig, mcpClient, mcpTimeout, annotations) {
        super(params);
        this.mcpTool = mcpTool;
        this.serverName = serverName;
        this.serverToolName = serverToolName;
        this.displayName = displayName;
        this.trust = trust;
        this.cliConfig = cliConfig;
        this.mcpClient = mcpClient;
        this.mcpTimeout = mcpTimeout;
        this.annotations = annotations;
      }
      async shouldConfirmExecute(_abortSignal) {
        const serverAllowListKey = this.serverName;
        const toolAllowListKey = `${this.serverName}.${this.serverToolName}`;
        if (this.cliConfig?.isTrustedFolder() && this.trust) {
          return false;
        }
        if (this.annotations?.readOnlyHint === true) {
          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, _payload) => {
            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 error2 = response?.error;
          const isError = error2?.isError;
          if (error2 && (isError === true || isError === "true")) {
            return true;
          }
        }
        return false;
      }
      async execute(signal, updateOutput2) {
        if (this.mcpClient) {
          return this.executeWithDirectClient(signal, updateOutput2);
        }
        return this.executeWithCallableTool(signal);
      }
      /**
       * Execute using the raw MCP SDK Client, which supports progress
       * notifications via the onprogress callback. This enables real-time
       * streaming of progress updates to the user during long-running
       * MCP tool calls (e.g., browser automation).
       */
      async executeWithDirectClient(signal, updateOutput2) {
        const callToolResult = await this.mcpClient.callTool({
          name: this.serverToolName,
          arguments: this.params
        }, void 0, {
          onprogress: /* @__PURE__ */ __name((progress) => {
            if (updateOutput2) {
              const progressData = {
                type: "mcp_tool_progress",
                progress: progress.progress,
                ...progress.total != null && { total: progress.total },
                ...progress.message != null && { message: progress.message }
              };
              updateOutput2(progressData);
            }
          }, "onprogress"),
          timeout: this.mcpTimeout,
          signal
        });
        const rawResponseParts = wrapMcpCallToolResultAsParts(this.serverToolName, callToolResult);
        if (this.isMCPToolError(rawResponseParts)) {
          const errorMessage = `MCP tool '${this.serverToolName}' reported tool error for function call: ${safeJsonStringify({
            name: this.serverToolName,
            args: this.params
          })} 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)
        };
      }
      /**
       * Fallback: execute using the @google/genai CallableTool wrapper.
       * This path does NOT support progress notifications.
       */
      async executeWithCallableTool(signal) {
        const functionCalls = [
          {
            name: this.serverToolName,
            args: this.params
          }
        ];
        const rawResponseParts = await new Promise((resolve30, reject) => {
          if (signal.aborted) {
            const error2 = new Error("Tool call aborted");
            error2.name = "AbortError";
            reject(error2);
            return;
          }
          const onAbort = /* @__PURE__ */ __name(() => {
            cleanup();
            const error2 = new Error("Tool call aborted");
            error2.name = "AbortError";
            reject(error2);
          }, "onAbort");
          const cleanup = /* @__PURE__ */ __name(() => {
            signal.removeEventListener("abort", onAbort);
          }, "cleanup");
          signal.addEventListener("abort", onAbort, { once: true });
          this.mcpTool.callTool(functionCalls).then((res) => {
            cleanup();
            resolve30(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;
      mcpClient;
      mcpTimeout;
      annotations;
      constructor(mcpTool, serverName, serverToolName, description, parameterSchema, trust, nameOverride, cliConfig, mcpClient, mcpTimeout, annotations) {
        super(
          nameOverride ?? generateValidName(`mcp__${serverName}__${serverToolName}`),
          `${serverToolName} (${serverName} MCP Server)`,
          description,
          annotations?.readOnlyHint === true ? Kind.Read : Kind.Other,
          parameterSchema,
          true,
          // isOutputMarkdown
          true
        );
        this.mcpTool = mcpTool;
        this.serverName = serverName;
        this.serverToolName = serverToolName;
        this.parameterSchema = parameterSchema;
        this.trust = trust;
        this.cliConfig = cliConfig;
        this.mcpClient = mcpClient;
        this.mcpTimeout = mcpTimeout;
        this.annotations = annotations;
      }
      asFullyQualifiedTool() {
        return new _DiscoveredMCPTool(this.mcpTool, this.serverName, this.serverToolName, this.description, this.parameterSchema, this.trust, generateValidName(`mcp__${this.serverName}__${this.serverToolName}`), this.cliConfig, this.mcpClient, this.mcpTimeout, this.annotations);
      }
      createInvocation(params) {
        return new DiscoveredMCPToolInvocation(this.mcpTool, this.serverName, this.serverToolName, this.displayName, this.trust, params, this.cliConfig, this.mcpClient, this.mcpTimeout, this.annotations);
      }
    };
    __name(wrapMcpCallToolResultAsParts, "wrapMcpCallToolResultAsParts");
    __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/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",
      GREP: "grep_search",
      GLOB: "glob",
      SHELL: "run_shell_command",
      TODO_WRITE: "todo_write",
      MEMORY: "save_memory",
      TASK: "task",
      SKILL: "skill",
      EXIT_PLAN_MODE: "exit_plan_mode",
      WEB_FETCH: "web_fetch",
      WEB_SEARCH: "web_search",
      LS: "list_directory",
      LSP: "lsp"
    };
    ToolDisplayNames = {
      EDIT: "Edit",
      WRITE_FILE: "WriteFile",
      READ_FILE: "ReadFile",
      GREP: "Grep",
      GLOB: "Glob",
      SHELL: "Shell",
      TODO_WRITE: "TodoWrite",
      MEMORY: "SaveMemory",
      TASK: "Task",
      SKILL: "Skill",
      EXIT_PLAN_MODE: "ExitPlanMode",
      WEB_FETCH: "WebFetch",
      WEB_SEARCH: "WebSearch",
      LS: "ListFiles",
      LSP: "Lsp"
    };
    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/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, compression_input_token_count, compression_output_token_count }) {
  return {
    "event.name": "chat_compression",
    "event.timestamp": (/* @__PURE__ */ new Date()).toISOString(),
    tokens_before,
    tokens_after,
    ...compression_input_token_count !== void 0 ? { compression_input_token_count } : {},
    ...compression_output_token_count !== void 0 ? { compression_output_token_count } : {}
  };
}
var StartSessionEvent, UserPromptEvent, ToolCallEvent, ApiRequestEvent, ApiErrorEvent, ApiCancelEvent, ApiResponseEvent, RipgrepFallbackEvent, LoopType, LoopDetectedEvent, LoopDetectionDisabledEvent, NextSpeakerCheckEvent, SlashCommandStatus, IdeConnectionType, IdeConnectionEvent, ConversationFinishedEvent, KittySequenceOverflowEvent, FileOperationEvent, ContentRetryEvent, ContentRetryFailureEvent, ExtensionInstallEvent, ToolOutputTruncatedEvent, ExtensionUninstallEvent, ExtensionUpdateEvent, ExtensionEnableEvent, ModelSlashCommandEvent, SubagentExecutionEvent, AuthEvent, SkillLaunchEvent, UserFeedbackRating, UserFeedbackEvent, ExtensionDisableEvent;
var init_types = __esm({
  "packages/core/dist/src/telemetry/types.js"() {
    "use strict";
    init_esbuild_shims();
    init_mcp_tool();
    init_contentGenerator();
    init_tool_call_decision();
    init_tool_names();
    StartSessionEvent = class {
      static {
        __name(this, "StartSessionEvent");
      }
      "event.name";
      "event.timestamp";
      session_id;
      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;
      skills;
      subagents;
      constructor(config2) {
        const generatorConfig = config2.getContentGeneratorConfig();
        const mcpServers = config2.getMcpServers();
        const toolRegistry = config2.getToolRegistry();
        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.session_id = config2.getSessionId();
        this.model = config2.getModel();
        this.embedding_model = config2.getEmbeddingModel();
        this.sandbox_enabled = typeof config2.getSandbox() === "string" || !!config2.getSandbox();
        this.core_tools_enabled = (config2.getCoreTools() ?? []).join(",");
        this.approval_mode = config2.getApprovalMode();
        this.api_key_enabled = useGemini || useVertex;
        this.vertex_ai_enabled = useVertex;
        this.debug_enabled = config2.getDebugMode();
        this.mcp_servers = mcpServers ? Object.keys(mcpServers).join(",") : "";
        this.telemetry_enabled = config2.getTelemetryEnabled();
        this.telemetry_log_user_prompts_enabled = config2.getTelemetryLogPromptsEnabled();
        this.file_filtering_respect_git_ignore = config2.getFileFilteringRespectGitIgnore();
        this.mcp_servers_count = mcpServers ? Object.keys(mcpServers).length : 0;
        this.output_format = config2.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(",");
          const skillTool = toolRegistry.getTool(ToolNames.SKILL);
          const skillNames = skillTool?.getAvailableSkillNames?.();
          if (skillNames && skillNames.length > 0) {
            this.skills = skillNames.join(",");
          }
          const taskTool = toolRegistry.getTool(ToolNames.TASK);
          const subagentNames = taskTool?.getAvailableSubagentNames?.();
          if (subagentNames && subagentNames.length > 0) {
            this.subagents = subagentNames.join(",");
          }
        }
      }
    };
    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, error2, 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 = error2;
        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;
      }
    };
    RipgrepFallbackEvent = class {
      static {
        __name(this, "RipgrepFallbackEvent");
      }
      "event.name";
      "event.timestamp";
      use_ripgrep;
      use_builtin_ripgrep;
      error;
      constructor(use_ripgrep, use_builtin_ripgrep, error2) {
        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 = error2;
      }
    };
    (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;
      }
    };
    ExtensionUpdateEvent = class {
      static {
        __name(this, "ExtensionUpdateEvent");
      }
      "event.name";
      "event.timestamp";
      extension_name;
      extension_id;
      extension_previous_version;
      extension_version;
      extension_source;
      status;
      constructor(extension_name, extension_id, extension_version, extension_previous_version, extension_source, status) {
        this["event.name"] = "extension_update";
        this["event.timestamp"] = (/* @__PURE__ */ new Date()).toISOString();
        this.extension_name = extension_name;
        this.extension_id = extension_id;
        this.extension_version = extension_version;
        this.extension_previous_version = extension_previous_version;
        this.extension_source = extension_source;
        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;
      }
    };
    SkillLaunchEvent = class {
      static {
        __name(this, "SkillLaunchEvent");
      }
      "event.name";
      "event.timestamp";
      skill_name;
      success;
      constructor(skill_name, success) {
        this["event.name"] = "skill_launch";
        this["event.timestamp"] = (/* @__PURE__ */ new Date()).toISOString();
        this.skill_name = skill_name;
        this.success = success;
      }
    };
    (function(UserFeedbackRating2) {
      UserFeedbackRating2[UserFeedbackRating2["BAD"] = 1] = "BAD";
      UserFeedbackRating2[UserFeedbackRating2["FINE"] = 2] = "FINE";
      UserFeedbackRating2[UserFeedbackRating2["GOOD"] = 3] = "GOOD";
    })(UserFeedbackRating || (UserFeedbackRating = {}));
    UserFeedbackEvent = class {
      static {
        __name(this, "UserFeedbackEvent");
      }
      "event.name";
      "event.timestamp";
      session_id;
      rating;
      model;
      approval_mode;
      prompt_id;
      constructor(session_id, rating, model, approval_mode, prompt_id) {
        this["event.name"] = "user_feedback";
        this["event.timestamp"] = (/* @__PURE__ */ new Date()).toISOString();
        this.session_id = session_id;
        this.rating = rating;
        this.model = model;
        this.approval_mode = approval_mode;
        this.prompt_id = prompt_id;
      }
    };
    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 _a7;
        return (_a7 = this.getDelegateLogger(name3, version2, options2)) !== null && _a7 !== void 0 ? _a7 : new ProxyLogger_1.ProxyLogger(this, name3, version2, options2);
      }
      getDelegate() {
        var _a7;
        return (_a7 = this._delegate) !== null && _a7 !== void 0 ? _a7 : NoopLoggerProvider_1.NOOP_LOGGER_PROVIDER;
      }
      /**
       * Set the delegate logger provider
       */
      setDelegate(delegate) {
        this._delegate = delegate;
      }
      getDelegateLogger(name3, version2, options2) {
        var _a7;
        return (_a7 = this._delegate) === null || _a7 === void 0 ? void 0 : _a7.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 _a7, _b2;
        return (_b2 = (_a7 = global_utils_1._global[global_utils_1.GLOBAL_LOGS_API_KEY]) === null || _a7 === void 0 ? void 0 : _a7.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_EXTENSION_UPDATE, 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_SKILL_LAUNCH, EVENT_AUTH, EVENT_USER_FEEDBACK;
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_EXTENSION_UPDATE = "qwen-code.extension_update";
    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_SKILL_LAUNCH = "qwen-code.skill_launch";
    EVENT_AUTH = "qwen-code.auth";
    EVENT_USER_FEEDBACK = "qwen-code.user_feedback";
  }
});

// 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_version = __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(v2) {
    rejectedVersions.add(v2);
    return false;
  }
  __name(_reject, "_reject");
  function _accept(v2) {
    acceptedVersions.add(v2);
    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_version();
    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 _a7;
  if (allowOverride === void 0) {
    allowOverride = false;
  }
  var api = _global[GLOBAL_OPENTELEMETRY_API_KEY] = (_a7 = _global[GLOBAL_OPENTELEMETRY_API_KEY]) !== null && _a7 !== void 0 ? _a7 : {
    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 _a7, _b2;
  var globalVersion = (_a7 = _global[GLOBAL_OPENTELEMETRY_API_KEY]) === null || _a7 === void 0 ? void 0 : _a7.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_version();
    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(o3, n3) {
      var m3 = typeof Symbol === "function" && o3[Symbol.iterator];
      if (!m3) return o3;
      var i3 = m3.call(o3), r5, ar2 = [], e4;
      try {
        while ((n3 === void 0 || n3-- > 0) && !(r5 = i3.next()).done) ar2.push(r5.value);
      } catch (error2) {
        e4 = { error: error2 };
      } finally {
        try {
          if (r5 && !r5.done && (m3 = i3["return"])) m3.call(i3);
        } finally {
          if (e4) throw e4.error;
        }
      }
      return ar2;
    };
    __spreadArray = function(to, from, pack) {
      if (pack || arguments.length === 2) for (var i3 = 0, l3 = from.length, ar2; i3 < l3; i3++) {
        if (ar2 || !(i3 in from)) {
          if (!ar2) ar2 = Array.prototype.slice.call(from, 0, i3);
          ar2[i3] = from[i3];
        }
      }
      return to.concat(ar2 || 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_types2 = __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_types2();
    __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_types2();
    init_global_utils();
    __read2 = function(o3, n3) {
      var m3 = typeof Symbol === "function" && o3[Symbol.iterator];
      if (!m3) return o3;
      var i3 = m3.call(o3), r5, ar2 = [], e4;
      try {
        while ((n3 === void 0 || n3-- > 0) && !(r5 = i3.next()).done) ar2.push(r5.value);
      } catch (error2) {
        e4 = { error: error2 };
      } finally {
        try {
          if (r5 && !r5.done && (m3 = i3["return"])) m3.call(i3);
        } finally {
          if (e4) throw e4.error;
        }
      }
      return ar2;
    };
    __spreadArray2 = function(to, from, pack) {
      if (pack || arguments.length === 2) for (var i3 = 0, l3 = from.length, ar2; i3 < l3; i3++) {
        if (ar2 || !(i3 in from)) {
          if (!ar2) ar2 = Array.prototype.slice.call(from, 0, i3);
          ar2[i3] = from[i3];
        }
      }
      return to.concat(ar2 || 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 _a7, _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((_a7 = err.stack) !== null && _a7 !== void 0 ? _a7 : 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(o3, n3) {
      var m3 = typeof Symbol === "function" && o3[Symbol.iterator];
      if (!m3) return o3;
      var i3 = m3.call(o3), r5, ar2 = [], e4;
      try {
        while ((n3 === void 0 || n3-- > 0) && !(r5 = i3.next()).done) ar2.push(r5.value);
      } catch (error2) {
        e4 = { error: error2 };
      } finally {
        try {
          if (r5 && !r5.done && (m3 = i3["return"])) m3.call(i3);
        } finally {
          if (e4) throw e4.error;
        }
      }
      return ar2;
    };
    __values2 = function(o3) {
      var s5 = typeof Symbol === "function" && Symbol.iterator, m3 = s5 && o3[s5], i3 = 0;
      if (m3) return m3.call(o3);
      if (o3 && typeof o3.length === "number") return {
        next: /* @__PURE__ */ __name(function() {
          if (o3 && i3 >= o3.length) o3 = void 0;
          return { value: o3 && o3[i3++], done: !o3 };
        }, "next")
      };
      throw new TypeError(s5 ? "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(_a7) {
          var _b2 = __read3(_a7, 2), k2 = _b2[0], v2 = _b2[1];
          return [k2, v2];
        });
      };
      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, _a7;
        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 && (_a7 = keys_1.return)) _a7.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 i3 = 0; i3 < consoleMap.length; i3++) {
          this[consoleMap[i3].n] = _consoleFunc(consoleMap[i3].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(d2, b2) {
        extendStatics = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function(d3, b3) {
          d3.__proto__ = b3;
        } || function(d3, b3) {
          for (var p2 in b3) if (Object.prototype.hasOwnProperty.call(b3, p2)) d3[p2] = b3[p2];
        };
        return extendStatics(d2, b2);
      }, "extendStatics");
      return function(d2, b2) {
        if (typeof b2 !== "function" && b2 !== null)
          throw new TypeError("Class extends value " + String(b2) + " is not a constructor or null");
        extendStatics(d2, b2);
        function __() {
          this.constructor = d2;
        }
        __name(__, "__");
        d2.prototype = b2 === null ? Object.create(b2) : (__.prototype = b2.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(o3, n3) {
      var m3 = typeof Symbol === "function" && o3[Symbol.iterator];
      if (!m3) return o3;
      var i3 = m3.call(o3), r5, ar2 = [], e4;
      try {
        while ((n3 === void 0 || n3-- > 0) && !(r5 = i3.next()).done) ar2.push(r5.value);
      } catch (error2) {
        e4 = { error: error2 };
      } finally {
        try {
          if (r5 && !r5.done && (m3 = i3["return"])) m3.call(i3);
        } finally {
          if (e4) throw e4.error;
        }
      }
      return ar2;
    };
    __spreadArray3 = function(to, from, pack) {
      if (pack || arguments.length === 2) for (var i3 = 0, l3 = from.length, ar2; i3 < l3; i3++) {
        if (ar2 || !(i3 in from)) {
          if (!ar2) ar2 = Array.prototype.slice.call(from, 0, i3);
          ar2[i3] = from[i3];
        }
      }
      return to.concat(ar2 || 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(o3, n3) {
      var m3 = typeof Symbol === "function" && o3[Symbol.iterator];
      if (!m3) return o3;
      var i3 = m3.call(o3), r5, ar2 = [], e4;
      try {
        while ((n3 === void 0 || n3-- > 0) && !(r5 = i3.next()).done) ar2.push(r5.value);
      } catch (error2) {
        e4 = { error: error2 };
      } finally {
        try {
          if (r5 && !r5.done && (m3 = i3["return"])) m3.call(i3);
        } finally {
          if (e4) throw e4.error;
        }
      }
      return ar2;
    };
    __spreadArray4 = function(to, from, pack) {
      if (pack || arguments.length === 2) for (var i3 = 0, l3 = from.length, ar2; i3 < l3; i3++) {
        if (ar2 || !(i3 in from)) {
          if (!ar2) ar2 = Array.prototype.slice.call(from, 0, i3);
          ar2[i3] = from[i3];
        }
      }
      return to.concat(ar2 || 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 _a7;
        var args = [];
        for (var _i = 3; _i < arguments.length; _i++) {
          args[_i - 3] = arguments[_i];
        }
        return (_a7 = this._getContextManager()).with.apply(_a7, __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 _a7;
  return (_a7 = getSpan(context2)) === null || _a7 === void 0 ? void 0 : _a7.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 _a7;
        return (_a7 = this.getDelegateTracer(name3, version2, options2)) !== null && _a7 !== void 0 ? _a7 : new ProxyTracer(this, name3, version2, options2);
      };
      ProxyTracerProvider2.prototype.getDelegate = function() {
        var _a7;
        return (_a7 = this._delegate) !== null && _a7 !== void 0 ? _a7 : NOOP_TRACER_PROVIDER;
      };
      ProxyTracerProvider2.prototype.setDelegate = function(delegate) {
        this._delegate = delegate;
      };
      ProxyTracerProvider2.prototype.getDelegateTracer = function(name3, version2, options2) {
        var _a7;
        return (_a7 = this._delegate) === null || _a7 === void 0 ? void 0 : _a7.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 i3 = listMember.indexOf(LIST_MEMBER_KEY_VALUE_SPLITTER);
          if (i3 !== -1) {
            var key = listMember.slice(0, i3);
            var value = listMember.slice(i3 + 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_types2();
    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(config2) {
  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(config2));
  initializePerformanceMonitoring(config2);
  isMetricsInitialized = true;
}
function recordChatCompressionMetrics(config2, attributes) {
  if (!chatCompressionCounter || !isMetricsInitialized)
    return;
  chatCompressionCounter.add(1, {
    ...baseMetricDefinition.getCommonAttributes(config2),
    ...attributes
  });
}
function recordToolCallMetrics(config2, durationMs, attributes) {
  if (!toolCallCounter || !toolCallLatencyHistogram || !isMetricsInitialized)
    return;
  const metricAttributes = {
    ...baseMetricDefinition.getCommonAttributes(config2),
    ...attributes
  };
  toolCallCounter.add(1, metricAttributes);
  toolCallLatencyHistogram.record(durationMs, {
    ...baseMetricDefinition.getCommonAttributes(config2),
    function_name: attributes.function_name
  });
}
function recordTokenUsageMetrics(config2, tokenCount, attributes) {
  if (!tokenUsageCounter || !isMetricsInitialized)
    return;
  tokenUsageCounter.add(tokenCount, {
    ...baseMetricDefinition.getCommonAttributes(config2),
    ...attributes
  });
}
function recordApiResponseMetrics(config2, durationMs, attributes) {
  if (!apiRequestCounter || !apiRequestLatencyHistogram || !isMetricsInitialized)
    return;
  const metricAttributes = {
    ...baseMetricDefinition.getCommonAttributes(config2),
    model: attributes.model,
    status_code: attributes.status_code ?? "ok"
  };
  apiRequestCounter.add(1, metricAttributes);
  apiRequestLatencyHistogram.record(durationMs, {
    ...baseMetricDefinition.getCommonAttributes(config2),
    model: attributes.model
  });
}
function recordApiErrorMetrics(config2, durationMs, attributes) {
  if (!apiRequestCounter || !apiRequestLatencyHistogram || !isMetricsInitialized)
    return;
  const metricAttributes = {
    ...baseMetricDefinition.getCommonAttributes(config2),
    model: attributes.model,
    status_code: attributes.status_code ?? "error",
    error_type: attributes.error_type ?? "unknown"
  };
  apiRequestCounter.add(1, metricAttributes);
  apiRequestLatencyHistogram.record(durationMs, {
    ...baseMetricDefinition.getCommonAttributes(config2),
    model: attributes.model
  });
}
function recordFileOperationMetric(config2, attributes) {
  if (!fileOperationCounter || !isMetricsInitialized)
    return;
  fileOperationCounter.add(1, {
    ...baseMetricDefinition.getCommonAttributes(config2),
    ...attributes
  });
}
function recordContentRetry(config2) {
  if (!contentRetryCounter || !isMetricsInitialized)
    return;
  contentRetryCounter.add(1, baseMetricDefinition.getCommonAttributes(config2));
}
function recordContentRetryFailure(config2) {
  if (!contentRetryFailureCounter || !isMetricsInitialized)
    return;
  contentRetryFailureCounter.add(1, baseMetricDefinition.getCommonAttributes(config2));
}
function recordModelSlashCommand(config2, event) {
  if (!modelSlashCommandCallCounter || !isMetricsInitialized)
    return;
  modelSlashCommandCallCounter.add(1, {
    ...baseMetricDefinition.getCommonAttributes(config2),
    "slash_command.model.model_name": event.model_name
  });
}
function initializePerformanceMonitoring(config2) {
  const meter = getMeter();
  if (!meter)
    return;
  isPerformanceMonitoringEnabled = config2.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(config2, subagentName, status, terminateReason) {
  if (!subagentExecutionCounter || !isMetricsInitialized)
    return;
  const attributes = {
    ...baseMetricDefinition.getCommonAttributes(config2),
    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((config2) => ({
        "session.id": config2.getSessionId()
      }), "getCommonAttributes")
    };
    COUNTER_DEFINITIONS = {
      [TOOL_CALL_COUNT]: {
        description: "Counts tool calls, tagged by function name and success.",
        valueType: ValueType.INT,
        assign: /* @__PURE__ */ __name((c4) => toolCallCounter = c4, "assign"),
        attributes: {}
      },
      [API_REQUEST_COUNT]: {
        description: "Counts API requests, tagged by model and status.",
        valueType: ValueType.INT,
        assign: /* @__PURE__ */ __name((c4) => apiRequestCounter = c4, "assign"),
        attributes: {}
      },
      [TOKEN_USAGE]: {
        description: "Counts the total number of tokens used.",
        valueType: ValueType.INT,
        assign: /* @__PURE__ */ __name((c4) => tokenUsageCounter = c4, "assign"),
        attributes: {}
      },
      [SESSION_COUNT]: {
        description: "Count of CLI sessions started.",
        valueType: ValueType.INT,
        assign: /* @__PURE__ */ __name((c4) => sessionCounter = c4, "assign"),
        attributes: {}
      },
      [FILE_OPERATION_COUNT]: {
        description: "Counts file operations (create, read, update).",
        valueType: ValueType.INT,
        assign: /* @__PURE__ */ __name((c4) => fileOperationCounter = c4, "assign"),
        attributes: {}
      },
      [INVALID_CHUNK_COUNT]: {
        description: "Counts invalid chunks received from a stream.",
        valueType: ValueType.INT,
        assign: /* @__PURE__ */ __name((c4) => invalidChunkCounter = c4, "assign"),
        attributes: {}
      },
      [CONTENT_RETRY_COUNT]: {
        description: "Counts retries due to content errors (e.g., empty stream).",
        valueType: ValueType.INT,
        assign: /* @__PURE__ */ __name((c4) => contentRetryCounter = c4, "assign"),
        attributes: {}
      },
      [CONTENT_RETRY_FAILURE_COUNT]: {
        description: "Counts occurrences of all content retries failing.",
        valueType: ValueType.INT,
        assign: /* @__PURE__ */ __name((c4) => contentRetryFailureCounter = c4, "assign"),
        attributes: {}
      },
      [MODEL_SLASH_COMMAND_CALL_COUNT]: {
        description: "Counts model slash command calls.",
        valueType: ValueType.INT,
        assign: /* @__PURE__ */ __name((c4) => modelSlashCommandCallCounter = c4, "assign"),
        attributes: {}
      },
      [EVENT_CHAT_COMPRESSION]: {
        description: "Counts chat compression events.",
        valueType: ValueType.INT,
        assign: /* @__PURE__ */ __name((c4) => chatCompressionCounter = c4, "assign"),
        attributes: {}
      }
    };
    HISTOGRAM_DEFINITIONS = {
      [TOOL_CALL_LATENCY]: {
        description: "Latency of tool calls in milliseconds.",
        unit: "ms",
        valueType: ValueType.INT,
        assign: /* @__PURE__ */ __name((h3) => toolCallLatencyHistogram = h3, "assign"),
        attributes: {}
      },
      [API_REQUEST_LATENCY]: {
        description: "Latency of API requests in milliseconds.",
        unit: "ms",
        valueType: ValueType.INT,
        assign: /* @__PURE__ */ __name((h3) => apiRequestLatencyHistogram = h3, "assign"),
        attributes: {}
      }
    };
    PERFORMANCE_COUNTER_DEFINITIONS = {
      [REGRESSION_DETECTION]: {
        description: "Performance regression detection events.",
        valueType: ValueType.INT,
        assign: /* @__PURE__ */ __name((c4) => regressionDetectionCounter = c4, "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((h3) => startupTimeHistogram = h3, "assign"),
        attributes: {}
      },
      [MEMORY_USAGE]: {
        description: "Memory usage in bytes.",
        unit: "bytes",
        valueType: ValueType.INT,
        assign: /* @__PURE__ */ __name((h3) => memoryUsageGauge = h3, "assign"),
        attributes: {}
      },
      [CPU_USAGE]: {
        description: "CPU usage percentage.",
        unit: "percent",
        valueType: ValueType.DOUBLE,
        assign: /* @__PURE__ */ __name((h3) => cpuUsageGauge = h3, "assign"),
        attributes: {}
      },
      [TOOL_QUEUE_DEPTH]: {
        description: "Number of tools in execution queue.",
        unit: "count",
        valueType: ValueType.INT,
        assign: /* @__PURE__ */ __name((h3) => toolQueueDepthGauge = h3, "assign"),
        attributes: {}
      },
      [TOOL_EXECUTION_BREAKDOWN]: {
        description: "Tool execution time breakdown by phase in milliseconds.",
        unit: "ms",
        valueType: ValueType.INT,
        assign: /* @__PURE__ */ __name((h3) => toolExecutionBreakdownHistogram = h3, "assign"),
        attributes: {}
      },
      [TOKEN_EFFICIENCY]: {
        description: "Token efficiency metrics (tokens per operation, cache hit rate, etc.).",
        unit: "ratio",
        valueType: ValueType.DOUBLE,
        assign: /* @__PURE__ */ __name((h3) => tokenEfficiencyHistogram = h3, "assign"),
        attributes: {}
      },
      [API_REQUEST_BREAKDOWN]: {
        description: "API request time breakdown by phase in milliseconds.",
        unit: "ms",
        valueType: ValueType.INT,
        assign: /* @__PURE__ */ __name((h3) => apiRequestBreakdownHistogram = h3, "assign"),
        attributes: {}
      },
      [PERFORMANCE_SCORE]: {
        description: "Composite performance score (0-100).",
        unit: "score",
        valueType: ValueType.DOUBLE,
        assign: /* @__PURE__ */ __name((h3) => performanceScoreGauge = h3, "assign"),
        attributes: {}
      },
      [REGRESSION_PERCENTAGE_CHANGE]: {
        description: "Percentage change compared to baseline for detected regressions.",
        unit: "percent",
        valueType: ValueType.DOUBLE,
        assign: /* @__PURE__ */ __name((h3) => regressionPercentageChangeHistogram = h3, "assign"),
        attributes: {}
      },
      [BASELINE_COMPARISON]: {
        description: "Performance comparison to established baseline (percentage change).",
        unit: "percent",
        valueType: ValueType.DOUBLE,
        assign: /* @__PURE__ */ __name((h3) => baselineComparisonHistogram = h3, "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 fs6 from "node:fs";
import { randomUUID } from "node:crypto";
import * as path4 from "node:path";
var debugLogger3, InstallationManager;
var init_installationManager = __esm({
  "packages/core/dist/src/utils/installationManager.js"() {
    "use strict";
    init_esbuild_shims();
    init_storage();
    init_debugLogger();
    debugLogger3 = createDebugLogger("INSTALLATION");
    InstallationManager = class {
      static {
        __name(this, "InstallationManager");
      }
      getInstallationIdPath() {
        return Storage.getInstallationIdPath();
      }
      readInstallationIdFromFile() {
        const installationIdFile = this.getInstallationIdPath();
        if (fs6.existsSync(installationIdFile)) {
          const installationid = fs6.readFileSync(installationIdFile, "utf-8").trim();
          return installationid || null;
        }
        return null;
      }
      writeInstallationIdToFile(installationId) {
        const installationIdFile = this.getInstallationIdPath();
        const dir = path4.dirname(installationIdFile);
        fs6.mkdirSync(dir, { recursive: true });
        fs6.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 = randomUUID();
            this.writeInstallationIdToFile(installationId);
          }
          return installationId;
        } catch (error2) {
          debugLogger3.error("Error accessing installation ID file, generating ephemeral ID:", error2);
          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(a2, b2) {
      if (a2 < b2)
        return -1;
      if (a2 > b2)
        return 1;
      return 0;
    }, "DEFAULT_COMPARATOR");
    var DEFAULT_REVERSE_COMPARATOR = /* @__PURE__ */ __name(function(a2, b2) {
      if (a2 < b2)
        return 1;
      if (a2 > b2)
        return -1;
      return 0;
    }, "DEFAULT_REVERSE_COMPARATOR");
    function reverseComparator(comparator) {
      return function(a2, b2) {
        return comparator(b2, a2);
      };
    }
    __name(reverseComparator, "reverseComparator");
    function createTupleComparator(size) {
      if (size === 2) {
        return function(a2, b2) {
          if (a2[0] < b2[0])
            return -1;
          if (a2[0] > b2[0])
            return 1;
          if (a2[1] < b2[1])
            return -1;
          if (a2[1] > b2[1])
            return 1;
          return 0;
        };
      }
      return function(a2, b2) {
        var i3 = 0;
        while (i3 < size) {
          if (a2[i3] < b2[i3])
            return -1;
          if (a2[i3] > b2[i3])
            return 1;
          i3++;
        }
        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, k2, i3, l3, s5;
      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 (i3 = 0, l3 = iterable.length; i3 < l3; i3++) callback(iterable[i3], i3);
        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;
        i3 = 0;
        while (s5 = iterator.next(), s5.done !== true) {
          callback(s5.value, i3);
          i3++;
        }
        return;
      }
      for (k2 in iterable) {
        if (iterable.hasOwnProperty(k2)) {
          callback(iterable[k2], k2);
        }
      }
      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, y2, x3) {
      removeFromRoot(heap, y2);
      y2.left = y2;
      y2.right = y2;
      mergeWithChild(x3, y2);
      x3.degree++;
      y2.parent = x3;
    }
    __name(link3, "link");
    function consolidate(heap) {
      var A4 = new Array(heap.size), nodes = consumeLinkedList(heap.root), i3, l3, x3, y2, d2, t5;
      for (i3 = 0, l3 = nodes.length; i3 < l3; i3++) {
        x3 = nodes[i3];
        d2 = x3.degree;
        while (A4[d2]) {
          y2 = A4[d2];
          if (heap.comparator(x3.item, y2.item) > 0) {
            t5 = x3;
            x3 = y2;
            y2 = t5;
          }
          link3(heap, y2, x3);
          A4[d2] = null;
          d2++;
        }
        A4[d2] = x3;
      }
      for (i3 = 0; i3 < heap.size; i3++) {
        if (A4[i3] && heap.comparator(A4[i3].item, heap.min.item) <= 0)
          heap.min = A4[i3];
      }
    }
    __name(consolidate, "consolidate");
    FibonacciHeap2.prototype.pop = function() {
      if (!this.size)
        return void 0;
      var z2 = this.min;
      if (z2.child) {
        var nodes = consumeLinkedList(z2.child), node, i3, l3;
        for (i3 = 0, l3 = nodes.length; i3 < l3; i3++) {
          node = nodes[i3];
          mergeWithRoot(this, node);
          delete node.parent;
        }
      }
      removeFromRoot(this, z2);
      if (z2 === z2.right) {
        this.min = null;
        this.root = null;
      } else {
        this.min = z2.right;
        consolidate(this);
      }
      this.size--;
      return z2.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(array2, getter) {
      var maxType = null, maxPriority = 0, p2, t5, v2, i3, l3;
      for (i3 = 0, l3 = array2.length; i3 < l3; i3++) {
        v2 = getter ? getter(array2[i3]) : array2[i3];
        t5 = exports2.getNumberType(v2);
        p2 = TYPE_PRIORITY[t5.name];
        if (p2 > maxPriority) {
          maxPriority = p2;
          maxType = t5;
        }
      }
      return maxType;
    };
    exports2.isTypedArray = function(value) {
      return typeof ArrayBuffer !== "undefined" && ArrayBuffer.isView(value);
    };
    exports2.concat = function() {
      var length = 0, i3, o3, l3;
      for (i3 = 0, l3 = arguments.length; i3 < l3; i3++)
        length += arguments[i3].length;
      var array2 = new arguments[0].constructor(length);
      for (i3 = 0, o3 = 0; i3 < l3; i3++) {
        array2.set(arguments[i3], o3);
        o3 += arguments[i3].length;
      }
      return array2;
    };
    exports2.indices = function(length) {
      var PointerArray = exports2.getPointerArray(length);
      var array2 = new PointerArray(length);
      for (var i3 = 0; i3 < length; i3++)
        array2[i3] = i3;
      return array2;
    };
  }
});

// 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 l3 = guessLength(target);
      var array2 = typeof l3 === "number" ? new Array(l3) : [];
      var i3 = 0;
      forEach2(target, function(value) {
        array2[i3++] = value;
      });
      return array2;
    }
    __name(toArray, "toArray");
    function toArrayWithIndices(target) {
      var l3 = guessLength(target);
      var IndexArray = typeof l3 === "number" ? typed.getPointerArray(l3) : Array;
      var array2 = typeof l3 === "number" ? new Array(l3) : [];
      var indices = typeof l3 === "number" ? new IndexArray(l3) : [];
      var i3 = 0;
      forEach2(target, function(value) {
        array2[i3] = value;
        indices[i3] = i3++;
      });
      return [array2, 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, i3) {
      var item = heap[i3], parentIndex, parent;
      while (i3 > startIndex) {
        parentIndex = i3 - 1 >> 1;
        parent = heap[parentIndex];
        if (compare(item, parent) < 0) {
          heap[i3] = parent;
          i3 = parentIndex;
          continue;
        }
        break;
      }
      heap[i3] = item;
    }
    __name(siftDown, "siftDown");
    function siftUp(compare, heap, i3) {
      var endIndex = heap.length, startIndex = i3, item = heap[i3], childIndex = 2 * i3 + 1, rightIndex;
      while (childIndex < endIndex) {
        rightIndex = childIndex + 1;
        if (rightIndex < endIndex && compare(heap[childIndex], heap[rightIndex]) >= 0) {
          childIndex = rightIndex;
        }
        heap[i3] = heap[childIndex];
        i3 = childIndex;
        childIndex = 2 * i3 + 1;
      }
      heap[i3] = item;
      siftDown(compare, heap, startIndex, i3);
    }
    __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, array2) {
      var n3 = array2.length, l3 = n3 >> 1, i3 = l3;
      while (--i3 >= 0)
        siftUp(compare, array2, i3);
    }
    __name(heapify, "heapify");
    function consume(compare, heap) {
      var l3 = heap.length, i3 = 0;
      var array2 = new Array(l3);
      while (i3 < l3)
        array2[i3++] = pop(compare, heap);
      return array2;
    }
    __name(consume, "consume");
    function nsmallest(compare, n3, iterable) {
      if (arguments.length === 2) {
        iterable = n3;
        n3 = compare;
        compare = DEFAULT_COMPARATOR;
      }
      var reverseCompare = reverseComparator(compare);
      var i3, l3, v2;
      var min = Infinity;
      var result;
      if (n3 === 1) {
        if (iterables.isArrayLike(iterable)) {
          for (i3 = 0, l3 = iterable.length; i3 < l3; i3++) {
            v2 = iterable[i3];
            if (min === Infinity || compare(v2, min) < 0)
              min = v2;
          }
          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 (n3 >= iterable.length)
          return iterable.slice().sort(compare);
        result = iterable.slice(0, n3);
        heapify(reverseCompare, result);
        for (i3 = n3, l3 = iterable.length; i3 < l3; i3++)
          if (reverseCompare(iterable[i3], result[0]) > 0)
            replace2(reverseCompare, result, iterable[i3]);
        return result.sort(compare);
      }
      var size = iterables.guessLength(iterable);
      if (size !== null && size < n3)
        n3 = size;
      result = new Array(n3);
      i3 = 0;
      forEach2(iterable, function(value) {
        if (i3 < n3) {
          result[i3] = value;
        } else {
          if (i3 === n3)
            heapify(reverseCompare, result);
          if (reverseCompare(value, result[0]) > 0)
            replace2(reverseCompare, result, value);
        }
        i3++;
      });
      if (result.length > i3)
        result.length = i3;
      return result.sort(compare);
    }
    __name(nsmallest, "nsmallest");
    function nlargest(compare, n3, iterable) {
      if (arguments.length === 2) {
        iterable = n3;
        n3 = compare;
        compare = DEFAULT_COMPARATOR;
      }
      var reverseCompare = reverseComparator(compare);
      var i3, l3, v2;
      var max = -Infinity;
      var result;
      if (n3 === 1) {
        if (iterables.isArrayLike(iterable)) {
          for (i3 = 0, l3 = iterable.length; i3 < l3; i3++) {
            v2 = iterable[i3];
            if (max === -Infinity || compare(v2, max) > 0)
              max = v2;
          }
          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 (n3 >= iterable.length)
          return iterable.slice().sort(reverseCompare);
        result = iterable.slice(0, n3);
        heapify(compare, result);
        for (i3 = n3, l3 = iterable.length; i3 < l3; i3++)
          if (compare(iterable[i3], result[0]) > 0)
            replace2(compare, result, iterable[i3]);
        return result.sort(reverseCompare);
      }
      var size = iterables.guessLength(iterable);
      if (size !== null && size < n3)
        n3 = size;
      result = new Array(n3);
      i3 = 0;
      forEach2(iterable, function(value) {
        if (i3 < n3) {
          result[i3] = value;
        } else {
          if (i3 === n3)
            heapify(compare, result);
          if (compare(value, result[0]) > 0)
            replace2(compare, result, value);
        }
        i3++;
      });
      if (result.length > i3)
        result.length = i3;
      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(string4, array2, offset) {
      var l3 = array2.length, buckets = [], i3 = l3, j2 = -1, b2, d2 = 0, bits;
      while (i3--)
        j2 = Math.max(string4[array2[i3] + offset], j2);
      bits = j2 >> 24 && 32 || j2 >> 16 && 24 || j2 >> 8 && 16 || 8;
      for (; d2 < bits; d2 += 4) {
        for (i3 = 16; i3--; )
          buckets[i3] = [];
        for (i3 = l3; i3--; )
          buckets[string4[array2[i3] + offset] >> d2 & 15].push(array2[i3]);
        for (b2 = 0; b2 < 16; b2++) {
          for (j2 = buckets[b2].length; j2--; )
            array2[++i3] = buckets[b2][j2];
        }
      }
    }
    __name(sort, "sort");
    function compare(string4, lookup, m3, n3) {
      return string4[m3] - string4[n3] || (m3 % 3 === 2 ? string4[m3 + 1] - string4[n3 + 1] || lookup[m3 + 2] - lookup[n3 + 2] : lookup[m3 + 1] - lookup[n3 + 1]);
    }
    __name(compare, "compare");
    function build(string4, l3) {
      var a2 = [], b2 = [], al = 2 * l3 / 3 | 0, bl = l3 - al, r5 = al + 1 >> 1, i3 = al, j2 = 0, k2, lookup = [], result = [];
      if (l3 === 1)
        return [0];
      while (i3--)
        a2[i3] = (i3 * 3 >> 1) + 1;
      for (i3 = 3; i3--; )
        sort(string4, a2, i3);
      j2 = b2[(a2[0] / 3 | 0) + (a2[0] % 3 === 1 ? 0 : r5)] = 1;
      for (i3 = 1; i3 < al; i3++) {
        if (string4[a2[i3]] !== string4[a2[i3 - 1]] || string4[a2[i3] + 1] !== string4[a2[i3 - 1] + 1] || string4[a2[i3] + 2] !== string4[a2[i3 - 1] + 2])
          j2++;
        b2[(a2[i3] / 3 | 0) + (a2[i3] % 3 === 1 ? 0 : r5)] = j2;
      }
      if (j2 < al) {
        b2 = build(b2, al);
        for (i3 = al; i3--; )
          a2[i3] = b2[i3] < r5 ? b2[i3] * 3 + 1 : (b2[i3] - r5) * 3 + 2;
      }
      for (i3 = al; i3--; )
        lookup[a2[i3]] = i3;
      lookup[l3] = -1;
      lookup[l3 + 1] = -2;
      b2 = l3 % 3 === 1 ? [l3 - 1] : [];
      for (i3 = 0; i3 < al; i3++) {
        if (a2[i3] % 3 === 1)
          b2.push(a2[i3] - 1);
      }
      sort(string4, b2, 0);
      for (i3 = 0, j2 = 0, k2 = 0; i3 < al && j2 < bl; )
        result[k2++] = compare(string4, lookup, a2[i3], b2[j2]) < 0 ? a2[i3++] : b2[j2++];
      while (i3 < al)
        result[k2++] = a2[i3++];
      while (j2 < bl)
        result[k2++] = b2[j2++];
      return result;
    }
    __name(build, "build");
    function convert2(target) {
      var length = target.length, paddingOffset = length % 3, array2 = new Array(length + paddingOffset), l3, i3;
      if (typeof target !== "string") {
        var uniqueTokens = /* @__PURE__ */ Object.create(null);
        for (i3 = 0; i3 < length; i3++) {
          if (!uniqueTokens[target[i3]])
            uniqueTokens[target[i3]] = true;
        }
        var alphabet2 = /* @__PURE__ */ Object.create(null), sortedUniqueTokens = Object.keys(uniqueTokens).sort();
        for (i3 = 0, l3 = sortedUniqueTokens.length; i3 < l3; i3++)
          alphabet2[sortedUniqueTokens[i3]] = i3 + 1;
        for (i3 = 0; i3 < length; i3++) {
          array2[i3] = alphabet2[target[i3]];
        }
      } else {
        for (i3 = 0; i3 < length; i3++)
          array2[i3] = target.charCodeAt(i3);
      }
      for (i3 = length; i3 < length + paddingOffset; i3++)
        array2[i3] = 0;
      return array2;
    }
    __name(convert2, "convert");
    function SuffixArray2(string4) {
      this.hasArbitrarySequence = typeof string4 !== "string";
      this.string = string4;
      this.length = string4.length;
      this.array = build(convert2(string4), 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 array2 = new Array(this.length);
      for (var i3 = 0; i3 < this.length; i3++)
        array2[i3] = this.string.slice(this.array[i3]);
      Object.defineProperty(array2, "constructor", {
        value: SuffixArray2,
        enumerable: false
      });
      return array2;
    };
    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 i3 = 0, l3 = this.size; i3 < l3; i3++) {
          this.text.push.apply(this.text, strings[i3]);
          if (i3 < l3 - 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, i3, j2, s5, t5;
      for (i3 = 1; i3 < this.length; i3++) {
        s5 = this.array[i3];
        t5 = this.array[i3 - 1];
        if (s5 < this.firstLength && t5 < this.firstLength)
          continue;
        if (s5 > this.firstLength && t5 > this.firstLength)
          continue;
        lcp = Math.min(this.length - s5, this.length - t5);
        for (j2 = 0; j2 < lcp; j2++) {
          if (this.text[s5 + j2] !== this.text[t5 + j2]) {
            lcp = j2;
            break;
          }
        }
        if (lcp > lcs.length)
          lcs = this.text.slice(s5, s5 + lcp);
      }
      return lcs;
    };
    GeneralizedSuffixArray2.prototype.toString = function() {
      return this.array.join(",");
    };
    GeneralizedSuffixArray2.prototype.toJSON = function() {
      return this.array;
    };
    GeneralizedSuffixArray2.prototype.inspect = function() {
      var array2 = new Array(this.length);
      for (var i3 = 0; i3 < this.length; i3++)
        array2[i3] = this.text.slice(this.array[i3]);
      Object.defineProperty(array2, "constructor", {
        value: GeneralizedSuffixArray2,
        enumerable: false
      });
      return array2;
    };
    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, l3 = args.length, i3 = 0;
      return new Iterator(function() {
        if (i3 >= l3) return { done: true };
        return { done: false, value: args[i3++] };
      });
    };
    Iterator.empty = function() {
      var iterator = new Iterator(function() {
        return { done: true };
      });
      return iterator;
    };
    Iterator.fromSequence = function(sequence) {
      var i3 = 0, l3 = sequence.length;
      return new Iterator(function() {
        if (i3 >= l3) return { done: true };
        return { done: false, value: sequence[i3++] };
      });
    };
    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 i3 = 0, l3 = this.length; i3 < l3; i3++)
            this.array[i3] = oldArray[i3];
        }
      } 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, l3 = this.length, i3 = 0;
      return new Iterator(function() {
        if (i3 >= l3)
          return {
            done: true
          };
        var value = items[i3];
        i3++;
        return {
          value,
          done: false
        };
      });
    };
    Vector2.prototype.entries = function() {
      var items = this.array, l3 = this.length, i3 = 0;
      return new Iterator(function() {
        if (i3 >= l3)
          return {
            done: true
          };
        var value = items[i3];
        return {
          value: [i3++, 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 k2 in Vector2.prototype) {
        if (Vector2.prototype.hasOwnProperty(k2))
          SubClass.prototype[k2] = Vector2.prototype[k2];
      }
      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 c4 = this.capacity, l3 = this.size, i3 = this.start, j2 = 0;
      while (j2 < l3) {
        callback.call(scope, this.items[i3], j2, this);
        i3++;
        j2++;
        if (i3 === c4)
          i3 = 0;
      }
    };
    FixedDeque.prototype.toArray = function() {
      var offset = this.start + this.size;
      if (offset < this.capacity)
        return this.items.slice(this.start, offset);
      var array2 = new this.ArrayClass(this.size), c4 = this.capacity, l3 = this.size, i3 = this.start, j2 = 0;
      while (j2 < l3) {
        array2[j2] = this.items[i3];
        i3++;
        j2++;
        if (i3 === c4)
          i3 = 0;
      }
      return array2;
    };
    FixedDeque.prototype.values = function() {
      var items = this.items, c4 = this.capacity, l3 = this.size, i3 = this.start, j2 = 0;
      return new Iterator(function() {
        if (j2 >= l3)
          return {
            done: true
          };
        var value = items[i3];
        i3++;
        j2++;
        if (i3 === c4)
          i3 = 0;
        return {
          value,
          done: false
        };
      });
    };
    FixedDeque.prototype.entries = function() {
      var items = this.items, c4 = this.capacity, l3 = this.size, i3 = this.start, j2 = 0;
      return new Iterator(function() {
        if (j2 >= l3)
          return {
            done: true
          };
        var value = items[i3];
        i3++;
        if (i3 === c4)
          i3 = 0;
        return {
          value: [j2++, value],
          done: false
        };
      });
    };
    if (typeof Symbol !== "undefined")
      FixedDeque.prototype[Symbol.iterator] = FixedDeque.prototype.values;
    FixedDeque.prototype.inspect = function() {
      var array2 = this.toArray();
      array2.type = this.ArrayClass.name;
      array2.capacity = this.capacity;
      Object.defineProperty(array2, "constructor", {
        value: FixedDeque,
        enumerable: false
      });
      return array2;
    };
    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 i3, l3;
        for (i3 = 0, l3 = iterable.length; i3 < l3; i3++)
          deque.items[i3] = iterable[i3];
        deque.size = l3;
        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 Buffer4 } from "buffer";
import * as https2 from "https";
import * as os3 from "node:os";
import fs7 from "node:fs";
import path5 from "node:path";
var import_https_proxy_agent, USAGE_STATS_HOSTNAME, USAGE_STATS_PATH, RUN_APP_ID, FLUSH_INTERVAL_MS, ERROR_LOG_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_debugLogger();
    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;
    ERROR_LOG_INTERVAL_MS = 5 * 60 * 1e3;
    MAX_EVENTS = 1e3;
    MAX_RETRY_EVENTS = 100;
    QwenLogger = class _QwenLogger {
      static {
        __name(this, "QwenLogger");
      }
      static instance;
      config;
      debugLogger;
      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;
      /**
       * Cached source information read from source.json.
       * Only read once at session start to avoid repeated file I/O.
       */
      sourceInfo = "";
      /**
       * 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;
      /**
       * Timestamp of the last network error log to prevent log spam.
       */
      lastErrorLogTime = 0;
      constructor(config2) {
        this.config = config2;
        this.debugLogger = createDebugLogger("QWEN_LOGGER");
        this.events = new import_fixed_deque.default(Array, MAX_EVENTS);
        this.installationManager = new InstallationManager();
        this.userId = this.generateUserId();
        this.sessionId = config2.getSessionId();
        this.sourceInfo = this.readSourceInfo();
      }
      generateUserId() {
        const installationId = this.installationManager.getInstallationId();
        return `user-${installationId ?? "unknown"}`;
      }
      static getInstance(config2) {
        if (config2 === void 0 || !config2?.getUsageStatisticsEnabled())
          return void 0;
        if (!_QwenLogger.instance) {
          _QwenLogger.instance = new _QwenLogger(config2);
        }
        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.debugLogger.debug(`QwenLogger: Dropped old event to prevent memory leak (queue size: ${this.events.size})`);
          }
        } catch (error2) {
          this.debugLogger.error("QwenLogger: Failed to enqueue log event.", error2);
        }
      }
      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: os3.platform(),
          version: os3.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",
            channel: this.sourceInfo || void 0
          },
          user: {
            id: this.userId
          },
          session: {
            id: this.sessionId || this.config?.getSessionId()
          },
          view: {
            id: this.sessionId || this.config?.getSessionId(),
            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 || "" : "",
            ...this.config?.getChannel?.() ? { channel: this.config.getChannel() } : {}
          },
          _v: `qwen-code@${version2}`
        };
      }
      flushIfNeeded() {
        if (Date.now() - this.lastFlushTime < FLUSH_INTERVAL_MS) {
          return;
        }
        void this.flushToRum();
      }
      readSourceInfo() {
        try {
          const sourceJsonPath = path5.join(os3.homedir(), ".qwen", "source.json");
          if (fs7.existsSync(sourceJsonPath)) {
            const sourceJsonContent = fs7.readFileSync(sourceJsonPath, "utf8");
            const sourceData = JSON.parse(sourceJsonContent);
            if (sourceData && typeof sourceData === "object" && sourceData.source && sourceData.source !== "unknown") {
              return sourceData.source;
            }
          }
        } catch (_error) {
        }
        return "";
      }
      async flushToRum() {
        if (this.isFlushInProgress) {
          this.debugLogger.debug("QwenLogger: Flush already in progress, marking pending flush.");
          this.pendingFlush = true;
          return Promise.resolve({});
        }
        this.isFlushInProgress = true;
        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((resolve30, reject) => {
            const body = safeJsonStringify(rumPayload);
            const options2 = {
              hostname: USAGE_STATS_HOSTNAME,
              path: USAGE_STATS_PATH,
              method: "POST",
              headers: {
                "Content-Length": Buffer4.byteLength(body),
                "Content-Type": "text/plain;charset=UTF-8"
              }
            };
            const bufs = [];
            const req = https2.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", () => resolve30(Buffer4.concat(bufs)));
            });
            req.on("error", reject);
            req.end(body);
          });
          this.lastFlushTime = Date.now();
          return {};
        } catch (error2) {
          const now = Date.now();
          if (now - this.lastErrorLogTime > ERROR_LOG_INTERVAL_MS) {
            this.debugLogger.error("RUM flush failed.", error2);
            this.lastErrorLogTime = now;
          }
          this.requeueFailedEvents(eventsToSend);
          return {};
        } finally {
          this.isFlushInProgress = false;
          if (this.pendingFlush) {
            this.pendingFlush = false;
            void this.flushToRum();
          }
        }
      }
      // session events
      async logStartSessionEvent(event) {
        await this.flushToRum();
        this.events.clear();
        this.sessionId = event.session_id;
        this.sourceInfo = this.readSourceInfo();
        const applicationEvent = this.createViewEvent("session", "session_start", {
          properties: {
            model: event.model,
            approval_mode: event.approval_mode,
            embedding_model: event.embedding_model,
            sandbox_enabled: event.sandbox_enabled,
            core_tools_enabled: event.core_tools_enabled,
            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,
            skills: event.skills,
            subagents: event.subagents
          }
        });
        this.enqueueLogEvent(applicationEvent);
        void this.flushToRum();
      }
      logEndSessionEvent(_event) {
        const applicationEvent = this.createViewEvent("session", "session_end", {});
        this.enqueueLogEvent(applicationEvent);
        void this.flushToRum();
      }
      logConversationFinishedEvent(event) {
        const rumEvent = this.createActionEvent("conversation", "conversation_finished", {
          properties: {
            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,
            prompt_length: event.prompt_length
          }
        });
        this.enqueueLogEvent(rumEvent);
        this.flushIfNeeded();
      }
      logSlashCommandEvent(event) {
        const rumEvent = this.createActionEvent("user", "slash_command", {
          properties: {
            command: event.command,
            subcommand: event.subcommand
          }
        });
        this.enqueueLogEvent(rumEvent);
        this.flushIfNeeded();
      }
      logModelSlashCommandEvent(event) {
        const rumEvent = this.createActionEvent("user", "model_slash_command", {
          properties: {
            model: 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,
            tool_name: event.function_name,
            permission: event.decision,
            success: event.success ? 1 : 0,
            duration_ms: event.duration_ms,
            error_type: event.error_type,
            error_message: event.error
          }
        });
        this.enqueueLogEvent(rumEvent);
        this.flushIfNeeded();
      }
      logFileOperationEvent(event) {
        const rumEvent = this.createActionEvent("tool", `file_operation#${event.tool_name}`, {
          properties: {
            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", {
          properties: {
            subagent_name: event.subagent_name,
            status: event.status,
            terminate_reason: event.terminate_reason
          },
          snapshots: JSON.stringify({
            ...event.execution_summary ? { execution_summary: event.execution_summary } : {}
          })
        });
        this.enqueueLogEvent(rumEvent);
        this.flushIfNeeded();
      }
      logToolOutputTruncatedEvent(event) {
        const rumEvent = this.createActionEvent("tool", "tool_output_truncated", {
          properties: {
            tool_name: event.tool_name
          },
          snapshots: JSON.stringify({
            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,
            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`,
          properties: {
            error_type: event.final_error_type,
            total_attempts: event.total_attempts,
            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,
            error_type: event.loop_type
          }
        });
        this.enqueueLogEvent(rumEvent);
        this.flushIfNeeded();
      }
      logKittySequenceOverflowEvent(event) {
        const rumEvent = this.createExceptionEvent("overflow", "kitty_sequence_overflow", {
          subtype: "kitty_sequence_overflow",
          properties: {
            sequence_length: event.sequence_length
          },
          snapshots: JSON.stringify({
            truncated_sequence: event.truncated_sequence
          })
        });
        this.enqueueLogEvent(rumEvent);
        this.flushIfNeeded();
      }
      // ide events
      logIdeConnectionEvent(event) {
        const rumEvent = this.createActionEvent("ide", "ide_connection", {
          properties: {
            connection_type: event.connection_type
          }
        });
        this.enqueueLogEvent(rumEvent);
        this.flushIfNeeded();
      }
      // extension events
      logExtensionInstallEvent(event) {
        const rumEvent = this.createActionEvent("extension", "extension_install", {
          properties: {
            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", {
          properties: {
            extension_name: event.extension_name,
            status: event.status
          }
        });
        this.enqueueLogEvent(rumEvent);
        this.flushIfNeeded();
      }
      logExtensionUpdateEvent(event) {
        const rumEvent = this.createActionEvent("extension", "extension_update", {
          properties: {
            extension_name: event.extension_name,
            status: event.status,
            extension_id: event.extension_id,
            extension_previous_version: event.extension_previous_version,
            extension_version: event.extension_version,
            extension_source: event.extension_source
          }
        });
        this.enqueueLogEvent(rumEvent);
        this.flushIfNeeded();
      }
      logExtensionEnableEvent(event) {
        const rumEvent = this.createActionEvent("extension", "extension_enable", {
          properties: {
            extension_name: event.extension_name,
            setting_scope: event.setting_scope
          }
        });
        this.enqueueLogEvent(rumEvent);
        this.flushIfNeeded();
      }
      logExtensionDisableEvent(event) {
        const rumEvent = this.createActionEvent("extension", "extension_disable", {
          properties: {
            extension_name: event.extension_name,
            setting_scope: event.setting_scope
          }
        });
        this.enqueueLogEvent(rumEvent);
        this.flushIfNeeded();
      }
      logAuthEvent(event) {
        const rumEvent = this.createActionEvent("auth", "auth", {
          properties: {
            auth_type: event.auth_type,
            action_type: event.action_type,
            success: event.status === "success" ? 1 : 0,
            error_type: event.status !== "success" ? event.status : void 0,
            error_message: event.status === "error" ? event.error_message : void 0
          }
        });
        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", {
          properties: {
            platform: process.platform,
            arch: process.arch,
            use_ripgrep: event.use_ripgrep,
            use_builtin_ripgrep: event.use_builtin_ripgrep,
            error_message: event.error
          }
        });
        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,
            finish_reason: event.finish_reason,
            result: event.result
          }
        });
        this.enqueueLogEvent(rumEvent);
        this.flushIfNeeded();
      }
      logSkillLaunchEvent(event) {
        const rumEvent = this.createActionEvent("misc", "skill_launch", {
          properties: {
            skill_name: event.skill_name,
            success: event.success ? 1 : 0
          }
        });
        this.enqueueLogEvent(rumEvent);
        this.flushIfNeeded();
      }
      logUserFeedbackEvent(event) {
        const rumEvent = this.createActionEvent("user", "user_feedback", {
          properties: {
            session_id: event.session_id,
            rating: event.rating,
            model: event.model,
            approval_mode: event.approval_mode,
            prompt_id: event.prompt_id || ""
          }
        });
        this.enqueueLogEvent(rumEvent);
        this.flushIfNeeded();
      }
      logChatCompressionEvent(event) {
        const rumEvent = this.createActionEvent("misc", "chat_compression", {
          properties: {
            tokens_before: event.tokens_before,
            tokens_after: event.tokens_after
          }
        });
        this.enqueueLogEvent(rumEvent);
        this.flushIfNeeded();
      }
      logContentRetryEvent(event) {
        const rumEvent = this.createActionEvent("misc", "content_retry", {
          properties: {
            error_type: event.error_type,
            attempt_number: event.attempt_number,
            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");
        }
      }
      requeueFailedEvents(eventsToSend) {
        const eventsToRetry = eventsToSend.slice(-MAX_RETRY_EVENTS);
        if (eventsToSend.length > MAX_RETRY_EVENTS) {
          this.debugLogger.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) {
          return;
        }
        const eventsToRequeue = eventsToRetry.slice(eventsToRetry.length - numEventsToRequeue);
        for (let i3 = eventsToRequeue.length - 1; i3 >= 0; i3--) {
          this.events.unshift(eventsToRequeue[i3]);
        }
        while (this.events.size > MAX_EVENTS) {
          this.events.pop();
        }
        this.debugLogger.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_types3 = __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_constants7 = __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_utils3 = __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_constants7();
    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_constants7();
    var utils_1 = require_utils3();
    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((v2) => v2.trim()).filter((s5) => s5 !== "");
    }
    __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(time3) {
      if (isTimeInputHrTime(time3)) {
        return time3;
      } else if (typeof time3 === "number") {
        if (time3 < getTimeOrigin()) {
          return hrTime(time3);
        } else {
          return millisToHrTime(time3);
        }
      } else if (time3 instanceof Date) {
        return millisToHrTime(time3.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(time3) {
      const precision = NANOSECOND_DIGITS;
      const tmp = `${"0".repeat(precision)}${time3[1]}Z`;
      const nanoString = tmp.substring(tmp.length - precision - 1);
      const date4 = new Date(time3[0] * 1e3).toISOString();
      return date4.replace("000Z", nanoString);
    }
    __name(hrTimeToTimeStamp, "hrTimeToTimeStamp");
    exports2.hrTimeToTimeStamp = hrTimeToTimeStamp;
    function hrTimeToNanoseconds(time3) {
      return time3[0] * SECOND_TO_NANOSECONDS + time3[1];
    }
    __name(hrTimeToNanoseconds, "hrTimeToNanoseconds");
    exports2.hrTimeToNanoseconds = hrTimeToNanoseconds;
    function hrTimeToMilliseconds(time3) {
      return time3[0] * 1e3 + time3[1] / 1e6;
    }
    __name(hrTimeToMilliseconds, "hrTimeToMilliseconds");
    exports2.hrTimeToMilliseconds = hrTimeToMilliseconds;
    function hrTimeToMicroseconds(time3) {
      return time3[0] * 1e6 + time3[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, time22) {
      const out = [time1[0] + time22[0], time1[1] + time22[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(config2 = {}) {
        this._propagators = config2.propagators ?? [];
        this._fields = Array.from(new Set(this._propagators.map((p2) => typeof p2.fields === "function" ? p2.fields() : []).reduce((x3, y2) => x3.concat(y2), [])));
      }
      /**
       * 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 i3 = listMember.indexOf(LIST_MEMBER_KEY_VALUE_SPLITTER2);
          if (i3 !== -1) {
            const key = listMember.slice(0, i3);
            const value = listMember.slice(i3 + 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 VERSION4 = "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 = `${VERSION4}-${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 isPlainObject7(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(isPlainObject7, "isPlainObject");
    exports2.isPlainObject = isPlainObject7;
    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 (e4) {
      }
      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 merge4(...args) {
      let result = args.shift();
      const objects = /* @__PURE__ */ new WeakMap();
      while (args.length > 0) {
        result = mergeTwoObjects(result, args.shift(), 0, objects);
      }
      return result;
    }
    __name(merge4, "merge");
    exports2.merge = merge4;
    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) || isFunction5(two)) {
        result = takeValue(two);
      } else if (isArray2(one)) {
        result = one.slice();
        if (isArray2(two)) {
          for (let i3 = 0, j2 = two.length; i3 < j2; i3++) {
            result.push(takeValue(two[i3]));
          }
        } else if (isObject4(two)) {
          const keys = Object.keys(two);
          for (let i3 = 0, j2 = keys.length; i3 < j2; i3++) {
            const key = keys[i3];
            result[key] = takeValue(two[key]);
          }
        }
      } else if (isObject4(one)) {
        if (isObject4(two)) {
          if (!shouldMerge(one, two)) {
            return two;
          }
          result = Object.assign({}, one);
          const keys = Object.keys(two);
          for (let i3 = 0, j2 = keys.length; i3 < j2; i3++) {
            const key = keys[i3];
            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 (isObject4(obj1) && isObject4(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 i3 = 0, j2 = arr.length; i3 < j2; i3++) {
        const info = arr[i3];
        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 isFunction5(value) {
      return typeof value === "function";
    }
    __name(isFunction5, "isFunction");
    function isObject4(value) {
      return !isPrimitive(value) && !isArray2(value) && !isFunction5(value) && typeof value === "object";
    }
    __name(isObject4, "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_promise = __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((resolve30, reject) => {
          this._resolve = resolve30;
          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_promise();
    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((resolve30) => {
        api_1.context.with((0, suppress_tracing_1.suppressTracing)(api_1.context.active()), () => {
          exporter.export(arg, (result) => {
            resolve30(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_utils3();
    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_types3();
    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 (e4) {
                this._diagLogger.warn("Export succeeded but could not deserialize response - is the response specification compliant?", e4, 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_types3();
    init_shared_configuration();
    init_legacy_node_configuration();
    init_otlp_network_export_delegate();
  }
});

// node_modules/@grpc/grpc-js/build/src/constants.js
var require_constants8 = __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 _a7;
    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_constants8();
    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 = (_a7 = process.env.GRPC_NODE_VERBOSITY) !== null && _a7 !== void 0 ? _a7 : 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 = getErrorCode3;
    function getErrorMessage4(error2) {
      if (error2 instanceof Error) {
        return error2.message;
      } else {
        return String(error2);
      }
    }
    __name(getErrorMessage4, "getErrorMessage");
    function getErrorCode3(error2) {
      if (typeof error2 === "object" && error2 !== null && "code" in error2 && typeof error2.code === "number") {
        return error2.code;
      } else {
        return null;
      }
    }
    __name(getErrorCode3, "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_constants8();
    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 validate3(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(validate3, "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);
        validate3(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);
        validate3(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 v2 = values[0];
            result[key] = Buffer.isBuffer(v2) ? Buffer.from(v2) : v2;
          }
        }
        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((v2) => {
            if (Buffer.isBuffer(v2)) {
              return Buffer.from(v2);
            } else {
              return v2;
            }
          });
          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((v2) => {
                    result.add(key, Buffer.from(v2.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 (error2) {
            const message = `Failed to add metadata entry ${key}: ${values}. ${(0, error_1.getErrorMessage)(error2)}. 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((resolve30, 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;
                }
                resolve30(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((resolve30, reject) => {
          this.metadataGenerator(options2, (err, metadata) => {
            if (metadata !== void 0) {
              resolve30(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 fs113 = __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 = fs113.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(path125) {
      if (path125.startsWith("[")) {
        const hostEnd = path125.indexOf("]");
        if (hostEnd === -1) {
          return null;
        }
        const host = path125.substring(1, hostEnd);
        if (host.indexOf(":") === -1) {
          return null;
        }
        if (path125.length > hostEnd + 1) {
          if (path125[hostEnd + 1] === ":") {
            const portString = path125.substring(hostEnd + 2);
            if (NUMBER_REGEX.test(portString)) {
              return {
                host,
                port: +portString
              };
            } else {
              return null;
            }
          } else {
            return null;
          }
        } else {
          return {
            host
          };
        }
      } else {
        const splitPath = path125.split(":");
        if (splitPath.length === 2) {
          if (NUMBER_REGEX.test(splitPath[1])) {
            return {
              host: splitPath[0],
              port: +splitPath[1]
            };
          } else {
            return null;
          }
        } else {
          return {
            host: path125
          };
        }
      }
    }
    __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_constants8();
    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 _a7;
        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: (_a7 = rootCerts !== null && rootCerts !== void 0 ? rootCerts : (0, tls_helpers_1.getDefaultRootsData)()) !== null && _a7 !== void 0 ? _a7 : 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 _a7, _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 = (_a7 = hostPort === null || hostPort === void 0 ? void 0 : hostPort.host) !== null && _a7 !== void 0 ? _a7 : 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((resolve30, reject) => {
          const tlsSocket = (0, tls_1.connect)(tlsConnectOptions, () => {
            var _a7;
            if (((_a7 = this.connectionOptions.rejectUnauthorized) !== null && _a7 !== void 0 ? _a7 : true) && !tlsSocket.authorized) {
              reject(tlsSocket.authorizationError);
              return;
            }
            resolve30({
              socket: tlsSocket,
              secure: true
            });
          });
          tlsSocket.on("error", (error2) => {
            reject(error2);
          });
        });
      }
      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 _a7, _b2;
        if (this === other2) {
          return true;
        }
        if (other2 instanceof _CertificateProviderChannelCredentialsImpl) {
          return this.caCertificateProvider === other2.caCertificateProvider && this.identityCertificateProvider === other2.identityCertificateProvider && ((_a7 = this.verifyOptions) === null || _a7 === void 0 ? void 0 : _a7.checkServerIdentity) === ((_b2 = other2.verifyOptions) === null || _b2 === void 0 ? void 0 : _b2.checkServerIdentity);
        } else {
          return false;
        }
      }
      ref() {
        var _a7;
        if (this.refcount === 0) {
          this.caCertificateProvider.addCaCertificateListener(this.caCertificateUpdateListener);
          (_a7 = this.identityCertificateProvider) === null || _a7 === void 0 ? void 0 : _a7.addIdentityCertificateListener(this.identityCertificateUpdateListener);
        }
        this.refcount += 1;
      }
      unref() {
        var _a7;
        this.refcount -= 1;
        if (this.refcount === 0) {
          this.caCertificateProvider.removeCaCertificateListener(this.caCertificateUpdateListener);
          (_a7 = this.identityCertificateProvider) === null || _a7 === void 0 ? void 0 : _a7.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((resolve30) => {
            this.secureContextWatchers.push(resolve30);
          });
        }
      }
      getLatestSecureContext() {
        var _a7, _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: (_a7 = this.latestIdentityUpdate) === null || _a7 === void 0 ? void 0 : _a7.privateKey,
            cert: (_b2 = this.latestIdentityUpdate) === null || _b2 === void 0 ? void 0 : _b2.certificate,
            ciphers: tls_helpers_1.CIPHER_SUITES
          });
        } catch (e4) {
          (0, logging_1.log)(constants_1.LogVerbosity.ERROR, "Failed to createSecureContext with error " + e4.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((resolve30, 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((error2) => {
            reject(error2);
          }, "errorCallback");
          const tlsSocket = (0, tls_1.connect)(tlsConnectOptions, () => {
            var _a7;
            tlsSocket.removeListener("close", closeCallback);
            tlsSocket.removeListener("error", errorCallback);
            if (((_a7 = this.parent.verifyOptions.rejectUnauthorized) !== null && _a7 !== void 0 ? _a7 : true) && !tlsSocket.authorized) {
              reject(tlsSocket.authorizationError);
              return;
            }
            resolve30({
              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_constants8();
    function createChildChannelControlHelper(parent, overrides) {
      var _a7, _b2, _c2, _d, _e2, _f, _g, _h, _j, _k;
      return {
        createSubchannel: (_b2 = (_a7 = overrides.createSubchannel) === null || _a7 === void 0 ? void 0 : _a7.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 = (_e2 = overrides.requestReresolution) === null || _e2 === void 0 ? void 0 : _e2.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(config2, channelControlHelper) {
      const typeName = config2.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 (e4) {
          throw new Error(`${typeName}: ${e4.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 config2 of configs) {
        try {
          return parseLoadBalancingConfig(config2);
        } catch (e4) {
          (0, logging_1.log)(constants_1.LogVerbosity.DEBUG, "Config parsing failed with error", e4.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 os47 = __require("os");
    var constants_1 = require_constants8();
    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 _a7;
      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: ((_a7 = timeoutParts[1]) !== null && _a7 !== void 0 ? _a7 : 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 config2 of obj.loadBalancingConfig) {
            result.loadBalancingConfig.push(validateLoadBalancingConfig(config2));
          }
        } 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 config2 of obj) {
        const validatedConfig = validateCanaryConfig(config2);
        if (typeof validatedConfig.percentage === "number" && percentage > validatedConfig.percentage) {
          continue;
        }
        if (Array.isArray(validatedConfig.clientHostname)) {
          let hostnameMatched = false;
          for (const hostname4 of validatedConfig.clientHostname) {
            if (hostname4 === os47.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 record2 of txtRecord) {
        if (record2.length > 0 && record2[0].startsWith("grpc_config=")) {
          const recordString = record2.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_constants8();
    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_constants8();
    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 _a7, _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 = (_a7 = this.timerId).unref) === null || _b2 === void 0 ? void 0 : _b2.call(_a7);
        }
      }
      /**
       * 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 _a7, _b2;
        this.hasRef = true;
        (_b2 = (_a7 = this.timerId).ref) === null || _b2 === void 0 ? void 0 : _b2.call(_a7);
      }
      /**
       * Set that while the timer is running, it should not keep the Node process
       * running.
       */
      unref() {
        var _a7, _b2;
        this.hasRef = false;
        (_b2 = (_a7 = this.timerId).unref) === null || _b2 === void 0 ? void 0 : _b2.call(_a7);
      }
      /**
       * 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 _a7;
            if (this.calledByPendingChild()) {
              if (connectivityState === connectivity_state_1.ConnectivityState.CONNECTING) {
                return;
              }
              (_a7 = this.parent.currentChild) === null || _a7 === void 0 ? void 0 : _a7.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 _a7;
            const latestChild = (_a7 = this.parent.pendingChild) !== null && _a7 !== void 0 ? _a7 : 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_constants8();
    var metadata_1 = require_metadata3();
    var logging = require_logging();
    var constants_2 = require_constants8();
    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 config2 of methodConfigs) {
        if (hasMatchingName(service, method, config2, matchLevel)) {
          return config2;
        }
      }
      return null;
    }
    __name(findMatchingConfig, "findMatchingConfig");
    function getDefaultConfigSelector(serviceConfig) {
      return {
        invoke(methodName, metadata) {
          var _a7, _b2;
          const splitName = methodName.split("/").filter((x3) => x3.length > 0);
          const service = (_a7 = splitName[0]) !== null && _a7 !== void 0 ? _a7 : "";
          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 _a7;
            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 = (_a7 = workingServiceConfig === null || workingServiceConfig === void 0 ? void 0 : workingServiceConfig.loadBalancingConfig) !== null && _a7 !== void 0 ? _a7 : [];
            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((error2) => {
            this.handleResolutionFailure(error2);
          }, "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(error2) {
        if (this.latestChildState === connectivity_state_1.ConnectivityState.IDLE) {
          this.updateState(connectivity_state_1.ConnectivityState.TRANSIENT_FAILURE, new picker_1.UnavailablePicker(error2), error2.details);
          this.onFailedResolution(error2);
        }
      }
      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 i3 = 0; i3 < keys1.length; i3 += 1) {
        if (keys1[i3] !== keys2[i3]) {
          return false;
        }
        if (options1[keys1[i3]] !== options2[keys2[i3]]) {
          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 i3 = 0; i3 < endpoint1.addresses.length; i3++) {
        if (!subchannelAddressEqual(endpoint1.addresses[i3], endpoint2.addresses[i3])) {
          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(t5, e4, s5 = 1) {
        this.i = void 0;
        this.h = void 0;
        this.o = void 0;
        this.u = t5;
        this.l = e4;
        this.p = s5;
      }
      I() {
        let t5 = this;
        const e4 = t5.o.o === t5;
        if (e4 && t5.p === 1) {
          t5 = t5.h;
        } else if (t5.i) {
          t5 = t5.i;
          while (t5.h) {
            t5 = t5.h;
          }
        } else {
          if (e4) {
            return t5.o;
          }
          let s5 = t5.o;
          while (s5.i === t5) {
            t5 = s5;
            s5 = t5.o;
          }
          t5 = s5;
        }
        return t5;
      }
      B() {
        let t5 = this;
        if (t5.h) {
          t5 = t5.h;
          while (t5.i) {
            t5 = t5.i;
          }
          return t5;
        } else {
          let e4 = t5.o;
          while (e4.h === t5) {
            t5 = e4;
            e4 = t5.o;
          }
          if (t5.h !== e4) {
            return e4;
          } else return t5;
        }
      }
      _() {
        const t5 = this.o;
        const e4 = this.h;
        const s5 = e4.i;
        if (t5.o === this) t5.o = e4;
        else if (t5.i === this) t5.i = e4;
        else t5.h = e4;
        e4.o = t5;
        e4.i = this;
        this.o = e4;
        this.h = s5;
        if (s5) s5.o = this;
        return e4;
      }
      g() {
        const t5 = this.o;
        const e4 = this.i;
        const s5 = e4.h;
        if (t5.o === this) t5.o = e4;
        else if (t5.i === this) t5.i = e4;
        else t5.h = e4;
        e4.o = t5;
        e4.h = this;
        this.o = e4;
        this.i = s5;
        if (s5) s5.o = this;
        return e4;
      }
    };
    var TreeNodeEnableIndex = class extends TreeNode {
      static {
        __name(this, "TreeNodeEnableIndex");
      }
      constructor() {
        super(...arguments);
        this.M = 1;
      }
      _() {
        const t5 = super._();
        this.O();
        t5.O();
        return t5;
      }
      g() {
        const t5 = super.g();
        this.O();
        t5.O();
        return t5;
      }
      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(t5 = 0) {
        this.iteratorType = t5;
      }
      equals(t5) {
        return this.T === t5.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(t5 = function(t6, e5) {
        if (t6 < e5) return -1;
        if (t6 > e5) return 1;
        return 0;
      }, e4 = false) {
        super();
        this.v = void 0;
        this.A = t5;
        this.enableIndex = e4;
        this.N = e4 ? TreeNodeEnableIndex : TreeNode;
        this.C = new this.N();
      }
      R(t5, e4) {
        let s5 = this.C;
        while (t5) {
          const i3 = this.A(t5.u, e4);
          if (i3 < 0) {
            t5 = t5.h;
          } else if (i3 > 0) {
            s5 = t5;
            t5 = t5.i;
          } else return t5;
        }
        return s5;
      }
      K(t5, e4) {
        let s5 = this.C;
        while (t5) {
          const i3 = this.A(t5.u, e4);
          if (i3 <= 0) {
            t5 = t5.h;
          } else {
            s5 = t5;
            t5 = t5.i;
          }
        }
        return s5;
      }
      L(t5, e4) {
        let s5 = this.C;
        while (t5) {
          const i3 = this.A(t5.u, e4);
          if (i3 < 0) {
            s5 = t5;
            t5 = t5.h;
          } else if (i3 > 0) {
            t5 = t5.i;
          } else return t5;
        }
        return s5;
      }
      k(t5, e4) {
        let s5 = this.C;
        while (t5) {
          const i3 = this.A(t5.u, e4);
          if (i3 < 0) {
            s5 = t5;
            t5 = t5.h;
          } else {
            t5 = t5.i;
          }
        }
        return s5;
      }
      P(t5) {
        while (true) {
          const e4 = t5.o;
          if (e4 === this.C) return;
          if (t5.p === 1) {
            t5.p = 0;
            return;
          }
          if (t5 === e4.i) {
            const s5 = e4.h;
            if (s5.p === 1) {
              s5.p = 0;
              e4.p = 1;
              if (e4 === this.v) {
                this.v = e4._();
              } else e4._();
            } else {
              if (s5.h && s5.h.p === 1) {
                s5.p = e4.p;
                e4.p = 0;
                s5.h.p = 0;
                if (e4 === this.v) {
                  this.v = e4._();
                } else e4._();
                return;
              } else if (s5.i && s5.i.p === 1) {
                s5.p = 1;
                s5.i.p = 0;
                s5.g();
              } else {
                s5.p = 1;
                t5 = e4;
              }
            }
          } else {
            const s5 = e4.i;
            if (s5.p === 1) {
              s5.p = 0;
              e4.p = 1;
              if (e4 === this.v) {
                this.v = e4.g();
              } else e4.g();
            } else {
              if (s5.i && s5.i.p === 1) {
                s5.p = e4.p;
                e4.p = 0;
                s5.i.p = 0;
                if (e4 === this.v) {
                  this.v = e4.g();
                } else e4.g();
                return;
              } else if (s5.h && s5.h.p === 1) {
                s5.p = 1;
                s5.h.p = 0;
                s5._();
              } else {
                s5.p = 1;
                t5 = e4;
              }
            }
          }
        }
      }
      S(t5) {
        if (this.m === 1) {
          this.clear();
          return;
        }
        let e4 = t5;
        while (e4.i || e4.h) {
          if (e4.h) {
            e4 = e4.h;
            while (e4.i) e4 = e4.i;
          } else {
            e4 = e4.i;
          }
          const s6 = t5.u;
          t5.u = e4.u;
          e4.u = s6;
          const i3 = t5.l;
          t5.l = e4.l;
          e4.l = i3;
          t5 = e4;
        }
        if (this.C.i === e4) {
          this.C.i = e4.o;
        } else if (this.C.h === e4) {
          this.C.h = e4.o;
        }
        this.P(e4);
        let s5 = e4.o;
        if (e4 === s5.i) {
          s5.i = void 0;
        } else s5.h = void 0;
        this.m -= 1;
        this.v.p = 0;
        if (this.enableIndex) {
          while (s5 !== this.C) {
            s5.M -= 1;
            s5 = s5.o;
          }
        }
      }
      U(t5) {
        const e4 = typeof t5 === "number" ? t5 : void 0;
        const s5 = typeof t5 === "function" ? t5 : void 0;
        const i3 = typeof t5 === "undefined" ? [] : void 0;
        let r5 = 0;
        let n3 = this.v;
        const h3 = [];
        while (h3.length || n3) {
          if (n3) {
            h3.push(n3);
            n3 = n3.i;
          } else {
            n3 = h3.pop();
            if (r5 === e4) return n3;
            i3 && i3.push(n3);
            s5 && s5(n3, r5, this);
            r5 += 1;
            n3 = n3.h;
          }
        }
        return i3;
      }
      j(t5) {
        while (true) {
          const e4 = t5.o;
          if (e4.p === 0) return;
          const s5 = e4.o;
          if (e4 === s5.i) {
            const i3 = s5.h;
            if (i3 && i3.p === 1) {
              i3.p = e4.p = 0;
              if (s5 === this.v) return;
              s5.p = 1;
              t5 = s5;
              continue;
            } else if (t5 === e4.h) {
              t5.p = 0;
              if (t5.i) {
                t5.i.o = e4;
              }
              if (t5.h) {
                t5.h.o = s5;
              }
              e4.h = t5.i;
              s5.i = t5.h;
              t5.i = e4;
              t5.h = s5;
              if (s5 === this.v) {
                this.v = t5;
                this.C.o = t5;
              } else {
                const e5 = s5.o;
                if (e5.i === s5) {
                  e5.i = t5;
                } else e5.h = t5;
              }
              t5.o = s5.o;
              e4.o = t5;
              s5.o = t5;
              s5.p = 1;
            } else {
              e4.p = 0;
              if (s5 === this.v) {
                this.v = s5.g();
              } else s5.g();
              s5.p = 1;
              return;
            }
          } else {
            const i3 = s5.i;
            if (i3 && i3.p === 1) {
              i3.p = e4.p = 0;
              if (s5 === this.v) return;
              s5.p = 1;
              t5 = s5;
              continue;
            } else if (t5 === e4.i) {
              t5.p = 0;
              if (t5.i) {
                t5.i.o = s5;
              }
              if (t5.h) {
                t5.h.o = e4;
              }
              s5.h = t5.i;
              e4.i = t5.h;
              t5.i = s5;
              t5.h = e4;
              if (s5 === this.v) {
                this.v = t5;
                this.C.o = t5;
              } else {
                const e5 = s5.o;
                if (e5.i === s5) {
                  e5.i = t5;
                } else e5.h = t5;
              }
              t5.o = s5.o;
              e4.o = t5;
              s5.o = t5;
              s5.p = 1;
            } else {
              e4.p = 0;
              if (s5 === this.v) {
                this.v = s5._();
              } else s5._();
              s5.p = 1;
              return;
            }
          }
          if (this.enableIndex) {
            e4.O();
            s5.O();
            t5.O();
          }
          return;
        }
      }
      q(t5, e4, s5) {
        if (this.v === void 0) {
          this.m += 1;
          this.v = new this.N(t5, e4, 0);
          this.v.o = this.C;
          this.C.o = this.C.i = this.C.h = this.v;
          return this.m;
        }
        let i3;
        const r5 = this.C.i;
        const n3 = this.A(r5.u, t5);
        if (n3 === 0) {
          r5.l = e4;
          return this.m;
        } else if (n3 > 0) {
          r5.i = new this.N(t5, e4);
          r5.i.o = r5;
          i3 = r5.i;
          this.C.i = i3;
        } else {
          const r6 = this.C.h;
          const n4 = this.A(r6.u, t5);
          if (n4 === 0) {
            r6.l = e4;
            return this.m;
          } else if (n4 < 0) {
            r6.h = new this.N(t5, e4);
            r6.h.o = r6;
            i3 = r6.h;
            this.C.h = i3;
          } else {
            if (s5 !== void 0) {
              const r7 = s5.T;
              if (r7 !== this.C) {
                const s6 = this.A(r7.u, t5);
                if (s6 === 0) {
                  r7.l = e4;
                  return this.m;
                } else if (s6 > 0) {
                  const s7 = r7.I();
                  const n5 = this.A(s7.u, t5);
                  if (n5 === 0) {
                    s7.l = e4;
                    return this.m;
                  } else if (n5 < 0) {
                    i3 = new this.N(t5, e4);
                    if (s7.h === void 0) {
                      s7.h = i3;
                      i3.o = s7;
                    } else {
                      r7.i = i3;
                      i3.o = r7;
                    }
                  }
                }
              }
            }
            if (i3 === void 0) {
              i3 = this.v;
              while (true) {
                const s6 = this.A(i3.u, t5);
                if (s6 > 0) {
                  if (i3.i === void 0) {
                    i3.i = new this.N(t5, e4);
                    i3.i.o = i3;
                    i3 = i3.i;
                    break;
                  }
                  i3 = i3.i;
                } else if (s6 < 0) {
                  if (i3.h === void 0) {
                    i3.h = new this.N(t5, e4);
                    i3.h.o = i3;
                    i3 = i3.h;
                    break;
                  }
                  i3 = i3.h;
                } else {
                  i3.l = e4;
                  return this.m;
                }
              }
            }
          }
        }
        if (this.enableIndex) {
          let t6 = i3.o;
          while (t6 !== this.C) {
            t6.M += 1;
            t6 = t6.o;
          }
        }
        this.j(i3);
        this.m += 1;
        return this.m;
      }
      H(t5, e4) {
        while (t5) {
          const s5 = this.A(t5.u, e4);
          if (s5 < 0) {
            t5 = t5.h;
          } else if (s5 > 0) {
            t5 = t5.i;
          } else return t5;
        }
        return t5 || this.C;
      }
      clear() {
        this.m = 0;
        this.v = void 0;
        this.C.o = void 0;
        this.C.i = this.C.h = void 0;
      }
      updateKeyByIterator(t5, e4) {
        const s5 = t5.T;
        if (s5 === this.C) {
          throwIteratorAccessError();
        }
        if (this.m === 1) {
          s5.u = e4;
          return true;
        }
        const i3 = s5.B().u;
        if (s5 === this.C.i) {
          if (this.A(i3, e4) > 0) {
            s5.u = e4;
            return true;
          }
          return false;
        }
        const r5 = s5.I().u;
        if (s5 === this.C.h) {
          if (this.A(r5, e4) < 0) {
            s5.u = e4;
            return true;
          }
          return false;
        }
        if (this.A(r5, e4) >= 0 || this.A(i3, e4) <= 0) return false;
        s5.u = e4;
        return true;
      }
      eraseElementByPos(t5) {
        if (t5 < 0 || t5 > this.m - 1) {
          throw new RangeError();
        }
        const e4 = this.U(t5);
        this.S(e4);
        return this.m;
      }
      eraseElementByKey(t5) {
        if (this.m === 0) return false;
        const e4 = this.H(this.v, t5);
        if (e4 === this.C) return false;
        this.S(e4);
        return true;
      }
      eraseElementByIterator(t5) {
        const e4 = t5.T;
        if (e4 === this.C) {
          throwIteratorAccessError();
        }
        const s5 = e4.h === void 0;
        const i3 = t5.iteratorType === 0;
        if (i3) {
          if (s5) t5.next();
        } else {
          if (!s5 || e4.i === void 0) t5.next();
        }
        this.S(e4);
        return t5;
      }
      getHeight() {
        if (this.m === 0) return 0;
        function traversal(t5) {
          if (!t5) return 0;
          return Math.max(traversal(t5.i), traversal(t5.h)) + 1;
        }
        __name(traversal, "traversal");
        return traversal(this.v);
      }
    };
    var TreeIterator = class extends ContainerIterator {
      static {
        __name(this, "TreeIterator");
      }
      constructor(t5, e4, s5) {
        super(s5);
        this.T = t5;
        this.C = e4;
        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 t5 = this.T;
        const e4 = this.C.o;
        if (t5 === this.C) {
          if (e4) {
            return e4.M - 1;
          }
          return 0;
        }
        let s5 = 0;
        if (t5.i) {
          s5 += t5.i.M;
        }
        while (t5 !== e4) {
          const e5 = t5.o;
          if (t5 === e5.h) {
            s5 += 1;
            if (e5.i) {
              s5 += e5.i.M;
            }
          }
          t5 = e5;
        }
        return s5;
      }
      isAccessible() {
        return this.T !== this.C;
      }
    };
    var OrderedMapIterator = class _OrderedMapIterator extends TreeIterator {
      static {
        __name(this, "OrderedMapIterator");
      }
      constructor(t5, e4, s5, i3) {
        super(t5, e4, i3);
        this.container = s5;
      }
      get pointer() {
        if (this.T === this.C) {
          throwIteratorAccessError();
        }
        const t5 = this;
        return new Proxy([], {
          get(e4, s5) {
            if (s5 === "0") return t5.T.u;
            else if (s5 === "1") return t5.T.l;
            e4[0] = t5.T.u;
            e4[1] = t5.T.l;
            return e4[s5];
          },
          set(e4, s5, i3) {
            if (s5 !== "1") {
              throw new TypeError("prop must be 1");
            }
            t5.T.l = i3;
            return true;
          }
        });
      }
      copy() {
        return new _OrderedMapIterator(this.T, this.C, this.container, this.iteratorType);
      }
    };
    var OrderedMap = class extends TreeContainer {
      static {
        __name(this, "OrderedMap");
      }
      constructor(t5 = [], e4, s5) {
        super(e4, s5);
        const i3 = this;
        t5.forEach(function(t6) {
          i3.setElement(t6[0], t6[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 t5 = this.C.i;
        return [t5.u, t5.l];
      }
      back() {
        if (this.m === 0) return;
        const t5 = this.C.h;
        return [t5.u, t5.l];
      }
      lowerBound(t5) {
        const e4 = this.R(this.v, t5);
        return new OrderedMapIterator(e4, this.C, this);
      }
      upperBound(t5) {
        const e4 = this.K(this.v, t5);
        return new OrderedMapIterator(e4, this.C, this);
      }
      reverseLowerBound(t5) {
        const e4 = this.L(this.v, t5);
        return new OrderedMapIterator(e4, this.C, this);
      }
      reverseUpperBound(t5) {
        const e4 = this.k(this.v, t5);
        return new OrderedMapIterator(e4, this.C, this);
      }
      forEach(t5) {
        this.U(function(e4, s5, i3) {
          t5([e4.u, e4.l], s5, i3);
        });
      }
      setElement(t5, e4, s5) {
        return this.q(t5, e4, s5);
      }
      getElementByPos(t5) {
        if (t5 < 0 || t5 > this.m - 1) {
          throw new RangeError();
        }
        const e4 = this.U(t5);
        return [e4.u, e4.l];
      }
      find(t5) {
        const e4 = this.H(this.v, t5);
        return new OrderedMapIterator(e4, this.C, this);
      }
      getElementByKey(t5) {
        const e4 = this.H(this.v, t5);
        return e4.l;
      }
      union(t5) {
        const e4 = this;
        t5.forEach(function(t6) {
          e4.setElement(t6[0], t6[1]);
        });
        return this.m;
      }
      *[Symbol.iterator]() {
        const t5 = this.m;
        const e4 = this.U();
        for (let s5 = 0; s5 < t5; ++s5) {
          const t6 = e4[s5];
          yield [t6.u, t6.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_constants8();
    function callErrorFromStatus(status, callerStack) {
      const message = `${status.code} ${constants_1.Status[status.code]}: ${status.details}`;
      const error2 = new Error(message);
      const stack = `${error2.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 _a7;
        (_a7 = this.call) === null || _a7 === void 0 ? void 0 : _a7.cancelWithStatus(constants_1.Status.CANCELLED, "Cancelled on client");
      }
      getPeer() {
        var _a7, _b2;
        return (_b2 = (_a7 = this.call) === null || _a7 === void 0 ? void 0 : _a7.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 _a7;
        (_a7 = this.call) === null || _a7 === void 0 ? void 0 : _a7.cancelWithStatus(constants_1.Status.CANCELLED, "Cancelled on client");
      }
      getPeer() {
        var _a7, _b2;
        return (_b2 = (_a7 = this.call) === null || _a7 === void 0 ? void 0 : _a7.getPeer()) !== null && _b2 !== void 0 ? _b2 : "unknown";
      }
      _read(_size3) {
        var _a7;
        (_a7 = this.call) === null || _a7 === void 0 ? void 0 : _a7.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 _a7;
        (_a7 = this.call) === null || _a7 === void 0 ? void 0 : _a7.cancelWithStatus(constants_1.Status.CANCELLED, "Cancelled on client");
      }
      getPeer() {
        var _a7, _b2;
        return (_b2 = (_a7 = this.call) === null || _a7 === void 0 ? void 0 : _a7.getPeer()) !== null && _b2 !== void 0 ? _b2 : "unknown";
      }
      _write(chunk, encoding, cb) {
        var _a7;
        const context2 = {
          callback: cb
        };
        const flags = Number(encoding);
        if (!Number.isNaN(flags)) {
          context2.flags = flags;
        }
        (_a7 = this.call) === null || _a7 === void 0 ? void 0 : _a7.sendMessageWithContext(context2, chunk);
      }
      _final(cb) {
        var _a7;
        (_a7 = this.call) === null || _a7 === void 0 ? void 0 : _a7.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 _a7;
        (_a7 = this.call) === null || _a7 === void 0 ? void 0 : _a7.cancelWithStatus(constants_1.Status.CANCELLED, "Cancelled on client");
      }
      getPeer() {
        var _a7, _b2;
        return (_b2 = (_a7 = this.call) === null || _a7 === void 0 ? void 0 : _a7.getPeer()) !== null && _b2 !== void 0 ? _b2 : "unknown";
      }
      _read(_size3) {
        var _a7;
        (_a7 = this.call) === null || _a7 === void 0 ? void 0 : _a7.startRead();
      }
      _write(chunk, encoding, cb) {
        var _a7;
        const context2 = {
          callback: cb
        };
        const flags = Number(encoding);
        if (!Number.isNaN(flags)) {
          context2.flags = flags;
        }
        (_a7 = this.call) === null || _a7 === void 0 ? void 0 : _a7.sendMessageWithContext(context2, chunk);
      }
      _final(cb) {
        var _a7;
        (_a7 = this.call) === null || _a7 === void 0 ? void 0 : _a7.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_constants8();
    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 _a7, _b2, _c2, _d;
        this.nextCall = nextCall;
        this.processingMetadata = false;
        this.pendingMessageContext = null;
        this.processingMessage = false;
        this.pendingHalfClose = false;
        if (requester) {
          this.requester = {
            start: (_a7 = requester.start) !== null && _a7 !== void 0 ? _a7 : 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 _a7, _b2, _c2, _d, _e2, _f;
        const fullInterceptingListener = {
          onReceiveMetadata: (_b2 = (_a7 = interceptingListener === null || interceptingListener === void 0 ? void 0 : interceptingListener.onReceiveMetadata) === null || _a7 === void 0 ? void 0 : _a7.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 = (_e2 = interceptingListener === null || interceptingListener === void 0 ? void 0 : interceptingListener.onReceiveStatus) === null || _e2 === void 0 ? void 0 : _e2.bind(interceptingListener)) !== null && _f !== void 0 ? _f : (status) => {
          }
        };
        this.processingMetadata = true;
        this.requester.start(metadata, fullInterceptingListener, (md, listener) => {
          var _a8, _b3, _c3;
          this.processingMetadata = false;
          let finalInterceptingListener;
          if ((0, call_interface_1.isInterceptingListener)(listener)) {
            finalInterceptingListener = listener;
          } else {
            const fullListener = {
              onReceiveMetadata: (_a8 = listener.onReceiveMetadata) !== null && _a8 !== void 0 ? _a8 : 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, path125, options2) {
      var _a7, _b2;
      const deadline = (_a7 = options2.deadline) !== null && _a7 !== void 0 ? _a7 : 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(path125, 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 (e4) {
          this.call.cancelWithStatus(constants_1.Status.INTERNAL, `Request message serialization failure: ${(0, error_1.getErrorMessage)(e4)}`);
          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 _a7;
            (_a7 = interceptingListener === null || interceptingListener === void 0 ? void 0 : interceptingListener.onReceiveMetadata) === null || _a7 === void 0 ? void 0 : _a7.call(interceptingListener, metadata2);
          }, "onReceiveMetadata"),
          onReceiveMessage: /* @__PURE__ */ __name((message) => {
            var _a7;
            let deserialized;
            try {
              deserialized = this.methodDefinition.responseDeserialize(message);
            } catch (e4) {
              readError = {
                code: constants_1.Status.INTERNAL,
                details: `Response message parsing error: ${(0, error_1.getErrorMessage)(e4)}`,
                metadata: new metadata_1.Metadata()
              };
              this.call.cancelWithStatus(readError.code, readError.details);
              return;
            }
            (_a7 = interceptingListener === null || interceptingListener === void 0 ? void 0 : interceptingListener.onReceiveMessage) === null || _a7 === void 0 ? void 0 : _a7.call(interceptingListener, deserialized);
          }, "onReceiveMessage"),
          onReceiveStatus: /* @__PURE__ */ __name((status) => {
            var _a7, _b2;
            if (readError) {
              (_a7 = interceptingListener === null || interceptingListener === void 0 ? void 0 : interceptingListener.onReceiveStatus) === null || _a7 === void 0 ? void 0 : _a7.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 _a7, _b2;
        let receivedMessage = false;
        const wrapperListener = {
          onReceiveMetadata: (_b2 = (_a7 = listener === null || listener === void 0 ? void 0 : listener.onReceiveMetadata) === null || _a7 === void 0 ? void 0 : _a7.bind(listener)) !== null && _b2 !== void 0 ? _b2 : (metadata2) => {
          },
          // eslint-disable-next-line @typescript-eslint/no-explicit-any
          onReceiveMessage: /* @__PURE__ */ __name((message) => {
            var _a8;
            receivedMessage = true;
            (_a8 = listener === null || listener === void 0 ? void 0 : listener.onReceiveMessage) === null || _a8 === void 0 ? void 0 : _a8.call(listener, message);
          }, "onReceiveMessage"),
          onReceiveStatus: /* @__PURE__ */ __name((status) => {
            var _a8, _b3;
            if (!receivedMessage) {
              (_a8 = listener === null || listener === void 0 ? void 0 : listener.onReceiveMessage) === null || _a8 === void 0 ? void 0 : _a8.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_constants8();
    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 isFunction5(arg) {
      return typeof arg === "function";
    }
    __name(isFunction5, "isFunction");
    function getErrorStackString(error2) {
      var _a7;
      return ((_a7 = error2.stack) === null || _a7 === void 0 ? void 0 : _a7.split("\n").slice(1).join("\n")) || "no stack trace available";
    }
    __name(getErrorStackString, "getErrorStackString");
    var Client3 = class {
      static {
        __name(this, "Client");
      }
      constructor(address, credentials, options2 = {}) {
        var _a7, _b2;
        options2 = Object.assign({}, options2);
        this[INTERCEPTOR_SYMBOL] = (_a7 = options2.interceptors) !== null && _a7 !== void 0 ? _a7 : [];
        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 (e4) {
            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 (e4) {
              callback(new Error("The channel has been closed"));
            }
          }
        }, "checkState");
        setImmediate(checkState);
      }
      checkOptionalUnaryResponseArguments(arg1, arg2, arg3) {
        if (isFunction5(arg1)) {
          return { metadata: new metadata_1.Metadata(), options: {}, callback: arg1 };
        } else if (isFunction5(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 && isFunction5(arg3))) {
            throw new Error("Incorrect arguments passed");
          }
          return { metadata: arg1, options: arg2, callback: arg3 };
        }
      }
      makeUnaryRequest(method, serialize2, deserialize, argument, metadata, options2, callback) {
        var _a7, _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: (_a7 = callProperties.callOptions.interceptors) !== null && _a7 !== void 0 ? _a7 : [],
          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 _a7, _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: (_a7 = callProperties.callOptions.interceptors) !== null && _a7 !== void 0 ? _a7 : [],
          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 _a7, _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: (_a7 = callProperties.callOptions.interceptors) !== null && _a7 !== void 0 ? _a7 : [],
          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 _a7, _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: (_a7 = callProperties.callOptions.interceptors) !== null && _a7 !== void 0 ? _a7 : [],
          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 = Client3;
  }
});

// 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 = partial2(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 partial2(fn, path125, serialize2, deserialize) {
      return function(...args) {
        return fn.call(this, path125, serialize2, deserialize, ...args);
      };
    }
    __name(partial2, "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(array2, iteratee, accumulator, initAccum) {
      var index = -1, length = array2 ? array2.length : 0;
      if (initAccum && length) {
        accumulator = array2[++index];
      }
      while (++index < length) {
        accumulator = iteratee(accumulator, array2[index], index, array2);
      }
      return accumulator;
    }
    __name(arrayReduce, "arrayReduce");
    function asciiToArray(string4) {
      return string4.split("");
    }
    __name(asciiToArray, "asciiToArray");
    function asciiWords(string4) {
      return string4.match(reAsciiWord) || [];
    }
    __name(asciiWords, "asciiWords");
    function basePropertyOf(object3) {
      return function(key) {
        return object3 == null ? void 0 : object3[key];
      };
    }
    __name(basePropertyOf, "basePropertyOf");
    var deburrLetter = basePropertyOf(deburredLetters);
    function hasUnicode(string4) {
      return reHasUnicode.test(string4);
    }
    __name(hasUnicode, "hasUnicode");
    function hasUnicodeWord(string4) {
      return reHasUnicodeWord.test(string4);
    }
    __name(hasUnicodeWord, "hasUnicodeWord");
    function stringToArray(string4) {
      return hasUnicode(string4) ? unicodeToArray(string4) : asciiToArray(string4);
    }
    __name(stringToArray, "stringToArray");
    function unicodeToArray(string4) {
      return string4.match(reUnicode) || [];
    }
    __name(unicodeToArray, "unicodeToArray");
    function unicodeWords(string4) {
      return string4.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(array2, start, end) {
      var index = -1, length = array2.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] = array2[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(array2, start, end) {
      var length = array2.length;
      end = end === void 0 ? length : end;
      return !start && end >= length ? array2 : baseSlice(array2, start, end);
    }
    __name(castSlice, "castSlice");
    function createCaseFirst(methodName) {
      return function(string4) {
        string4 = toString(string4);
        var strSymbols = hasUnicode(string4) ? stringToArray(string4) : void 0;
        var chr = strSymbols ? strSymbols[0] : string4.charAt(0);
        var trailing = strSymbols ? castSlice(strSymbols, 1).join("") : string4.slice(1);
        return chr[methodName]() + trailing;
      };
    }
    __name(createCaseFirst, "createCaseFirst");
    function createCompounder(callback) {
      return function(string4) {
        return arrayReduce(words(deburr(string4).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(string4) {
      return upperFirst(toString(string4).toLowerCase());
    }
    __name(capitalize, "capitalize");
    function deburr(string4) {
      string4 = toString(string4);
      return string4 && string4.replace(reLatin, deburrLetter).replace(reComboMark, "");
    }
    __name(deburr, "deburr");
    var upperFirst = createCaseFirst("toUpperCase");
    function words(string4, pattern, guard) {
      string4 = toString(string4);
      pattern = guard ? void 0 : pattern;
      if (pattern === void 0) {
        return hasUnicodeWord(string4) ? unicodeWords(string4) : asciiWords(string4);
      }
      return string4.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(resolve30, 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];
              resolve30.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 base642 = exports2;
    base642.length = /* @__PURE__ */ __name(function length(string4) {
      var p2 = string4.length;
      if (!p2)
        return 0;
      var n3 = 0;
      while (--p2 % 4 > 1 && string4.charAt(p2) === "=")
        ++n3;
      return Math.ceil(string4.length * 3) / 4 - n3;
    }, "length");
    var b64 = new Array(64);
    var s64 = new Array(123);
    for (i3 = 0; i3 < 64; )
      s64[b64[i3] = i3 < 26 ? i3 + 65 : i3 < 52 ? i3 + 71 : i3 < 62 ? i3 - 4 : i3 - 59 | 43] = i3++;
    var i3;
    base642.encode = /* @__PURE__ */ __name(function encode4(buffer, start, end) {
      var parts = null, chunk = [];
      var i4 = 0, j2 = 0, t5;
      while (start < end) {
        var b2 = buffer[start++];
        switch (j2) {
          case 0:
            chunk[i4++] = b64[b2 >> 2];
            t5 = (b2 & 3) << 4;
            j2 = 1;
            break;
          case 1:
            chunk[i4++] = b64[t5 | b2 >> 4];
            t5 = (b2 & 15) << 2;
            j2 = 2;
            break;
          case 2:
            chunk[i4++] = b64[t5 | b2 >> 6];
            chunk[i4++] = b64[b2 & 63];
            j2 = 0;
            break;
        }
        if (i4 > 8191) {
          (parts || (parts = [])).push(String.fromCharCode.apply(String, chunk));
          i4 = 0;
        }
      }
      if (j2) {
        chunk[i4++] = b64[t5];
        chunk[i4++] = 61;
        if (j2 === 1)
          chunk[i4++] = 61;
      }
      if (parts) {
        if (i4)
          parts.push(String.fromCharCode.apply(String, chunk.slice(0, i4)));
        return parts.join("");
      }
      return String.fromCharCode.apply(String, chunk.slice(0, i4));
    }, "encode");
    var invalidEncoding = "invalid encoding";
    base642.decode = /* @__PURE__ */ __name(function decode2(string4, buffer, offset) {
      var start = offset;
      var j2 = 0, t5;
      for (var i4 = 0; i4 < string4.length; ) {
        var c4 = string4.charCodeAt(i4++);
        if (c4 === 61 && j2 > 1)
          break;
        if ((c4 = s64[c4]) === void 0)
          throw Error(invalidEncoding);
        switch (j2) {
          case 0:
            t5 = c4;
            j2 = 1;
            break;
          case 1:
            buffer[offset++] = t5 << 2 | (c4 & 48) >> 4;
            t5 = c4;
            j2 = 2;
            break;
          case 2:
            buffer[offset++] = (t5 & 15) << 4 | (c4 & 60) >> 2;
            t5 = c4;
            j2 = 3;
            break;
          case 3:
            buffer[offset++] = (t5 & 3) << 6 | c4;
            j2 = 0;
            break;
        }
      }
      if (j2 === 1)
        throw Error(invalidEncoding);
      return offset - start;
    }, "decode");
    base642.test = /* @__PURE__ */ __name(function test(string4) {
      return /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(string4);
    }, "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 = EventEmitter11;
    function EventEmitter11() {
      this._listeners = {};
    }
    __name(EventEmitter11, "EventEmitter");
    EventEmitter11.prototype.on = /* @__PURE__ */ __name(function on(evt, fn, ctx) {
      (this._listeners[evt] || (this._listeners[evt] = [])).push({
        fn,
        ctx: ctx || this
      });
      return this;
    }, "on");
    EventEmitter11.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 i3 = 0; i3 < listeners.length; )
            if (listeners[i3].fn === fn)
              listeners.splice(i3, 1);
            else
              ++i3;
        }
      }
      return this;
    }, "off");
    EventEmitter11.prototype.emit = /* @__PURE__ */ __name(function emit(evt) {
      var listeners = this._listeners[evt];
      if (listeners) {
        var args = [], i3 = 1;
        for (; i3 < arguments.length; )
          args.push(arguments[i3++]);
        for (i3 = 0; i3 < listeners.length; )
          listeners[i3].fn.apply(listeners[i3++].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), le2 = 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 = le2 ? writeFloat_f32_cpy : writeFloat_f32_rev;
        exports3.writeFloatBE = le2 ? 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 = le2 ? readFloat_f32_cpy : readFloat_f32_rev;
        exports3.readFloatBE = le2 ? 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), le2 = 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 = le2 ? writeDouble_f64_cpy : writeDouble_f64_rev;
        exports3.writeDoubleBE = le2 ? 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 = le2 ? readDouble_f64_cpy : readDouble_f64_rev;
        exports3.readDoubleBE = le2 ? 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 (e4) {
      }
      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(string4) {
      var len = 0, c4 = 0;
      for (var i3 = 0; i3 < string4.length; ++i3) {
        c4 = string4.charCodeAt(i3);
        if (c4 < 128)
          len += 1;
        else if (c4 < 2048)
          len += 2;
        else if ((c4 & 64512) === 55296 && (string4.charCodeAt(i3 + 1) & 64512) === 56320) {
          ++i3;
          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 = [], i3 = 0, t5;
      while (start < end) {
        t5 = buffer[start++];
        if (t5 < 128)
          chunk[i3++] = t5;
        else if (t5 > 191 && t5 < 224)
          chunk[i3++] = (t5 & 31) << 6 | buffer[start++] & 63;
        else if (t5 > 239 && t5 < 365) {
          t5 = ((t5 & 7) << 18 | (buffer[start++] & 63) << 12 | (buffer[start++] & 63) << 6 | buffer[start++] & 63) - 65536;
          chunk[i3++] = 55296 + (t5 >> 10);
          chunk[i3++] = 56320 + (t5 & 1023);
        } else
          chunk[i3++] = (t5 & 15) << 12 | (buffer[start++] & 63) << 6 | buffer[start++] & 63;
        if (i3 > 8191) {
          (parts || (parts = [])).push(String.fromCharCode.apply(String, chunk));
          i3 = 0;
        }
      }
      if (parts) {
        if (i3)
          parts.push(String.fromCharCode.apply(String, chunk.slice(0, i3)));
        return parts.join("");
      }
      return String.fromCharCode.apply(String, chunk.slice(0, i3));
    }, "utf8_read");
    utf8.write = /* @__PURE__ */ __name(function utf8_write(string4, buffer, offset) {
      var start = offset, c1, c22;
      for (var i3 = 0; i3 < string4.length; ++i3) {
        c1 = string4.charCodeAt(i3);
        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 = string4.charCodeAt(i3 + 1)) & 64512) === 56320) {
          c1 = 65536 + ((c1 & 1023) << 10) + (c22 & 1023);
          ++i3;
          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 util3 = 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 (util3.isString(value)) {
        if (util3.Long)
          value = util3.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 util3.Long ? new util3.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 util3 = exports2;
    util3.asPromise = require_aspromise();
    util3.base64 = require_base64();
    util3.EventEmitter = require_eventemitter();
    util3.float = require_float();
    util3.inquire = require_inquire();
    util3.utf8 = require_utf8();
    util3.pool = require_pool2();
    util3.LongBits = require_longbits();
    util3.isNode = Boolean(typeof globalThis !== "undefined" && globalThis && globalThis.process && globalThis.process.versions && globalThis.process.versions.node);
    util3.global = util3.isNode && globalThis || typeof window !== "undefined" && window || typeof self !== "undefined" && self || exports2;
    util3.emptyArray = Object.freeze ? Object.freeze([]) : (
      /* istanbul ignore next */
      []
    );
    util3.emptyObject = Object.freeze ? Object.freeze({}) : (
      /* istanbul ignore next */
      {}
    );
    util3.isInteger = Number.isInteger || /* istanbul ignore next */
    /* @__PURE__ */ __name(function isInteger2(value) {
      return typeof value === "number" && isFinite(value) && Math.floor(value) === value;
    }, "isInteger");
    util3.isString = /* @__PURE__ */ __name(function isString2(value) {
      return typeof value === "string" || value instanceof String;
    }, "isString");
    util3.isObject = /* @__PURE__ */ __name(function isObject4(value) {
      return value && typeof value === "object";
    }, "isObject");
    util3.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`
     */
    util3.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");
    util3.Buffer = function() {
      try {
        var Buffer9 = util3.inquire("buffer").Buffer;
        return Buffer9.prototype.utf8Write ? Buffer9 : (
          /* istanbul ignore next */
          null
        );
      } catch (e4) {
        return null;
      }
    }();
    util3._Buffer_from = null;
    util3._Buffer_allocUnsafe = null;
    util3.newBuffer = /* @__PURE__ */ __name(function newBuffer(sizeOrArray) {
      return typeof sizeOrArray === "number" ? util3.Buffer ? util3._Buffer_allocUnsafe(sizeOrArray) : new util3.Array(sizeOrArray) : util3.Buffer ? util3._Buffer_from(sizeOrArray) : typeof Uint8Array === "undefined" ? sizeOrArray : new Uint8Array(sizeOrArray);
    }, "newBuffer");
    util3.Array = typeof Uint8Array !== "undefined" ? Uint8Array : Array;
    util3.Long = /* istanbul ignore next */
    util3.global.dcodeIO && /* istanbul ignore next */
    util3.global.dcodeIO.Long || /* istanbul ignore next */
    util3.global.Long || util3.inquire("long");
    util3.key2Re = /^true|false|0|1$/;
    util3.key32Re = /^-?(?:0|[1-9][0-9]*)$/;
    util3.key64Re = /^(?:[\\x00-\\xff]{8}|-?(?:0|[1-9][0-9]*))$/;
    util3.longToHash = /* @__PURE__ */ __name(function longToHash(value) {
      return value ? util3.LongBits.from(value).toHash() : util3.LongBits.zeroHash;
    }, "longToHash");
    util3.longFromHash = /* @__PURE__ */ __name(function longFromHash(hash, unsigned) {
      var bits = util3.LongBits.fromHash(hash);
      if (util3.Long)
        return util3.Long.fromBits(bits.lo, bits.hi, unsigned);
      return bits.toNumber(Boolean(unsigned));
    }, "longFromHash");
    function merge4(dst, src, ifNotSet) {
      for (var keys = Object.keys(src), i3 = 0; i3 < keys.length; ++i3)
        if (dst[keys[i3]] === void 0 || !ifNotSet)
          dst[keys[i3]] = src[keys[i3]];
      return dst;
    }
    __name(merge4, "merge");
    util3.merge = merge4;
    util3.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)
          merge4(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 get4() {
            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");
    util3.newError = newError;
    util3.ProtocolError = newError("ProtocolError");
    util3.oneOfGetter = /* @__PURE__ */ __name(function getOneOf(fieldNames) {
      var fieldMap = {};
      for (var i3 = 0; i3 < fieldNames.length; ++i3)
        fieldMap[fieldNames[i3]] = 1;
      return function() {
        for (var keys = Object.keys(this), i4 = keys.length - 1; i4 > -1; --i4)
          if (fieldMap[keys[i4]] === 1 && this[keys[i4]] !== void 0 && this[keys[i4]] !== null)
            return keys[i4];
      };
    }, "getOneOf");
    util3.oneOfSetter = /* @__PURE__ */ __name(function setOneOf(fieldNames) {
      return function(name3) {
        for (var i3 = 0; i3 < fieldNames.length; ++i3)
          if (fieldNames[i3] !== name3)
            delete this[fieldNames[i3]];
      };
    }, "setOneOf");
    util3.toJSONOptions = {
      longs: String,
      enums: String,
      bytes: String,
      json: true
    };
    util3._configure = function() {
      var Buffer9 = util3.Buffer;
      if (!Buffer9) {
        util3._Buffer_from = util3._Buffer_allocUnsafe = null;
        return;
      }
      util3._Buffer_from = Buffer9.from !== Uint8Array.from && Buffer9.from || /* istanbul ignore next */
      /* @__PURE__ */ __name(function Buffer_from(value, encoding) {
        return new Buffer9(value, encoding);
      }, "Buffer_from");
      util3._Buffer_allocUnsafe = Buffer9.allocUnsafe || /* istanbul ignore next */
      /* @__PURE__ */ __name(function Buffer_allocUnsafe(size) {
        return new Buffer9(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 util3 = require_minimal();
    var BufferWriter;
    var LongBits = util3.LongBits;
    var base642 = util3.base64;
    var utf8 = util3.utf8;
    function Op(fn, len, val) {
      this.fn = fn;
      this.len = len;
      this.next = void 0;
      this.val = val;
    }
    __name(Op, "Op");
    function noop8() {
    }
    __name(noop8, "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(noop8, 0, 0);
      this.tail = this.head;
      this.states = null;
    }
    __name(Writer, "Writer");
    var create3 = /* @__PURE__ */ __name(function create4() {
      return util3.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 util3.Array(size);
    }, "alloc");
    if (util3.Array !== Array)
      Writer.alloc = util3.pool(Writer.alloc, util3.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(util3.float.writeFloatLE, 4, value);
    }, "write_float");
    Writer.prototype.double = /* @__PURE__ */ __name(function write_double(value) {
      return this._push(util3.float.writeDoubleLE, 8, value);
    }, "write_double");
    var writeBytes = util3.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 i3 = 0; i3 < val.length; ++i3)
        buf[pos2 + i3] = val[i3];
    }, "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 (util3.isString(value)) {
        var buf = Writer.alloc(len = base642.length(value));
        base642.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(noop8, 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(noop8, 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 util3 = require_minimal();
    function BufferWriter() {
      Writer.call(this);
    }
    __name(BufferWriter, "BufferWriter");
    BufferWriter._configure = function() {
      BufferWriter.alloc = util3._Buffer_allocUnsafe;
      BufferWriter.writeBytesBuffer = util3.Buffer && util3.Buffer.prototype instanceof Uint8Array && util3.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 i3 = 0; i3 < val.length; )
          buf[pos2++] = val[i3++];
      }, "writeBytesBuffer_copy");
    };
    BufferWriter.prototype.bytes = /* @__PURE__ */ __name(function write_bytes_buffer(value) {
      if (util3.isString(value))
        value = util3._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)
        util3.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 = util3.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 util3 = require_minimal();
    var BufferReader;
    var LongBits = util3.LongBits;
    var utf8 = util3.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 util3.Buffer ? /* @__PURE__ */ __name(function create_buffer_setup(buffer) {
        return (Reader.create = /* @__PURE__ */ __name(function create_buffer(buffer2) {
          return util3.Buffer.isBuffer(buffer2) ? new BufferReader(buffer2) : create_array(buffer2);
        }, "create_buffer"))(buffer);
      }, "create_buffer_setup") : create_array;
    }, "create");
    Reader.create = create3();
    Reader.prototype._slice = util3.Array.prototype.subarray || /* istanbul ignore next */
    util3.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 i3 = 0;
      if (this.len - this.pos > 4) {
        for (; i3 < 4; ++i3) {
          bits.lo = (bits.lo | (this.buf[this.pos] & 127) << i3 * 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;
        i3 = 0;
      } else {
        for (; i3 < 3; ++i3) {
          if (this.pos >= this.len)
            throw indexOutOfRange(this);
          bits.lo = (bits.lo | (this.buf[this.pos] & 127) << i3 * 7) >>> 0;
          if (this.buf[this.pos++] < 128)
            return bits;
        }
        bits.lo = (bits.lo | (this.buf[this.pos++] & 127) << i3 * 7) >>> 0;
        return bits;
      }
      if (this.len - this.pos > 4) {
        for (; i3 < 5; ++i3) {
          bits.hi = (bits.hi | (this.buf[this.pos] & 127) << i3 * 7 + 3) >>> 0;
          if (this.buf[this.pos++] < 128)
            return bits;
        }
      } else {
        for (; i3 < 5; ++i3) {
          if (this.pos >= this.len)
            throw indexOutOfRange(this);
          bits.hi = (bits.hi | (this.buf[this.pos] & 127) << i3 * 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 = util3.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 = util3.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 = util3.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 = util3.Long ? "toLong" : (
        /* istanbul ignore next */
        "toNumber"
      );
      util3.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 util3 = require_minimal();
    function BufferReader(buffer) {
      Reader.call(this, buffer);
    }
    __name(BufferReader, "BufferReader");
    BufferReader._configure = function() {
      if (util3.Buffer)
        BufferReader.prototype._slice = util3.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 util3 = require_minimal();
    (Service.prototype = Object.create(util3.EventEmitter.prototype)).constructor = Service;
    function Service(rpcImpl, requestDelimited, responseDelimited) {
      if (typeof rpcImpl !== "function")
        throw TypeError("rpcImpl must be a function");
      util3.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 util3.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 = fetch5;
    var asPromise = require_aspromise();
    var inquire2 = require_inquire();
    var fs113 = inquire2("fs");
    function fetch5(filename, options2, callback) {
      if (typeof options2 === "function") {
        callback = options2;
        options2 = {};
      } else if (!options2)
        options2 = {};
      if (!callback)
        return asPromise(fetch5, this, filename, options2);
      if (!options2.xhr && fs113 && fs113.readFile)
        return fs113.readFile(filename, /* @__PURE__ */ __name(function fetchReadFileCallback(err, contents) {
          return err && typeof XMLHttpRequest !== "undefined" ? fetch5.xhr(filename, options2, callback) : err ? callback(err) : callback(null, options2.binary ? contents : contents.toString("utf8"));
        }, "fetchReadFileCallback"));
      return fetch5.xhr(filename, options2, callback);
    }
    __name(fetch5, "fetch");
    fetch5.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 i3 = 0; i3 < xhr.responseText.length; ++i3)
              buffer.push(xhr.responseText.charCodeAt(i3) & 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 path125 = exports2;
    var isAbsolute14 = (
      /**
       * Tests if the specified path is absolute.
       * @param {string} path Path to test
       * @returns {boolean} `true` if path is absolute
       */
      path125.isAbsolute = /* @__PURE__ */ __name(function isAbsolute15(path126) {
        return /^(?:\/|\w+:)/.test(path126);
      }, "isAbsolute")
    );
    var normalize12 = (
      /**
       * Normalizes the specified path.
       * @param {string} path Path to normalize
       * @returns {string} Normalized path
       */
      path125.normalize = /* @__PURE__ */ __name(function normalize13(path126) {
        path126 = path126.replace(/\\/g, "/").replace(/\/{2,}/g, "/");
        var parts = path126.split("/"), absolute = isAbsolute14(path126), prefix = "";
        if (absolute)
          prefix = parts.shift() + "/";
        for (var i3 = 0; i3 < parts.length; ) {
          if (parts[i3] === "..") {
            if (i3 > 0 && parts[i3 - 1] !== "..")
              parts.splice(--i3, 2);
            else if (absolute)
              parts.splice(i3, 1);
            else
              ++i3;
          } else if (parts[i3] === ".")
            parts.splice(i3, 1);
          else
            ++i3;
        }
        return prefix + parts.join("/");
      }, "normalize")
    );
    path125.resolve = /* @__PURE__ */ __name(function resolve30(originPath, includePath, alreadyNormalized) {
      if (!alreadyNormalized)
        includePath = normalize12(includePath);
      if (isAbsolute14(includePath))
        return includePath;
      if (!alreadyNormalized)
        originPath = normalize12(originPath);
      return (originPath = originPath.replace(/(?:\/|^)[^/]+$/, "")).length ? normalize12(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 util3 = require_util13();
    var OneOf = require_oneof();
    var Type3;
    var Service;
    var Enum;
    Namespace.fromJSON = /* @__PURE__ */ __name(function fromJSON(name3, json2) {
      return new Namespace(name3, json2.options).addJSON(json2.nested);
    }, "fromJSON");
    function arrayToJSON(array2, toJSONOptions) {
      if (!(array2 && array2.length))
        return void 0;
      var obj = {};
      for (var i3 = 0; i3 < array2.length; ++i3)
        obj[array2[i3].name] = array2[i3].toJSON(toJSONOptions);
      return obj;
    }
    __name(arrayToJSON, "arrayToJSON");
    Namespace.arrayToJSON = arrayToJSON;
    Namespace.isReservedId = /* @__PURE__ */ __name(function isReservedId(reserved, id) {
      if (reserved) {
        for (var i3 = 0; i3 < reserved.length; ++i3)
          if (typeof reserved[i3] !== "string" && reserved[i3][0] <= id && reserved[i3][1] > id)
            return true;
      }
      return false;
    }, "isReservedId");
    Namespace.isReservedName = /* @__PURE__ */ __name(function isReservedName(reserved, name3) {
      if (reserved) {
        for (var i3 = 0; i3 < reserved.length; ++i3)
          if (reserved[i3] === 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 = util3.toArray(this.nested));
      }, "get")
    });
    Namespace.prototype.toJSON = /* @__PURE__ */ __name(function toJSON(toJSONOptions) {
      return util3.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), i3 = 0, nested; i3 < names.length; ++i3) {
          nested = nestedJson[names[i3]];
          ns.add(
            // most to least likely
            (nested.fields !== void 0 ? Type3.fromJSON : nested.values !== void 0 ? Enum.fromJSON : nested.methods !== void 0 ? Service.fromJSON : nested.id !== void 0 ? Field.fromJSON : Namespace.fromJSON)(names[i3], nested)
          );
        }
      }
      return this;
    }, "addJSON");
    Namespace.prototype.get = /* @__PURE__ */ __name(function get4(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(object3) {
      if (!(object3 instanceof Field && object3.extend !== void 0 || object3 instanceof Type3 || object3 instanceof OneOf || object3 instanceof Enum || object3 instanceof Service || object3 instanceof Namespace))
        throw TypeError("object must be a valid nested object");
      if (!this.nested)
        this.nested = {};
      else {
        var prev = this.get(object3.name);
        if (prev) {
          if (prev instanceof Namespace && object3 instanceof Namespace && !(prev instanceof Type3 || prev instanceof Service)) {
            var nested = prev.nestedArray;
            for (var i3 = 0; i3 < nested.length; ++i3)
              object3.add(nested[i3]);
            this.remove(prev);
            if (!this.nested)
              this.nested = {};
            object3.setOptions(prev.options, true);
          } else
            throw Error("duplicate name '" + object3.name + "' in " + this);
        }
      }
      this.nested[object3.name] = object3;
      if (!(this instanceof Type3 || this instanceof Service || this instanceof Enum || this instanceof Field)) {
        if (!object3._edition) {
          object3._edition = object3._defaultEdition;
        }
      }
      this._needsRecursiveFeatureResolution = true;
      this._needsRecursiveResolve = true;
      var parent = this;
      while (parent = parent.parent) {
        parent._needsRecursiveFeatureResolution = true;
        parent._needsRecursiveResolve = true;
      }
      object3.onAdd(this);
      return clearCache(this);
    }, "add");
    Namespace.prototype.remove = /* @__PURE__ */ __name(function remove2(object3) {
      if (!(object3 instanceof ReflectionObject))
        throw TypeError("object must be a ReflectionObject");
      if (object3.parent !== this)
        throw Error(object3 + " is not a member of " + this);
      delete this.nested[object3.name];
      if (!Object.keys(this.nested).length)
        this.nested = void 0;
      object3.onRemove(this);
      return clearCache(this);
    }, "remove");
    Namespace.prototype.define = /* @__PURE__ */ __name(function define2(path125, json2) {
      if (util3.isString(path125))
        path125 = path125.split(".");
      else if (!Array.isArray(path125))
        throw TypeError("illegal path");
      if (path125 && path125.length && path125[0] === "")
        throw Error("path must be relative");
      var ptr = this;
      while (path125.length > 0) {
        var part = path125.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, i3 = 0;
      this.resolve();
      while (i3 < nested.length)
        if (nested[i3] instanceof Namespace)
          nested[i3++].resolveAll();
        else
          nested[i3++].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(path125, filterTypes, parentAlreadyChecked) {
      if (typeof filterTypes === "boolean") {
        parentAlreadyChecked = filterTypes;
        filterTypes = void 0;
      } else if (filterTypes && !Array.isArray(filterTypes))
        filterTypes = [filterTypes];
      if (util3.isString(path125) && path125.length) {
        if (path125 === ".")
          return this.root;
        path125 = path125.split(".");
      } else if (!path125.length)
        return this;
      var flatPath = path125.join(".");
      if (path125[0] === "")
        return this.root.lookup(path125.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(path125, 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(path125, flatPath);
        if (found && (!filterTypes || filterTypes.indexOf(found.constructor) > -1)) {
          return found;
        }
        current = current.parent;
      }
      return null;
    }, "lookup");
    Namespace.prototype._lookupImpl = /* @__PURE__ */ __name(function lookup(path125, flatPath) {
      if (Object.prototype.hasOwnProperty.call(this._lookupCache, flatPath)) {
        return this._lookupCache[flatPath];
      }
      var found = this.get(path125[0]);
      var exact = null;
      if (found) {
        if (path125.length === 1) {
          exact = found;
        } else if (found instanceof Namespace) {
          path125 = path125.slice(1);
          exact = found._lookupImpl(path125, path125.join("."));
        }
      } else {
        for (var i3 = 0; i3 < this.nestedArray.length; ++i3)
          if (this._nestedArray[i3] instanceof Namespace && (found = this._nestedArray[i3]._lookupImpl(path125, flatPath)))
            exact = found;
      }
      this._lookupCache[flatPath] = exact;
      return exact;
    }, "lookup");
    Namespace.prototype.lookupType = /* @__PURE__ */ __name(function lookupType(path125) {
      var found = this.lookup(path125, [Type3]);
      if (!found)
        throw Error("no such type: " + path125);
      return found;
    }, "lookupType");
    Namespace.prototype.lookupEnum = /* @__PURE__ */ __name(function lookupEnum(path125) {
      var found = this.lookup(path125, [Enum]);
      if (!found)
        throw Error("no such Enum '" + path125 + "' in " + this);
      return found;
    }, "lookupEnum");
    Namespace.prototype.lookupTypeOrEnum = /* @__PURE__ */ __name(function lookupTypeOrEnum(path125) {
      var found = this.lookup(path125, [Type3, Enum]);
      if (!found)
        throw Error("no such Type or Enum '" + path125 + "' in " + this);
      return found;
    }, "lookupTypeOrEnum");
    Namespace.prototype.lookupService = /* @__PURE__ */ __name(function lookupService(path125) {
      var found = this.lookup(path125, [Service]);
      if (!found)
        throw Error("no such Service '" + path125 + "' in " + this);
      return found;
    }, "lookupService");
    Namespace._configure = function(Type_, Service_, Enum_) {
      Type3 = 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 types7 = require_types3();
    var util3 = require_util13();
    function MapField(name3, id, keyType, type, options2, comment) {
      Field.call(this, name3, id, type, void 0, void 0, options2, comment);
      if (!util3.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 util3.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 resolve30() {
      if (this.resolved)
        return this;
      if (types7.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 = util3.decorateType(fieldValueType).name;
      else if (fieldValueType && typeof fieldValueType === "object")
        fieldValueType = util3.decorateEnum(fieldValueType).name;
      return /* @__PURE__ */ __name(function mapFieldDecorator(prototype, fieldName) {
        util3.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 util3 = require_util13();
    function Method(name3, type, requestType, responseType, requestStream, responseStream, options2, comment, parsedOptions) {
      if (util3.isObject(requestStream)) {
        options2 = requestStream;
        requestStream = responseStream = void 0;
      } else if (util3.isObject(responseStream)) {
        options2 = responseStream;
        responseStream = void 0;
      }
      if (!(type === void 0 || util3.isString(type)))
        throw TypeError("type must be a string");
      if (!util3.isString(requestType))
        throw TypeError("requestType must be a string");
      if (!util3.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 util3.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 resolve30() {
      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 util3 = require_util13();
    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), i3 = 0; i3 < names.length; ++i3)
          service.add(Method.fromJSON(names[i3], json2.methods[names[i3]]));
      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 util3.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 = util3.toArray(this.methods));
      }, "get")
    });
    function clearCache(service) {
      service._methodsArray = null;
      return service;
    }
    __name(clearCache, "clearCache");
    Service.prototype.get = /* @__PURE__ */ __name(function get4(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 i3 = 0; i3 < methods.length; ++i3)
        methods[i3].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(object3) {
      if (this.get(object3.name))
        throw Error("duplicate name '" + object3.name + "' in " + this);
      if (object3 instanceof Method) {
        this.methods[object3.name] = object3;
        object3.parent = this;
        return clearCache(this);
      }
      return Namespace.prototype.add.call(this, object3);
    }, "add");
    Service.prototype.remove = /* @__PURE__ */ __name(function remove2(object3) {
      if (object3 instanceof Method) {
        if (this.methods[object3.name] !== object3)
          throw Error(object3 + " is not a member of " + this);
        delete this.methods[object3.name];
        object3.parent = null;
        return clearCache(this);
      }
      return Namespace.prototype.remove.call(this, object3);
    }, "remove");
    Service.prototype.create = /* @__PURE__ */ __name(function create3(rpcImpl, requestDelimited, responseDelimited) {
      var rpcService = new rpc.Service(rpcImpl, requestDelimited, responseDelimited);
      for (var i3 = 0, method; i3 < /* initializes */
      this.methodsArray.length; ++i3) {
        var methodName = util3.lcFirst((method = this._methodsArray[i3]).resolve().name).replace(/[^$\w_]/g, "");
        rpcService[methodName] = util3.codegen(["r", "c"], util3.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 util3 = require_minimal();
    function Message(properties) {
      if (properties)
        for (var keys = Object.keys(properties), i3 = 0; i3 < keys.length; ++i3)
          this[keys[i3]] = properties[keys[i3]];
    }
    __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(object3) {
      return this.$type.fromObject(object3);
    }, "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, util3.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 types7 = require_types3();
    var util3 = require_util13();
    function missing(field) {
      return "missing required '" + field.name + "'";
    }
    __name(missing, "missing");
    function decoder(mtype) {
      var gen = util3.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 i3 = 0;
      for (; i3 < /* initializes */
      mtype.fieldsArray.length; ++i3) {
        var field = mtype._fieldsArray[i3].resolve(), type = field.resolvedType instanceof Enum ? "int32" : field.type, ref = "m" + util3.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 (types7.defaults[field.keyType] !== void 0) gen("k=%j", types7.defaults[field.keyType]);
          else gen("k=null");
          if (types7.defaults[type] !== void 0) gen("value=%j", types7.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 (types7.basic[type] === void 0) gen("value=types[%i].decode(r,r.uint32())", i3);
          else gen("value=r.%s()", type);
          gen("break")("default:")("r.skipType(tag2&7)")("break")("}")("}");
          if (types7.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 (types7.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 (types7.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, i3);
          else gen("%s.push(r.%s())", ref, type);
        } else if (types7.basic[type] === void 0) gen(field.delimited ? "%s=types[%i].decode(r,undefined,((t&~7)|4))" : "%s=types[%i].decode(r,r.uint32())", ref, i3);
        else gen("%s=r.%s()", ref, type);
        gen("break")("}");
      }
      gen("default:")("r.skipType(t&7)")("break")("}")("}");
      for (i3 = 0; i3 < mtype._fieldsArray.length; ++i3) {
        var rfield = mtype._fieldsArray[i3];
        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 util3 = require_util13();
    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), j2 = 0; j2 < keys.length; ++j2) gen("case %i:", field.resolvedType.values[keys[j2]]);
          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 = util3.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 i3 = 0; i3 < /* initializes */
      mtype.fieldsArray.length; ++i3) {
        var field = mtype._fieldsArray[i3].resolve(), ref = "m" + util3.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, i3, 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, i3, ref + "[i]")("}");
        } else {
          if (field.partOf) {
            var oneofProp = util3.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, i3, 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 util3 = require_util13();
    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), i3 = 0; i3 < keys.length; ++i3) {
            if (values[keys[i3]] === 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[i3])("case %i:", values[keys[i3]])("m%s=%j", prop, values[keys[i3]])("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 = util3.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 i3 = 0; i3 < fields.length; ++i3) {
        var field = fields[i3].resolve(), prop = util3.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 */
            i3,
            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 */
            i3,
            prop + "[i]"
          )("}")("}");
        } else {
          if (!(field.resolvedType instanceof Enum)) gen("if(d%s!=null){", prop);
          genValuePartial_fromObject(
            gen,
            field,
            /* not sorted */
            i3,
            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(util3.compareFieldsById);
      if (!fields.length)
        return util3.codegen()("return {}");
      var gen = util3.codegen(["m", "o"], mtype.name + "$toObject")("if(!o)")("o={}")("var d={}");
      var repeatedFields = [], mapFields = [], normalFields = [], i3 = 0;
      for (; i3 < fields.length; ++i3)
        if (!fields[i3].partOf)
          (fields[i3].resolve().repeated ? repeatedFields : fields[i3].map ? mapFields : normalFields).push(fields[i3]);
      if (repeatedFields.length) {
        gen("if(o.arrays||o.defaults){");
        for (i3 = 0; i3 < repeatedFields.length; ++i3) gen("d%s=[]", util3.safeProp(repeatedFields[i3].name));
        gen("}");
      }
      if (mapFields.length) {
        gen("if(o.objects||o.defaults){");
        for (i3 = 0; i3 < mapFields.length; ++i3) gen("d%s={}", util3.safeProp(mapFields[i3].name));
        gen("}");
      }
      if (normalFields.length) {
        gen("if(o.defaults){");
        for (i3 = 0; i3 < normalFields.length; ++i3) {
          var field = normalFields[i3], prop = util3.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 (i3 = 0; i3 < fields.length; ++i3) {
        var field = fields[i3], index = mtype._fieldsArray.indexOf(field), prop = util3.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", util3.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(object3) {
        if (object3 && object3["@type"]) {
          var name3 = object3["@type"].substring(object3["@type"].lastIndexOf("/") + 1);
          var type = this.lookup(name3);
          if (type) {
            var type_url = object3["@type"].charAt(0) === "." ? object3["@type"].slice(1) : object3["@type"];
            if (type_url.indexOf("/") === -1) {
              type_url = "/" + type_url;
            }
            return this.create({
              type_url,
              value: type.encode(type.fromObject(object3)).finish()
            });
          }
        }
        return this.fromObject(object3);
      }, "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 object3 = 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;
          object3["@type"] = name3;
          return object3;
        }
        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 = Type3;
    var Namespace = require_namespace();
    ((Type3.prototype = Object.create(Namespace.prototype)).constructor = Type3).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 util3 = require_util13();
    var encoder = require_encoder();
    var decoder = require_decoder();
    var verifier = require_verifier();
    var converter = require_converter();
    var wrappers = require_wrappers();
    function Type3(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(Type3, "Type");
    Object.defineProperties(Type3.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), i3 = 0; i3 < names.length; ++i3) {
            var field = this.fields[names[i3]], 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 = util3.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 = util3.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 = Type3.generateConstructor(this)());
        }, "get"),
        set: /* @__PURE__ */ __name(function(ctor) {
          var prototype = ctor.prototype;
          if (!(prototype instanceof Message)) {
            (ctor.prototype = new Message()).constructor = ctor;
            util3.merge(ctor.prototype, prototype);
          }
          ctor.$type = ctor.prototype.$type = this;
          util3.merge(ctor, Message, true);
          this._ctor = ctor;
          var i3 = 0;
          for (; i3 < /* initializes */
          this.fieldsArray.length; ++i3)
            this._fieldsArray[i3].resolve();
          var ctorProperties = {};
          for (i3 = 0; i3 < /* initializes */
          this.oneofsArray.length; ++i3)
            ctorProperties[this._oneofsArray[i3].resolve().name] = {
              get: util3.oneOfGetter(this._oneofsArray[i3].oneof),
              set: util3.oneOfSetter(this._oneofsArray[i3].oneof)
            };
          if (i3)
            Object.defineProperties(ctor.prototype, ctorProperties);
        }, "set")
      }
    });
    Type3.generateConstructor = /* @__PURE__ */ __name(function generateConstructor(mtype) {
      var gen = util3.codegen(["p"], mtype.name);
      for (var i3 = 0, field; i3 < mtype.fieldsArray.length; ++i3)
        if ((field = mtype._fieldsArray[i3]).map) gen("this%s={}", util3.safeProp(field.name));
        else if (field.repeated) gen("this%s=[]", util3.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");
    Type3.fromJSON = /* @__PURE__ */ __name(function fromJSON(name3, json2) {
      var type = new Type3(name3, json2.options);
      type.extensions = json2.extensions;
      type.reserved = json2.reserved;
      var names = Object.keys(json2.fields), i3 = 0;
      for (; i3 < names.length; ++i3)
        type.add(
          (typeof json2.fields[names[i3]].keyType !== "undefined" ? MapField.fromJSON : Field.fromJSON)(names[i3], json2.fields[names[i3]])
        );
      if (json2.oneofs)
        for (names = Object.keys(json2.oneofs), i3 = 0; i3 < names.length; ++i3)
          type.add(OneOf.fromJSON(names[i3], json2.oneofs[names[i3]]));
      if (json2.nested)
        for (names = Object.keys(json2.nested), i3 = 0; i3 < names.length; ++i3) {
          var nested = json2.nested[names[i3]];
          type.add(
            // most to least likely
            (nested.id !== void 0 ? Field.fromJSON : nested.fields !== void 0 ? Type3.fromJSON : nested.values !== void 0 ? Enum.fromJSON : nested.methods !== void 0 ? Service.fromJSON : Namespace.fromJSON)(names[i3], 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");
    Type3.prototype.toJSON = /* @__PURE__ */ __name(function toJSON(toJSONOptions) {
      var inherited = Namespace.prototype.toJSON.call(this, toJSONOptions);
      var keepComments = toJSONOptions ? Boolean(toJSONOptions.keepComments) : false;
      return util3.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");
    Type3.prototype.resolveAll = /* @__PURE__ */ __name(function resolveAll() {
      if (!this._needsRecursiveResolve) return this;
      Namespace.prototype.resolveAll.call(this);
      var oneofs = this.oneofsArray;
      i3 = 0;
      while (i3 < oneofs.length)
        oneofs[i3++].resolve();
      var fields = this.fieldsArray, i3 = 0;
      while (i3 < fields.length)
        fields[i3++].resolve();
      return this;
    }, "resolveAll");
    Type3.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");
    Type3.prototype.get = /* @__PURE__ */ __name(function get4(name3) {
      return this.fields[name3] || this.oneofs && this.oneofs[name3] || this.nested && this.nested[name3] || null;
    }, "get");
    Type3.prototype.add = /* @__PURE__ */ __name(function add(object3) {
      if (this.get(object3.name))
        throw Error("duplicate name '" + object3.name + "' in " + this);
      if (object3 instanceof Field && object3.extend === void 0) {
        if (this._fieldsById ? (
          /* istanbul ignore next */
          this._fieldsById[object3.id]
        ) : this.fieldsById[object3.id])
          throw Error("duplicate id " + object3.id + " in " + this);
        if (this.isReservedId(object3.id))
          throw Error("id " + object3.id + " is reserved in " + this);
        if (this.isReservedName(object3.name))
          throw Error("name '" + object3.name + "' is reserved in " + this);
        if (object3.parent)
          object3.parent.remove(object3);
        this.fields[object3.name] = object3;
        object3.message = this;
        object3.onAdd(this);
        return clearCache(this);
      }
      if (object3 instanceof OneOf) {
        if (!this.oneofs)
          this.oneofs = {};
        this.oneofs[object3.name] = object3;
        object3.onAdd(this);
        return clearCache(this);
      }
      return Namespace.prototype.add.call(this, object3);
    }, "add");
    Type3.prototype.remove = /* @__PURE__ */ __name(function remove2(object3) {
      if (object3 instanceof Field && object3.extend === void 0) {
        if (!this.fields || this.fields[object3.name] !== object3)
          throw Error(object3 + " is not a member of " + this);
        delete this.fields[object3.name];
        object3.parent = null;
        object3.onRemove(this);
        return clearCache(this);
      }
      if (object3 instanceof OneOf) {
        if (!this.oneofs || this.oneofs[object3.name] !== object3)
          throw Error(object3 + " is not a member of " + this);
        delete this.oneofs[object3.name];
        object3.parent = null;
        object3.onRemove(this);
        return clearCache(this);
      }
      return Namespace.prototype.remove.call(this, object3);
    }, "remove");
    Type3.prototype.isReservedId = /* @__PURE__ */ __name(function isReservedId(id) {
      return Namespace.isReservedId(this.reserved, id);
    }, "isReservedId");
    Type3.prototype.isReservedName = /* @__PURE__ */ __name(function isReservedName(name3) {
      return Namespace.isReservedName(this.reserved, name3);
    }, "isReservedName");
    Type3.prototype.create = /* @__PURE__ */ __name(function create3(properties) {
      return new this.ctor(properties);
    }, "create");
    Type3.prototype.setup = /* @__PURE__ */ __name(function setup() {
      var fullName = this.fullName, types7 = [];
      for (var i3 = 0; i3 < /* initializes */
      this.fieldsArray.length; ++i3)
        types7.push(this._fieldsArray[i3].resolve().resolvedType);
      this.encode = encoder(this)({
        Writer,
        types: types7,
        util: util3
      });
      this.decode = decoder(this)({
        Reader,
        types: types7,
        util: util3
      });
      this.verify = verifier(this)({
        types: types7,
        util: util3
      });
      this.fromObject = converter.fromObject(this)({
        types: types7,
        util: util3
      });
      this.toObject = converter.toObject(this)({
        types: types7,
        util: util3
      });
      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");
    Type3.prototype.encode = /* @__PURE__ */ __name(function encode_setup(message, writer) {
      return this.setup().encode(message, writer);
    }, "encode_setup");
    Type3.prototype.encodeDelimited = /* @__PURE__ */ __name(function encodeDelimited(message, writer) {
      return this.encode(message, writer && writer.len ? writer.fork() : writer).ldelim();
    }, "encodeDelimited");
    Type3.prototype.decode = /* @__PURE__ */ __name(function decode_setup(reader, length) {
      return this.setup().decode(reader, length);
    }, "decode_setup");
    Type3.prototype.decodeDelimited = /* @__PURE__ */ __name(function decodeDelimited(reader) {
      if (!(reader instanceof Reader))
        reader = Reader.create(reader);
      return this.decode(reader, reader.uint32());
    }, "decodeDelimited");
    Type3.prototype.verify = /* @__PURE__ */ __name(function verify_setup(message) {
      return this.setup().verify(message);
    }, "verify_setup");
    Type3.prototype.fromObject = /* @__PURE__ */ __name(function fromObject(object3) {
      return this.setup().fromObject(object3);
    }, "fromObject");
    Type3.prototype.toObject = /* @__PURE__ */ __name(function toObject(message, options2) {
      return this.setup().toObject(message, options2);
    }, "toObject");
    Type3.d = /* @__PURE__ */ __name(function decorateType(typeName) {
      return /* @__PURE__ */ __name(function typeDecorator(target) {
        util3.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 util3 = require_util13();
    var Type3;
    var parse14;
    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 = util3.path.resolve;
    Root2.prototype.fetch = util3.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 util3.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 process50(filename2, source2) {
        try {
          if (util3.isString(source2) && source2.charAt(0) === "{")
            source2 = JSON.parse(source2);
          if (!util3.isString(source2))
            self2.setOptions(source2.options).addJSON(source2.nested);
          else {
            parse14.filename = filename2;
            var parsed = parse14(source2, self2, options2), resolved2, i4 = 0;
            if (parsed.imports) {
              for (; i4 < parsed.imports.length; ++i4)
                if (resolved2 = getBundledFileName(parsed.imports[i4]) || self2.resolvePath(filename2, parsed.imports[i4]))
                  fetch5(resolved2);
            }
            if (parsed.weakImports) {
              for (i4 = 0; i4 < parsed.weakImports.length; ++i4)
                if (resolved2 = getBundledFileName(parsed.weakImports[i4]) || self2.resolvePath(filename2, parsed.weakImports[i4]))
                  fetch5(resolved2, true);
            }
          }
        } catch (err) {
          finish(err);
        }
        if (!sync2 && !queued) {
          finish(null, self2);
        }
      }
      __name(process50, "process");
      function fetch5(filename2, weak) {
        filename2 = getBundledFileName(filename2) || filename2;
        if (self2.files.indexOf(filename2) > -1) {
          return;
        }
        self2.files.push(filename2);
        if (filename2 in common) {
          if (sync2) {
            process50(filename2, common[filename2]);
          } else {
            ++queued;
            setTimeout(function() {
              --queued;
              process50(filename2, common[filename2]);
            });
          }
          return;
        }
        if (sync2) {
          var source2;
          try {
            source2 = util3.fs.readFileSync(filename2).toString("utf8");
          } catch (err) {
            if (!weak)
              finish(err);
            return;
          }
          process50(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;
            }
            process50(filename2, source3);
          });
        }
      }
      __name(fetch5, "fetch");
      var queued = 0;
      if (util3.isString(filename)) {
        filename = [filename];
      }
      for (var i3 = 0, resolved; i3 < filename.length; ++i3)
        if (resolved = self2.resolvePath("", filename[i3]))
          fetch5(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 (!util3.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(object3) {
      if (object3 instanceof Field) {
        if (
          /* an extension field (implies not part of a oneof) */
          object3.extend !== void 0 && /* not already handled */
          !object3.extensionField
        ) {
          if (!tryHandleExtension(this, object3))
            this.deferred.push(object3);
        }
      } else if (object3 instanceof Enum) {
        if (exposeRe.test(object3.name))
          object3.parent[object3.name] = object3.values;
      } else if (!(object3 instanceof OneOf)) {
        if (object3 instanceof Type3)
          for (var i3 = 0; i3 < this.deferred.length; )
            if (tryHandleExtension(this, this.deferred[i3]))
              this.deferred.splice(i3, 1);
            else
              ++i3;
        for (var j2 = 0; j2 < /* initializes */
        object3.nestedArray.length; ++j2)
          this._handleAdd(object3._nestedArray[j2]);
        if (exposeRe.test(object3.name))
          object3.parent[object3.name] = object3;
      }
      if (object3 instanceof Type3 || object3 instanceof Enum || object3 instanceof Field) {
        this._fullyQualifiedObjects[object3.fullName] = object3;
      }
    }, "_handleAdd");
    Root2.prototype._handleRemove = /* @__PURE__ */ __name(function _handleRemove(object3) {
      if (object3 instanceof Field) {
        if (
          /* an extension field */
          object3.extend !== void 0
        ) {
          if (
            /* already handled */
            object3.extensionField
          ) {
            object3.extensionField.parent.remove(object3.extensionField);
            object3.extensionField = null;
          } else {
            var index = this.deferred.indexOf(object3);
            if (index > -1)
              this.deferred.splice(index, 1);
          }
        }
      } else if (object3 instanceof Enum) {
        if (exposeRe.test(object3.name))
          delete object3.parent[object3.name];
      } else if (object3 instanceof Namespace) {
        for (var i3 = 0; i3 < /* initializes */
        object3.nestedArray.length; ++i3)
          this._handleRemove(object3._nestedArray[i3]);
        if (exposeRe.test(object3.name))
          delete object3.parent[object3.name];
      }
      delete this._fullyQualifiedObjects[object3.fullName];
    }, "_handleRemove");
    Root2._configure = function(Type_, parse_2, common_) {
      Type3 = Type_;
      parse14 = parse_2;
      common = common_;
    };
  }
});

// node_modules/protobufjs/src/util.js
var require_util13 = __commonJS({
  "node_modules/protobufjs/src/util.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var util3 = module2.exports = require_minimal();
    var roots = require_roots();
    var Type3;
    var Enum;
    util3.codegen = require_codegen3();
    util3.fetch = require_fetch2();
    util3.path = require_path();
    util3.fs = util3.inquire("fs");
    util3.toArray = /* @__PURE__ */ __name(function toArray(object3) {
      if (object3) {
        var keys = Object.keys(object3), array2 = new Array(keys.length), index = 0;
        while (index < keys.length)
          array2[index] = object3[keys[index++]];
        return array2;
      }
      return [];
    }, "toArray");
    util3.toObject = /* @__PURE__ */ __name(function toObject(array2) {
      var object3 = {}, index = 0;
      while (index < array2.length) {
        var key = array2[index++], val = array2[index++];
        if (val !== void 0)
          object3[key] = val;
      }
      return object3;
    }, "toObject");
    var safePropBackslashRe = /\\/g;
    var safePropQuoteRe = /"/g;
    util3.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");
    util3.safeProp = /* @__PURE__ */ __name(function safeProp(prop) {
      if (!/^[$\w_]+$/.test(prop) || util3.isReserved(prop))
        return '["' + prop.replace(safePropBackslashRe, "\\\\").replace(safePropQuoteRe, '\\"') + '"]';
      return "." + prop;
    }, "safeProp");
    util3.ucFirst = /* @__PURE__ */ __name(function ucFirst(str2) {
      return str2.charAt(0).toUpperCase() + str2.substring(1);
    }, "ucFirst");
    var camelCaseRe = /_([a-z])/g;
    util3.camelCase = /* @__PURE__ */ __name(function camelCase3(str2) {
      return str2.substring(0, 1) + str2.substring(1).replace(camelCaseRe, function($0, $1) {
        return $1.toUpperCase();
      });
    }, "camelCase");
    util3.compareFieldsById = /* @__PURE__ */ __name(function compareFieldsById(a2, b2) {
      return a2.id - b2.id;
    }, "compareFieldsById");
    util3.decorateType = /* @__PURE__ */ __name(function decorateType(ctor, typeName) {
      if (ctor.$type) {
        if (typeName && ctor.$type.name !== typeName) {
          util3.decorateRoot.remove(ctor.$type);
          ctor.$type.name = typeName;
          util3.decorateRoot.add(ctor.$type);
        }
        return ctor.$type;
      }
      if (!Type3)
        Type3 = require_type();
      var type = new Type3(typeName || ctor.name);
      util3.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;
    util3.decorateEnum = /* @__PURE__ */ __name(function decorateEnum(object3) {
      if (object3.$type)
        return object3.$type;
      if (!Enum)
        Enum = require_enum3();
      var enm = new Enum("Enum" + decorateEnumIndex++, object3);
      util3.decorateRoot.add(enm);
      Object.defineProperty(object3, "$type", { value: enm, enumerable: false });
      return enm;
    }, "decorateEnum");
    util3.setProperty = /* @__PURE__ */ __name(function setProperty2(dst, path125, value, ifNotSet) {
      function setProp(dst2, path126, value2) {
        var part = path126.shift();
        if (part === "__proto__" || part === "prototype") {
          return dst2;
        }
        if (path126.length > 0) {
          dst2[part] = setProp(dst2[part] || {}, path126, 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 (!path125)
        throw TypeError("path must be specified");
      path125 = path125.split(".");
      return setProp(dst, path125, value);
    }, "setProperty");
    Object.defineProperty(util3, "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 types7 = exports2;
    var util3 = require_util13();
    var s5 = [
      "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 i3 = 0, o3 = {};
      offset |= 0;
      while (i3 < values.length) o3[s5[i3 + offset]] = values[i3++];
      return o3;
    }
    __name(bake, "bake");
    types7.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
    ]);
    types7.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    */
      util3.emptyArray,
      /* message  */
      null
    ]);
    types7.long = bake([
      /* int64    */
      0,
      /* uint64   */
      0,
      /* sint64   */
      0,
      /* fixed64  */
      1,
      /* sfixed64 */
      1
    ], 7);
    types7.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);
    types7.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 types7 = require_types3();
    var util3 = require_util13();
    var Type3;
    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, extend2, options2, comment) {
      if (util3.isObject(rule)) {
        comment = extend2;
        options2 = rule;
        rule = extend2 = void 0;
      } else if (util3.isObject(extend2)) {
        comment = options2;
        options2 = extend2;
        extend2 = void 0;
      }
      ReflectionObject.call(this, name3, options2);
      if (!util3.isInteger(id) || id < 0)
        throw TypeError("id must be a non-negative integer");
      if (!util3.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 (extend2 !== void 0 && !util3.isString(extend2))
        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 = extend2 || void 0;
      this.repeated = rule === "repeated";
      this.map = false;
      this.message = null;
      this.partOf = null;
      this.typeDefault = null;
      this.defaultValue = null;
      this.long = util3.Long ? types7.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 Type3 && 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 util3.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 resolve30() {
      if (this.resolved)
        return this;
      if ((this.typeDefault = types7.defaults[this.type]) === void 0) {
        this.resolvedType = (this.declaringField ? this.declaringField.parent : this.parent).lookupTypeOrEnum(this.type);
        if (this.resolvedType instanceof Type3)
          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 = util3.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 (util3.base64.test(this.typeDefault))
          util3.base64.decode(this.typeDefault, buf = util3.newBuffer(util3.base64.length(this.typeDefault)), 0);
        else
          util3.utf8.write(this.typeDefault, buf = util3.newBuffer(util3.utf8.length(this.typeDefault)), 0);
        this.typeDefault = buf;
      }
      if (this.map)
        this.defaultValue = util3.emptyObject;
      else if (this.repeated)
        this.defaultValue = util3.emptyArray;
      else
        this.defaultValue = this.typeDefault;
      if (this.parent instanceof Type3)
        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 && types7.defaults[this.type] === void 0) {
        var type = this.parent.get(this.type.split(".").pop());
        if (type && type instanceof Type3 && 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 = util3.decorateType(fieldType).name;
      else if (fieldType && typeof fieldType === "object")
        fieldType = util3.decorateEnum(fieldType).name;
      return /* @__PURE__ */ __name(function fieldDecorator(prototype, fieldName) {
        util3.decorateType(prototype.constructor).add(new Field(fieldName, fieldId, fieldType, fieldRule, { "default": defaultValue }));
      }, "fieldDecorator");
    }, "decorateField");
    Field._configure = /* @__PURE__ */ __name(function configure(Type_) {
      Type3 = 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 util3 = require_util13();
    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 util3.toObject([
        "options",
        this.options,
        "oneof",
        this.oneof,
        "comment",
        keepComments ? this.comment : void 0
      ]);
    }, "toJSON");
    function addFieldsToParent(oneof) {
      if (oneof.parent) {
        for (var i3 = 0; i3 < oneof.fieldsArray.length; ++i3)
          if (!oneof.fieldsArray[i3].parent)
            oneof.parent.add(oneof.fieldsArray[i3]);
      }
    }
    __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 i3 = 0; i3 < this.oneof.length; ++i3) {
        var field = parent.get(this.oneof[i3]);
        if (field && !field.partOf) {
          field.partOf = self2;
          self2.fieldsArray.push(field);
        }
      }
      addFieldsToParent(this);
    }, "onAdd");
    OneOf.prototype.onRemove = /* @__PURE__ */ __name(function onRemove(parent) {
      for (var i3 = 0, field; i3 < this.fieldsArray.length; ++i3)
        if ((field = this.fieldsArray[i3]).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) {
        util3.decorateType(prototype.constructor).add(new OneOf(oneofName, fieldNames));
        Object.defineProperty(prototype, oneofName, {
          get: util3.oneOfGetter(fieldNames),
          set: util3.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 util3 = require_util13();
    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 (!util3.isString(name3))
        throw TypeError("name must be a string");
      if (options2 && !util3.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 path125 = [this.name], ptr = this.parent;
          while (ptr) {
            path125.unshift(ptr.name);
            ptr = ptr.parent;
          }
          return path125.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 resolve30() {
      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)) {
        util3.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];
          util3.setProperty(newValue, propName, value);
        } else {
          opt = {};
          opt[name3] = util3.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), i3 = 0; i3 < keys.length; ++i3)
          this.setOption(keys[i3], options2[keys[i3]], 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 util3 = require_util13();
    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), i3 = 0; i3 < keys.length; ++i3)
          if (typeof values[keys[i3]] === "number")
            this.valuesById[this.values[keys[i3]] = values[keys[i3]]] = keys[i3];
      }
    }
    __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 util3.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 (!util3.isString(name3))
        throw TypeError("name must be a string");
      if (!util3.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 (!util3.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 types7 = require_types3();
    var util3 = require_util13();
    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 = util3.codegen(["m", "w"], mtype.name + "$encode")("if(!w)")("w=Writer.create()");
      var i3, ref;
      var fields = (
        /* initializes */
        mtype.fieldsArray.slice().sort(util3.compareFieldsById)
      );
      for (var i3 = 0; i3 < fields.length; ++i3) {
        var field = fields[i3].resolve(), index = mtype._fieldsArray.indexOf(field), type = field.resolvedType instanceof Enum ? "int32" : field.type, wireType = types7.basic[type];
        ref = "m" + util3.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 | types7.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 && types7.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_util13();
    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 = tokenize5;
    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");
    tokenize5.unescape = unescape4;
    function tokenize5(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 re3 = stringDelim === "'" ? stringSingleRe : stringDoubleRe;
        re3.lastIndex = offset - 1;
        var match2 = re3.exec(source2);
        if (!match2)
          throw illegal("string");
        offset = re3.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, c4;
        do {
          if (--commentOffset < 0 || (c4 = source2.charAt(commentOffset)) === "\n") {
            comment.lineEmpty = true;
            break;
          }
        } while (c4 === " " || c4 === "	");
        var lines = source2.substring(start, end).split(setCommentSplitRe);
        for (var i3 = 0; i3 < lines.length; ++i3)
          lines[i3] = lines[i3].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, optional2) {
        var actual = peek(), equals2 = actual === expected;
        if (equals2) {
          next();
          return true;
        }
        if (!optional2)
          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(tokenize5, "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 = parse14;
    parse14.filename = null;
    parse14.defaults = { keepCase: false };
    var tokenize5 = require_tokenize();
    var Root2 = require_root();
    var Type3 = 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 types7 = require_types3();
    var util3 = require_util13();
    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 parse14(source2, root, options2) {
      if (!(root instanceof Root2)) {
        options2 = root;
        root = new Root2();
      }
      if (!options2)
        options2 = parse14.defaults;
      var preferTrailingComment = options2.preferTrailingComment || false;
      var tn = tokenize5(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;
      } : util3.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 = parse14.filename;
        if (!insideTryCatch)
          parse14.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 (e4) {
          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 = parse14.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 Type3(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, extend2) {
        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, extend2);
        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 = util3.lcFirst(name3);
        if (name3 === fieldName)
          name3 = util3.ucFirst(name3);
        skip("=");
        var id = parseId(next());
        var type = new Type3(name3);
        type.group = true;
        var field = new Field(fieldName, id, name3, rule);
        field.filename = parse14.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 (types7.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();
      parse14.filename = null;
      return {
        "package": pkg2,
        "imports": imports,
        weakImports,
        root
      };
    }
    __name(parse14, "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 get4(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 Type3 = $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 j2 = 0, i3; j2 < descriptor2.file.length; ++j2) {
          filePackage = root;
          if ((fileDescriptor = descriptor2.file[j2])["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 (i3 = 0; i3 < fileDescriptor.messageType.length; ++i3)
              filePackage.add(Type3.fromDescriptor(fileDescriptor.messageType[i3], edition));
          if (fileDescriptor.enumType)
            for (i3 = 0; i3 < fileDescriptor.enumType.length; ++i3)
              filePackage.add(Enum.fromDescriptor(fileDescriptor.enumType[i3], edition));
          if (fileDescriptor.extension)
            for (i3 = 0; i3 < fileDescriptor.extension.length; ++i3)
              filePackage.add(Field.fromDescriptor(fileDescriptor.extension[i3], edition));
          if (fileDescriptor.service)
            for (i3 = 0; i3 < fileDescriptor.service.length; ++i3)
              filePackage.add(Service.fromDescriptor(fileDescriptor.service[i3], edition));
          var opts = fromDescriptorOptions(fileDescriptor.options, exports2.FileOptions);
          if (opts) {
            var ks = Object.keys(opts);
            for (i3 = 0; i3 < ks.length; ++i3)
              filePackage.setOption(ks[i3], opts[ks[i3]]);
          }
        }
      }
      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 i3 = 0, nested; i3 < ns.nestedArray.length; ++i3)
        if ((nested = ns._nestedArray[i3]) instanceof Type3)
          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;
    Type3.fromDescriptor = /* @__PURE__ */ __name(function fromDescriptor(descriptor2, edition, nested) {
      if (typeof descriptor2.length === "number")
        descriptor2 = exports2.DescriptorProto.decode(descriptor2);
      var type = new Type3(descriptor2.name.length ? descriptor2.name : "Type" + unnamedMessageIndex++, fromDescriptorOptions(descriptor2.options, exports2.MessageOptions)), i3;
      if (!nested)
        type._edition = edition;
      if (descriptor2.oneofDecl)
        for (i3 = 0; i3 < descriptor2.oneofDecl.length; ++i3)
          type.add(OneOf.fromDescriptor(descriptor2.oneofDecl[i3]));
      if (descriptor2.field)
        for (i3 = 0; i3 < descriptor2.field.length; ++i3) {
          var field = Field.fromDescriptor(descriptor2.field[i3], edition, true);
          type.add(field);
          if (descriptor2.field[i3].hasOwnProperty("oneofIndex"))
            type.oneofsArray[descriptor2.field[i3].oneofIndex].add(field);
        }
      if (descriptor2.extension)
        for (i3 = 0; i3 < descriptor2.extension.length; ++i3)
          type.add(Field.fromDescriptor(descriptor2.extension[i3], edition, true));
      if (descriptor2.nestedType)
        for (i3 = 0; i3 < descriptor2.nestedType.length; ++i3) {
          type.add(Type3.fromDescriptor(descriptor2.nestedType[i3], edition, true));
          if (descriptor2.nestedType[i3].options && descriptor2.nestedType[i3].options.mapEntry)
            type.setOption("map_entry", true);
        }
      if (descriptor2.enumType)
        for (i3 = 0; i3 < descriptor2.enumType.length; ++i3)
          type.add(Enum.fromDescriptor(descriptor2.enumType[i3], edition, true));
      if (descriptor2.extensionRange && descriptor2.extensionRange.length) {
        type.extensions = [];
        for (i3 = 0; i3 < descriptor2.extensionRange.length; ++i3)
          type.extensions.push([descriptor2.extensionRange[i3].start, descriptor2.extensionRange[i3].end]);
      }
      if (descriptor2.reservedRange && descriptor2.reservedRange.length || descriptor2.reservedName && descriptor2.reservedName.length) {
        type.reserved = [];
        if (descriptor2.reservedRange)
          for (i3 = 0; i3 < descriptor2.reservedRange.length; ++i3)
            type.reserved.push([descriptor2.reservedRange[i3].start, descriptor2.reservedRange[i3].end]);
        if (descriptor2.reservedName)
          for (i3 = 0; i3 < descriptor2.reservedName.length; ++i3)
            type.reserved.push(descriptor2.reservedName[i3]);
      }
      return type;
    }, "fromDescriptor");
    Type3.prototype.toDescriptor = /* @__PURE__ */ __name(function toDescriptor(edition) {
      var descriptor2 = exports2.DescriptorProto.create({ name: this.name }), i3;
      for (i3 = 0; i3 < this.fieldsArray.length; ++i3) {
        var fieldDescriptor;
        descriptor2.field.push(fieldDescriptor = this._fieldsArray[i3].toDescriptor(edition));
        if (this._fieldsArray[i3] instanceof MapField) {
          var keyType = toDescriptorType(this._fieldsArray[i3].keyType, this._fieldsArray[i3].resolvedKeyType, false), valueType = toDescriptorType(this._fieldsArray[i3].type, this._fieldsArray[i3].resolvedType, false), valueTypeName = valueType === /* type */
          11 || valueType === /* enum */
          14 ? this._fieldsArray[i3].resolvedType && shortname(this.parent, this._fieldsArray[i3].resolvedType) || this._fieldsArray[i3].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 (i3 = 0; i3 < this.oneofsArray.length; ++i3)
        descriptor2.oneofDecl.push(this._oneofsArray[i3].toDescriptor());
      for (i3 = 0; i3 < this.nestedArray.length; ++i3) {
        if (this._nestedArray[i3] instanceof Field)
          descriptor2.field.push(this._nestedArray[i3].toDescriptor(edition));
        else if (this._nestedArray[i3] instanceof Type3)
          descriptor2.nestedType.push(this._nestedArray[i3].toDescriptor(edition));
        else if (this._nestedArray[i3] instanceof Enum)
          descriptor2.enumType.push(this._nestedArray[i3].toDescriptor());
      }
      if (this.extensions)
        for (i3 = 0; i3 < this.extensions.length; ++i3)
          descriptor2.extensionRange.push(exports2.DescriptorProto.ExtensionRange.create({ start: this.extensions[i3][0], end: this.extensions[i3][1] }));
      if (this.reserved)
        for (i3 = 0; i3 < this.reserved.length; ++i3)
          if (typeof this.reserved[i3] === "string")
            descriptor2.reservedName.push(this.reserved[i3]);
          else
            descriptor2.reservedRange.push(exports2.DescriptorProto.ReservedRange.create({ start: this.reserved[i3][0], end: this.reserved[i3][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 i3 = 0; i3 < descriptor2.value.length; ++i3) {
          var name3 = descriptor2.value[i3].name, value = descriptor2.value[i3].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 i3 = 0, ks = Object.keys(this.values); i3 < ks.length; ++i3)
        values.push(exports2.EnumValueDescriptorProto.create({ name: ks[i3], number: this.values[ks[i3]] }));
      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 i3 = 0; i3 < descriptor2.method.length; ++i3)
          service.add(Method.fromDescriptor(descriptor2.method[i3]));
      return service;
    }, "fromDescriptor");
    Service.prototype.toDescriptor = /* @__PURE__ */ __name(function toDescriptor() {
      var methods = [];
      for (var i3 = 0; i3 < this.methodsArray.length; ++i3)
        methods.push(this._methodsArray[i3].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 Type3)
        return delimited ? 10 : 11;
      throw Error("illegal type: " + type);
    }
    __name(toDescriptorType, "toDescriptorType");
    function fromDescriptorOptionsRecursive(obj, type) {
      var val = {};
      for (var i3 = 0, field, key; i3 < type.fieldsArray.length; ++i3) {
        if ((key = (field = type._fieldsArray[i3]).name) === "uninterpretedOption") continue;
        if (!Object.prototype.hasOwnProperty.call(obj, key)) continue;
        var newKey = underScore(key);
        if (field.resolvedType instanceof Type3) {
          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 i3 = 0; i3 < keys.length; ++i3) {
        var key = keys[i3];
        var newKey = $protobuf.util.camelCase(key);
        if (!Object.prototype.hasOwnProperty.call(type.fields, newKey)) continue;
        var field = type.fields[newKey];
        if (field.resolvedType instanceof Type3) {
          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("."), i3 = 0, j2 = 0, k2 = toPath3.length - 1;
      if (!(from instanceof Root2) && to instanceof Namespace)
        while (i3 < fromPath.length && j2 < k2 && fromPath[i3] === toPath3[j2]) {
          var other2 = to.lookup(fromPath[i3++], true);
          if (other2 !== null && other2 !== to)
            break;
          ++j2;
        }
      else
        for (; i3 < fromPath.length && j2 < k2 && fromPath[i3] === toPath3[j2]; ++i3, ++j2) ;
      return toPath3.slice(j2).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_util14 = __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 fs113 = __require("fs");
    var path125 = __require("path");
    var Protobuf = require_protobufjs();
    function addIncludePathResolver(root, includePaths) {
      const originalResolvePath = root.resolvePath;
      root.resolvePath = (origin, target) => {
        if (path125.isAbsolute(target)) {
          return target;
        }
        for (const directory of includePaths) {
          const fullPath = path125.join(directory, target);
          try {
            fs113.accessSync(fullPath, fs113.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 c4 = Math.clz32(value & -value);
          return value ? 31 - c4 : c4;
        }
        __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 p2;
          if ((p2 = str2.indexOf("-")) > 0) throw Error("interior hyphen");
          else if (p2 === 0) {
            return fromString(str2.substring(1), unsigned, radix).neg();
          }
          var radixToPower = fromNumber(pow_dbl(radix, 8));
          var result = ZERO;
          for (var i3 = 0; i3 < str2.length; i3 += 8) {
            var size = Math.min(8, str2.length - i3), value = parseInt(str2.substring(i3, i3 + 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 or2(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 b2;
          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) {
            b2 = 32 - numBits;
            return fromBits(
              this.low << numBits | this.high >>> b2,
              this.high << numBits | this.low >>> b2,
              this.unsigned
            );
          }
          numBits -= 32;
          b2 = 32 - numBits;
          return fromBits(
            this.high << numBits | this.low >>> b2,
            this.low << numBits | this.high >>> b2,
            this.unsigned
          );
        }, "rotateLeft");
        LongPrototype.rotl = LongPrototype.rotateLeft;
        LongPrototype.rotateRight = /* @__PURE__ */ __name(function rotateRight(numBits) {
          var b2;
          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) {
            b2 = 32 - numBits;
            return fromBits(
              this.high << b2 | this.low >>> numBits,
              this.low << b2 | this.high >>> numBits,
              this.unsigned
            );
          }
          numBits -= 32;
          b2 = 32 - numBits;
          return fromBits(
            this.low << b2 | this.high >>> numBits,
            this.high << b2 | 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(le2) {
          return le2 ? 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, le2) {
          return le2 ? 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 _default2 = _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_util14();
    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_constants8();
    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((kind2) => {
      let nextId = 1;
      function getNextId() {
        return nextId++;
      }
      __name(getNextId, "getNextId");
      const entityMap = entityMaps[kind2];
      return (name3, getInfo, channelzEnabled) => {
        const id = getNextId();
        const ref = { id, name: name3, kind: kind2 };
        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(date4) {
      if (!date4) {
        return null;
      }
      const millisSinceEpoch = date4.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 i3;
      for (i3 = channelEntries.lowerBound(startId); !i3.equals(channelEntries.end()) && resultList.length < maxResults; i3 = i3.next()) {
        resultList.push(getChannelMessage(i3.pointer[1]));
      }
      callback(null, {
        channel: resultList,
        end: i3.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 i3;
      for (i3 = serverEntries.lowerBound(startId); !i3.equals(serverEntries.end()) && resultList.length < maxResults; i3 = i3.next()) {
        resultList.push(getServerMessage(i3.pointer[1]));
      }
      callback(null, {
        server: resultList,
        end: i3.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 _a7;
      if ((0, subchannel_address_1.isTcpSubchannelAddress)(subchannelAddress)) {
        return {
          address: "tcpip_address",
          tcpip_address: {
            ip_address: (_a7 = ipAddressStringToBuffer(subchannelAddress.host)) !== null && _a7 !== void 0 ? _a7 : void 0,
            port: subchannelAddress.port
          }
        };
      } else {
        return {
          address: "uds_address",
          uds_address: {
            filename: subchannelAddress.path
          }
        };
      }
    }
    __name(subchannelAddressToAddressMessage, "subchannelAddressToAddressMessage");
    function GetSocket(call, callback) {
      var _a7, _b2, _c2, _d, _e2;
      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: (_a7 = resolvedInfo.security.cipherSuiteStandardName) !== null && _a7 !== void 0 ? _a7 : 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: (_e2 = resolvedInfo.remoteName) !== null && _e2 !== void 0 ? _e2 : 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 i3;
      for (i3 = allSockets.lowerBound(startId); !i3.equals(allSockets.end()) && resultList.length < maxResults; i3 = i3.next()) {
        resultList.push(socketRefToMessage(i3.pointer[1].ref));
      }
      callback(null, {
        socket_ref: resultList,
        end: i3.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_constants8();
    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 _a7;
        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 = (_a7 = options2["grpc.keepalive_time_ms"]) !== null && _a7 !== void 0 ? _a7 : -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();
          }
        }, (error2) => {
          this.transitionToState([connectivity_state_1.ConnectivityState.CONNECTING], connectivity_state_1.ConnectivityState.TRANSIENT_FAILURE, `${error2}`);
        });
      }
      /**
       * 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 _a7, _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());
            }
            (_a7 = this.transport) === null || _a7 === void 0 ? void 0 : _a7.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 _a7;
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.GRPC_NODE_USE_ALTERNATIVE_RESOLVER = void 0;
    exports2.GRPC_NODE_USE_ALTERNATIVE_RESOLVER = ((_a7 = process.env.GRPC_NODE_USE_ALTERNATIVE_RESOLVER) !== null && _a7 !== void 0 ? _a7 : "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_constants8();
    var metadata_1 = require_metadata3();
    var logging = require_logging();
    var constants_2 = require_constants8();
    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 _a7, _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: (_a7 = hostPort.port) !== null && _a7 !== void 0 ? _a7 : 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 hostname4 = this.dnsHostname;
          this.pendingLookupPromise = this.lookup(hostname4);
          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(hostname4);
            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(hostname4) {
        if (environment_1.GRPC_NODE_USE_ALTERNATIVE_RESOLVER) {
          trace2("Using alternative DNS resolver.");
          const records = await Promise.allSettled([
            this.alternativeResolver.resolve4(hostname4),
            this.alternativeResolver.resolve6(hostname4)
          ]);
          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(hostname4, { all: true });
        return addressList.map((addr) => ({ host: addr.address, port: +this.port }));
      }
      async resolveTxt(hostname4) {
        if (environment_1.GRPC_NODE_USE_ALTERNATIVE_RESOLVER) {
          trace2("Using alternative DNS resolver.");
          return this.alternativeResolver.resolveTxt(hostname4);
        }
        return dns_1.promises.resolveTxt(hostname4);
      }
      startNextResolutionTimer() {
        var _a7, _b2;
        clearTimeout(this.nextResolutionTimer);
        this.nextResolutionTimer = setTimeout(() => {
          this.stopNextResolutionTimer();
          if (this.continueResolving) {
            this.startResolutionWithBackoff();
          }
        }, this.minTimeBetweenResolutionsMs);
        (_b2 = (_a7 = this.nextResolutionTimer).unref) === null || _b2 === void 0 ? void 0 : _b2.call(_a7);
        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_constants8();
    var net_1 = __require("net");
    var http7 = __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 (e4) {
        (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 hostname4 = proxyUrl.hostname;
      let port = proxyUrl.port;
      if (port === "") {
        port = "80";
      }
      const result = {
        address: `${hostname4}:${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 _a7;
      const noProxyResult = {
        target,
        extraOptions: {}
      };
      if (((_a7 = options2["grpc.enable_http_proxy"]) !== null && _a7 !== void 0 ? _a7 : 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 _a7;
      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}:${(_a7 = splitHostPost.port) !== null && _a7 !== void 0 ? _a7 : 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((resolve30, reject) => {
        const request4 = http7.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);
            resolve30(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 os47 = __require("os");
    var constants_1 = require_constants8();
    var metadata_1 = require_metadata3();
    var stream_decoder_1 = require_stream_decoder();
    var logging = require_logging();
    var constants_2 = require_constants8();
    var TRACER_NAME = "subchannel_call";
    function getSystemErrorName(errno) {
      for (const [name3, num] of Object.entries(os47.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 _a7;
        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 = (_a7 = transport.getOptions()["grpc.max_receive_message_length"]) !== null && _a7 !== void 0 ? _a7 : 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 (error2) {
              this.endCall({
                code: constants_1.Status.UNKNOWN,
                details: error2.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 (e4) {
            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, e4.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 _a8;
            this.trace("HTTP/2 stream closed with code " + http2Stream.rstCode);
            if (((_a8 = this.finalStatus) === null || _a8 === void 0 ? void 0 : _a8.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 (e4) {
          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 (e4) {
              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 _a7;
        if (this.http2Stream.destroyed) {
          return;
        }
        if (this.serverEndedCall) {
          this.http2Stream.end();
        } else {
          let code2;
          if (((_a7 = this.finalStatus) === null || _a7 === void 0 ? void 0 : _a7.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((error2) => {
          process.nextTick(() => {
            var _a7;
            let code2 = constants_1.Status.UNAVAILABLE;
            if ((error2 === null || error2 === void 0 ? void 0 : error2.code) === "ERR_STREAM_WRITE_AFTER_END") {
              code2 = constants_1.Status.INTERNAL;
            }
            if (error2) {
              this.cancelWithStatus(code2, `Write error: ${error2.message}`);
            }
            (_a7 = context2.callback) === null || _a7 === void 0 ? void 0 : _a7.call(context2);
          });
        }, "cb");
        this.trace("sending data chunk of length " + message.length);
        this.callEventTracker.addMessageSent();
        try {
          this.http2Stream.write(message, cb);
        } catch (error2) {
          this.endCall({
            code: constants_1.Status.UNAVAILABLE,
            details: `Write failed with error ${error2.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_constants8();
    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((e4) => e4).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", (error2) => {
          this.trace("connection closed with error " + error2.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 _a7, _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: (_a7 = cipherInfo.standardName) !== null && _a7 !== void 0 ? _a7 : 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 _a7, _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 = (_a7 = this.keepaliveTimer).unref) === null || _b2 === void 0 ? void 0 : _b2.call(_a7);
        let pingSendError = "";
        try {
          const pingSentSuccessfully = this.session.ping((err, duration3, 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 (e4) {
          pingSendError = (e4 instanceof Error ? e4.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 _a7, _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 = (_a7 = this.keepaliveTimer).unref) === null || _b2 === void 0 ? void 0 : _b2.call(_a7);
        }
      }
      /**
       * 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 (e4) {
          this.handleDisconnect();
          throw e4;
        }
        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 _a7;
              this.messagesSent += 1;
              this.lastMessageSentTimestamp = /* @__PURE__ */ new Date();
              (_a7 = subchannelCallStatsTracker.addMessageSent) === null || _a7 === void 0 ? void 0 : _a7.call(subchannelCallStatsTracker);
            }, "addMessageSent"),
            addMessageReceived: /* @__PURE__ */ __name(() => {
              var _a7;
              this.messagesReceived += 1;
              this.lastMessageReceivedTimestamp = /* @__PURE__ */ new Date();
              (_a7 = subchannelCallStatsTracker.addMessageReceived) === null || _a7 === void 0 ? void 0 : _a7.call(subchannelCallStatsTracker);
            }, "addMessageReceived"),
            onCallEnd: /* @__PURE__ */ __name((status) => {
              var _a7;
              (_a7 = subchannelCallStatsTracker.onCallEnd) === null || _a7 === void 0 ? void 0 : _a7.call(subchannelCallStatsTracker, status);
              this.removeActiveCall(call);
            }, "onCallEnd"),
            onStreamEnd: /* @__PURE__ */ __name((success) => {
              var _a7;
              if (success) {
                this.streamTracker.addCallSucceeded();
              } else {
                this.streamTracker.addCallFailed();
              }
              (_a7 = subchannelCallStatsTracker.onStreamEnd) === null || _a7 === void 0 ? void 0 : _a7.call(subchannelCallStatsTracker, success);
            }, "onStreamEnd")
          };
        } else {
          eventTracker = {
            addMessageSent: /* @__PURE__ */ __name(() => {
              var _a7;
              (_a7 = subchannelCallStatsTracker.addMessageSent) === null || _a7 === void 0 ? void 0 : _a7.call(subchannelCallStatsTracker);
            }, "addMessageSent"),
            addMessageReceived: /* @__PURE__ */ __name(() => {
              var _a7;
              (_a7 = subchannelCallStatsTracker.addMessageReceived) === null || _a7 === void 0 ? void 0 : _a7.call(subchannelCallStatsTracker);
            }, "addMessageReceived"),
            onCallEnd: /* @__PURE__ */ __name((status) => {
              var _a7;
              (_a7 = subchannelCallStatsTracker.onCallEnd) === null || _a7 === void 0 ? void 0 : _a7.call(subchannelCallStatsTracker, status);
              this.removeActiveCall(call);
            }, "onCallEnd"),
            onStreamEnd: /* @__PURE__ */ __name((success) => {
              var _a7;
              (_a7 = subchannelCallStatsTracker.onStreamEnd) === null || _a7 === void 0 ? void 0 : _a7.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((resolve30, 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 _a7;
            (_a7 = this.session) === null || _a7 === void 0 ? void 0 : _a7.destroy();
            this.session = null;
            setImmediate(() => {
              if (!reportedError) {
                reportedError = true;
                reject(`${errorMessage.trim()} (${(/* @__PURE__ */ new Date()).toISOString()})`);
              }
            });
          }, "closeHandler");
          const errorHandler = /* @__PURE__ */ __name((error2) => {
            var _a7;
            (_a7 = this.session) === null || _a7 === void 0 ? void 0 : _a7.destroy();
            errorMessage = error2.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);
            resolve30(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((resolve30, reject) => {
              const closeCallback = /* @__PURE__ */ __name(() => {
                reject(new Error("Socket closed"));
              }, "closeCallback");
              const errorCallback = /* @__PURE__ */ __name((error2) => {
                reject(error2);
              }, "errorCallback");
              const socket = net2.connect(address, () => {
                socket.removeListener("close", closeCallback);
                socket.removeListener("error", errorCallback);
                resolve30(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 (e4) {
          tcpConnection === null || tcpConnection === void 0 ? void 0 : tcpConnection.destroy();
          secureConnectResult === null || secureConnectResult === void 0 ? void 0 : secureConnectResult.socket.destroy();
          throw e4;
        }
      }
      shutdown() {
        var _a7;
        this.isShutdown = true;
        (_a7 = this.session) === null || _a7 === void 0 ? void 0 : _a7.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 _a7, _b2;
        if (this.cleanupTimer === null) {
          this.cleanupTimer = setInterval(() => {
            this.unrefUnusedSubchannels();
          }, REF_CHECK_INTERVAL);
          (_b2 = (_a7 = this.cleanupTimer).unref) === null || _b2 === void 0 ? void 0 : _b2.call(_a7);
        }
      }
      /**
       * 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 i3 = 0; i3 < this.filters.length; i3++) {
          result = this.filters[i3].sendMetadata(result);
        }
        return result;
      }
      receiveMetadata(metadata) {
        let result = metadata;
        for (let i3 = this.filters.length - 1; i3 >= 0; i3--) {
          result = this.filters[i3].receiveMetadata(result);
        }
        return result;
      }
      sendMessage(message) {
        let result = message;
        for (let i3 = 0; i3 < this.filters.length; i3++) {
          result = this.filters[i3].sendMessage(result);
        }
        return result;
      }
      receiveMessage(message) {
        let result = message;
        for (let i3 = this.filters.length - 1; i3 >= 0; i3--) {
          result = this.filters[i3].receiveMessage(result);
        }
        return result;
      }
      receiveTrailers(status) {
        let result = status;
        for (let i3 = this.filters.length - 1; i3 >= 0; i3--) {
          result = this.filters[i3].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 zlib4 = __require("zlib");
    var compression_algorithms_1 = require_compression_algorithms();
    var constants_1 = require_constants8();
    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((resolve30, reject) => {
          zlib4.deflate(message, (err, output) => {
            if (err) {
              reject(err);
            } else {
              resolve30(output);
            }
          });
        });
      }
      decompressMessage(message) {
        return new Promise((resolve30, reject) => {
          let totalLength = 0;
          const messageParts = [];
          const decompresser = zlib4.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", () => {
            resolve30(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((resolve30, reject) => {
          zlib4.gzip(message, (err, output) => {
            if (err) {
              reject(err);
            } else {
              resolve30(output);
            }
          });
        });
      }
      decompressMessage(message) {
        return new Promise((resolve30, reject) => {
          let totalLength = 0;
          const messageParts = [];
          const decompresser = zlib4.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", () => {
            resolve30(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 _a7, _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 = (_a7 = channelOptions["grpc.max_receive_message_length"]) !== null && _a7 !== void 0 ? _a7 : 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 _a7;
        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 = (((_a7 = resolvedMessage.flags) !== null && _a7 !== void 0 ? _a7 : 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_constants8();
    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_constants8();
    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 _a7, _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 hostname4 = (_b2 = (_a7 = (0, uri_parser_1.splitHostPort)(this.host)) === null || _a7 === void 0 ? void 0 : _a7.host) !== null && _b2 !== void 0 ? _b2 : "localhost";
        this.serviceUrl = `https://${hostname4}/${serviceName}`;
        this.startTime = /* @__PURE__ */ new Date();
      }
      getDeadlineInfo() {
        var _a7, _b2;
        const deadlineInfo = [];
        if (this.childStartTime) {
          if (this.childStartTime > this.startTime) {
            if ((_a7 = this.metadata) === null || _a7 === void 0 ? void 0 : _a7.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 _a7, _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 });
          (_a7 = this.listener) === null || _a7 === void 0 ? void 0 : _a7.onReceiveStatus(finalStatus);
          (_b2 = this.onCallEnded) === null || _b2 === void 0 ? void 0 : _b2.call(this, finalStatus.code);
        }
      }
      doPick() {
        var _a7, _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: " + ((_a7 = pickResult.status) === null || _a7 === void 0 ? void 0 : _a7.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 _a8;
              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 (error2) {
                this.trace("Failed to start call on picked subchannel " + subchannelString + " with error " + error2.message);
                this.outputStatus({
                  code: constants_1.Status.INTERNAL,
                  details: "Failed to start HTTP/2 stream with error " + error2.message,
                  metadata: new metadata_1.Metadata()
                }, "NOT_STARTED");
                return;
              }
              (_a8 = pickResult.onCallStarted) === null || _a8 === void 0 ? void 0 : _a8.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();
              }
            }, (error2) => {
              const { code: code3, details: details2 } = (0, control_plane_status_1.restrictControlPlaneStatusCode)(typeof error2.code === "number" ? error2.code : constants_1.Status.UNKNOWN, `Getting metadata from plugin failed with error: ${error2.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 _a7;
        this.trace("cancelWithStatus code: " + status + ' details: "' + details + '"');
        (_a7 = this.child) === null || _a7 === void 0 ? void 0 : _a7.cancelWithStatus(status, details);
        this.outputStatus({ code: status, details, metadata: new metadata_1.Metadata() }, "PROCESSED");
      }
      getPeer() {
        var _a7, _b2;
        return (_b2 = (_a7 = this.child) === null || _a7 === void 0 ? void 0 : _a7.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_constants8();
    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 _a7;
            (_a7 = this.listener) === null || _a7 === void 0 ? void 0 : _a7.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 config2 = configResult.config;
        if (config2.status !== constants_1.Status.OK) {
          const { code: code2, details } = (0, control_plane_status_1.restrictControlPlaneStatusCode)(config2.status, "Failed to route call to method " + this.method);
          this.outputStatus({
            code: code2,
            details,
            metadata: new metadata_1.Metadata()
          });
          return;
        }
        if (config2.methodConfig.timeout) {
          const configDeadline = /* @__PURE__ */ new Date();
          configDeadline.setSeconds(configDeadline.getSeconds() + config2.methodConfig.timeout.seconds);
          configDeadline.setMilliseconds(configDeadline.getMilliseconds() + config2.methodConfig.timeout.nanos / 1e6);
          this.deadline = (0, deadline_1.minDeadline)(this.deadline, configDeadline);
          this.runDeadlineTimer();
        }
        this.filterStackFactory.push(config2.dynamicFilterFactories);
        this.filterStack = this.filterStackFactory.createFilter();
        this.filterStack.sendMetadata(Promise.resolve(this.metadata)).then((filteredMetadata) => {
          this.child = this.channel.createRetryingCall(config2, 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 _a7;
        if ((_a7 = this.metadata) === null || _a7 === void 0 ? void 0 : _a7.getOptions().waitForReady) {
          this.channel.queueCallForConfig(this);
        } else {
          this.outputStatus(status);
        }
      }
      cancelWithStatus(status, details) {
        var _a7;
        this.trace("cancelWithStatus code: " + status + ' details: "' + details + '"');
        (_a7 = this.child) === null || _a7 === void 0 ? void 0 : _a7.cancelWithStatus(status, details);
        this.outputStatus({
          code: status,
          details,
          metadata: new metadata_1.Metadata()
        });
      }
      getPeer() {
        var _a7, _b2;
        return (_b2 = (_a7 = this.child) === null || _a7 === void 0 ? void 0 : _a7.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_constants8();
    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 _a7;
        const currentPerCall = (_a7 = this.allocatedPerCall.get(callId)) !== null && _a7 !== void 0 ? _a7 : 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 _a7;
        if (this.totalAllocated < size) {
          throw new Error(`Invalid buffer allocation state: call ${callId} freed ${size} > total allocated ${this.totalAllocated}`);
        }
        this.totalAllocated -= size;
        const currentPerCall = (_a7 = this.allocatedPerCall.get(callId)) !== null && _a7 !== void 0 ? _a7 : 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 _a7;
        const currentPerCall = (_a7 = this.allocatedPerCall.get(callId)) !== null && _a7 !== void 0 ? _a7 : 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 _a7;
        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 = (_a7 = channel.getOptions()["grpc-node.retry_max_attempts_limit"]) !== null && _a7 !== void 0 ? _a7 : 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 _a7;
          (_a7 = this.listener) === null || _a7 === void 0 ? void 0 : _a7.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 _a7;
        return (_a7 = this.writeBuffer[messageIndex - this.writeBufferOffset]) !== null && _a7 !== void 0 ? _a7 : {
          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 _a7, _b2;
        if (this.state === "COMMITTED") {
          return;
        }
        this.trace("Committing call [" + this.underlyingCalls[index].call.getCallNumber() + "] at index " + index);
        this.state = "COMMITTED";
        (_b2 = (_a7 = this.callConfig).onCommitted) === null || _b2 === void 0 ? void 0 : _b2.call(_a7);
        this.committedCallIndex = index;
        for (let i3 = 0; i3 < this.underlyingCalls.length; i3++) {
          if (i3 === index) {
            continue;
          }
          if (this.underlyingCalls[i3].state === "COMPLETED") {
            continue;
          }
          this.underlyingCalls[i3].state = "COMPLETED";
          this.underlyingCalls[i3].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 _a7;
          return value === code2 || value.toString().toLowerCase() === ((_a7 = constants_1.Status[code2]) === null || _a7 === void 0 ? void 0 : _a7.toLowerCase());
        });
      }
      getNextRetryBackoffMs() {
        var _a7;
        const retryPolicy = (_a7 = this.callConfig) === null || _a7 === void 0 ? void 0 : _a7.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 _a7, _b2;
          if (this.state !== "RETRY") {
            callback(false);
            return;
          }
          if ((_b2 = (_a7 = this.retryThrottler) === null || _a7 === void 0 ? void 0 : _a7.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 _a7, _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((_a7 = this.callConfig.methodConfig.hedgingPolicy.nonFatalStatusCodes) !== null && _a7 !== void 0 ? _a7 : [], 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 (e4) {
          return -1;
        }
      }
      handleChildStatus(status, callIndex) {
        var _a7;
        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) {
          (_a7 = this.retryThrottler) === null || _a7 === void 0 ? void 0 : _a7.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 _a7, _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 = (_a7 = hedgingPolicy.hedgingDelay) !== null && _a7 !== void 0 ? _a7 : "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 _a7, _b2;
        const childCall = this.underlyingCalls[childIndex];
        const messageIndex = childCall.nextMessageToSend;
        (_b2 = (_a7 = this.getBufferEntry(messageIndex)).callback) === null || _b2 === void 0 ? void 0 : _b2.call(_a7);
        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((error2) => {
                  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 _a7;
        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) {
          (_a7 = context2.callback) === null || _a7 === void 0 ? void 0 : _a7.call(context2);
          for (const [callIndex, call] of this.underlyingCalls.entries()) {
            if (call.state === "ACTIVE" && call.nextMessageToSend === messageIndex) {
              call.call.sendMessageWithContext({
                callback: /* @__PURE__ */ __name((error2) => {
                  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((error2) => {
                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_constants8();
    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 _a7, _b2, _c2, _d, _e2, _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)(((_a7 = this.options["grpc.use_local_subchannel_pool"]) !== null && _a7 !== void 0 ? _a7 : 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((_e2 = this.options["grpc.client_idle_timeout_ms"]) !== null && _e2 !== void 0 ? _e2 : 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 _a8;
          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");
          }
          (_a8 = this.configSelector) === null || _a8 === void 0 ? void 0 : _a8.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 error2 = 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 = error2.stack) === null || _f === void 0 ? void 0 : _f.substring(error2.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 _a7, _b2, _c2, _d;
        if (!this.callRefTimer) {
          this.callRefTimer = setInterval(() => {
          }, MAX_TIMEOUT_TIME);
        }
        if (!((_b2 = (_a7 = this.callRefTimer).hasRef) === null || _b2 === void 0 ? void 0 : _b2.call(_a7))) {
          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 _a7, _b2, _c2;
        if (!((_a7 = this.callRefTimer) === null || _a7 === void 0 ? void 0 : _a7.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 _a7, _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 = (_a7 = this.idleTimer).unref) === null || _b2 === void 0 ? void 0 : _b2.call(_a7);
      }
      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 _a7;
        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();
        (_a7 = this.configSelector) === null || _a7 === void 0 ? void 0 : _a7.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_constants8();
    var metadata_1 = require_metadata3();
    function serverErrorToStatus(error2, overrideTrailers) {
      var _a7;
      const status = {
        code: constants_1.Status.UNKNOWN,
        details: "message" in error2 ? error2.message : "Unknown Error",
        metadata: (_a7 = overrideTrailers !== null && overrideTrailers !== void 0 ? overrideTrailers : error2.metadata) !== null && _a7 !== void 0 ? _a7 : null
      };
      if ("code" in error2 && typeof error2.code === "number" && Number.isInteger(error2.code)) {
        status.code = error2.code;
        if ("details" in error2 && typeof error2.details === "string") {
          status.details = error2.details;
        }
      }
      return status;
    }
    __name(serverErrorToStatus, "serverErrorToStatus");
    var ServerUnaryCallImpl = class extends events_1.EventEmitter {
      static {
        __name(this, "ServerUnaryCallImpl");
      }
      constructor(path125, call, metadata, request4) {
        super();
        this.path = path125;
        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(path125, call, metadata) {
        super({ objectMode: true });
        this.path = path125;
        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(path125, call, metadata, request4) {
        super({ objectMode: true });
        this.path = path125;
        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 _a7;
        callback(null);
        this.call.sendStatus(Object.assign(Object.assign({}, this.pendingStatus), { metadata: (_a7 = this.pendingStatus.metadata) !== null && _a7 !== void 0 ? _a7 : 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(path125, call, metadata) {
        super({ objectMode: true });
        this.path = path125;
        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 _a7;
        callback(null);
        this.call.sendStatus(Object.assign(Object.assign({}, this.pendingStatus), { metadata: (_a7 = this.pendingStatus.metadata) !== null && _a7 !== void 0 ? _a7 : 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 _a7;
        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 i3 = 0; i3 < keyCertPairs.length; i3++) {
          const pair = keyCertPairs[i3];
          if (pair === null || typeof pair !== "object") {
            throw new TypeError(`keyCertPair[${i3}] must be an object`);
          }
          if (!Buffer.isBuffer(pair.private_key)) {
            throw new TypeError(`keyCertPair[${i3}].private_key must be a Buffer`);
          }
          if (!Buffer.isBuffer(pair.cert_chain)) {
            throw new TypeError(`keyCertPair[${i3}].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: (_a7 = rootCerts !== null && rootCerts !== void 0 ? rootCerts : (0, tls_helpers_1.getDefaultRootsData)()) !== null && _a7 !== void 0 ? _a7 : 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 i3 = 0; i3 < this.options.cert.length; i3++) {
            const thisCert = this.options.cert[i3];
            const otherCert = other2.options.cert[i3];
            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 i3 = 0; i3 < this.options.key.length; i3++) {
            const thisKey = this.options.key[i3];
            const otherKey = other2.options.key[i3];
            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 _a7;
        if (this.getWatcherCount() === 0) {
          (_a7 = this.caCertificateProvider) === null || _a7 === void 0 ? void 0 : _a7.addCaCertificateListener(this.caCertificateUpdateListener);
          this.identityCertificateProvider.addIdentityCertificateListener(this.identityCertificateUpdateListener);
        }
        super._addWatcher(watcher);
      }
      _removeWatcher(watcher) {
        var _a7;
        super._removeWatcher(watcher);
        if (this.getWatcherCount() === 0) {
          (_a7 = this.caCertificateProvider) === null || _a7 === void 0 ? void 0 : _a7.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 _a7;
        if (this.latestIdentityUpdate === null) {
          return null;
        }
        if (this.caCertificateProvider !== null && this.latestCaUpdate === null) {
          return null;
        }
        return {
          ca: (_a7 = this.latestCaUpdate) === null || _a7 === void 0 ? void 0 : _a7.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 i3 = 0; i3 < this.interceptors.length; i3++) {
          if (this.interceptors[i3] !== other2.interceptors[i3]) {
            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_constants8();
    var http22 = __require("http2");
    var error_1 = require_error();
    var zlib4 = __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 _a7, _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: (_a7 = responder === null || responder === void 0 ? void 0 : responder.start) !== null && _a7 !== void 0 ? _a7 : 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 _a7, _b2, _c2, _d;
          const fullInterceptedListener = {
            onReceiveMetadata: (_a7 = interceptedListener === null || interceptedListener === void 0 ? void 0 : interceptedListener.onReceiveMetadata) !== null && _a7 !== void 0 ? _a7 : 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 _a7;
        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 _a8;
          trace2("Request to method " + ((_a8 = this.handler) === null || _a8 === void 0 ? void 0 : _a8.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 = (_a7 = headers[":authority"]) !== null && _a7 !== void 0 ? _a7 : 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 _a7;
          (_a7 = this.listener) === null || _a7 === void 0 ? void 0 : _a7.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 = zlib4.createInflate();
          } else {
            decompresser = zlib4.createGunzip();
          }
          return new Promise((resolve30, 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", () => {
              resolve30(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 _a7;
        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 (e4) {
          this.sendStatus({ code: constants_1.Status.RESOURCE_EXHAUSTED, details: e4.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);
          (_a7 = this.callEventTracker) === null || _a7 === void 0 ? void 0 : _a7.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 custom3 = metadata ? metadata.toHttp2Headers() : null;
        const headers = Object.assign(Object.assign(Object.assign({}, defaultResponseHeaders), defaultCompressionHeaders), custom3);
        this.stream.respond(headers, defaultResponseOptions);
      }
      sendMessage(message, callback) {
        if (this.checkCancelled()) {
          return;
        }
        let response;
        try {
          response = this.serializeMessage(message);
        } catch (e4) {
          this.sendStatus({
            code: constants_1.Status.INTERNAL,
            details: `Error serializing response: ${(0, error_1.getErrorMessage)(e4)}`,
            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, (error2) => {
          var _a7;
          if (error2) {
            this.sendStatus({
              code: constants_1.Status.INTERNAL,
              details: `Error writing message: ${(0, error_1.getErrorMessage)(error2)}`,
              metadata: null
            });
            return;
          }
          (_a7 = this.callEventTracker) === null || _a7 === void 0 ? void 0 : _a7.addMessageSent();
          callback();
        });
      }
      sendStatus(status) {
        var _a7, _b2;
        if (this.checkCancelled()) {
          return;
        }
        trace2("Request to method " + ((_a7 = this.handler) === null || _a7 === void 0 ? void 0 : _a7.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 _a8;
              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) }, (_a8 = status.metadata) === null || _a8 === void 0 ? void 0 : _a8.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 _a7;
        const socket = (_a7 = this.stream.session) === null || _a7 === void 0 ? void 0 : _a7.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 i3 = 0; i3 < initializers.length; i3++) {
        value = useValue ? initializers[i3].call(thisArg, value) : initializers[i3].call(thisArg);
      }
      return useValue ? value : void 0;
    };
    var __esDecorate = exports2 && exports2.__esDecorate || function(ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {
      function accept(f5) {
        if (f5 !== void 0 && typeof f5 !== "function") throw new TypeError("Function expected");
        return f5;
      }
      __name(accept, "accept");
      var kind2 = contextIn.kind, key = kind2 === "getter" ? "get" : kind2 === "setter" ? "set" : "value";
      var target = !descriptorIn && ctor ? contextIn["static"] ? ctor : ctor.prototype : null;
      var descriptor2 = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {});
      var _2, done = false;
      for (var i3 = decorators.length - 1; i3 >= 0; i3--) {
        var context2 = {};
        for (var p2 in contextIn) context2[p2] = p2 === "access" ? {} : contextIn[p2];
        for (var p2 in contextIn.access) context2.access[p2] = contextIn.access[p2];
        context2.addInitializer = function(f5) {
          if (done) throw new TypeError("Cannot add initializers after decoration has completed");
          extraInitializers.push(accept(f5 || null));
        };
        var result = (0, decorators[i3])(kind2 === "accessor" ? { get: descriptor2.get, set: descriptor2.set } : descriptor2[key], context2);
        if (kind2 === "accessor") {
          if (result === void 0) continue;
          if (result === null || typeof result !== "object") throw new TypeError("Object expected");
          if (_2 = accept(result.get)) descriptor2.get = _2;
          if (_2 = accept(result.set)) descriptor2.set = _2;
          if (_2 = accept(result.init)) initializers.unshift(_2);
        } else if (_2 = accept(result)) {
          if (kind2 === "field") initializers.unshift(_2);
          else descriptor2[key] = _2;
        }
      }
      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 util3 = __require("util");
    var constants_1 = require_constants8();
    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 noop8() {
    }
    __name(noop8, "noop");
    function deprecate6(message) {
      return function(target, context2) {
        return util3.deprecate(target, message);
      };
    }
    __name(deprecate6, "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 _a7;
      let _instanceExtraInitializers = [];
      let _start_decorators;
      return _a7 = class Server {
        static {
          __name(this, "Server");
        }
        constructor(options2) {
          var _b2, _c2, _d, _e2, _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 = (_e2 = this.options["grpc.keepalive_timeout_ms"]) !== null && _e2 !== void 0 ? _e2 : 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", (e4) => {
                this.trace("An incoming TLS connection closed with error: " + e4.message);
              });
            });
            const credsWatcher = /* @__PURE__ */ __name((options2) => {
              if (options2) {
                const secureServer = http2Server;
                try {
                  secureServer.setSecureContext(options2);
                } catch (e4) {
                  logging.log(constants_1.LogVerbosity.ERROR, "Failed to set secure context with error " + e4.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, noop8);
          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((resolve30, reject) => {
            const onError2 = /* @__PURE__ */ __name((err) => {
              this.trace("Failed to bind " + (0, subchannel_address_1.subchannelAddressToString)(address) + " with error " + err.message);
              resolve30({
                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));
              resolve30({
                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((resolve30, 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;
                }
                resolve30(addressList);
              }, "onSuccessfulResolution"),
              onError: /* @__PURE__ */ __name((error2) => {
                reject(new Error(error2.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((error2, port2) => {
            process.nextTick(() => callback(error2, 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), (error2) => callback(error2, 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);
            }, (error2) => {
              callback(error2, 0);
            });
          } else {
            this.boundPorts.set(boundPortObject.mapKey, boundPortObject);
            completionPromise.then((portNum) => {
              boundPortObject.completionPromise = null;
              boundPortObject.portNumber = portNum;
              callback(null, portNum);
            }, (error2) => {
              callback(error2, 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((error2) => {
            (0, channelz_1.unregisterChannelzRef)(this.channelzRef);
            callback(error2);
          }, "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(path125) {
          serverCallTrace("Received call to method " + path125 + " at address " + this.serverAddressString);
          const handler = this.handlers.get(path125);
          if (handler === void 0) {
            serverCallTrace("No handler registered for method " + path125 + ". 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 path125 = headers[HTTP2_HEADER_PATH];
          const handler = this._retrieveHandler(path125);
          if (!handler) {
            this._respondWithError(getUnimplementedStatusResponse(path125), 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 path125 = headers[HTTP2_HEADER_PATH];
          const handler = this._retrieveHandler(path125);
          if (!handler) {
            this._respondWithError(getUnimplementedStatusResponse(path125), 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 (e4) {
                  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, duration3, 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 (e4) {
                pingSendError = (e4 instanceof Error ? e4.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, _e2;
            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 (e4) {
                  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);
              (_e2 = connectionAgeTimer.unref) === null || _e2 === void 0 ? void 0 : _e2.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, duration3, 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 " + duration3);
                    sessionClosedByServer = true;
                    session.close();
                  } else {
                    this.keepaliveTrace("Received ping response");
                    maybeStartKeepalivePingTimer();
                  }
                });
                if (!pingSentSuccessfully) {
                  pingSendError = "Ping returned false";
                }
              } catch (e4) {
                pingSendError = (e4 instanceof Error ? e4.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 = [deprecate6("Calling start() is no longer necessary. It can be safely omitted.")];
        __esDecorate(_a7, 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(_a7, Symbol.metadata, { enumerable: true, configurable: true, writable: true, value: _metadata });
      })(), _a7;
    })();
    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(duration3) {
      return duration3.seconds * 1e3 + duration3.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_constants8();
    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 i3 = result.length - 1; i3 > 1; i3--) {
        const j2 = Math.floor(Math.random() * (i3 + 1));
        const temp = result[i3];
        result[i3] = result[j2];
        result[j2] = 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 i3 = 0; i3 < Math.max(firstList.length, secondList.length); i3++) {
        if (i3 < firstList.length) {
          result.push(firstList[i3]);
        }
        if (i3 < secondList.length) {
          result.push(secondList[i3]);
        }
      }
      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 _a7;
        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 (((_a7 = this.latestAddressList) === null || _a7 === void 0 ? void 0 : _a7.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 _a7;
        if ((_a7 = this.currentPick) === null || _a7 === void 0 ? void 0 : _a7.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 _a7, _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 _a8;
            (_a8 = this.children[subchannelIndex]) === null || _a8 === void 0 ? void 0 : _a8.subchannel.startConnecting();
          });
        }
        this.connectionDelayTimeout = setTimeout(() => {
          this.startNextSubchannelConnecting(subchannelIndex + 1);
        }, CONNECTION_DELAY_INTERVAL_MS);
        (_b2 = (_a7 = this.connectionDelayTimeout).unref) === null || _b2 === void 0 ? void 0 : _b2.call(_a7);
      }
      /**
       * 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 fs113 = __require("fs");
    var logging = require_logging();
    var constants_1 = require_constants8();
    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)(fs113.readFile);
    var FileWatcherCertificateProvider = class {
      static {
        __name(this, "FileWatcherCertificateProvider");
      }
      constructor(config2) {
        this.config = config2;
        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 (config2.certificateFile === void 0 !== (config2.privateKeyFile === void 0)) {
          throw new Error("certificateFile and privateKeyFile must be set or unset together");
        }
        if (config2.certificateFile === void 0 && config2.caCertificateFile === void 0) {
          throw new Error("At least one of certificateFile and caCertificateFile must be set");
        }
        trace2("File watcher constructed with config " + JSON.stringify(config2));
      }
      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 path125;
        if (target.authority === "") {
          path125 = "/" + target.path;
        } else {
          path125 = target.path;
        }
        this.endpoints = [{ addresses: [{ path: path125 }] }];
      }
      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_constants8();
    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 _a7;
        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 path125 of pathList) {
          const hostPort = (0, uri_parser_1.splitHostPort)(path125);
          if (hostPort === null) {
            this.error = {
              code: constants_1.Status.UNAVAILABLE,
              details: `Failed to parse ${target.scheme} address ${path125}`,
              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 ${path125}`,
              metadata: new metadata_1.Metadata()
            };
            return;
          }
          addresses.push({
            host: hostPort.host,
            port: (_a7 = hostPort.port) !== null && _a7 !== void 0 ? _a7 : 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_constants8();
    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 _a7;
    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_constants8();
    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 = ((_a7 = process.env.GRPC_EXPERIMENTAL_ENABLE_OUTLIER_DETECTION) !== null && _a7 !== void 0 ? _a7 : "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 _a8, _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: (_a8 = this.successRateEjection) !== null && _a8 !== void 0 ? _a8 : 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 _a8;
        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, (_a8 = obj.max_ejection_percent) !== null && _a8 !== void 0 ? _a8 : 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 _a8;
                if (statusCode === constants_1.Status.OK) {
                  mapEntry.counter.addSuccess();
                } else {
                  mapEntry.counter.addFailure();
                }
                (_a8 = wrappedPick.onCallEnded) === null || _a8 === void 0 ? void 0 : _a8.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((a2, b2) => a2 + b2) / 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 _a8, _b2;
        this.ejectionTimer = setTimeout(() => this.runChecks(), delayMs);
        (_b2 = (_a8 = this.ejectionTimer).unref) === null || _b2 === void 0 ? void 0 : _b2.call(_a8);
      }
      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_constants8();
    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(path125, name3) {
      const serviceDefinition = {
        export: {
          path: path125,
          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 (error2) {
            return Promise.resolve({
              status: "failure",
              error: error2
            });
          }
          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 (error2) {
            return Promise.resolve({
              status: "failure",
              error: error2
            });
          }
        }
        return new Promise((resolve30) => {
          const deadline = Date.now() + timeoutMillis;
          if (this._metadata == null) {
            return resolve30({
              error: new Error("metadata was null"),
              status: "failure"
            });
          }
          this._client.export(buffer, this._metadata, { deadline }, (err, response) => {
            if (err) {
              resolve30({
                status: "failure",
                error: err
              });
            } else {
              resolve30({
                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 http3 from "http";
import * as https3 from "https";
import * as zlib2 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:" ? http3.request : https3.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 error2 = new OTLPExporterError(res.statusMessage, res.statusCode, Buffer.concat(responseData).toString());
        onDone({
          status: "failure",
          error: error2
        });
      }
    });
  });
  req.setTimeout(timeoutMillis, () => {
    req.destroy();
    onDone({
      status: "failure",
      error: new Error("Request Timeout")
    });
  });
  req.on("error", (error2) => {
    onDone({
      status: "failure",
      error: error2
    });
  });
  compressAndSend(req, params.compression, data, (error2) => {
    onDone({
      status: "failure",
      error: error2
    });
  });
}
function compressAndSend(req, compression, data, onError2) {
  let dataStream = readableFromUint8Array(data);
  if (compression === "gzip") {
    req.setHeader("Content-Encoding", "gzip");
    dataStream = dataStream.on("error", onError2).pipe(zlib2.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 Agent4 = parsedUrl.protocol === "http:" ? http3.Agent : https3.Agent;
  return new Agent4(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_types3();
    __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((resolve30) => {
          send(this._parameters, agent, data, (result) => {
            resolve30(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((resolve30, reject) => {
          setTimeout(() => {
            this._transport.send(data, timeoutMillis).then(resolve30, 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, path125) {
  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 += path125;
  try {
    new URL(url2);
  } catch {
    diag2.warn(`Configuration: Provided URL appended with '${path125}' 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(config2) {
  if (config2?.keepAlive != null) {
    if (config2.httpAgentOptions != null) {
      if (config2.httpAgentOptions.keepAlive == null) {
        config2.httpAgentOptions.keepAlive = config2.keepAlive;
      }
    } else {
      config2.httpAgentOptions = {
        keepAlive: config2.keepAlive
      };
    }
  }
  return config2.httpAgentOptions;
}
function convertLegacyHttpOptions(config2, signalIdentifier, signalResourcePath, requiredHeaders) {
  if (config2.metadata) {
    diag2.warn("Metadata cannot be set when using http");
  }
  return mergeOtlpHttpConfigurationWithDefaults({
    url: config2.url,
    headers: wrapStaticHeadersInFunction(config2.headers),
    concurrencyLimit: config2.concurrencyLimit,
    timeoutMillis: config2.timeoutMillis,
    compression: config2.compression,
    agentOptions: convertLegacyAgentOptions(config2)
  }, 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 fs113 = __require("fs");
    var path125 = __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 fs113.readFileSync(path125.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(config2, signalIdentifier) {
      if (config2.headers) {
        api_1.diag.warn("Headers cannot be set when using grpc");
      }
      const userProvidedCredentials = config2.credentials;
      return (0, otlp_grpc_configuration_1.mergeOtlpGrpcConfigurationWithDefaults)({
        url: config2.url,
        metadata: /* @__PURE__ */ __name(() => {
          return config2.metadata ?? (0, grpc_exporter_transport_1.createEmptyMetadata)();
        }, "metadata"),
        compression: config2.compression,
        timeoutMillis: config2.timeoutMillis,
        concurrencyLimit: config2.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 v1 = {};
            v1.AnyValue = function() {
              function AnyValue(properties) {
                if (properties) {
                  for (var keys = Object.keys(properties), i3 = 0; i3 < keys.length; ++i3)
                    if (properties[keys[i3]] != null)
                      this[keys[i3]] = properties[keys[i3]];
                }
              }
              __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, error2) {
                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 === error2)
                    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 error2 = $root.opentelemetry.proto.common.v1.ArrayValue.verify(message.arrayValue);
                    if (error2)
                      return "arrayValue." + error2;
                  }
                }
                if (message.kvlistValue != null && message.hasOwnProperty("kvlistValue")) {
                  if (properties.value === 1)
                    return "value: multiple values";
                  properties.value = 1;
                  {
                    var error2 = $root.opentelemetry.proto.common.v1.KeyValueList.verify(message.kvlistValue);
                    if (error2)
                      return "kvlistValue." + error2;
                  }
                }
                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(object3) {
                if (object3 instanceof $root.opentelemetry.proto.common.v1.AnyValue)
                  return object3;
                var message = new $root.opentelemetry.proto.common.v1.AnyValue();
                if (object3.stringValue != null)
                  message.stringValue = String(object3.stringValue);
                if (object3.boolValue != null)
                  message.boolValue = Boolean(object3.boolValue);
                if (object3.intValue != null) {
                  if ($util.Long)
                    (message.intValue = $util.Long.fromValue(object3.intValue)).unsigned = false;
                  else if (typeof object3.intValue === "string")
                    message.intValue = parseInt(object3.intValue, 10);
                  else if (typeof object3.intValue === "number")
                    message.intValue = object3.intValue;
                  else if (typeof object3.intValue === "object")
                    message.intValue = new $util.LongBits(object3.intValue.low >>> 0, object3.intValue.high >>> 0).toNumber();
                }
                if (object3.doubleValue != null)
                  message.doubleValue = Number(object3.doubleValue);
                if (object3.arrayValue != null) {
                  if (typeof object3.arrayValue !== "object")
                    throw TypeError(".opentelemetry.proto.common.v1.AnyValue.arrayValue: object expected");
                  message.arrayValue = $root.opentelemetry.proto.common.v1.ArrayValue.fromObject(object3.arrayValue);
                }
                if (object3.kvlistValue != null) {
                  if (typeof object3.kvlistValue !== "object")
                    throw TypeError(".opentelemetry.proto.common.v1.AnyValue.kvlistValue: object expected");
                  message.kvlistValue = $root.opentelemetry.proto.common.v1.KeyValueList.fromObject(object3.kvlistValue);
                }
                if (object3.bytesValue != null) {
                  if (typeof object3.bytesValue === "string")
                    $util.base64.decode(object3.bytesValue, message.bytesValue = $util.newBuffer($util.base64.length(object3.bytesValue)), 0);
                  else if (object3.bytesValue.length >= 0)
                    message.bytesValue = object3.bytesValue;
                }
                return message;
              }, "fromObject");
              AnyValue.toObject = /* @__PURE__ */ __name(function toObject(message, options2) {
                if (!options2)
                  options2 = {};
                var object3 = {};
                if (message.stringValue != null && message.hasOwnProperty("stringValue")) {
                  object3.stringValue = message.stringValue;
                  if (options2.oneofs)
                    object3.value = "stringValue";
                }
                if (message.boolValue != null && message.hasOwnProperty("boolValue")) {
                  object3.boolValue = message.boolValue;
                  if (options2.oneofs)
                    object3.value = "boolValue";
                }
                if (message.intValue != null && message.hasOwnProperty("intValue")) {
                  if (typeof message.intValue === "number")
                    object3.intValue = options2.longs === String ? String(message.intValue) : message.intValue;
                  else
                    object3.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)
                    object3.value = "intValue";
                }
                if (message.doubleValue != null && message.hasOwnProperty("doubleValue")) {
                  object3.doubleValue = options2.json && !isFinite(message.doubleValue) ? String(message.doubleValue) : message.doubleValue;
                  if (options2.oneofs)
                    object3.value = "doubleValue";
                }
                if (message.arrayValue != null && message.hasOwnProperty("arrayValue")) {
                  object3.arrayValue = $root.opentelemetry.proto.common.v1.ArrayValue.toObject(message.arrayValue, options2);
                  if (options2.oneofs)
                    object3.value = "arrayValue";
                }
                if (message.kvlistValue != null && message.hasOwnProperty("kvlistValue")) {
                  object3.kvlistValue = $root.opentelemetry.proto.common.v1.KeyValueList.toObject(message.kvlistValue, options2);
                  if (options2.oneofs)
                    object3.value = "kvlistValue";
                }
                if (message.bytesValue != null && message.hasOwnProperty("bytesValue")) {
                  object3.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)
                    object3.value = "bytesValue";
                }
                return object3;
              }, "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;
            }();
            v1.ArrayValue = function() {
              function ArrayValue(properties) {
                this.values = [];
                if (properties) {
                  for (var keys = Object.keys(properties), i3 = 0; i3 < keys.length; ++i3)
                    if (properties[keys[i3]] != null)
                      this[keys[i3]] = properties[keys[i3]];
                }
              }
              __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 i3 = 0; i3 < message.values.length; ++i3)
                    $root.opentelemetry.proto.common.v1.AnyValue.encode(message.values[i3], 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, error2) {
                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 === error2)
                    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 i3 = 0; i3 < message.values.length; ++i3) {
                    var error2 = $root.opentelemetry.proto.common.v1.AnyValue.verify(message.values[i3]);
                    if (error2)
                      return "values." + error2;
                  }
                }
                return null;
              }, "verify");
              ArrayValue.fromObject = /* @__PURE__ */ __name(function fromObject(object3) {
                if (object3 instanceof $root.opentelemetry.proto.common.v1.ArrayValue)
                  return object3;
                var message = new $root.opentelemetry.proto.common.v1.ArrayValue();
                if (object3.values) {
                  if (!Array.isArray(object3.values))
                    throw TypeError(".opentelemetry.proto.common.v1.ArrayValue.values: array expected");
                  message.values = [];
                  for (var i3 = 0; i3 < object3.values.length; ++i3) {
                    if (typeof object3.values[i3] !== "object")
                      throw TypeError(".opentelemetry.proto.common.v1.ArrayValue.values: object expected");
                    message.values[i3] = $root.opentelemetry.proto.common.v1.AnyValue.fromObject(object3.values[i3]);
                  }
                }
                return message;
              }, "fromObject");
              ArrayValue.toObject = /* @__PURE__ */ __name(function toObject(message, options2) {
                if (!options2)
                  options2 = {};
                var object3 = {};
                if (options2.arrays || options2.defaults)
                  object3.values = [];
                if (message.values && message.values.length) {
                  object3.values = [];
                  for (var j2 = 0; j2 < message.values.length; ++j2)
                    object3.values[j2] = $root.opentelemetry.proto.common.v1.AnyValue.toObject(message.values[j2], options2);
                }
                return object3;
              }, "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;
            }();
            v1.KeyValueList = function() {
              function KeyValueList(properties) {
                this.values = [];
                if (properties) {
                  for (var keys = Object.keys(properties), i3 = 0; i3 < keys.length; ++i3)
                    if (properties[keys[i3]] != null)
                      this[keys[i3]] = properties[keys[i3]];
                }
              }
              __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 i3 = 0; i3 < message.values.length; ++i3)
                    $root.opentelemetry.proto.common.v1.KeyValue.encode(message.values[i3], 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, error2) {
                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 === error2)
                    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 i3 = 0; i3 < message.values.length; ++i3) {
                    var error2 = $root.opentelemetry.proto.common.v1.KeyValue.verify(message.values[i3]);
                    if (error2)
                      return "values." + error2;
                  }
                }
                return null;
              }, "verify");
              KeyValueList.fromObject = /* @__PURE__ */ __name(function fromObject(object3) {
                if (object3 instanceof $root.opentelemetry.proto.common.v1.KeyValueList)
                  return object3;
                var message = new $root.opentelemetry.proto.common.v1.KeyValueList();
                if (object3.values) {
                  if (!Array.isArray(object3.values))
                    throw TypeError(".opentelemetry.proto.common.v1.KeyValueList.values: array expected");
                  message.values = [];
                  for (var i3 = 0; i3 < object3.values.length; ++i3) {
                    if (typeof object3.values[i3] !== "object")
                      throw TypeError(".opentelemetry.proto.common.v1.KeyValueList.values: object expected");
                    message.values[i3] = $root.opentelemetry.proto.common.v1.KeyValue.fromObject(object3.values[i3]);
                  }
                }
                return message;
              }, "fromObject");
              KeyValueList.toObject = /* @__PURE__ */ __name(function toObject(message, options2) {
                if (!options2)
                  options2 = {};
                var object3 = {};
                if (options2.arrays || options2.defaults)
                  object3.values = [];
                if (message.values && message.values.length) {
                  object3.values = [];
                  for (var j2 = 0; j2 < message.values.length; ++j2)
                    object3.values[j2] = $root.opentelemetry.proto.common.v1.KeyValue.toObject(message.values[j2], options2);
                }
                return object3;
              }, "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;
            }();
            v1.KeyValue = function() {
              function KeyValue(properties) {
                if (properties) {
                  for (var keys = Object.keys(properties), i3 = 0; i3 < keys.length; ++i3)
                    if (properties[keys[i3]] != null)
                      this[keys[i3]] = properties[keys[i3]];
                }
              }
              __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, error2) {
                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 === error2)
                    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 error2 = $root.opentelemetry.proto.common.v1.AnyValue.verify(message.value);
                  if (error2)
                    return "value." + error2;
                }
                return null;
              }, "verify");
              KeyValue.fromObject = /* @__PURE__ */ __name(function fromObject(object3) {
                if (object3 instanceof $root.opentelemetry.proto.common.v1.KeyValue)
                  return object3;
                var message = new $root.opentelemetry.proto.common.v1.KeyValue();
                if (object3.key != null)
                  message.key = String(object3.key);
                if (object3.value != null) {
                  if (typeof object3.value !== "object")
                    throw TypeError(".opentelemetry.proto.common.v1.KeyValue.value: object expected");
                  message.value = $root.opentelemetry.proto.common.v1.AnyValue.fromObject(object3.value);
                }
                return message;
              }, "fromObject");
              KeyValue.toObject = /* @__PURE__ */ __name(function toObject(message, options2) {
                if (!options2)
                  options2 = {};
                var object3 = {};
                if (options2.defaults) {
                  object3.key = "";
                  object3.value = null;
                }
                if (message.key != null && message.hasOwnProperty("key"))
                  object3.key = message.key;
                if (message.value != null && message.hasOwnProperty("value"))
                  object3.value = $root.opentelemetry.proto.common.v1.AnyValue.toObject(message.value, options2);
                return object3;
              }, "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;
            }();
            v1.InstrumentationScope = function() {
              function InstrumentationScope(properties) {
                this.attributes = [];
                if (properties) {
                  for (var keys = Object.keys(properties), i3 = 0; i3 < keys.length; ++i3)
                    if (properties[keys[i3]] != null)
                      this[keys[i3]] = properties[keys[i3]];
                }
              }
              __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 i3 = 0; i3 < message.attributes.length; ++i3)
                    $root.opentelemetry.proto.common.v1.KeyValue.encode(message.attributes[i3], 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, error2) {
                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 === error2)
                    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 i3 = 0; i3 < message.attributes.length; ++i3) {
                    var error2 = $root.opentelemetry.proto.common.v1.KeyValue.verify(message.attributes[i3]);
                    if (error2)
                      return "attributes." + error2;
                  }
                }
                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(object3) {
                if (object3 instanceof $root.opentelemetry.proto.common.v1.InstrumentationScope)
                  return object3;
                var message = new $root.opentelemetry.proto.common.v1.InstrumentationScope();
                if (object3.name != null)
                  message.name = String(object3.name);
                if (object3.version != null)
                  message.version = String(object3.version);
                if (object3.attributes) {
                  if (!Array.isArray(object3.attributes))
                    throw TypeError(".opentelemetry.proto.common.v1.InstrumentationScope.attributes: array expected");
                  message.attributes = [];
                  for (var i3 = 0; i3 < object3.attributes.length; ++i3) {
                    if (typeof object3.attributes[i3] !== "object")
                      throw TypeError(".opentelemetry.proto.common.v1.InstrumentationScope.attributes: object expected");
                    message.attributes[i3] = $root.opentelemetry.proto.common.v1.KeyValue.fromObject(object3.attributes[i3]);
                  }
                }
                if (object3.droppedAttributesCount != null)
                  message.droppedAttributesCount = object3.droppedAttributesCount >>> 0;
                return message;
              }, "fromObject");
              InstrumentationScope.toObject = /* @__PURE__ */ __name(function toObject(message, options2) {
                if (!options2)
                  options2 = {};
                var object3 = {};
                if (options2.arrays || options2.defaults)
                  object3.attributes = [];
                if (options2.defaults) {
                  object3.name = "";
                  object3.version = "";
                  object3.droppedAttributesCount = 0;
                }
                if (message.name != null && message.hasOwnProperty("name"))
                  object3.name = message.name;
                if (message.version != null && message.hasOwnProperty("version"))
                  object3.version = message.version;
                if (message.attributes && message.attributes.length) {
                  object3.attributes = [];
                  for (var j2 = 0; j2 < message.attributes.length; ++j2)
                    object3.attributes[j2] = $root.opentelemetry.proto.common.v1.KeyValue.toObject(message.attributes[j2], options2);
                }
                if (message.droppedAttributesCount != null && message.hasOwnProperty("droppedAttributesCount"))
                  object3.droppedAttributesCount = message.droppedAttributesCount;
                return object3;
              }, "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;
            }();
            v1.EntityRef = function() {
              function EntityRef(properties) {
                this.idKeys = [];
                this.descriptionKeys = [];
                if (properties) {
                  for (var keys = Object.keys(properties), i3 = 0; i3 < keys.length; ++i3)
                    if (properties[keys[i3]] != null)
                      this[keys[i3]] = properties[keys[i3]];
                }
              }
              __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 i3 = 0; i3 < message.idKeys.length; ++i3)
                    writer.uint32(
                      /* id 3, wireType 2 =*/
                      26
                    ).string(message.idKeys[i3]);
                if (message.descriptionKeys != null && message.descriptionKeys.length)
                  for (var i3 = 0; i3 < message.descriptionKeys.length; ++i3)
                    writer.uint32(
                      /* id 4, wireType 2 =*/
                      34
                    ).string(message.descriptionKeys[i3]);
                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, error2) {
                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 === error2)
                    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 i3 = 0; i3 < message.idKeys.length; ++i3)
                    if (!$util.isString(message.idKeys[i3]))
                      return "idKeys: string[] expected";
                }
                if (message.descriptionKeys != null && message.hasOwnProperty("descriptionKeys")) {
                  if (!Array.isArray(message.descriptionKeys))
                    return "descriptionKeys: array expected";
                  for (var i3 = 0; i3 < message.descriptionKeys.length; ++i3)
                    if (!$util.isString(message.descriptionKeys[i3]))
                      return "descriptionKeys: string[] expected";
                }
                return null;
              }, "verify");
              EntityRef.fromObject = /* @__PURE__ */ __name(function fromObject(object3) {
                if (object3 instanceof $root.opentelemetry.proto.common.v1.EntityRef)
                  return object3;
                var message = new $root.opentelemetry.proto.common.v1.EntityRef();
                if (object3.schemaUrl != null)
                  message.schemaUrl = String(object3.schemaUrl);
                if (object3.type != null)
                  message.type = String(object3.type);
                if (object3.idKeys) {
                  if (!Array.isArray(object3.idKeys))
                    throw TypeError(".opentelemetry.proto.common.v1.EntityRef.idKeys: array expected");
                  message.idKeys = [];
                  for (var i3 = 0; i3 < object3.idKeys.length; ++i3)
                    message.idKeys[i3] = String(object3.idKeys[i3]);
                }
                if (object3.descriptionKeys) {
                  if (!Array.isArray(object3.descriptionKeys))
                    throw TypeError(".opentelemetry.proto.common.v1.EntityRef.descriptionKeys: array expected");
                  message.descriptionKeys = [];
                  for (var i3 = 0; i3 < object3.descriptionKeys.length; ++i3)
                    message.descriptionKeys[i3] = String(object3.descriptionKeys[i3]);
                }
                return message;
              }, "fromObject");
              EntityRef.toObject = /* @__PURE__ */ __name(function toObject(message, options2) {
                if (!options2)
                  options2 = {};
                var object3 = {};
                if (options2.arrays || options2.defaults) {
                  object3.idKeys = [];
                  object3.descriptionKeys = [];
                }
                if (options2.defaults) {
                  object3.schemaUrl = "";
                  object3.type = "";
                }
                if (message.schemaUrl != null && message.hasOwnProperty("schemaUrl"))
                  object3.schemaUrl = message.schemaUrl;
                if (message.type != null && message.hasOwnProperty("type"))
                  object3.type = message.type;
                if (message.idKeys && message.idKeys.length) {
                  object3.idKeys = [];
                  for (var j2 = 0; j2 < message.idKeys.length; ++j2)
                    object3.idKeys[j2] = message.idKeys[j2];
                }
                if (message.descriptionKeys && message.descriptionKeys.length) {
                  object3.descriptionKeys = [];
                  for (var j2 = 0; j2 < message.descriptionKeys.length; ++j2)
                    object3.descriptionKeys[j2] = message.descriptionKeys[j2];
                }
                return object3;
              }, "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 v1;
          }();
          return common;
        }();
        proto3.resource = function() {
          var resource = {};
          resource.v1 = function() {
            var v1 = {};
            v1.Resource = function() {
              function Resource(properties) {
                this.attributes = [];
                this.entityRefs = [];
                if (properties) {
                  for (var keys = Object.keys(properties), i3 = 0; i3 < keys.length; ++i3)
                    if (properties[keys[i3]] != null)
                      this[keys[i3]] = properties[keys[i3]];
                }
              }
              __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 i3 = 0; i3 < message.attributes.length; ++i3)
                    $root.opentelemetry.proto.common.v1.KeyValue.encode(message.attributes[i3], 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 i3 = 0; i3 < message.entityRefs.length; ++i3)
                    $root.opentelemetry.proto.common.v1.EntityRef.encode(message.entityRefs[i3], 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, error2) {
                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 === error2)
                    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 i3 = 0; i3 < message.attributes.length; ++i3) {
                    var error2 = $root.opentelemetry.proto.common.v1.KeyValue.verify(message.attributes[i3]);
                    if (error2)
                      return "attributes." + error2;
                  }
                }
                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 i3 = 0; i3 < message.entityRefs.length; ++i3) {
                    var error2 = $root.opentelemetry.proto.common.v1.EntityRef.verify(message.entityRefs[i3]);
                    if (error2)
                      return "entityRefs." + error2;
                  }
                }
                return null;
              }, "verify");
              Resource.fromObject = /* @__PURE__ */ __name(function fromObject(object3) {
                if (object3 instanceof $root.opentelemetry.proto.resource.v1.Resource)
                  return object3;
                var message = new $root.opentelemetry.proto.resource.v1.Resource();
                if (object3.attributes) {
                  if (!Array.isArray(object3.attributes))
                    throw TypeError(".opentelemetry.proto.resource.v1.Resource.attributes: array expected");
                  message.attributes = [];
                  for (var i3 = 0; i3 < object3.attributes.length; ++i3) {
                    if (typeof object3.attributes[i3] !== "object")
                      throw TypeError(".opentelemetry.proto.resource.v1.Resource.attributes: object expected");
                    message.attributes[i3] = $root.opentelemetry.proto.common.v1.KeyValue.fromObject(object3.attributes[i3]);
                  }
                }
                if (object3.droppedAttributesCount != null)
                  message.droppedAttributesCount = object3.droppedAttributesCount >>> 0;
                if (object3.entityRefs) {
                  if (!Array.isArray(object3.entityRefs))
                    throw TypeError(".opentelemetry.proto.resource.v1.Resource.entityRefs: array expected");
                  message.entityRefs = [];
                  for (var i3 = 0; i3 < object3.entityRefs.length; ++i3) {
                    if (typeof object3.entityRefs[i3] !== "object")
                      throw TypeError(".opentelemetry.proto.resource.v1.Resource.entityRefs: object expected");
                    message.entityRefs[i3] = $root.opentelemetry.proto.common.v1.EntityRef.fromObject(object3.entityRefs[i3]);
                  }
                }
                return message;
              }, "fromObject");
              Resource.toObject = /* @__PURE__ */ __name(function toObject(message, options2) {
                if (!options2)
                  options2 = {};
                var object3 = {};
                if (options2.arrays || options2.defaults) {
                  object3.attributes = [];
                  object3.entityRefs = [];
                }
                if (options2.defaults)
                  object3.droppedAttributesCount = 0;
                if (message.attributes && message.attributes.length) {
                  object3.attributes = [];
                  for (var j2 = 0; j2 < message.attributes.length; ++j2)
                    object3.attributes[j2] = $root.opentelemetry.proto.common.v1.KeyValue.toObject(message.attributes[j2], options2);
                }
                if (message.droppedAttributesCount != null && message.hasOwnProperty("droppedAttributesCount"))
                  object3.droppedAttributesCount = message.droppedAttributesCount;
                if (message.entityRefs && message.entityRefs.length) {
                  object3.entityRefs = [];
                  for (var j2 = 0; j2 < message.entityRefs.length; ++j2)
                    object3.entityRefs[j2] = $root.opentelemetry.proto.common.v1.EntityRef.toObject(message.entityRefs[j2], options2);
                }
                return object3;
              }, "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 v1;
          }();
          return resource;
        }();
        proto3.trace = function() {
          var trace2 = {};
          trace2.v1 = function() {
            var v1 = {};
            v1.TracesData = function() {
              function TracesData(properties) {
                this.resourceSpans = [];
                if (properties) {
                  for (var keys = Object.keys(properties), i3 = 0; i3 < keys.length; ++i3)
                    if (properties[keys[i3]] != null)
                      this[keys[i3]] = properties[keys[i3]];
                }
              }
              __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 i3 = 0; i3 < message.resourceSpans.length; ++i3)
                    $root.opentelemetry.proto.trace.v1.ResourceSpans.encode(message.resourceSpans[i3], 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, error2) {
                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 === error2)
                    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 i3 = 0; i3 < message.resourceSpans.length; ++i3) {
                    var error2 = $root.opentelemetry.proto.trace.v1.ResourceSpans.verify(message.resourceSpans[i3]);
                    if (error2)
                      return "resourceSpans." + error2;
                  }
                }
                return null;
              }, "verify");
              TracesData.fromObject = /* @__PURE__ */ __name(function fromObject(object3) {
                if (object3 instanceof $root.opentelemetry.proto.trace.v1.TracesData)
                  return object3;
                var message = new $root.opentelemetry.proto.trace.v1.TracesData();
                if (object3.resourceSpans) {
                  if (!Array.isArray(object3.resourceSpans))
                    throw TypeError(".opentelemetry.proto.trace.v1.TracesData.resourceSpans: array expected");
                  message.resourceSpans = [];
                  for (var i3 = 0; i3 < object3.resourceSpans.length; ++i3) {
                    if (typeof object3.resourceSpans[i3] !== "object")
                      throw TypeError(".opentelemetry.proto.trace.v1.TracesData.resourceSpans: object expected");
                    message.resourceSpans[i3] = $root.opentelemetry.proto.trace.v1.ResourceSpans.fromObject(object3.resourceSpans[i3]);
                  }
                }
                return message;
              }, "fromObject");
              TracesData.toObject = /* @__PURE__ */ __name(function toObject(message, options2) {
                if (!options2)
                  options2 = {};
                var object3 = {};
                if (options2.arrays || options2.defaults)
                  object3.resourceSpans = [];
                if (message.resourceSpans && message.resourceSpans.length) {
                  object3.resourceSpans = [];
                  for (var j2 = 0; j2 < message.resourceSpans.length; ++j2)
                    object3.resourceSpans[j2] = $root.opentelemetry.proto.trace.v1.ResourceSpans.toObject(message.resourceSpans[j2], options2);
                }
                return object3;
              }, "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;
            }();
            v1.ResourceSpans = function() {
              function ResourceSpans(properties) {
                this.scopeSpans = [];
                if (properties) {
                  for (var keys = Object.keys(properties), i3 = 0; i3 < keys.length; ++i3)
                    if (properties[keys[i3]] != null)
                      this[keys[i3]] = properties[keys[i3]];
                }
              }
              __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 i3 = 0; i3 < message.scopeSpans.length; ++i3)
                    $root.opentelemetry.proto.trace.v1.ScopeSpans.encode(message.scopeSpans[i3], 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, error2) {
                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 === error2)
                    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 error2 = $root.opentelemetry.proto.resource.v1.Resource.verify(message.resource);
                  if (error2)
                    return "resource." + error2;
                }
                if (message.scopeSpans != null && message.hasOwnProperty("scopeSpans")) {
                  if (!Array.isArray(message.scopeSpans))
                    return "scopeSpans: array expected";
                  for (var i3 = 0; i3 < message.scopeSpans.length; ++i3) {
                    var error2 = $root.opentelemetry.proto.trace.v1.ScopeSpans.verify(message.scopeSpans[i3]);
                    if (error2)
                      return "scopeSpans." + error2;
                  }
                }
                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(object3) {
                if (object3 instanceof $root.opentelemetry.proto.trace.v1.ResourceSpans)
                  return object3;
                var message = new $root.opentelemetry.proto.trace.v1.ResourceSpans();
                if (object3.resource != null) {
                  if (typeof object3.resource !== "object")
                    throw TypeError(".opentelemetry.proto.trace.v1.ResourceSpans.resource: object expected");
                  message.resource = $root.opentelemetry.proto.resource.v1.Resource.fromObject(object3.resource);
                }
                if (object3.scopeSpans) {
                  if (!Array.isArray(object3.scopeSpans))
                    throw TypeError(".opentelemetry.proto.trace.v1.ResourceSpans.scopeSpans: array expected");
                  message.scopeSpans = [];
                  for (var i3 = 0; i3 < object3.scopeSpans.length; ++i3) {
                    if (typeof object3.scopeSpans[i3] !== "object")
                      throw TypeError(".opentelemetry.proto.trace.v1.ResourceSpans.scopeSpans: object expected");
                    message.scopeSpans[i3] = $root.opentelemetry.proto.trace.v1.ScopeSpans.fromObject(object3.scopeSpans[i3]);
                  }
                }
                if (object3.schemaUrl != null)
                  message.schemaUrl = String(object3.schemaUrl);
                return message;
              }, "fromObject");
              ResourceSpans.toObject = /* @__PURE__ */ __name(function toObject(message, options2) {
                if (!options2)
                  options2 = {};
                var object3 = {};
                if (options2.arrays || options2.defaults)
                  object3.scopeSpans = [];
                if (options2.defaults) {
                  object3.resource = null;
                  object3.schemaUrl = "";
                }
                if (message.resource != null && message.hasOwnProperty("resource"))
                  object3.resource = $root.opentelemetry.proto.resource.v1.Resource.toObject(message.resource, options2);
                if (message.scopeSpans && message.scopeSpans.length) {
                  object3.scopeSpans = [];
                  for (var j2 = 0; j2 < message.scopeSpans.length; ++j2)
                    object3.scopeSpans[j2] = $root.opentelemetry.proto.trace.v1.ScopeSpans.toObject(message.scopeSpans[j2], options2);
                }
                if (message.schemaUrl != null && message.hasOwnProperty("schemaUrl"))
                  object3.schemaUrl = message.schemaUrl;
                return object3;
              }, "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;
            }();
            v1.ScopeSpans = function() {
              function ScopeSpans(properties) {
                this.spans = [];
                if (properties) {
                  for (var keys = Object.keys(properties), i3 = 0; i3 < keys.length; ++i3)
                    if (properties[keys[i3]] != null)
                      this[keys[i3]] = properties[keys[i3]];
                }
              }
              __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 i3 = 0; i3 < message.spans.length; ++i3)
                    $root.opentelemetry.proto.trace.v1.Span.encode(message.spans[i3], 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, error2) {
                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 === error2)
                    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 error2 = $root.opentelemetry.proto.common.v1.InstrumentationScope.verify(message.scope);
                  if (error2)
                    return "scope." + error2;
                }
                if (message.spans != null && message.hasOwnProperty("spans")) {
                  if (!Array.isArray(message.spans))
                    return "spans: array expected";
                  for (var i3 = 0; i3 < message.spans.length; ++i3) {
                    var error2 = $root.opentelemetry.proto.trace.v1.Span.verify(message.spans[i3]);
                    if (error2)
                      return "spans." + error2;
                  }
                }
                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(object3) {
                if (object3 instanceof $root.opentelemetry.proto.trace.v1.ScopeSpans)
                  return object3;
                var message = new $root.opentelemetry.proto.trace.v1.ScopeSpans();
                if (object3.scope != null) {
                  if (typeof object3.scope !== "object")
                    throw TypeError(".opentelemetry.proto.trace.v1.ScopeSpans.scope: object expected");
                  message.scope = $root.opentelemetry.proto.common.v1.InstrumentationScope.fromObject(object3.scope);
                }
                if (object3.spans) {
                  if (!Array.isArray(object3.spans))
                    throw TypeError(".opentelemetry.proto.trace.v1.ScopeSpans.spans: array expected");
                  message.spans = [];
                  for (var i3 = 0; i3 < object3.spans.length; ++i3) {
                    if (typeof object3.spans[i3] !== "object")
                      throw TypeError(".opentelemetry.proto.trace.v1.ScopeSpans.spans: object expected");
                    message.spans[i3] = $root.opentelemetry.proto.trace.v1.Span.fromObject(object3.spans[i3]);
                  }
                }
                if (object3.schemaUrl != null)
                  message.schemaUrl = String(object3.schemaUrl);
                return message;
              }, "fromObject");
              ScopeSpans.toObject = /* @__PURE__ */ __name(function toObject(message, options2) {
                if (!options2)
                  options2 = {};
                var object3 = {};
                if (options2.arrays || options2.defaults)
                  object3.spans = [];
                if (options2.defaults) {
                  object3.scope = null;
                  object3.schemaUrl = "";
                }
                if (message.scope != null && message.hasOwnProperty("scope"))
                  object3.scope = $root.opentelemetry.proto.common.v1.InstrumentationScope.toObject(message.scope, options2);
                if (message.spans && message.spans.length) {
                  object3.spans = [];
                  for (var j2 = 0; j2 < message.spans.length; ++j2)
                    object3.spans[j2] = $root.opentelemetry.proto.trace.v1.Span.toObject(message.spans[j2], options2);
                }
                if (message.schemaUrl != null && message.hasOwnProperty("schemaUrl"))
                  object3.schemaUrl = message.schemaUrl;
                return object3;
              }, "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;
            }();
            v1.Span = function() {
              function Span(properties) {
                this.attributes = [];
                this.events = [];
                this.links = [];
                if (properties) {
                  for (var keys = Object.keys(properties), i3 = 0; i3 < keys.length; ++i3)
                    if (properties[keys[i3]] != null)
                      this[keys[i3]] = properties[keys[i3]];
                }
              }
              __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 i3 = 0; i3 < message.attributes.length; ++i3)
                    $root.opentelemetry.proto.common.v1.KeyValue.encode(message.attributes[i3], 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 i3 = 0; i3 < message.events.length; ++i3)
                    $root.opentelemetry.proto.trace.v1.Span.Event.encode(message.events[i3], 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 i3 = 0; i3 < message.links.length; ++i3)
                    $root.opentelemetry.proto.trace.v1.Span.Link.encode(message.links[i3], 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, error2) {
                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 === error2)
                    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 i3 = 0; i3 < message.attributes.length; ++i3) {
                    var error2 = $root.opentelemetry.proto.common.v1.KeyValue.verify(message.attributes[i3]);
                    if (error2)
                      return "attributes." + error2;
                  }
                }
                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 i3 = 0; i3 < message.events.length; ++i3) {
                    var error2 = $root.opentelemetry.proto.trace.v1.Span.Event.verify(message.events[i3]);
                    if (error2)
                      return "events." + error2;
                  }
                }
                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 i3 = 0; i3 < message.links.length; ++i3) {
                    var error2 = $root.opentelemetry.proto.trace.v1.Span.Link.verify(message.links[i3]);
                    if (error2)
                      return "links." + error2;
                  }
                }
                if (message.droppedLinksCount != null && message.hasOwnProperty("droppedLinksCount")) {
                  if (!$util.isInteger(message.droppedLinksCount))
                    return "droppedLinksCount: integer expected";
                }
                if (message.status != null && message.hasOwnProperty("status")) {
                  var error2 = $root.opentelemetry.proto.trace.v1.Status.verify(message.status);
                  if (error2)
                    return "status." + error2;
                }
                return null;
              }, "verify");
              Span.fromObject = /* @__PURE__ */ __name(function fromObject(object3) {
                if (object3 instanceof $root.opentelemetry.proto.trace.v1.Span)
                  return object3;
                var message = new $root.opentelemetry.proto.trace.v1.Span();
                if (object3.traceId != null) {
                  if (typeof object3.traceId === "string")
                    $util.base64.decode(object3.traceId, message.traceId = $util.newBuffer($util.base64.length(object3.traceId)), 0);
                  else if (object3.traceId.length >= 0)
                    message.traceId = object3.traceId;
                }
                if (object3.spanId != null) {
                  if (typeof object3.spanId === "string")
                    $util.base64.decode(object3.spanId, message.spanId = $util.newBuffer($util.base64.length(object3.spanId)), 0);
                  else if (object3.spanId.length >= 0)
                    message.spanId = object3.spanId;
                }
                if (object3.traceState != null)
                  message.traceState = String(object3.traceState);
                if (object3.parentSpanId != null) {
                  if (typeof object3.parentSpanId === "string")
                    $util.base64.decode(object3.parentSpanId, message.parentSpanId = $util.newBuffer($util.base64.length(object3.parentSpanId)), 0);
                  else if (object3.parentSpanId.length >= 0)
                    message.parentSpanId = object3.parentSpanId;
                }
                if (object3.flags != null)
                  message.flags = object3.flags >>> 0;
                if (object3.name != null)
                  message.name = String(object3.name);
                switch (object3.kind) {
                  default:
                    if (typeof object3.kind === "number") {
                      message.kind = object3.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 (object3.startTimeUnixNano != null) {
                  if ($util.Long)
                    (message.startTimeUnixNano = $util.Long.fromValue(object3.startTimeUnixNano)).unsigned = false;
                  else if (typeof object3.startTimeUnixNano === "string")
                    message.startTimeUnixNano = parseInt(object3.startTimeUnixNano, 10);
                  else if (typeof object3.startTimeUnixNano === "number")
                    message.startTimeUnixNano = object3.startTimeUnixNano;
                  else if (typeof object3.startTimeUnixNano === "object")
                    message.startTimeUnixNano = new $util.LongBits(object3.startTimeUnixNano.low >>> 0, object3.startTimeUnixNano.high >>> 0).toNumber();
                }
                if (object3.endTimeUnixNano != null) {
                  if ($util.Long)
                    (message.endTimeUnixNano = $util.Long.fromValue(object3.endTimeUnixNano)).unsigned = false;
                  else if (typeof object3.endTimeUnixNano === "string")
                    message.endTimeUnixNano = parseInt(object3.endTimeUnixNano, 10);
                  else if (typeof object3.endTimeUnixNano === "number")
                    message.endTimeUnixNano = object3.endTimeUnixNano;
                  else if (typeof object3.endTimeUnixNano === "object")
                    message.endTimeUnixNano = new $util.LongBits(object3.endTimeUnixNano.low >>> 0, object3.endTimeUnixNano.high >>> 0).toNumber();
                }
                if (object3.attributes) {
                  if (!Array.isArray(object3.attributes))
                    throw TypeError(".opentelemetry.proto.trace.v1.Span.attributes: array expected");
                  message.attributes = [];
                  for (var i3 = 0; i3 < object3.attributes.length; ++i3) {
                    if (typeof object3.attributes[i3] !== "object")
                      throw TypeError(".opentelemetry.proto.trace.v1.Span.attributes: object expected");
                    message.attributes[i3] = $root.opentelemetry.proto.common.v1.KeyValue.fromObject(object3.attributes[i3]);
                  }
                }
                if (object3.droppedAttributesCount != null)
                  message.droppedAttributesCount = object3.droppedAttributesCount >>> 0;
                if (object3.events) {
                  if (!Array.isArray(object3.events))
                    throw TypeError(".opentelemetry.proto.trace.v1.Span.events: array expected");
                  message.events = [];
                  for (var i3 = 0; i3 < object3.events.length; ++i3) {
                    if (typeof object3.events[i3] !== "object")
                      throw TypeError(".opentelemetry.proto.trace.v1.Span.events: object expected");
                    message.events[i3] = $root.opentelemetry.proto.trace.v1.Span.Event.fromObject(object3.events[i3]);
                  }
                }
                if (object3.droppedEventsCount != null)
                  message.droppedEventsCount = object3.droppedEventsCount >>> 0;
                if (object3.links) {
                  if (!Array.isArray(object3.links))
                    throw TypeError(".opentelemetry.proto.trace.v1.Span.links: array expected");
                  message.links = [];
                  for (var i3 = 0; i3 < object3.links.length; ++i3) {
                    if (typeof object3.links[i3] !== "object")
                      throw TypeError(".opentelemetry.proto.trace.v1.Span.links: object expected");
                    message.links[i3] = $root.opentelemetry.proto.trace.v1.Span.Link.fromObject(object3.links[i3]);
                  }
                }
                if (object3.droppedLinksCount != null)
                  message.droppedLinksCount = object3.droppedLinksCount >>> 0;
                if (object3.status != null) {
                  if (typeof object3.status !== "object")
                    throw TypeError(".opentelemetry.proto.trace.v1.Span.status: object expected");
                  message.status = $root.opentelemetry.proto.trace.v1.Status.fromObject(object3.status);
                }
                return message;
              }, "fromObject");
              Span.toObject = /* @__PURE__ */ __name(function toObject(message, options2) {
                if (!options2)
                  options2 = {};
                var object3 = {};
                if (options2.arrays || options2.defaults) {
                  object3.attributes = [];
                  object3.events = [];
                  object3.links = [];
                }
                if (options2.defaults) {
                  if (options2.bytes === String)
                    object3.traceId = "";
                  else {
                    object3.traceId = [];
                    if (options2.bytes !== Array)
                      object3.traceId = $util.newBuffer(object3.traceId);
                  }
                  if (options2.bytes === String)
                    object3.spanId = "";
                  else {
                    object3.spanId = [];
                    if (options2.bytes !== Array)
                      object3.spanId = $util.newBuffer(object3.spanId);
                  }
                  object3.traceState = "";
                  if (options2.bytes === String)
                    object3.parentSpanId = "";
                  else {
                    object3.parentSpanId = [];
                    if (options2.bytes !== Array)
                      object3.parentSpanId = $util.newBuffer(object3.parentSpanId);
                  }
                  object3.name = "";
                  object3.kind = options2.enums === String ? "SPAN_KIND_UNSPECIFIED" : 0;
                  if ($util.Long) {
                    var long = new $util.Long(0, 0, false);
                    object3.startTimeUnixNano = options2.longs === String ? long.toString() : options2.longs === Number ? long.toNumber() : long;
                  } else
                    object3.startTimeUnixNano = options2.longs === String ? "0" : 0;
                  if ($util.Long) {
                    var long = new $util.Long(0, 0, false);
                    object3.endTimeUnixNano = options2.longs === String ? long.toString() : options2.longs === Number ? long.toNumber() : long;
                  } else
                    object3.endTimeUnixNano = options2.longs === String ? "0" : 0;
                  object3.droppedAttributesCount = 0;
                  object3.droppedEventsCount = 0;
                  object3.droppedLinksCount = 0;
                  object3.status = null;
                  object3.flags = 0;
                }
                if (message.traceId != null && message.hasOwnProperty("traceId"))
                  object3.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"))
                  object3.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"))
                  object3.traceState = message.traceState;
                if (message.parentSpanId != null && message.hasOwnProperty("parentSpanId"))
                  object3.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"))
                  object3.name = message.name;
                if (message.kind != null && message.hasOwnProperty("kind"))
                  object3.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")
                    object3.startTimeUnixNano = options2.longs === String ? String(message.startTimeUnixNano) : message.startTimeUnixNano;
                  else
                    object3.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")
                    object3.endTimeUnixNano = options2.longs === String ? String(message.endTimeUnixNano) : message.endTimeUnixNano;
                  else
                    object3.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) {
                  object3.attributes = [];
                  for (var j2 = 0; j2 < message.attributes.length; ++j2)
                    object3.attributes[j2] = $root.opentelemetry.proto.common.v1.KeyValue.toObject(message.attributes[j2], options2);
                }
                if (message.droppedAttributesCount != null && message.hasOwnProperty("droppedAttributesCount"))
                  object3.droppedAttributesCount = message.droppedAttributesCount;
                if (message.events && message.events.length) {
                  object3.events = [];
                  for (var j2 = 0; j2 < message.events.length; ++j2)
                    object3.events[j2] = $root.opentelemetry.proto.trace.v1.Span.Event.toObject(message.events[j2], options2);
                }
                if (message.droppedEventsCount != null && message.hasOwnProperty("droppedEventsCount"))
                  object3.droppedEventsCount = message.droppedEventsCount;
                if (message.links && message.links.length) {
                  object3.links = [];
                  for (var j2 = 0; j2 < message.links.length; ++j2)
                    object3.links[j2] = $root.opentelemetry.proto.trace.v1.Span.Link.toObject(message.links[j2], options2);
                }
                if (message.droppedLinksCount != null && message.hasOwnProperty("droppedLinksCount"))
                  object3.droppedLinksCount = message.droppedLinksCount;
                if (message.status != null && message.hasOwnProperty("status"))
                  object3.status = $root.opentelemetry.proto.trace.v1.Status.toObject(message.status, options2);
                if (message.flags != null && message.hasOwnProperty("flags"))
                  object3.flags = message.flags;
                return object3;
              }, "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), i3 = 0; i3 < keys.length; ++i3)
                      if (properties[keys[i3]] != null)
                        this[keys[i3]] = properties[keys[i3]];
                  }
                }
                __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 i3 = 0; i3 < message.attributes.length; ++i3)
                      $root.opentelemetry.proto.common.v1.KeyValue.encode(message.attributes[i3], 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, error2) {
                  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 === error2)
                      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 i3 = 0; i3 < message.attributes.length; ++i3) {
                      var error2 = $root.opentelemetry.proto.common.v1.KeyValue.verify(message.attributes[i3]);
                      if (error2)
                        return "attributes." + error2;
                    }
                  }
                  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(object3) {
                  if (object3 instanceof $root.opentelemetry.proto.trace.v1.Span.Event)
                    return object3;
                  var message = new $root.opentelemetry.proto.trace.v1.Span.Event();
                  if (object3.timeUnixNano != null) {
                    if ($util.Long)
                      (message.timeUnixNano = $util.Long.fromValue(object3.timeUnixNano)).unsigned = false;
                    else if (typeof object3.timeUnixNano === "string")
                      message.timeUnixNano = parseInt(object3.timeUnixNano, 10);
                    else if (typeof object3.timeUnixNano === "number")
                      message.timeUnixNano = object3.timeUnixNano;
                    else if (typeof object3.timeUnixNano === "object")
                      message.timeUnixNano = new $util.LongBits(object3.timeUnixNano.low >>> 0, object3.timeUnixNano.high >>> 0).toNumber();
                  }
                  if (object3.name != null)
                    message.name = String(object3.name);
                  if (object3.attributes) {
                    if (!Array.isArray(object3.attributes))
                      throw TypeError(".opentelemetry.proto.trace.v1.Span.Event.attributes: array expected");
                    message.attributes = [];
                    for (var i3 = 0; i3 < object3.attributes.length; ++i3) {
                      if (typeof object3.attributes[i3] !== "object")
                        throw TypeError(".opentelemetry.proto.trace.v1.Span.Event.attributes: object expected");
                      message.attributes[i3] = $root.opentelemetry.proto.common.v1.KeyValue.fromObject(object3.attributes[i3]);
                    }
                  }
                  if (object3.droppedAttributesCount != null)
                    message.droppedAttributesCount = object3.droppedAttributesCount >>> 0;
                  return message;
                }, "fromObject");
                Event2.toObject = /* @__PURE__ */ __name(function toObject(message, options2) {
                  if (!options2)
                    options2 = {};
                  var object3 = {};
                  if (options2.arrays || options2.defaults)
                    object3.attributes = [];
                  if (options2.defaults) {
                    if ($util.Long) {
                      var long = new $util.Long(0, 0, false);
                      object3.timeUnixNano = options2.longs === String ? long.toString() : options2.longs === Number ? long.toNumber() : long;
                    } else
                      object3.timeUnixNano = options2.longs === String ? "0" : 0;
                    object3.name = "";
                    object3.droppedAttributesCount = 0;
                  }
                  if (message.timeUnixNano != null && message.hasOwnProperty("timeUnixNano"))
                    if (typeof message.timeUnixNano === "number")
                      object3.timeUnixNano = options2.longs === String ? String(message.timeUnixNano) : message.timeUnixNano;
                    else
                      object3.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"))
                    object3.name = message.name;
                  if (message.attributes && message.attributes.length) {
                    object3.attributes = [];
                    for (var j2 = 0; j2 < message.attributes.length; ++j2)
                      object3.attributes[j2] = $root.opentelemetry.proto.common.v1.KeyValue.toObject(message.attributes[j2], options2);
                  }
                  if (message.droppedAttributesCount != null && message.hasOwnProperty("droppedAttributesCount"))
                    object3.droppedAttributesCount = message.droppedAttributesCount;
                  return object3;
                }, "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), i3 = 0; i3 < keys.length; ++i3)
                      if (properties[keys[i3]] != null)
                        this[keys[i3]] = properties[keys[i3]];
                  }
                }
                __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 i3 = 0; i3 < message.attributes.length; ++i3)
                      $root.opentelemetry.proto.common.v1.KeyValue.encode(message.attributes[i3], 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, error2) {
                  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 === error2)
                      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 i3 = 0; i3 < message.attributes.length; ++i3) {
                      var error2 = $root.opentelemetry.proto.common.v1.KeyValue.verify(message.attributes[i3]);
                      if (error2)
                        return "attributes." + error2;
                    }
                  }
                  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(object3) {
                  if (object3 instanceof $root.opentelemetry.proto.trace.v1.Span.Link)
                    return object3;
                  var message = new $root.opentelemetry.proto.trace.v1.Span.Link();
                  if (object3.traceId != null) {
                    if (typeof object3.traceId === "string")
                      $util.base64.decode(object3.traceId, message.traceId = $util.newBuffer($util.base64.length(object3.traceId)), 0);
                    else if (object3.traceId.length >= 0)
                      message.traceId = object3.traceId;
                  }
                  if (object3.spanId != null) {
                    if (typeof object3.spanId === "string")
                      $util.base64.decode(object3.spanId, message.spanId = $util.newBuffer($util.base64.length(object3.spanId)), 0);
                    else if (object3.spanId.length >= 0)
                      message.spanId = object3.spanId;
                  }
                  if (object3.traceState != null)
                    message.traceState = String(object3.traceState);
                  if (object3.attributes) {
                    if (!Array.isArray(object3.attributes))
                      throw TypeError(".opentelemetry.proto.trace.v1.Span.Link.attributes: array expected");
                    message.attributes = [];
                    for (var i3 = 0; i3 < object3.attributes.length; ++i3) {
                      if (typeof object3.attributes[i3] !== "object")
                        throw TypeError(".opentelemetry.proto.trace.v1.Span.Link.attributes: object expected");
                      message.attributes[i3] = $root.opentelemetry.proto.common.v1.KeyValue.fromObject(object3.attributes[i3]);
                    }
                  }
                  if (object3.droppedAttributesCount != null)
                    message.droppedAttributesCount = object3.droppedAttributesCount >>> 0;
                  if (object3.flags != null)
                    message.flags = object3.flags >>> 0;
                  return message;
                }, "fromObject");
                Link2.toObject = /* @__PURE__ */ __name(function toObject(message, options2) {
                  if (!options2)
                    options2 = {};
                  var object3 = {};
                  if (options2.arrays || options2.defaults)
                    object3.attributes = [];
                  if (options2.defaults) {
                    if (options2.bytes === String)
                      object3.traceId = "";
                    else {
                      object3.traceId = [];
                      if (options2.bytes !== Array)
                        object3.traceId = $util.newBuffer(object3.traceId);
                    }
                    if (options2.bytes === String)
                      object3.spanId = "";
                    else {
                      object3.spanId = [];
                      if (options2.bytes !== Array)
                        object3.spanId = $util.newBuffer(object3.spanId);
                    }
                    object3.traceState = "";
                    object3.droppedAttributesCount = 0;
                    object3.flags = 0;
                  }
                  if (message.traceId != null && message.hasOwnProperty("traceId"))
                    object3.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"))
                    object3.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"))
                    object3.traceState = message.traceState;
                  if (message.attributes && message.attributes.length) {
                    object3.attributes = [];
                    for (var j2 = 0; j2 < message.attributes.length; ++j2)
                      object3.attributes[j2] = $root.opentelemetry.proto.common.v1.KeyValue.toObject(message.attributes[j2], options2);
                  }
                  if (message.droppedAttributesCount != null && message.hasOwnProperty("droppedAttributesCount"))
                    object3.droppedAttributesCount = message.droppedAttributesCount;
                  if (message.flags != null && message.hasOwnProperty("flags"))
                    object3.flags = message.flags;
                  return object3;
                }, "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;
            }();
            v1.Status = function() {
              function Status(properties) {
                if (properties) {
                  for (var keys = Object.keys(properties), i3 = 0; i3 < keys.length; ++i3)
                    if (properties[keys[i3]] != null)
                      this[keys[i3]] = properties[keys[i3]];
                }
              }
              __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, error2) {
                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 === error2)
                    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(object3) {
                if (object3 instanceof $root.opentelemetry.proto.trace.v1.Status)
                  return object3;
                var message = new $root.opentelemetry.proto.trace.v1.Status();
                if (object3.message != null)
                  message.message = String(object3.message);
                switch (object3.code) {
                  default:
                    if (typeof object3.code === "number") {
                      message.code = object3.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 object3 = {};
                if (options2.defaults) {
                  object3.message = "";
                  object3.code = options2.enums === String ? "STATUS_CODE_UNSET" : 0;
                }
                if (message.message != null && message.hasOwnProperty("message"))
                  object3.message = message.message;
                if (message.code != null && message.hasOwnProperty("code"))
                  object3.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 object3;
              }, "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;
            }();
            v1.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 v1;
          }();
          return trace2;
        }();
        proto3.collector = function() {
          var collector = {};
          collector.trace = function() {
            var trace2 = {};
            trace2.v1 = function() {
              var v1 = {};
              v1.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;
              }();
              v1.ExportTraceServiceRequest = function() {
                function ExportTraceServiceRequest(properties) {
                  this.resourceSpans = [];
                  if (properties) {
                    for (var keys = Object.keys(properties), i3 = 0; i3 < keys.length; ++i3)
                      if (properties[keys[i3]] != null)
                        this[keys[i3]] = properties[keys[i3]];
                  }
                }
                __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 i3 = 0; i3 < message.resourceSpans.length; ++i3)
                      $root.opentelemetry.proto.trace.v1.ResourceSpans.encode(message.resourceSpans[i3], 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, error2) {
                  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 === error2)
                      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 i3 = 0; i3 < message.resourceSpans.length; ++i3) {
                      var error2 = $root.opentelemetry.proto.trace.v1.ResourceSpans.verify(message.resourceSpans[i3]);
                      if (error2)
                        return "resourceSpans." + error2;
                    }
                  }
                  return null;
                }, "verify");
                ExportTraceServiceRequest.fromObject = /* @__PURE__ */ __name(function fromObject(object3) {
                  if (object3 instanceof $root.opentelemetry.proto.collector.trace.v1.ExportTraceServiceRequest)
                    return object3;
                  var message = new $root.opentelemetry.proto.collector.trace.v1.ExportTraceServiceRequest();
                  if (object3.resourceSpans) {
                    if (!Array.isArray(object3.resourceSpans))
                      throw TypeError(".opentelemetry.proto.collector.trace.v1.ExportTraceServiceRequest.resourceSpans: array expected");
                    message.resourceSpans = [];
                    for (var i3 = 0; i3 < object3.resourceSpans.length; ++i3) {
                      if (typeof object3.resourceSpans[i3] !== "object")
                        throw TypeError(".opentelemetry.proto.collector.trace.v1.ExportTraceServiceRequest.resourceSpans: object expected");
                      message.resourceSpans[i3] = $root.opentelemetry.proto.trace.v1.ResourceSpans.fromObject(object3.resourceSpans[i3]);
                    }
                  }
                  return message;
                }, "fromObject");
                ExportTraceServiceRequest.toObject = /* @__PURE__ */ __name(function toObject(message, options2) {
                  if (!options2)
                    options2 = {};
                  var object3 = {};
                  if (options2.arrays || options2.defaults)
                    object3.resourceSpans = [];
                  if (message.resourceSpans && message.resourceSpans.length) {
                    object3.resourceSpans = [];
                    for (var j2 = 0; j2 < message.resourceSpans.length; ++j2)
                      object3.resourceSpans[j2] = $root.opentelemetry.proto.trace.v1.ResourceSpans.toObject(message.resourceSpans[j2], options2);
                  }
                  return object3;
                }, "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;
              }();
              v1.ExportTraceServiceResponse = function() {
                function ExportTraceServiceResponse(properties) {
                  if (properties) {
                    for (var keys = Object.keys(properties), i3 = 0; i3 < keys.length; ++i3)
                      if (properties[keys[i3]] != null)
                        this[keys[i3]] = properties[keys[i3]];
                  }
                }
                __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, error2) {
                  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 === error2)
                      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 error2 = $root.opentelemetry.proto.collector.trace.v1.ExportTracePartialSuccess.verify(message.partialSuccess);
                    if (error2)
                      return "partialSuccess." + error2;
                  }
                  return null;
                }, "verify");
                ExportTraceServiceResponse.fromObject = /* @__PURE__ */ __name(function fromObject(object3) {
                  if (object3 instanceof $root.opentelemetry.proto.collector.trace.v1.ExportTraceServiceResponse)
                    return object3;
                  var message = new $root.opentelemetry.proto.collector.trace.v1.ExportTraceServiceResponse();
                  if (object3.partialSuccess != null) {
                    if (typeof object3.partialSuccess !== "object")
                      throw TypeError(".opentelemetry.proto.collector.trace.v1.ExportTraceServiceResponse.partialSuccess: object expected");
                    message.partialSuccess = $root.opentelemetry.proto.collector.trace.v1.ExportTracePartialSuccess.fromObject(object3.partialSuccess);
                  }
                  return message;
                }, "fromObject");
                ExportTraceServiceResponse.toObject = /* @__PURE__ */ __name(function toObject(message, options2) {
                  if (!options2)
                    options2 = {};
                  var object3 = {};
                  if (options2.defaults)
                    object3.partialSuccess = null;
                  if (message.partialSuccess != null && message.hasOwnProperty("partialSuccess"))
                    object3.partialSuccess = $root.opentelemetry.proto.collector.trace.v1.ExportTracePartialSuccess.toObject(message.partialSuccess, options2);
                  return object3;
                }, "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;
              }();
              v1.ExportTracePartialSuccess = function() {
                function ExportTracePartialSuccess(properties) {
                  if (properties) {
                    for (var keys = Object.keys(properties), i3 = 0; i3 < keys.length; ++i3)
                      if (properties[keys[i3]] != null)
                        this[keys[i3]] = properties[keys[i3]];
                  }
                }
                __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, error2) {
                  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 === error2)
                      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(object3) {
                  if (object3 instanceof $root.opentelemetry.proto.collector.trace.v1.ExportTracePartialSuccess)
                    return object3;
                  var message = new $root.opentelemetry.proto.collector.trace.v1.ExportTracePartialSuccess();
                  if (object3.rejectedSpans != null) {
                    if ($util.Long)
                      (message.rejectedSpans = $util.Long.fromValue(object3.rejectedSpans)).unsigned = false;
                    else if (typeof object3.rejectedSpans === "string")
                      message.rejectedSpans = parseInt(object3.rejectedSpans, 10);
                    else if (typeof object3.rejectedSpans === "number")
                      message.rejectedSpans = object3.rejectedSpans;
                    else if (typeof object3.rejectedSpans === "object")
                      message.rejectedSpans = new $util.LongBits(object3.rejectedSpans.low >>> 0, object3.rejectedSpans.high >>> 0).toNumber();
                  }
                  if (object3.errorMessage != null)
                    message.errorMessage = String(object3.errorMessage);
                  return message;
                }, "fromObject");
                ExportTracePartialSuccess.toObject = /* @__PURE__ */ __name(function toObject(message, options2) {
                  if (!options2)
                    options2 = {};
                  var object3 = {};
                  if (options2.defaults) {
                    if ($util.Long) {
                      var long = new $util.Long(0, 0, false);
                      object3.rejectedSpans = options2.longs === String ? long.toString() : options2.longs === Number ? long.toNumber() : long;
                    } else
                      object3.rejectedSpans = options2.longs === String ? "0" : 0;
                    object3.errorMessage = "";
                  }
                  if (message.rejectedSpans != null && message.hasOwnProperty("rejectedSpans"))
                    if (typeof message.rejectedSpans === "number")
                      object3.rejectedSpans = options2.longs === String ? String(message.rejectedSpans) : message.rejectedSpans;
                    else
                      object3.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"))
                    object3.errorMessage = message.errorMessage;
                  return object3;
                }, "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 v1;
            }();
            return trace2;
          }();
          collector.metrics = function() {
            var metrics2 = {};
            metrics2.v1 = function() {
              var v1 = {};
              v1.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;
              }();
              v1.ExportMetricsServiceRequest = function() {
                function ExportMetricsServiceRequest(properties) {
                  this.resourceMetrics = [];
                  if (properties) {
                    for (var keys = Object.keys(properties), i3 = 0; i3 < keys.length; ++i3)
                      if (properties[keys[i3]] != null)
                        this[keys[i3]] = properties[keys[i3]];
                  }
                }
                __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 i3 = 0; i3 < message.resourceMetrics.length; ++i3)
                      $root.opentelemetry.proto.metrics.v1.ResourceMetrics.encode(message.resourceMetrics[i3], 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, error2) {
                  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 === error2)
                      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 i3 = 0; i3 < message.resourceMetrics.length; ++i3) {
                      var error2 = $root.opentelemetry.proto.metrics.v1.ResourceMetrics.verify(message.resourceMetrics[i3]);
                      if (error2)
                        return "resourceMetrics." + error2;
                    }
                  }
                  return null;
                }, "verify");
                ExportMetricsServiceRequest.fromObject = /* @__PURE__ */ __name(function fromObject(object3) {
                  if (object3 instanceof $root.opentelemetry.proto.collector.metrics.v1.ExportMetricsServiceRequest)
                    return object3;
                  var message = new $root.opentelemetry.proto.collector.metrics.v1.ExportMetricsServiceRequest();
                  if (object3.resourceMetrics) {
                    if (!Array.isArray(object3.resourceMetrics))
                      throw TypeError(".opentelemetry.proto.collector.metrics.v1.ExportMetricsServiceRequest.resourceMetrics: array expected");
                    message.resourceMetrics = [];
                    for (var i3 = 0; i3 < object3.resourceMetrics.length; ++i3) {
                      if (typeof object3.resourceMetrics[i3] !== "object")
                        throw TypeError(".opentelemetry.proto.collector.metrics.v1.ExportMetricsServiceRequest.resourceMetrics: object expected");
                      message.resourceMetrics[i3] = $root.opentelemetry.proto.metrics.v1.ResourceMetrics.fromObject(object3.resourceMetrics[i3]);
                    }
                  }
                  return message;
                }, "fromObject");
                ExportMetricsServiceRequest.toObject = /* @__PURE__ */ __name(function toObject(message, options2) {
                  if (!options2)
                    options2 = {};
                  var object3 = {};
                  if (options2.arrays || options2.defaults)
                    object3.resourceMetrics = [];
                  if (message.resourceMetrics && message.resourceMetrics.length) {
                    object3.resourceMetrics = [];
                    for (var j2 = 0; j2 < message.resourceMetrics.length; ++j2)
                      object3.resourceMetrics[j2] = $root.opentelemetry.proto.metrics.v1.ResourceMetrics.toObject(message.resourceMetrics[j2], options2);
                  }
                  return object3;
                }, "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;
              }();
              v1.ExportMetricsServiceResponse = function() {
                function ExportMetricsServiceResponse(properties) {
                  if (properties) {
                    for (var keys = Object.keys(properties), i3 = 0; i3 < keys.length; ++i3)
                      if (properties[keys[i3]] != null)
                        this[keys[i3]] = properties[keys[i3]];
                  }
                }
                __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, error2) {
                  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 === error2)
                      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 error2 = $root.opentelemetry.proto.collector.metrics.v1.ExportMetricsPartialSuccess.verify(message.partialSuccess);
                    if (error2)
                      return "partialSuccess." + error2;
                  }
                  return null;
                }, "verify");
                ExportMetricsServiceResponse.fromObject = /* @__PURE__ */ __name(function fromObject(object3) {
                  if (object3 instanceof $root.opentelemetry.proto.collector.metrics.v1.ExportMetricsServiceResponse)
                    return object3;
                  var message = new $root.opentelemetry.proto.collector.metrics.v1.ExportMetricsServiceResponse();
                  if (object3.partialSuccess != null) {
                    if (typeof object3.partialSuccess !== "object")
                      throw TypeError(".opentelemetry.proto.collector.metrics.v1.ExportMetricsServiceResponse.partialSuccess: object expected");
                    message.partialSuccess = $root.opentelemetry.proto.collector.metrics.v1.ExportMetricsPartialSuccess.fromObject(object3.partialSuccess);
                  }
                  return message;
                }, "fromObject");
                ExportMetricsServiceResponse.toObject = /* @__PURE__ */ __name(function toObject(message, options2) {
                  if (!options2)
                    options2 = {};
                  var object3 = {};
                  if (options2.defaults)
                    object3.partialSuccess = null;
                  if (message.partialSuccess != null && message.hasOwnProperty("partialSuccess"))
                    object3.partialSuccess = $root.opentelemetry.proto.collector.metrics.v1.ExportMetricsPartialSuccess.toObject(message.partialSuccess, options2);
                  return object3;
                }, "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;
              }();
              v1.ExportMetricsPartialSuccess = function() {
                function ExportMetricsPartialSuccess(properties) {
                  if (properties) {
                    for (var keys = Object.keys(properties), i3 = 0; i3 < keys.length; ++i3)
                      if (properties[keys[i3]] != null)
                        this[keys[i3]] = properties[keys[i3]];
                  }
                }
                __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, error2) {
                  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 === error2)
                      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(object3) {
                  if (object3 instanceof $root.opentelemetry.proto.collector.metrics.v1.ExportMetricsPartialSuccess)
                    return object3;
                  var message = new $root.opentelemetry.proto.collector.metrics.v1.ExportMetricsPartialSuccess();
                  if (object3.rejectedDataPoints != null) {
                    if ($util.Long)
                      (message.rejectedDataPoints = $util.Long.fromValue(object3.rejectedDataPoints)).unsigned = false;
                    else if (typeof object3.rejectedDataPoints === "string")
                      message.rejectedDataPoints = parseInt(object3.rejectedDataPoints, 10);
                    else if (typeof object3.rejectedDataPoints === "number")
                      message.rejectedDataPoints = object3.rejectedDataPoints;
                    else if (typeof object3.rejectedDataPoints === "object")
                      message.rejectedDataPoints = new $util.LongBits(object3.rejectedDataPoints.low >>> 0, object3.rejectedDataPoints.high >>> 0).toNumber();
                  }
                  if (object3.errorMessage != null)
                    message.errorMessage = String(object3.errorMessage);
                  return message;
                }, "fromObject");
                ExportMetricsPartialSuccess.toObject = /* @__PURE__ */ __name(function toObject(message, options2) {
                  if (!options2)
                    options2 = {};
                  var object3 = {};
                  if (options2.defaults) {
                    if ($util.Long) {
                      var long = new $util.Long(0, 0, false);
                      object3.rejectedDataPoints = options2.longs === String ? long.toString() : options2.longs === Number ? long.toNumber() : long;
                    } else
                      object3.rejectedDataPoints = options2.longs === String ? "0" : 0;
                    object3.errorMessage = "";
                  }
                  if (message.rejectedDataPoints != null && message.hasOwnProperty("rejectedDataPoints"))
                    if (typeof message.rejectedDataPoints === "number")
                      object3.rejectedDataPoints = options2.longs === String ? String(message.rejectedDataPoints) : message.rejectedDataPoints;
                    else
                      object3.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"))
                    object3.errorMessage = message.errorMessage;
                  return object3;
                }, "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 v1;
            }();
            return metrics2;
          }();
          collector.logs = function() {
            var logs2 = {};
            logs2.v1 = function() {
              var v1 = {};
              v1.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;
              }();
              v1.ExportLogsServiceRequest = function() {
                function ExportLogsServiceRequest(properties) {
                  this.resourceLogs = [];
                  if (properties) {
                    for (var keys = Object.keys(properties), i3 = 0; i3 < keys.length; ++i3)
                      if (properties[keys[i3]] != null)
                        this[keys[i3]] = properties[keys[i3]];
                  }
                }
                __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 i3 = 0; i3 < message.resourceLogs.length; ++i3)
                      $root.opentelemetry.proto.logs.v1.ResourceLogs.encode(message.resourceLogs[i3], 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, error2) {
                  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 === error2)
                      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 i3 = 0; i3 < message.resourceLogs.length; ++i3) {
                      var error2 = $root.opentelemetry.proto.logs.v1.ResourceLogs.verify(message.resourceLogs[i3]);
                      if (error2)
                        return "resourceLogs." + error2;
                    }
                  }
                  return null;
                }, "verify");
                ExportLogsServiceRequest.fromObject = /* @__PURE__ */ __name(function fromObject(object3) {
                  if (object3 instanceof $root.opentelemetry.proto.collector.logs.v1.ExportLogsServiceRequest)
                    return object3;
                  var message = new $root.opentelemetry.proto.collector.logs.v1.ExportLogsServiceRequest();
                  if (object3.resourceLogs) {
                    if (!Array.isArray(object3.resourceLogs))
                      throw TypeError(".opentelemetry.proto.collector.logs.v1.ExportLogsServiceRequest.resourceLogs: array expected");
                    message.resourceLogs = [];
                    for (var i3 = 0; i3 < object3.resourceLogs.length; ++i3) {
                      if (typeof object3.resourceLogs[i3] !== "object")
                        throw TypeError(".opentelemetry.proto.collector.logs.v1.ExportLogsServiceRequest.resourceLogs: object expected");
                      message.resourceLogs[i3] = $root.opentelemetry.proto.logs.v1.ResourceLogs.fromObject(object3.resourceLogs[i3]);
                    }
                  }
                  return message;
                }, "fromObject");
                ExportLogsServiceRequest.toObject = /* @__PURE__ */ __name(function toObject(message, options2) {
                  if (!options2)
                    options2 = {};
                  var object3 = {};
                  if (options2.arrays || options2.defaults)
                    object3.resourceLogs = [];
                  if (message.resourceLogs && message.resourceLogs.length) {
                    object3.resourceLogs = [];
                    for (var j2 = 0; j2 < message.resourceLogs.length; ++j2)
                      object3.resourceLogs[j2] = $root.opentelemetry.proto.logs.v1.ResourceLogs.toObject(message.resourceLogs[j2], options2);
                  }
                  return object3;
                }, "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;
              }();
              v1.ExportLogsServiceResponse = function() {
                function ExportLogsServiceResponse(properties) {
                  if (properties) {
                    for (var keys = Object.keys(properties), i3 = 0; i3 < keys.length; ++i3)
                      if (properties[keys[i3]] != null)
                        this[keys[i3]] = properties[keys[i3]];
                  }
                }
                __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, error2) {
                  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 === error2)
                      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 error2 = $root.opentelemetry.proto.collector.logs.v1.ExportLogsPartialSuccess.verify(message.partialSuccess);
                    if (error2)
                      return "partialSuccess." + error2;
                  }
                  return null;
                }, "verify");
                ExportLogsServiceResponse.fromObject = /* @__PURE__ */ __name(function fromObject(object3) {
                  if (object3 instanceof $root.opentelemetry.proto.collector.logs.v1.ExportLogsServiceResponse)
                    return object3;
                  var message = new $root.opentelemetry.proto.collector.logs.v1.ExportLogsServiceResponse();
                  if (object3.partialSuccess != null) {
                    if (typeof object3.partialSuccess !== "object")
                      throw TypeError(".opentelemetry.proto.collector.logs.v1.ExportLogsServiceResponse.partialSuccess: object expected");
                    message.partialSuccess = $root.opentelemetry.proto.collector.logs.v1.ExportLogsPartialSuccess.fromObject(object3.partialSuccess);
                  }
                  return message;
                }, "fromObject");
                ExportLogsServiceResponse.toObject = /* @__PURE__ */ __name(function toObject(message, options2) {
                  if (!options2)
                    options2 = {};
                  var object3 = {};
                  if (options2.defaults)
                    object3.partialSuccess = null;
                  if (message.partialSuccess != null && message.hasOwnProperty("partialSuccess"))
                    object3.partialSuccess = $root.opentelemetry.proto.collector.logs.v1.ExportLogsPartialSuccess.toObject(message.partialSuccess, options2);
                  return object3;
                }, "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;
              }();
              v1.ExportLogsPartialSuccess = function() {
                function ExportLogsPartialSuccess(properties) {
                  if (properties) {
                    for (var keys = Object.keys(properties), i3 = 0; i3 < keys.length; ++i3)
                      if (properties[keys[i3]] != null)
                        this[keys[i3]] = properties[keys[i3]];
                  }
                }
                __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, error2) {
                  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 === error2)
                      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(object3) {
                  if (object3 instanceof $root.opentelemetry.proto.collector.logs.v1.ExportLogsPartialSuccess)
                    return object3;
                  var message = new $root.opentelemetry.proto.collector.logs.v1.ExportLogsPartialSuccess();
                  if (object3.rejectedLogRecords != null) {
                    if ($util.Long)
                      (message.rejectedLogRecords = $util.Long.fromValue(object3.rejectedLogRecords)).unsigned = false;
                    else if (typeof object3.rejectedLogRecords === "string")
                      message.rejectedLogRecords = parseInt(object3.rejectedLogRecords, 10);
                    else if (typeof object3.rejectedLogRecords === "number")
                      message.rejectedLogRecords = object3.rejectedLogRecords;
                    else if (typeof object3.rejectedLogRecords === "object")
                      message.rejectedLogRecords = new $util.LongBits(object3.rejectedLogRecords.low >>> 0, object3.rejectedLogRecords.high >>> 0).toNumber();
                  }
                  if (object3.errorMessage != null)
                    message.errorMessage = String(object3.errorMessage);
                  return message;
                }, "fromObject");
                ExportLogsPartialSuccess.toObject = /* @__PURE__ */ __name(function toObject(message, options2) {
                  if (!options2)
                    options2 = {};
                  var object3 = {};
                  if (options2.defaults) {
                    if ($util.Long) {
                      var long = new $util.Long(0, 0, false);
                      object3.rejectedLogRecords = options2.longs === String ? long.toString() : options2.longs === Number ? long.toNumber() : long;
                    } else
                      object3.rejectedLogRecords = options2.longs === String ? "0" : 0;
                    object3.errorMessage = "";
                  }
                  if (message.rejectedLogRecords != null && message.hasOwnProperty("rejectedLogRecords"))
                    if (typeof message.rejectedLogRecords === "number")
                      object3.rejectedLogRecords = options2.longs === String ? String(message.rejectedLogRecords) : message.rejectedLogRecords;
                    else
                      object3.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"))
                    object3.errorMessage = message.errorMessage;
                  return object3;
                }, "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 v1;
            }();
            return logs2;
          }();
          return collector;
        }();
        proto3.metrics = function() {
          var metrics2 = {};
          metrics2.v1 = function() {
            var v1 = {};
            v1.MetricsData = function() {
              function MetricsData(properties) {
                this.resourceMetrics = [];
                if (properties) {
                  for (var keys = Object.keys(properties), i3 = 0; i3 < keys.length; ++i3)
                    if (properties[keys[i3]] != null)
                      this[keys[i3]] = properties[keys[i3]];
                }
              }
              __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 i3 = 0; i3 < message.resourceMetrics.length; ++i3)
                    $root.opentelemetry.proto.metrics.v1.ResourceMetrics.encode(message.resourceMetrics[i3], 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, error2) {
                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 === error2)
                    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 i3 = 0; i3 < message.resourceMetrics.length; ++i3) {
                    var error2 = $root.opentelemetry.proto.metrics.v1.ResourceMetrics.verify(message.resourceMetrics[i3]);
                    if (error2)
                      return "resourceMetrics." + error2;
                  }
                }
                return null;
              }, "verify");
              MetricsData.fromObject = /* @__PURE__ */ __name(function fromObject(object3) {
                if (object3 instanceof $root.opentelemetry.proto.metrics.v1.MetricsData)
                  return object3;
                var message = new $root.opentelemetry.proto.metrics.v1.MetricsData();
                if (object3.resourceMetrics) {
                  if (!Array.isArray(object3.resourceMetrics))
                    throw TypeError(".opentelemetry.proto.metrics.v1.MetricsData.resourceMetrics: array expected");
                  message.resourceMetrics = [];
                  for (var i3 = 0; i3 < object3.resourceMetrics.length; ++i3) {
                    if (typeof object3.resourceMetrics[i3] !== "object")
                      throw TypeError(".opentelemetry.proto.metrics.v1.MetricsData.resourceMetrics: object expected");
                    message.resourceMetrics[i3] = $root.opentelemetry.proto.metrics.v1.ResourceMetrics.fromObject(object3.resourceMetrics[i3]);
                  }
                }
                return message;
              }, "fromObject");
              MetricsData.toObject = /* @__PURE__ */ __name(function toObject(message, options2) {
                if (!options2)
                  options2 = {};
                var object3 = {};
                if (options2.arrays || options2.defaults)
                  object3.resourceMetrics = [];
                if (message.resourceMetrics && message.resourceMetrics.length) {
                  object3.resourceMetrics = [];
                  for (var j2 = 0; j2 < message.resourceMetrics.length; ++j2)
                    object3.resourceMetrics[j2] = $root.opentelemetry.proto.metrics.v1.ResourceMetrics.toObject(message.resourceMetrics[j2], options2);
                }
                return object3;
              }, "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;
            }();
            v1.ResourceMetrics = function() {
              function ResourceMetrics(properties) {
                this.scopeMetrics = [];
                if (properties) {
                  for (var keys = Object.keys(properties), i3 = 0; i3 < keys.length; ++i3)
                    if (properties[keys[i3]] != null)
                      this[keys[i3]] = properties[keys[i3]];
                }
              }
              __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 i3 = 0; i3 < message.scopeMetrics.length; ++i3)
                    $root.opentelemetry.proto.metrics.v1.ScopeMetrics.encode(message.scopeMetrics[i3], 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, error2) {
                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 === error2)
                    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 error2 = $root.opentelemetry.proto.resource.v1.Resource.verify(message.resource);
                  if (error2)
                    return "resource." + error2;
                }
                if (message.scopeMetrics != null && message.hasOwnProperty("scopeMetrics")) {
                  if (!Array.isArray(message.scopeMetrics))
                    return "scopeMetrics: array expected";
                  for (var i3 = 0; i3 < message.scopeMetrics.length; ++i3) {
                    var error2 = $root.opentelemetry.proto.metrics.v1.ScopeMetrics.verify(message.scopeMetrics[i3]);
                    if (error2)
                      return "scopeMetrics." + error2;
                  }
                }
                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(object3) {
                if (object3 instanceof $root.opentelemetry.proto.metrics.v1.ResourceMetrics)
                  return object3;
                var message = new $root.opentelemetry.proto.metrics.v1.ResourceMetrics();
                if (object3.resource != null) {
                  if (typeof object3.resource !== "object")
                    throw TypeError(".opentelemetry.proto.metrics.v1.ResourceMetrics.resource: object expected");
                  message.resource = $root.opentelemetry.proto.resource.v1.Resource.fromObject(object3.resource);
                }
                if (object3.scopeMetrics) {
                  if (!Array.isArray(object3.scopeMetrics))
                    throw TypeError(".opentelemetry.proto.metrics.v1.ResourceMetrics.scopeMetrics: array expected");
                  message.scopeMetrics = [];
                  for (var i3 = 0; i3 < object3.scopeMetrics.length; ++i3) {
                    if (typeof object3.scopeMetrics[i3] !== "object")
                      throw TypeError(".opentelemetry.proto.metrics.v1.ResourceMetrics.scopeMetrics: object expected");
                    message.scopeMetrics[i3] = $root.opentelemetry.proto.metrics.v1.ScopeMetrics.fromObject(object3.scopeMetrics[i3]);
                  }
                }
                if (object3.schemaUrl != null)
                  message.schemaUrl = String(object3.schemaUrl);
                return message;
              }, "fromObject");
              ResourceMetrics.toObject = /* @__PURE__ */ __name(function toObject(message, options2) {
                if (!options2)
                  options2 = {};
                var object3 = {};
                if (options2.arrays || options2.defaults)
                  object3.scopeMetrics = [];
                if (options2.defaults) {
                  object3.resource = null;
                  object3.schemaUrl = "";
                }
                if (message.resource != null && message.hasOwnProperty("resource"))
                  object3.resource = $root.opentelemetry.proto.resource.v1.Resource.toObject(message.resource, options2);
                if (message.scopeMetrics && message.scopeMetrics.length) {
                  object3.scopeMetrics = [];
                  for (var j2 = 0; j2 < message.scopeMetrics.length; ++j2)
                    object3.scopeMetrics[j2] = $root.opentelemetry.proto.metrics.v1.ScopeMetrics.toObject(message.scopeMetrics[j2], options2);
                }
                if (message.schemaUrl != null && message.hasOwnProperty("schemaUrl"))
                  object3.schemaUrl = message.schemaUrl;
                return object3;
              }, "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;
            }();
            v1.ScopeMetrics = function() {
              function ScopeMetrics(properties) {
                this.metrics = [];
                if (properties) {
                  for (var keys = Object.keys(properties), i3 = 0; i3 < keys.length; ++i3)
                    if (properties[keys[i3]] != null)
                      this[keys[i3]] = properties[keys[i3]];
                }
              }
              __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 i3 = 0; i3 < message.metrics.length; ++i3)
                    $root.opentelemetry.proto.metrics.v1.Metric.encode(message.metrics[i3], 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, error2) {
                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 === error2)
                    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 error2 = $root.opentelemetry.proto.common.v1.InstrumentationScope.verify(message.scope);
                  if (error2)
                    return "scope." + error2;
                }
                if (message.metrics != null && message.hasOwnProperty("metrics")) {
                  if (!Array.isArray(message.metrics))
                    return "metrics: array expected";
                  for (var i3 = 0; i3 < message.metrics.length; ++i3) {
                    var error2 = $root.opentelemetry.proto.metrics.v1.Metric.verify(message.metrics[i3]);
                    if (error2)
                      return "metrics." + error2;
                  }
                }
                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(object3) {
                if (object3 instanceof $root.opentelemetry.proto.metrics.v1.ScopeMetrics)
                  return object3;
                var message = new $root.opentelemetry.proto.metrics.v1.ScopeMetrics();
                if (object3.scope != null) {
                  if (typeof object3.scope !== "object")
                    throw TypeError(".opentelemetry.proto.metrics.v1.ScopeMetrics.scope: object expected");
                  message.scope = $root.opentelemetry.proto.common.v1.InstrumentationScope.fromObject(object3.scope);
                }
                if (object3.metrics) {
                  if (!Array.isArray(object3.metrics))
                    throw TypeError(".opentelemetry.proto.metrics.v1.ScopeMetrics.metrics: array expected");
                  message.metrics = [];
                  for (var i3 = 0; i3 < object3.metrics.length; ++i3) {
                    if (typeof object3.metrics[i3] !== "object")
                      throw TypeError(".opentelemetry.proto.metrics.v1.ScopeMetrics.metrics: object expected");
                    message.metrics[i3] = $root.opentelemetry.proto.metrics.v1.Metric.fromObject(object3.metrics[i3]);
                  }
                }
                if (object3.schemaUrl != null)
                  message.schemaUrl = String(object3.schemaUrl);
                return message;
              }, "fromObject");
              ScopeMetrics.toObject = /* @__PURE__ */ __name(function toObject(message, options2) {
                if (!options2)
                  options2 = {};
                var object3 = {};
                if (options2.arrays || options2.defaults)
                  object3.metrics = [];
                if (options2.defaults) {
                  object3.scope = null;
                  object3.schemaUrl = "";
                }
                if (message.scope != null && message.hasOwnProperty("scope"))
                  object3.scope = $root.opentelemetry.proto.common.v1.InstrumentationScope.toObject(message.scope, options2);
                if (message.metrics && message.metrics.length) {
                  object3.metrics = [];
                  for (var j2 = 0; j2 < message.metrics.length; ++j2)
                    object3.metrics[j2] = $root.opentelemetry.proto.metrics.v1.Metric.toObject(message.metrics[j2], options2);
                }
                if (message.schemaUrl != null && message.hasOwnProperty("schemaUrl"))
                  object3.schemaUrl = message.schemaUrl;
                return object3;
              }, "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;
            }();
            v1.Metric = function() {
              function Metric(properties) {
                this.metadata = [];
                if (properties) {
                  for (var keys = Object.keys(properties), i3 = 0; i3 < keys.length; ++i3)
                    if (properties[keys[i3]] != null)
                      this[keys[i3]] = properties[keys[i3]];
                }
              }
              __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 i3 = 0; i3 < message.metadata.length; ++i3)
                    $root.opentelemetry.proto.common.v1.KeyValue.encode(message.metadata[i3], 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, error2) {
                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 === error2)
                    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 error2 = $root.opentelemetry.proto.metrics.v1.Gauge.verify(message.gauge);
                    if (error2)
                      return "gauge." + error2;
                  }
                }
                if (message.sum != null && message.hasOwnProperty("sum")) {
                  if (properties.data === 1)
                    return "data: multiple values";
                  properties.data = 1;
                  {
                    var error2 = $root.opentelemetry.proto.metrics.v1.Sum.verify(message.sum);
                    if (error2)
                      return "sum." + error2;
                  }
                }
                if (message.histogram != null && message.hasOwnProperty("histogram")) {
                  if (properties.data === 1)
                    return "data: multiple values";
                  properties.data = 1;
                  {
                    var error2 = $root.opentelemetry.proto.metrics.v1.Histogram.verify(message.histogram);
                    if (error2)
                      return "histogram." + error2;
                  }
                }
                if (message.exponentialHistogram != null && message.hasOwnProperty("exponentialHistogram")) {
                  if (properties.data === 1)
                    return "data: multiple values";
                  properties.data = 1;
                  {
                    var error2 = $root.opentelemetry.proto.metrics.v1.ExponentialHistogram.verify(message.exponentialHistogram);
                    if (error2)
                      return "exponentialHistogram." + error2;
                  }
                }
                if (message.summary != null && message.hasOwnProperty("summary")) {
                  if (properties.data === 1)
                    return "data: multiple values";
                  properties.data = 1;
                  {
                    var error2 = $root.opentelemetry.proto.metrics.v1.Summary.verify(message.summary);
                    if (error2)
                      return "summary." + error2;
                  }
                }
                if (message.metadata != null && message.hasOwnProperty("metadata")) {
                  if (!Array.isArray(message.metadata))
                    return "metadata: array expected";
                  for (var i3 = 0; i3 < message.metadata.length; ++i3) {
                    var error2 = $root.opentelemetry.proto.common.v1.KeyValue.verify(message.metadata[i3]);
                    if (error2)
                      return "metadata." + error2;
                  }
                }
                return null;
              }, "verify");
              Metric.fromObject = /* @__PURE__ */ __name(function fromObject(object3) {
                if (object3 instanceof $root.opentelemetry.proto.metrics.v1.Metric)
                  return object3;
                var message = new $root.opentelemetry.proto.metrics.v1.Metric();
                if (object3.name != null)
                  message.name = String(object3.name);
                if (object3.description != null)
                  message.description = String(object3.description);
                if (object3.unit != null)
                  message.unit = String(object3.unit);
                if (object3.gauge != null) {
                  if (typeof object3.gauge !== "object")
                    throw TypeError(".opentelemetry.proto.metrics.v1.Metric.gauge: object expected");
                  message.gauge = $root.opentelemetry.proto.metrics.v1.Gauge.fromObject(object3.gauge);
                }
                if (object3.sum != null) {
                  if (typeof object3.sum !== "object")
                    throw TypeError(".opentelemetry.proto.metrics.v1.Metric.sum: object expected");
                  message.sum = $root.opentelemetry.proto.metrics.v1.Sum.fromObject(object3.sum);
                }
                if (object3.histogram != null) {
                  if (typeof object3.histogram !== "object")
                    throw TypeError(".opentelemetry.proto.metrics.v1.Metric.histogram: object expected");
                  message.histogram = $root.opentelemetry.proto.metrics.v1.Histogram.fromObject(object3.histogram);
                }
                if (object3.exponentialHistogram != null) {
                  if (typeof object3.exponentialHistogram !== "object")
                    throw TypeError(".opentelemetry.proto.metrics.v1.Metric.exponentialHistogram: object expected");
                  message.exponentialHistogram = $root.opentelemetry.proto.metrics.v1.ExponentialHistogram.fromObject(object3.exponentialHistogram);
                }
                if (object3.summary != null) {
                  if (typeof object3.summary !== "object")
                    throw TypeError(".opentelemetry.proto.metrics.v1.Metric.summary: object expected");
                  message.summary = $root.opentelemetry.proto.metrics.v1.Summary.fromObject(object3.summary);
                }
                if (object3.metadata) {
                  if (!Array.isArray(object3.metadata))
                    throw TypeError(".opentelemetry.proto.metrics.v1.Metric.metadata: array expected");
                  message.metadata = [];
                  for (var i3 = 0; i3 < object3.metadata.length; ++i3) {
                    if (typeof object3.metadata[i3] !== "object")
                      throw TypeError(".opentelemetry.proto.metrics.v1.Metric.metadata: object expected");
                    message.metadata[i3] = $root.opentelemetry.proto.common.v1.KeyValue.fromObject(object3.metadata[i3]);
                  }
                }
                return message;
              }, "fromObject");
              Metric.toObject = /* @__PURE__ */ __name(function toObject(message, options2) {
                if (!options2)
                  options2 = {};
                var object3 = {};
                if (options2.arrays || options2.defaults)
                  object3.metadata = [];
                if (options2.defaults) {
                  object3.name = "";
                  object3.description = "";
                  object3.unit = "";
                }
                if (message.name != null && message.hasOwnProperty("name"))
                  object3.name = message.name;
                if (message.description != null && message.hasOwnProperty("description"))
                  object3.description = message.description;
                if (message.unit != null && message.hasOwnProperty("unit"))
                  object3.unit = message.unit;
                if (message.gauge != null && message.hasOwnProperty("gauge")) {
                  object3.gauge = $root.opentelemetry.proto.metrics.v1.Gauge.toObject(message.gauge, options2);
                  if (options2.oneofs)
                    object3.data = "gauge";
                }
                if (message.sum != null && message.hasOwnProperty("sum")) {
                  object3.sum = $root.opentelemetry.proto.metrics.v1.Sum.toObject(message.sum, options2);
                  if (options2.oneofs)
                    object3.data = "sum";
                }
                if (message.histogram != null && message.hasOwnProperty("histogram")) {
                  object3.histogram = $root.opentelemetry.proto.metrics.v1.Histogram.toObject(message.histogram, options2);
                  if (options2.oneofs)
                    object3.data = "histogram";
                }
                if (message.exponentialHistogram != null && message.hasOwnProperty("exponentialHistogram")) {
                  object3.exponentialHistogram = $root.opentelemetry.proto.metrics.v1.ExponentialHistogram.toObject(message.exponentialHistogram, options2);
                  if (options2.oneofs)
                    object3.data = "exponentialHistogram";
                }
                if (message.summary != null && message.hasOwnProperty("summary")) {
                  object3.summary = $root.opentelemetry.proto.metrics.v1.Summary.toObject(message.summary, options2);
                  if (options2.oneofs)
                    object3.data = "summary";
                }
                if (message.metadata && message.metadata.length) {
                  object3.metadata = [];
                  for (var j2 = 0; j2 < message.metadata.length; ++j2)
                    object3.metadata[j2] = $root.opentelemetry.proto.common.v1.KeyValue.toObject(message.metadata[j2], options2);
                }
                return object3;
              }, "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;
            }();
            v1.Gauge = function() {
              function Gauge(properties) {
                this.dataPoints = [];
                if (properties) {
                  for (var keys = Object.keys(properties), i3 = 0; i3 < keys.length; ++i3)
                    if (properties[keys[i3]] != null)
                      this[keys[i3]] = properties[keys[i3]];
                }
              }
              __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 i3 = 0; i3 < message.dataPoints.length; ++i3)
                    $root.opentelemetry.proto.metrics.v1.NumberDataPoint.encode(message.dataPoints[i3], 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, error2) {
                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 === error2)
                    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 i3 = 0; i3 < message.dataPoints.length; ++i3) {
                    var error2 = $root.opentelemetry.proto.metrics.v1.NumberDataPoint.verify(message.dataPoints[i3]);
                    if (error2)
                      return "dataPoints." + error2;
                  }
                }
                return null;
              }, "verify");
              Gauge.fromObject = /* @__PURE__ */ __name(function fromObject(object3) {
                if (object3 instanceof $root.opentelemetry.proto.metrics.v1.Gauge)
                  return object3;
                var message = new $root.opentelemetry.proto.metrics.v1.Gauge();
                if (object3.dataPoints) {
                  if (!Array.isArray(object3.dataPoints))
                    throw TypeError(".opentelemetry.proto.metrics.v1.Gauge.dataPoints: array expected");
                  message.dataPoints = [];
                  for (var i3 = 0; i3 < object3.dataPoints.length; ++i3) {
                    if (typeof object3.dataPoints[i3] !== "object")
                      throw TypeError(".opentelemetry.proto.metrics.v1.Gauge.dataPoints: object expected");
                    message.dataPoints[i3] = $root.opentelemetry.proto.metrics.v1.NumberDataPoint.fromObject(object3.dataPoints[i3]);
                  }
                }
                return message;
              }, "fromObject");
              Gauge.toObject = /* @__PURE__ */ __name(function toObject(message, options2) {
                if (!options2)
                  options2 = {};
                var object3 = {};
                if (options2.arrays || options2.defaults)
                  object3.dataPoints = [];
                if (message.dataPoints && message.dataPoints.length) {
                  object3.dataPoints = [];
                  for (var j2 = 0; j2 < message.dataPoints.length; ++j2)
                    object3.dataPoints[j2] = $root.opentelemetry.proto.metrics.v1.NumberDataPoint.toObject(message.dataPoints[j2], options2);
                }
                return object3;
              }, "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;
            }();
            v1.Sum = function() {
              function Sum(properties) {
                this.dataPoints = [];
                if (properties) {
                  for (var keys = Object.keys(properties), i3 = 0; i3 < keys.length; ++i3)
                    if (properties[keys[i3]] != null)
                      this[keys[i3]] = properties[keys[i3]];
                }
              }
              __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 i3 = 0; i3 < message.dataPoints.length; ++i3)
                    $root.opentelemetry.proto.metrics.v1.NumberDataPoint.encode(message.dataPoints[i3], 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, error2) {
                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 === error2)
                    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 i3 = 0; i3 < message.dataPoints.length; ++i3) {
                    var error2 = $root.opentelemetry.proto.metrics.v1.NumberDataPoint.verify(message.dataPoints[i3]);
                    if (error2)
                      return "dataPoints." + error2;
                  }
                }
                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(object3) {
                if (object3 instanceof $root.opentelemetry.proto.metrics.v1.Sum)
                  return object3;
                var message = new $root.opentelemetry.proto.metrics.v1.Sum();
                if (object3.dataPoints) {
                  if (!Array.isArray(object3.dataPoints))
                    throw TypeError(".opentelemetry.proto.metrics.v1.Sum.dataPoints: array expected");
                  message.dataPoints = [];
                  for (var i3 = 0; i3 < object3.dataPoints.length; ++i3) {
                    if (typeof object3.dataPoints[i3] !== "object")
                      throw TypeError(".opentelemetry.proto.metrics.v1.Sum.dataPoints: object expected");
                    message.dataPoints[i3] = $root.opentelemetry.proto.metrics.v1.NumberDataPoint.fromObject(object3.dataPoints[i3]);
                  }
                }
                switch (object3.aggregationTemporality) {
                  default:
                    if (typeof object3.aggregationTemporality === "number") {
                      message.aggregationTemporality = object3.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 (object3.isMonotonic != null)
                  message.isMonotonic = Boolean(object3.isMonotonic);
                return message;
              }, "fromObject");
              Sum.toObject = /* @__PURE__ */ __name(function toObject(message, options2) {
                if (!options2)
                  options2 = {};
                var object3 = {};
                if (options2.arrays || options2.defaults)
                  object3.dataPoints = [];
                if (options2.defaults) {
                  object3.aggregationTemporality = options2.enums === String ? "AGGREGATION_TEMPORALITY_UNSPECIFIED" : 0;
                  object3.isMonotonic = false;
                }
                if (message.dataPoints && message.dataPoints.length) {
                  object3.dataPoints = [];
                  for (var j2 = 0; j2 < message.dataPoints.length; ++j2)
                    object3.dataPoints[j2] = $root.opentelemetry.proto.metrics.v1.NumberDataPoint.toObject(message.dataPoints[j2], options2);
                }
                if (message.aggregationTemporality != null && message.hasOwnProperty("aggregationTemporality"))
                  object3.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"))
                  object3.isMonotonic = message.isMonotonic;
                return object3;
              }, "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;
            }();
            v1.Histogram = function() {
              function Histogram(properties) {
                this.dataPoints = [];
                if (properties) {
                  for (var keys = Object.keys(properties), i3 = 0; i3 < keys.length; ++i3)
                    if (properties[keys[i3]] != null)
                      this[keys[i3]] = properties[keys[i3]];
                }
              }
              __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 i3 = 0; i3 < message.dataPoints.length; ++i3)
                    $root.opentelemetry.proto.metrics.v1.HistogramDataPoint.encode(message.dataPoints[i3], 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, error2) {
                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 === error2)
                    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 i3 = 0; i3 < message.dataPoints.length; ++i3) {
                    var error2 = $root.opentelemetry.proto.metrics.v1.HistogramDataPoint.verify(message.dataPoints[i3]);
                    if (error2)
                      return "dataPoints." + error2;
                  }
                }
                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(object3) {
                if (object3 instanceof $root.opentelemetry.proto.metrics.v1.Histogram)
                  return object3;
                var message = new $root.opentelemetry.proto.metrics.v1.Histogram();
                if (object3.dataPoints) {
                  if (!Array.isArray(object3.dataPoints))
                    throw TypeError(".opentelemetry.proto.metrics.v1.Histogram.dataPoints: array expected");
                  message.dataPoints = [];
                  for (var i3 = 0; i3 < object3.dataPoints.length; ++i3) {
                    if (typeof object3.dataPoints[i3] !== "object")
                      throw TypeError(".opentelemetry.proto.metrics.v1.Histogram.dataPoints: object expected");
                    message.dataPoints[i3] = $root.opentelemetry.proto.metrics.v1.HistogramDataPoint.fromObject(object3.dataPoints[i3]);
                  }
                }
                switch (object3.aggregationTemporality) {
                  default:
                    if (typeof object3.aggregationTemporality === "number") {
                      message.aggregationTemporality = object3.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 object3 = {};
                if (options2.arrays || options2.defaults)
                  object3.dataPoints = [];
                if (options2.defaults)
                  object3.aggregationTemporality = options2.enums === String ? "AGGREGATION_TEMPORALITY_UNSPECIFIED" : 0;
                if (message.dataPoints && message.dataPoints.length) {
                  object3.dataPoints = [];
                  for (var j2 = 0; j2 < message.dataPoints.length; ++j2)
                    object3.dataPoints[j2] = $root.opentelemetry.proto.metrics.v1.HistogramDataPoint.toObject(message.dataPoints[j2], options2);
                }
                if (message.aggregationTemporality != null && message.hasOwnProperty("aggregationTemporality"))
                  object3.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 object3;
              }, "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;
            }();
            v1.ExponentialHistogram = function() {
              function ExponentialHistogram(properties) {
                this.dataPoints = [];
                if (properties) {
                  for (var keys = Object.keys(properties), i3 = 0; i3 < keys.length; ++i3)
                    if (properties[keys[i3]] != null)
                      this[keys[i3]] = properties[keys[i3]];
                }
              }
              __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 i3 = 0; i3 < message.dataPoints.length; ++i3)
                    $root.opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint.encode(message.dataPoints[i3], 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, error2) {
                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 === error2)
                    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 i3 = 0; i3 < message.dataPoints.length; ++i3) {
                    var error2 = $root.opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint.verify(message.dataPoints[i3]);
                    if (error2)
                      return "dataPoints." + error2;
                  }
                }
                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(object3) {
                if (object3 instanceof $root.opentelemetry.proto.metrics.v1.ExponentialHistogram)
                  return object3;
                var message = new $root.opentelemetry.proto.metrics.v1.ExponentialHistogram();
                if (object3.dataPoints) {
                  if (!Array.isArray(object3.dataPoints))
                    throw TypeError(".opentelemetry.proto.metrics.v1.ExponentialHistogram.dataPoints: array expected");
                  message.dataPoints = [];
                  for (var i3 = 0; i3 < object3.dataPoints.length; ++i3) {
                    if (typeof object3.dataPoints[i3] !== "object")
                      throw TypeError(".opentelemetry.proto.metrics.v1.ExponentialHistogram.dataPoints: object expected");
                    message.dataPoints[i3] = $root.opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint.fromObject(object3.dataPoints[i3]);
                  }
                }
                switch (object3.aggregationTemporality) {
                  default:
                    if (typeof object3.aggregationTemporality === "number") {
                      message.aggregationTemporality = object3.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 object3 = {};
                if (options2.arrays || options2.defaults)
                  object3.dataPoints = [];
                if (options2.defaults)
                  object3.aggregationTemporality = options2.enums === String ? "AGGREGATION_TEMPORALITY_UNSPECIFIED" : 0;
                if (message.dataPoints && message.dataPoints.length) {
                  object3.dataPoints = [];
                  for (var j2 = 0; j2 < message.dataPoints.length; ++j2)
                    object3.dataPoints[j2] = $root.opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint.toObject(message.dataPoints[j2], options2);
                }
                if (message.aggregationTemporality != null && message.hasOwnProperty("aggregationTemporality"))
                  object3.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 object3;
              }, "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;
            }();
            v1.Summary = function() {
              function Summary(properties) {
                this.dataPoints = [];
                if (properties) {
                  for (var keys = Object.keys(properties), i3 = 0; i3 < keys.length; ++i3)
                    if (properties[keys[i3]] != null)
                      this[keys[i3]] = properties[keys[i3]];
                }
              }
              __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 i3 = 0; i3 < message.dataPoints.length; ++i3)
                    $root.opentelemetry.proto.metrics.v1.SummaryDataPoint.encode(message.dataPoints[i3], 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, error2) {
                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 === error2)
                    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 i3 = 0; i3 < message.dataPoints.length; ++i3) {
                    var error2 = $root.opentelemetry.proto.metrics.v1.SummaryDataPoint.verify(message.dataPoints[i3]);
                    if (error2)
                      return "dataPoints." + error2;
                  }
                }
                return null;
              }, "verify");
              Summary.fromObject = /* @__PURE__ */ __name(function fromObject(object3) {
                if (object3 instanceof $root.opentelemetry.proto.metrics.v1.Summary)
                  return object3;
                var message = new $root.opentelemetry.proto.metrics.v1.Summary();
                if (object3.dataPoints) {
                  if (!Array.isArray(object3.dataPoints))
                    throw TypeError(".opentelemetry.proto.metrics.v1.Summary.dataPoints: array expected");
                  message.dataPoints = [];
                  for (var i3 = 0; i3 < object3.dataPoints.length; ++i3) {
                    if (typeof object3.dataPoints[i3] !== "object")
                      throw TypeError(".opentelemetry.proto.metrics.v1.Summary.dataPoints: object expected");
                    message.dataPoints[i3] = $root.opentelemetry.proto.metrics.v1.SummaryDataPoint.fromObject(object3.dataPoints[i3]);
                  }
                }
                return message;
              }, "fromObject");
              Summary.toObject = /* @__PURE__ */ __name(function toObject(message, options2) {
                if (!options2)
                  options2 = {};
                var object3 = {};
                if (options2.arrays || options2.defaults)
                  object3.dataPoints = [];
                if (message.dataPoints && message.dataPoints.length) {
                  object3.dataPoints = [];
                  for (var j2 = 0; j2 < message.dataPoints.length; ++j2)
                    object3.dataPoints[j2] = $root.opentelemetry.proto.metrics.v1.SummaryDataPoint.toObject(message.dataPoints[j2], options2);
                }
                return object3;
              }, "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;
            }();
            v1.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;
            }();
            v1.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;
            }();
            v1.NumberDataPoint = function() {
              function NumberDataPoint(properties) {
                this.attributes = [];
                this.exemplars = [];
                if (properties) {
                  for (var keys = Object.keys(properties), i3 = 0; i3 < keys.length; ++i3)
                    if (properties[keys[i3]] != null)
                      this[keys[i3]] = properties[keys[i3]];
                }
              }
              __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 i3 = 0; i3 < message.exemplars.length; ++i3)
                    $root.opentelemetry.proto.metrics.v1.Exemplar.encode(message.exemplars[i3], 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 i3 = 0; i3 < message.attributes.length; ++i3)
                    $root.opentelemetry.proto.common.v1.KeyValue.encode(message.attributes[i3], 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, error2) {
                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 === error2)
                    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 i3 = 0; i3 < message.attributes.length; ++i3) {
                    var error2 = $root.opentelemetry.proto.common.v1.KeyValue.verify(message.attributes[i3]);
                    if (error2)
                      return "attributes." + error2;
                  }
                }
                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 i3 = 0; i3 < message.exemplars.length; ++i3) {
                    var error2 = $root.opentelemetry.proto.metrics.v1.Exemplar.verify(message.exemplars[i3]);
                    if (error2)
                      return "exemplars." + error2;
                  }
                }
                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(object3) {
                if (object3 instanceof $root.opentelemetry.proto.metrics.v1.NumberDataPoint)
                  return object3;
                var message = new $root.opentelemetry.proto.metrics.v1.NumberDataPoint();
                if (object3.attributes) {
                  if (!Array.isArray(object3.attributes))
                    throw TypeError(".opentelemetry.proto.metrics.v1.NumberDataPoint.attributes: array expected");
                  message.attributes = [];
                  for (var i3 = 0; i3 < object3.attributes.length; ++i3) {
                    if (typeof object3.attributes[i3] !== "object")
                      throw TypeError(".opentelemetry.proto.metrics.v1.NumberDataPoint.attributes: object expected");
                    message.attributes[i3] = $root.opentelemetry.proto.common.v1.KeyValue.fromObject(object3.attributes[i3]);
                  }
                }
                if (object3.startTimeUnixNano != null) {
                  if ($util.Long)
                    (message.startTimeUnixNano = $util.Long.fromValue(object3.startTimeUnixNano)).unsigned = false;
                  else if (typeof object3.startTimeUnixNano === "string")
                    message.startTimeUnixNano = parseInt(object3.startTimeUnixNano, 10);
                  else if (typeof object3.startTimeUnixNano === "number")
                    message.startTimeUnixNano = object3.startTimeUnixNano;
                  else if (typeof object3.startTimeUnixNano === "object")
                    message.startTimeUnixNano = new $util.LongBits(object3.startTimeUnixNano.low >>> 0, object3.startTimeUnixNano.high >>> 0).toNumber();
                }
                if (object3.timeUnixNano != null) {
                  if ($util.Long)
                    (message.timeUnixNano = $util.Long.fromValue(object3.timeUnixNano)).unsigned = false;
                  else if (typeof object3.timeUnixNano === "string")
                    message.timeUnixNano = parseInt(object3.timeUnixNano, 10);
                  else if (typeof object3.timeUnixNano === "number")
                    message.timeUnixNano = object3.timeUnixNano;
                  else if (typeof object3.timeUnixNano === "object")
                    message.timeUnixNano = new $util.LongBits(object3.timeUnixNano.low >>> 0, object3.timeUnixNano.high >>> 0).toNumber();
                }
                if (object3.asDouble != null)
                  message.asDouble = Number(object3.asDouble);
                if (object3.asInt != null) {
                  if ($util.Long)
                    (message.asInt = $util.Long.fromValue(object3.asInt)).unsigned = false;
                  else if (typeof object3.asInt === "string")
                    message.asInt = parseInt(object3.asInt, 10);
                  else if (typeof object3.asInt === "number")
                    message.asInt = object3.asInt;
                  else if (typeof object3.asInt === "object")
                    message.asInt = new $util.LongBits(object3.asInt.low >>> 0, object3.asInt.high >>> 0).toNumber();
                }
                if (object3.exemplars) {
                  if (!Array.isArray(object3.exemplars))
                    throw TypeError(".opentelemetry.proto.metrics.v1.NumberDataPoint.exemplars: array expected");
                  message.exemplars = [];
                  for (var i3 = 0; i3 < object3.exemplars.length; ++i3) {
                    if (typeof object3.exemplars[i3] !== "object")
                      throw TypeError(".opentelemetry.proto.metrics.v1.NumberDataPoint.exemplars: object expected");
                    message.exemplars[i3] = $root.opentelemetry.proto.metrics.v1.Exemplar.fromObject(object3.exemplars[i3]);
                  }
                }
                if (object3.flags != null)
                  message.flags = object3.flags >>> 0;
                return message;
              }, "fromObject");
              NumberDataPoint.toObject = /* @__PURE__ */ __name(function toObject(message, options2) {
                if (!options2)
                  options2 = {};
                var object3 = {};
                if (options2.arrays || options2.defaults) {
                  object3.exemplars = [];
                  object3.attributes = [];
                }
                if (options2.defaults) {
                  if ($util.Long) {
                    var long = new $util.Long(0, 0, false);
                    object3.startTimeUnixNano = options2.longs === String ? long.toString() : options2.longs === Number ? long.toNumber() : long;
                  } else
                    object3.startTimeUnixNano = options2.longs === String ? "0" : 0;
                  if ($util.Long) {
                    var long = new $util.Long(0, 0, false);
                    object3.timeUnixNano = options2.longs === String ? long.toString() : options2.longs === Number ? long.toNumber() : long;
                  } else
                    object3.timeUnixNano = options2.longs === String ? "0" : 0;
                  object3.flags = 0;
                }
                if (message.startTimeUnixNano != null && message.hasOwnProperty("startTimeUnixNano"))
                  if (typeof message.startTimeUnixNano === "number")
                    object3.startTimeUnixNano = options2.longs === String ? String(message.startTimeUnixNano) : message.startTimeUnixNano;
                  else
                    object3.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")
                    object3.timeUnixNano = options2.longs === String ? String(message.timeUnixNano) : message.timeUnixNano;
                  else
                    object3.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")) {
                  object3.asDouble = options2.json && !isFinite(message.asDouble) ? String(message.asDouble) : message.asDouble;
                  if (options2.oneofs)
                    object3.value = "asDouble";
                }
                if (message.exemplars && message.exemplars.length) {
                  object3.exemplars = [];
                  for (var j2 = 0; j2 < message.exemplars.length; ++j2)
                    object3.exemplars[j2] = $root.opentelemetry.proto.metrics.v1.Exemplar.toObject(message.exemplars[j2], options2);
                }
                if (message.asInt != null && message.hasOwnProperty("asInt")) {
                  if (typeof message.asInt === "number")
                    object3.asInt = options2.longs === String ? String(message.asInt) : message.asInt;
                  else
                    object3.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)
                    object3.value = "asInt";
                }
                if (message.attributes && message.attributes.length) {
                  object3.attributes = [];
                  for (var j2 = 0; j2 < message.attributes.length; ++j2)
                    object3.attributes[j2] = $root.opentelemetry.proto.common.v1.KeyValue.toObject(message.attributes[j2], options2);
                }
                if (message.flags != null && message.hasOwnProperty("flags"))
                  object3.flags = message.flags;
                return object3;
              }, "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;
            }();
            v1.HistogramDataPoint = function() {
              function HistogramDataPoint(properties) {
                this.attributes = [];
                this.bucketCounts = [];
                this.explicitBounds = [];
                this.exemplars = [];
                if (properties) {
                  for (var keys = Object.keys(properties), i3 = 0; i3 < keys.length; ++i3)
                    if (properties[keys[i3]] != null)
                      this[keys[i3]] = properties[keys[i3]];
                }
              }
              __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 i3 = 0; i3 < message.bucketCounts.length; ++i3)
                    writer.fixed64(message.bucketCounts[i3]);
                  writer.ldelim();
                }
                if (message.explicitBounds != null && message.explicitBounds.length) {
                  writer.uint32(
                    /* id 7, wireType 2 =*/
                    58
                  ).fork();
                  for (var i3 = 0; i3 < message.explicitBounds.length; ++i3)
                    writer.double(message.explicitBounds[i3]);
                  writer.ldelim();
                }
                if (message.exemplars != null && message.exemplars.length)
                  for (var i3 = 0; i3 < message.exemplars.length; ++i3)
                    $root.opentelemetry.proto.metrics.v1.Exemplar.encode(message.exemplars[i3], writer.uint32(
                      /* id 8, wireType 2 =*/
                      66
                    ).fork()).ldelim();
                if (message.attributes != null && message.attributes.length)
                  for (var i3 = 0; i3 < message.attributes.length; ++i3)
                    $root.opentelemetry.proto.common.v1.KeyValue.encode(message.attributes[i3], 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, error2) {
                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 === error2)
                    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 i3 = 0; i3 < message.attributes.length; ++i3) {
                    var error2 = $root.opentelemetry.proto.common.v1.KeyValue.verify(message.attributes[i3]);
                    if (error2)
                      return "attributes." + error2;
                  }
                }
                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 i3 = 0; i3 < message.bucketCounts.length; ++i3)
                    if (!$util.isInteger(message.bucketCounts[i3]) && !(message.bucketCounts[i3] && $util.isInteger(message.bucketCounts[i3].low) && $util.isInteger(message.bucketCounts[i3].high)))
                      return "bucketCounts: integer|Long[] expected";
                }
                if (message.explicitBounds != null && message.hasOwnProperty("explicitBounds")) {
                  if (!Array.isArray(message.explicitBounds))
                    return "explicitBounds: array expected";
                  for (var i3 = 0; i3 < message.explicitBounds.length; ++i3)
                    if (typeof message.explicitBounds[i3] !== "number")
                      return "explicitBounds: number[] expected";
                }
                if (message.exemplars != null && message.hasOwnProperty("exemplars")) {
                  if (!Array.isArray(message.exemplars))
                    return "exemplars: array expected";
                  for (var i3 = 0; i3 < message.exemplars.length; ++i3) {
                    var error2 = $root.opentelemetry.proto.metrics.v1.Exemplar.verify(message.exemplars[i3]);
                    if (error2)
                      return "exemplars." + error2;
                  }
                }
                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(object3) {
                if (object3 instanceof $root.opentelemetry.proto.metrics.v1.HistogramDataPoint)
                  return object3;
                var message = new $root.opentelemetry.proto.metrics.v1.HistogramDataPoint();
                if (object3.attributes) {
                  if (!Array.isArray(object3.attributes))
                    throw TypeError(".opentelemetry.proto.metrics.v1.HistogramDataPoint.attributes: array expected");
                  message.attributes = [];
                  for (var i3 = 0; i3 < object3.attributes.length; ++i3) {
                    if (typeof object3.attributes[i3] !== "object")
                      throw TypeError(".opentelemetry.proto.metrics.v1.HistogramDataPoint.attributes: object expected");
                    message.attributes[i3] = $root.opentelemetry.proto.common.v1.KeyValue.fromObject(object3.attributes[i3]);
                  }
                }
                if (object3.startTimeUnixNano != null) {
                  if ($util.Long)
                    (message.startTimeUnixNano = $util.Long.fromValue(object3.startTimeUnixNano)).unsigned = false;
                  else if (typeof object3.startTimeUnixNano === "string")
                    message.startTimeUnixNano = parseInt(object3.startTimeUnixNano, 10);
                  else if (typeof object3.startTimeUnixNano === "number")
                    message.startTimeUnixNano = object3.startTimeUnixNano;
                  else if (typeof object3.startTimeUnixNano === "object")
                    message.startTimeUnixNano = new $util.LongBits(object3.startTimeUnixNano.low >>> 0, object3.startTimeUnixNano.high >>> 0).toNumber();
                }
                if (object3.timeUnixNano != null) {
                  if ($util.Long)
                    (message.timeUnixNano = $util.Long.fromValue(object3.timeUnixNano)).unsigned = false;
                  else if (typeof object3.timeUnixNano === "string")
                    message.timeUnixNano = parseInt(object3.timeUnixNano, 10);
                  else if (typeof object3.timeUnixNano === "number")
                    message.timeUnixNano = object3.timeUnixNano;
                  else if (typeof object3.timeUnixNano === "object")
                    message.timeUnixNano = new $util.LongBits(object3.timeUnixNano.low >>> 0, object3.timeUnixNano.high >>> 0).toNumber();
                }
                if (object3.count != null) {
                  if ($util.Long)
                    (message.count = $util.Long.fromValue(object3.count)).unsigned = false;
                  else if (typeof object3.count === "string")
                    message.count = parseInt(object3.count, 10);
                  else if (typeof object3.count === "number")
                    message.count = object3.count;
                  else if (typeof object3.count === "object")
                    message.count = new $util.LongBits(object3.count.low >>> 0, object3.count.high >>> 0).toNumber();
                }
                if (object3.sum != null)
                  message.sum = Number(object3.sum);
                if (object3.bucketCounts) {
                  if (!Array.isArray(object3.bucketCounts))
                    throw TypeError(".opentelemetry.proto.metrics.v1.HistogramDataPoint.bucketCounts: array expected");
                  message.bucketCounts = [];
                  for (var i3 = 0; i3 < object3.bucketCounts.length; ++i3)
                    if ($util.Long)
                      (message.bucketCounts[i3] = $util.Long.fromValue(object3.bucketCounts[i3])).unsigned = false;
                    else if (typeof object3.bucketCounts[i3] === "string")
                      message.bucketCounts[i3] = parseInt(object3.bucketCounts[i3], 10);
                    else if (typeof object3.bucketCounts[i3] === "number")
                      message.bucketCounts[i3] = object3.bucketCounts[i3];
                    else if (typeof object3.bucketCounts[i3] === "object")
                      message.bucketCounts[i3] = new $util.LongBits(object3.bucketCounts[i3].low >>> 0, object3.bucketCounts[i3].high >>> 0).toNumber();
                }
                if (object3.explicitBounds) {
                  if (!Array.isArray(object3.explicitBounds))
                    throw TypeError(".opentelemetry.proto.metrics.v1.HistogramDataPoint.explicitBounds: array expected");
                  message.explicitBounds = [];
                  for (var i3 = 0; i3 < object3.explicitBounds.length; ++i3)
                    message.explicitBounds[i3] = Number(object3.explicitBounds[i3]);
                }
                if (object3.exemplars) {
                  if (!Array.isArray(object3.exemplars))
                    throw TypeError(".opentelemetry.proto.metrics.v1.HistogramDataPoint.exemplars: array expected");
                  message.exemplars = [];
                  for (var i3 = 0; i3 < object3.exemplars.length; ++i3) {
                    if (typeof object3.exemplars[i3] !== "object")
                      throw TypeError(".opentelemetry.proto.metrics.v1.HistogramDataPoint.exemplars: object expected");
                    message.exemplars[i3] = $root.opentelemetry.proto.metrics.v1.Exemplar.fromObject(object3.exemplars[i3]);
                  }
                }
                if (object3.flags != null)
                  message.flags = object3.flags >>> 0;
                if (object3.min != null)
                  message.min = Number(object3.min);
                if (object3.max != null)
                  message.max = Number(object3.max);
                return message;
              }, "fromObject");
              HistogramDataPoint.toObject = /* @__PURE__ */ __name(function toObject(message, options2) {
                if (!options2)
                  options2 = {};
                var object3 = {};
                if (options2.arrays || options2.defaults) {
                  object3.bucketCounts = [];
                  object3.explicitBounds = [];
                  object3.exemplars = [];
                  object3.attributes = [];
                }
                if (options2.defaults) {
                  if ($util.Long) {
                    var long = new $util.Long(0, 0, false);
                    object3.startTimeUnixNano = options2.longs === String ? long.toString() : options2.longs === Number ? long.toNumber() : long;
                  } else
                    object3.startTimeUnixNano = options2.longs === String ? "0" : 0;
                  if ($util.Long) {
                    var long = new $util.Long(0, 0, false);
                    object3.timeUnixNano = options2.longs === String ? long.toString() : options2.longs === Number ? long.toNumber() : long;
                  } else
                    object3.timeUnixNano = options2.longs === String ? "0" : 0;
                  if ($util.Long) {
                    var long = new $util.Long(0, 0, false);
                    object3.count = options2.longs === String ? long.toString() : options2.longs === Number ? long.toNumber() : long;
                  } else
                    object3.count = options2.longs === String ? "0" : 0;
                  object3.flags = 0;
                }
                if (message.startTimeUnixNano != null && message.hasOwnProperty("startTimeUnixNano"))
                  if (typeof message.startTimeUnixNano === "number")
                    object3.startTimeUnixNano = options2.longs === String ? String(message.startTimeUnixNano) : message.startTimeUnixNano;
                  else
                    object3.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")
                    object3.timeUnixNano = options2.longs === String ? String(message.timeUnixNano) : message.timeUnixNano;
                  else
                    object3.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")
                    object3.count = options2.longs === String ? String(message.count) : message.count;
                  else
                    object3.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")) {
                  object3.sum = options2.json && !isFinite(message.sum) ? String(message.sum) : message.sum;
                  if (options2.oneofs)
                    object3._sum = "sum";
                }
                if (message.bucketCounts && message.bucketCounts.length) {
                  object3.bucketCounts = [];
                  for (var j2 = 0; j2 < message.bucketCounts.length; ++j2)
                    if (typeof message.bucketCounts[j2] === "number")
                      object3.bucketCounts[j2] = options2.longs === String ? String(message.bucketCounts[j2]) : message.bucketCounts[j2];
                    else
                      object3.bucketCounts[j2] = options2.longs === String ? $util.Long.prototype.toString.call(message.bucketCounts[j2]) : options2.longs === Number ? new $util.LongBits(message.bucketCounts[j2].low >>> 0, message.bucketCounts[j2].high >>> 0).toNumber() : message.bucketCounts[j2];
                }
                if (message.explicitBounds && message.explicitBounds.length) {
                  object3.explicitBounds = [];
                  for (var j2 = 0; j2 < message.explicitBounds.length; ++j2)
                    object3.explicitBounds[j2] = options2.json && !isFinite(message.explicitBounds[j2]) ? String(message.explicitBounds[j2]) : message.explicitBounds[j2];
                }
                if (message.exemplars && message.exemplars.length) {
                  object3.exemplars = [];
                  for (var j2 = 0; j2 < message.exemplars.length; ++j2)
                    object3.exemplars[j2] = $root.opentelemetry.proto.metrics.v1.Exemplar.toObject(message.exemplars[j2], options2);
                }
                if (message.attributes && message.attributes.length) {
                  object3.attributes = [];
                  for (var j2 = 0; j2 < message.attributes.length; ++j2)
                    object3.attributes[j2] = $root.opentelemetry.proto.common.v1.KeyValue.toObject(message.attributes[j2], options2);
                }
                if (message.flags != null && message.hasOwnProperty("flags"))
                  object3.flags = message.flags;
                if (message.min != null && message.hasOwnProperty("min")) {
                  object3.min = options2.json && !isFinite(message.min) ? String(message.min) : message.min;
                  if (options2.oneofs)
                    object3._min = "min";
                }
                if (message.max != null && message.hasOwnProperty("max")) {
                  object3.max = options2.json && !isFinite(message.max) ? String(message.max) : message.max;
                  if (options2.oneofs)
                    object3._max = "max";
                }
                return object3;
              }, "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;
            }();
            v1.ExponentialHistogramDataPoint = function() {
              function ExponentialHistogramDataPoint(properties) {
                this.attributes = [];
                this.exemplars = [];
                if (properties) {
                  for (var keys = Object.keys(properties), i3 = 0; i3 < keys.length; ++i3)
                    if (properties[keys[i3]] != null)
                      this[keys[i3]] = properties[keys[i3]];
                }
              }
              __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 i3 = 0; i3 < message.attributes.length; ++i3)
                    $root.opentelemetry.proto.common.v1.KeyValue.encode(message.attributes[i3], 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 i3 = 0; i3 < message.exemplars.length; ++i3)
                    $root.opentelemetry.proto.metrics.v1.Exemplar.encode(message.exemplars[i3], 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, error2) {
                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 === error2)
                    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 i3 = 0; i3 < message.attributes.length; ++i3) {
                    var error2 = $root.opentelemetry.proto.common.v1.KeyValue.verify(message.attributes[i3]);
                    if (error2)
                      return "attributes." + error2;
                  }
                }
                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 error2 = $root.opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint.Buckets.verify(message.positive);
                  if (error2)
                    return "positive." + error2;
                }
                if (message.negative != null && message.hasOwnProperty("negative")) {
                  var error2 = $root.opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint.Buckets.verify(message.negative);
                  if (error2)
                    return "negative." + error2;
                }
                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 i3 = 0; i3 < message.exemplars.length; ++i3) {
                    var error2 = $root.opentelemetry.proto.metrics.v1.Exemplar.verify(message.exemplars[i3]);
                    if (error2)
                      return "exemplars." + error2;
                  }
                }
                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(object3) {
                if (object3 instanceof $root.opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint)
                  return object3;
                var message = new $root.opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint();
                if (object3.attributes) {
                  if (!Array.isArray(object3.attributes))
                    throw TypeError(".opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint.attributes: array expected");
                  message.attributes = [];
                  for (var i3 = 0; i3 < object3.attributes.length; ++i3) {
                    if (typeof object3.attributes[i3] !== "object")
                      throw TypeError(".opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint.attributes: object expected");
                    message.attributes[i3] = $root.opentelemetry.proto.common.v1.KeyValue.fromObject(object3.attributes[i3]);
                  }
                }
                if (object3.startTimeUnixNano != null) {
                  if ($util.Long)
                    (message.startTimeUnixNano = $util.Long.fromValue(object3.startTimeUnixNano)).unsigned = false;
                  else if (typeof object3.startTimeUnixNano === "string")
                    message.startTimeUnixNano = parseInt(object3.startTimeUnixNano, 10);
                  else if (typeof object3.startTimeUnixNano === "number")
                    message.startTimeUnixNano = object3.startTimeUnixNano;
                  else if (typeof object3.startTimeUnixNano === "object")
                    message.startTimeUnixNano = new $util.LongBits(object3.startTimeUnixNano.low >>> 0, object3.startTimeUnixNano.high >>> 0).toNumber();
                }
                if (object3.timeUnixNano != null) {
                  if ($util.Long)
                    (message.timeUnixNano = $util.Long.fromValue(object3.timeUnixNano)).unsigned = false;
                  else if (typeof object3.timeUnixNano === "string")
                    message.timeUnixNano = parseInt(object3.timeUnixNano, 10);
                  else if (typeof object3.timeUnixNano === "number")
                    message.timeUnixNano = object3.timeUnixNano;
                  else if (typeof object3.timeUnixNano === "object")
                    message.timeUnixNano = new $util.LongBits(object3.timeUnixNano.low >>> 0, object3.timeUnixNano.high >>> 0).toNumber();
                }
                if (object3.count != null) {
                  if ($util.Long)
                    (message.count = $util.Long.fromValue(object3.count)).unsigned = false;
                  else if (typeof object3.count === "string")
                    message.count = parseInt(object3.count, 10);
                  else if (typeof object3.count === "number")
                    message.count = object3.count;
                  else if (typeof object3.count === "object")
                    message.count = new $util.LongBits(object3.count.low >>> 0, object3.count.high >>> 0).toNumber();
                }
                if (object3.sum != null)
                  message.sum = Number(object3.sum);
                if (object3.scale != null)
                  message.scale = object3.scale | 0;
                if (object3.zeroCount != null) {
                  if ($util.Long)
                    (message.zeroCount = $util.Long.fromValue(object3.zeroCount)).unsigned = false;
                  else if (typeof object3.zeroCount === "string")
                    message.zeroCount = parseInt(object3.zeroCount, 10);
                  else if (typeof object3.zeroCount === "number")
                    message.zeroCount = object3.zeroCount;
                  else if (typeof object3.zeroCount === "object")
                    message.zeroCount = new $util.LongBits(object3.zeroCount.low >>> 0, object3.zeroCount.high >>> 0).toNumber();
                }
                if (object3.positive != null) {
                  if (typeof object3.positive !== "object")
                    throw TypeError(".opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint.positive: object expected");
                  message.positive = $root.opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint.Buckets.fromObject(object3.positive);
                }
                if (object3.negative != null) {
                  if (typeof object3.negative !== "object")
                    throw TypeError(".opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint.negative: object expected");
                  message.negative = $root.opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint.Buckets.fromObject(object3.negative);
                }
                if (object3.flags != null)
                  message.flags = object3.flags >>> 0;
                if (object3.exemplars) {
                  if (!Array.isArray(object3.exemplars))
                    throw TypeError(".opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint.exemplars: array expected");
                  message.exemplars = [];
                  for (var i3 = 0; i3 < object3.exemplars.length; ++i3) {
                    if (typeof object3.exemplars[i3] !== "object")
                      throw TypeError(".opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint.exemplars: object expected");
                    message.exemplars[i3] = $root.opentelemetry.proto.metrics.v1.Exemplar.fromObject(object3.exemplars[i3]);
                  }
                }
                if (object3.min != null)
                  message.min = Number(object3.min);
                if (object3.max != null)
                  message.max = Number(object3.max);
                if (object3.zeroThreshold != null)
                  message.zeroThreshold = Number(object3.zeroThreshold);
                return message;
              }, "fromObject");
              ExponentialHistogramDataPoint.toObject = /* @__PURE__ */ __name(function toObject(message, options2) {
                if (!options2)
                  options2 = {};
                var object3 = {};
                if (options2.arrays || options2.defaults) {
                  object3.attributes = [];
                  object3.exemplars = [];
                }
                if (options2.defaults) {
                  if ($util.Long) {
                    var long = new $util.Long(0, 0, false);
                    object3.startTimeUnixNano = options2.longs === String ? long.toString() : options2.longs === Number ? long.toNumber() : long;
                  } else
                    object3.startTimeUnixNano = options2.longs === String ? "0" : 0;
                  if ($util.Long) {
                    var long = new $util.Long(0, 0, false);
                    object3.timeUnixNano = options2.longs === String ? long.toString() : options2.longs === Number ? long.toNumber() : long;
                  } else
                    object3.timeUnixNano = options2.longs === String ? "0" : 0;
                  if ($util.Long) {
                    var long = new $util.Long(0, 0, false);
                    object3.count = options2.longs === String ? long.toString() : options2.longs === Number ? long.toNumber() : long;
                  } else
                    object3.count = options2.longs === String ? "0" : 0;
                  object3.scale = 0;
                  if ($util.Long) {
                    var long = new $util.Long(0, 0, false);
                    object3.zeroCount = options2.longs === String ? long.toString() : options2.longs === Number ? long.toNumber() : long;
                  } else
                    object3.zeroCount = options2.longs === String ? "0" : 0;
                  object3.positive = null;
                  object3.negative = null;
                  object3.flags = 0;
                  object3.zeroThreshold = 0;
                }
                if (message.attributes && message.attributes.length) {
                  object3.attributes = [];
                  for (var j2 = 0; j2 < message.attributes.length; ++j2)
                    object3.attributes[j2] = $root.opentelemetry.proto.common.v1.KeyValue.toObject(message.attributes[j2], options2);
                }
                if (message.startTimeUnixNano != null && message.hasOwnProperty("startTimeUnixNano"))
                  if (typeof message.startTimeUnixNano === "number")
                    object3.startTimeUnixNano = options2.longs === String ? String(message.startTimeUnixNano) : message.startTimeUnixNano;
                  else
                    object3.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")
                    object3.timeUnixNano = options2.longs === String ? String(message.timeUnixNano) : message.timeUnixNano;
                  else
                    object3.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")
                    object3.count = options2.longs === String ? String(message.count) : message.count;
                  else
                    object3.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")) {
                  object3.sum = options2.json && !isFinite(message.sum) ? String(message.sum) : message.sum;
                  if (options2.oneofs)
                    object3._sum = "sum";
                }
                if (message.scale != null && message.hasOwnProperty("scale"))
                  object3.scale = message.scale;
                if (message.zeroCount != null && message.hasOwnProperty("zeroCount"))
                  if (typeof message.zeroCount === "number")
                    object3.zeroCount = options2.longs === String ? String(message.zeroCount) : message.zeroCount;
                  else
                    object3.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"))
                  object3.positive = $root.opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint.Buckets.toObject(message.positive, options2);
                if (message.negative != null && message.hasOwnProperty("negative"))
                  object3.negative = $root.opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint.Buckets.toObject(message.negative, options2);
                if (message.flags != null && message.hasOwnProperty("flags"))
                  object3.flags = message.flags;
                if (message.exemplars && message.exemplars.length) {
                  object3.exemplars = [];
                  for (var j2 = 0; j2 < message.exemplars.length; ++j2)
                    object3.exemplars[j2] = $root.opentelemetry.proto.metrics.v1.Exemplar.toObject(message.exemplars[j2], options2);
                }
                if (message.min != null && message.hasOwnProperty("min")) {
                  object3.min = options2.json && !isFinite(message.min) ? String(message.min) : message.min;
                  if (options2.oneofs)
                    object3._min = "min";
                }
                if (message.max != null && message.hasOwnProperty("max")) {
                  object3.max = options2.json && !isFinite(message.max) ? String(message.max) : message.max;
                  if (options2.oneofs)
                    object3._max = "max";
                }
                if (message.zeroThreshold != null && message.hasOwnProperty("zeroThreshold"))
                  object3.zeroThreshold = options2.json && !isFinite(message.zeroThreshold) ? String(message.zeroThreshold) : message.zeroThreshold;
                return object3;
              }, "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), i3 = 0; i3 < keys.length; ++i3)
                      if (properties[keys[i3]] != null)
                        this[keys[i3]] = properties[keys[i3]];
                  }
                }
                __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 i3 = 0; i3 < message.bucketCounts.length; ++i3)
                      writer.uint64(message.bucketCounts[i3]);
                    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, error2) {
                  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 === error2)
                      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 i3 = 0; i3 < message.bucketCounts.length; ++i3)
                      if (!$util.isInteger(message.bucketCounts[i3]) && !(message.bucketCounts[i3] && $util.isInteger(message.bucketCounts[i3].low) && $util.isInteger(message.bucketCounts[i3].high)))
                        return "bucketCounts: integer|Long[] expected";
                  }
                  return null;
                }, "verify");
                Buckets.fromObject = /* @__PURE__ */ __name(function fromObject(object3) {
                  if (object3 instanceof $root.opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint.Buckets)
                    return object3;
                  var message = new $root.opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint.Buckets();
                  if (object3.offset != null)
                    message.offset = object3.offset | 0;
                  if (object3.bucketCounts) {
                    if (!Array.isArray(object3.bucketCounts))
                      throw TypeError(".opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint.Buckets.bucketCounts: array expected");
                    message.bucketCounts = [];
                    for (var i3 = 0; i3 < object3.bucketCounts.length; ++i3)
                      if ($util.Long)
                        (message.bucketCounts[i3] = $util.Long.fromValue(object3.bucketCounts[i3])).unsigned = true;
                      else if (typeof object3.bucketCounts[i3] === "string")
                        message.bucketCounts[i3] = parseInt(object3.bucketCounts[i3], 10);
                      else if (typeof object3.bucketCounts[i3] === "number")
                        message.bucketCounts[i3] = object3.bucketCounts[i3];
                      else if (typeof object3.bucketCounts[i3] === "object")
                        message.bucketCounts[i3] = new $util.LongBits(object3.bucketCounts[i3].low >>> 0, object3.bucketCounts[i3].high >>> 0).toNumber(true);
                  }
                  return message;
                }, "fromObject");
                Buckets.toObject = /* @__PURE__ */ __name(function toObject(message, options2) {
                  if (!options2)
                    options2 = {};
                  var object3 = {};
                  if (options2.arrays || options2.defaults)
                    object3.bucketCounts = [];
                  if (options2.defaults)
                    object3.offset = 0;
                  if (message.offset != null && message.hasOwnProperty("offset"))
                    object3.offset = message.offset;
                  if (message.bucketCounts && message.bucketCounts.length) {
                    object3.bucketCounts = [];
                    for (var j2 = 0; j2 < message.bucketCounts.length; ++j2)
                      if (typeof message.bucketCounts[j2] === "number")
                        object3.bucketCounts[j2] = options2.longs === String ? String(message.bucketCounts[j2]) : message.bucketCounts[j2];
                      else
                        object3.bucketCounts[j2] = options2.longs === String ? $util.Long.prototype.toString.call(message.bucketCounts[j2]) : options2.longs === Number ? new $util.LongBits(message.bucketCounts[j2].low >>> 0, message.bucketCounts[j2].high >>> 0).toNumber(true) : message.bucketCounts[j2];
                  }
                  return object3;
                }, "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;
            }();
            v1.SummaryDataPoint = function() {
              function SummaryDataPoint(properties) {
                this.attributes = [];
                this.quantileValues = [];
                if (properties) {
                  for (var keys = Object.keys(properties), i3 = 0; i3 < keys.length; ++i3)
                    if (properties[keys[i3]] != null)
                      this[keys[i3]] = properties[keys[i3]];
                }
              }
              __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 i3 = 0; i3 < message.quantileValues.length; ++i3)
                    $root.opentelemetry.proto.metrics.v1.SummaryDataPoint.ValueAtQuantile.encode(message.quantileValues[i3], writer.uint32(
                      /* id 6, wireType 2 =*/
                      50
                    ).fork()).ldelim();
                if (message.attributes != null && message.attributes.length)
                  for (var i3 = 0; i3 < message.attributes.length; ++i3)
                    $root.opentelemetry.proto.common.v1.KeyValue.encode(message.attributes[i3], 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, error2) {
                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 === error2)
                    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 i3 = 0; i3 < message.attributes.length; ++i3) {
                    var error2 = $root.opentelemetry.proto.common.v1.KeyValue.verify(message.attributes[i3]);
                    if (error2)
                      return "attributes." + error2;
                  }
                }
                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 i3 = 0; i3 < message.quantileValues.length; ++i3) {
                    var error2 = $root.opentelemetry.proto.metrics.v1.SummaryDataPoint.ValueAtQuantile.verify(message.quantileValues[i3]);
                    if (error2)
                      return "quantileValues." + error2;
                  }
                }
                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(object3) {
                if (object3 instanceof $root.opentelemetry.proto.metrics.v1.SummaryDataPoint)
                  return object3;
                var message = new $root.opentelemetry.proto.metrics.v1.SummaryDataPoint();
                if (object3.attributes) {
                  if (!Array.isArray(object3.attributes))
                    throw TypeError(".opentelemetry.proto.metrics.v1.SummaryDataPoint.attributes: array expected");
                  message.attributes = [];
                  for (var i3 = 0; i3 < object3.attributes.length; ++i3) {
                    if (typeof object3.attributes[i3] !== "object")
                      throw TypeError(".opentelemetry.proto.metrics.v1.SummaryDataPoint.attributes: object expected");
                    message.attributes[i3] = $root.opentelemetry.proto.common.v1.KeyValue.fromObject(object3.attributes[i3]);
                  }
                }
                if (object3.startTimeUnixNano != null) {
                  if ($util.Long)
                    (message.startTimeUnixNano = $util.Long.fromValue(object3.startTimeUnixNano)).unsigned = false;
                  else if (typeof object3.startTimeUnixNano === "string")
                    message.startTimeUnixNano = parseInt(object3.startTimeUnixNano, 10);
                  else if (typeof object3.startTimeUnixNano === "number")
                    message.startTimeUnixNano = object3.startTimeUnixNano;
                  else if (typeof object3.startTimeUnixNano === "object")
                    message.startTimeUnixNano = new $util.LongBits(object3.startTimeUnixNano.low >>> 0, object3.startTimeUnixNano.high >>> 0).toNumber();
                }
                if (object3.timeUnixNano != null) {
                  if ($util.Long)
                    (message.timeUnixNano = $util.Long.fromValue(object3.timeUnixNano)).unsigned = false;
                  else if (typeof object3.timeUnixNano === "string")
                    message.timeUnixNano = parseInt(object3.timeUnixNano, 10);
                  else if (typeof object3.timeUnixNano === "number")
                    message.timeUnixNano = object3.timeUnixNano;
                  else if (typeof object3.timeUnixNano === "object")
                    message.timeUnixNano = new $util.LongBits(object3.timeUnixNano.low >>> 0, object3.timeUnixNano.high >>> 0).toNumber();
                }
                if (object3.count != null) {
                  if ($util.Long)
                    (message.count = $util.Long.fromValue(object3.count)).unsigned = false;
                  else if (typeof object3.count === "string")
                    message.count = parseInt(object3.count, 10);
                  else if (typeof object3.count === "number")
                    message.count = object3.count;
                  else if (typeof object3.count === "object")
                    message.count = new $util.LongBits(object3.count.low >>> 0, object3.count.high >>> 0).toNumber();
                }
                if (object3.sum != null)
                  message.sum = Number(object3.sum);
                if (object3.quantileValues) {
                  if (!Array.isArray(object3.quantileValues))
                    throw TypeError(".opentelemetry.proto.metrics.v1.SummaryDataPoint.quantileValues: array expected");
                  message.quantileValues = [];
                  for (var i3 = 0; i3 < object3.quantileValues.length; ++i3) {
                    if (typeof object3.quantileValues[i3] !== "object")
                      throw TypeError(".opentelemetry.proto.metrics.v1.SummaryDataPoint.quantileValues: object expected");
                    message.quantileValues[i3] = $root.opentelemetry.proto.metrics.v1.SummaryDataPoint.ValueAtQuantile.fromObject(object3.quantileValues[i3]);
                  }
                }
                if (object3.flags != null)
                  message.flags = object3.flags >>> 0;
                return message;
              }, "fromObject");
              SummaryDataPoint.toObject = /* @__PURE__ */ __name(function toObject(message, options2) {
                if (!options2)
                  options2 = {};
                var object3 = {};
                if (options2.arrays || options2.defaults) {
                  object3.quantileValues = [];
                  object3.attributes = [];
                }
                if (options2.defaults) {
                  if ($util.Long) {
                    var long = new $util.Long(0, 0, false);
                    object3.startTimeUnixNano = options2.longs === String ? long.toString() : options2.longs === Number ? long.toNumber() : long;
                  } else
                    object3.startTimeUnixNano = options2.longs === String ? "0" : 0;
                  if ($util.Long) {
                    var long = new $util.Long(0, 0, false);
                    object3.timeUnixNano = options2.longs === String ? long.toString() : options2.longs === Number ? long.toNumber() : long;
                  } else
                    object3.timeUnixNano = options2.longs === String ? "0" : 0;
                  if ($util.Long) {
                    var long = new $util.Long(0, 0, false);
                    object3.count = options2.longs === String ? long.toString() : options2.longs === Number ? long.toNumber() : long;
                  } else
                    object3.count = options2.longs === String ? "0" : 0;
                  object3.sum = 0;
                  object3.flags = 0;
                }
                if (message.startTimeUnixNano != null && message.hasOwnProperty("startTimeUnixNano"))
                  if (typeof message.startTimeUnixNano === "number")
                    object3.startTimeUnixNano = options2.longs === String ? String(message.startTimeUnixNano) : message.startTimeUnixNano;
                  else
                    object3.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")
                    object3.timeUnixNano = options2.longs === String ? String(message.timeUnixNano) : message.timeUnixNano;
                  else
                    object3.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")
                    object3.count = options2.longs === String ? String(message.count) : message.count;
                  else
                    object3.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"))
                  object3.sum = options2.json && !isFinite(message.sum) ? String(message.sum) : message.sum;
                if (message.quantileValues && message.quantileValues.length) {
                  object3.quantileValues = [];
                  for (var j2 = 0; j2 < message.quantileValues.length; ++j2)
                    object3.quantileValues[j2] = $root.opentelemetry.proto.metrics.v1.SummaryDataPoint.ValueAtQuantile.toObject(message.quantileValues[j2], options2);
                }
                if (message.attributes && message.attributes.length) {
                  object3.attributes = [];
                  for (var j2 = 0; j2 < message.attributes.length; ++j2)
                    object3.attributes[j2] = $root.opentelemetry.proto.common.v1.KeyValue.toObject(message.attributes[j2], options2);
                }
                if (message.flags != null && message.hasOwnProperty("flags"))
                  object3.flags = message.flags;
                return object3;
              }, "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), i3 = 0; i3 < keys.length; ++i3)
                      if (properties[keys[i3]] != null)
                        this[keys[i3]] = properties[keys[i3]];
                  }
                }
                __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, error2) {
                  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 === error2)
                      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(object3) {
                  if (object3 instanceof $root.opentelemetry.proto.metrics.v1.SummaryDataPoint.ValueAtQuantile)
                    return object3;
                  var message = new $root.opentelemetry.proto.metrics.v1.SummaryDataPoint.ValueAtQuantile();
                  if (object3.quantile != null)
                    message.quantile = Number(object3.quantile);
                  if (object3.value != null)
                    message.value = Number(object3.value);
                  return message;
                }, "fromObject");
                ValueAtQuantile.toObject = /* @__PURE__ */ __name(function toObject(message, options2) {
                  if (!options2)
                    options2 = {};
                  var object3 = {};
                  if (options2.defaults) {
                    object3.quantile = 0;
                    object3.value = 0;
                  }
                  if (message.quantile != null && message.hasOwnProperty("quantile"))
                    object3.quantile = options2.json && !isFinite(message.quantile) ? String(message.quantile) : message.quantile;
                  if (message.value != null && message.hasOwnProperty("value"))
                    object3.value = options2.json && !isFinite(message.value) ? String(message.value) : message.value;
                  return object3;
                }, "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;
            }();
            v1.Exemplar = function() {
              function Exemplar(properties) {
                this.filteredAttributes = [];
                if (properties) {
                  for (var keys = Object.keys(properties), i3 = 0; i3 < keys.length; ++i3)
                    if (properties[keys[i3]] != null)
                      this[keys[i3]] = properties[keys[i3]];
                }
              }
              __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 i3 = 0; i3 < message.filteredAttributes.length; ++i3)
                    $root.opentelemetry.proto.common.v1.KeyValue.encode(message.filteredAttributes[i3], 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, error2) {
                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 === error2)
                    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 i3 = 0; i3 < message.filteredAttributes.length; ++i3) {
                    var error2 = $root.opentelemetry.proto.common.v1.KeyValue.verify(message.filteredAttributes[i3]);
                    if (error2)
                      return "filteredAttributes." + error2;
                  }
                }
                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(object3) {
                if (object3 instanceof $root.opentelemetry.proto.metrics.v1.Exemplar)
                  return object3;
                var message = new $root.opentelemetry.proto.metrics.v1.Exemplar();
                if (object3.filteredAttributes) {
                  if (!Array.isArray(object3.filteredAttributes))
                    throw TypeError(".opentelemetry.proto.metrics.v1.Exemplar.filteredAttributes: array expected");
                  message.filteredAttributes = [];
                  for (var i3 = 0; i3 < object3.filteredAttributes.length; ++i3) {
                    if (typeof object3.filteredAttributes[i3] !== "object")
                      throw TypeError(".opentelemetry.proto.metrics.v1.Exemplar.filteredAttributes: object expected");
                    message.filteredAttributes[i3] = $root.opentelemetry.proto.common.v1.KeyValue.fromObject(object3.filteredAttributes[i3]);
                  }
                }
                if (object3.timeUnixNano != null) {
                  if ($util.Long)
                    (message.timeUnixNano = $util.Long.fromValue(object3.timeUnixNano)).unsigned = false;
                  else if (typeof object3.timeUnixNano === "string")
                    message.timeUnixNano = parseInt(object3.timeUnixNano, 10);
                  else if (typeof object3.timeUnixNano === "number")
                    message.timeUnixNano = object3.timeUnixNano;
                  else if (typeof object3.timeUnixNano === "object")
                    message.timeUnixNano = new $util.LongBits(object3.timeUnixNano.low >>> 0, object3.timeUnixNano.high >>> 0).toNumber();
                }
                if (object3.asDouble != null)
                  message.asDouble = Number(object3.asDouble);
                if (object3.asInt != null) {
                  if ($util.Long)
                    (message.asInt = $util.Long.fromValue(object3.asInt)).unsigned = false;
                  else if (typeof object3.asInt === "string")
                    message.asInt = parseInt(object3.asInt, 10);
                  else if (typeof object3.asInt === "number")
                    message.asInt = object3.asInt;
                  else if (typeof object3.asInt === "object")
                    message.asInt = new $util.LongBits(object3.asInt.low >>> 0, object3.asInt.high >>> 0).toNumber();
                }
                if (object3.spanId != null) {
                  if (typeof object3.spanId === "string")
                    $util.base64.decode(object3.spanId, message.spanId = $util.newBuffer($util.base64.length(object3.spanId)), 0);
                  else if (object3.spanId.length >= 0)
                    message.spanId = object3.spanId;
                }
                if (object3.traceId != null) {
                  if (typeof object3.traceId === "string")
                    $util.base64.decode(object3.traceId, message.traceId = $util.newBuffer($util.base64.length(object3.traceId)), 0);
                  else if (object3.traceId.length >= 0)
                    message.traceId = object3.traceId;
                }
                return message;
              }, "fromObject");
              Exemplar.toObject = /* @__PURE__ */ __name(function toObject(message, options2) {
                if (!options2)
                  options2 = {};
                var object3 = {};
                if (options2.arrays || options2.defaults)
                  object3.filteredAttributes = [];
                if (options2.defaults) {
                  if ($util.Long) {
                    var long = new $util.Long(0, 0, false);
                    object3.timeUnixNano = options2.longs === String ? long.toString() : options2.longs === Number ? long.toNumber() : long;
                  } else
                    object3.timeUnixNano = options2.longs === String ? "0" : 0;
                  if (options2.bytes === String)
                    object3.spanId = "";
                  else {
                    object3.spanId = [];
                    if (options2.bytes !== Array)
                      object3.spanId = $util.newBuffer(object3.spanId);
                  }
                  if (options2.bytes === String)
                    object3.traceId = "";
                  else {
                    object3.traceId = [];
                    if (options2.bytes !== Array)
                      object3.traceId = $util.newBuffer(object3.traceId);
                  }
                }
                if (message.timeUnixNano != null && message.hasOwnProperty("timeUnixNano"))
                  if (typeof message.timeUnixNano === "number")
                    object3.timeUnixNano = options2.longs === String ? String(message.timeUnixNano) : message.timeUnixNano;
                  else
                    object3.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")) {
                  object3.asDouble = options2.json && !isFinite(message.asDouble) ? String(message.asDouble) : message.asDouble;
                  if (options2.oneofs)
                    object3.value = "asDouble";
                }
                if (message.spanId != null && message.hasOwnProperty("spanId"))
                  object3.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"))
                  object3.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")
                    object3.asInt = options2.longs === String ? String(message.asInt) : message.asInt;
                  else
                    object3.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)
                    object3.value = "asInt";
                }
                if (message.filteredAttributes && message.filteredAttributes.length) {
                  object3.filteredAttributes = [];
                  for (var j2 = 0; j2 < message.filteredAttributes.length; ++j2)
                    object3.filteredAttributes[j2] = $root.opentelemetry.proto.common.v1.KeyValue.toObject(message.filteredAttributes[j2], options2);
                }
                return object3;
              }, "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 v1;
          }();
          return metrics2;
        }();
        proto3.logs = function() {
          var logs2 = {};
          logs2.v1 = function() {
            var v1 = {};
            v1.LogsData = function() {
              function LogsData(properties) {
                this.resourceLogs = [];
                if (properties) {
                  for (var keys = Object.keys(properties), i3 = 0; i3 < keys.length; ++i3)
                    if (properties[keys[i3]] != null)
                      this[keys[i3]] = properties[keys[i3]];
                }
              }
              __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 i3 = 0; i3 < message.resourceLogs.length; ++i3)
                    $root.opentelemetry.proto.logs.v1.ResourceLogs.encode(message.resourceLogs[i3], 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, error2) {
                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 === error2)
                    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 i3 = 0; i3 < message.resourceLogs.length; ++i3) {
                    var error2 = $root.opentelemetry.proto.logs.v1.ResourceLogs.verify(message.resourceLogs[i3]);
                    if (error2)
                      return "resourceLogs." + error2;
                  }
                }
                return null;
              }, "verify");
              LogsData.fromObject = /* @__PURE__ */ __name(function fromObject(object3) {
                if (object3 instanceof $root.opentelemetry.proto.logs.v1.LogsData)
                  return object3;
                var message = new $root.opentelemetry.proto.logs.v1.LogsData();
                if (object3.resourceLogs) {
                  if (!Array.isArray(object3.resourceLogs))
                    throw TypeError(".opentelemetry.proto.logs.v1.LogsData.resourceLogs: array expected");
                  message.resourceLogs = [];
                  for (var i3 = 0; i3 < object3.resourceLogs.length; ++i3) {
                    if (typeof object3.resourceLogs[i3] !== "object")
                      throw TypeError(".opentelemetry.proto.logs.v1.LogsData.resourceLogs: object expected");
                    message.resourceLogs[i3] = $root.opentelemetry.proto.logs.v1.ResourceLogs.fromObject(object3.resourceLogs[i3]);
                  }
                }
                return message;
              }, "fromObject");
              LogsData.toObject = /* @__PURE__ */ __name(function toObject(message, options2) {
                if (!options2)
                  options2 = {};
                var object3 = {};
                if (options2.arrays || options2.defaults)
                  object3.resourceLogs = [];
                if (message.resourceLogs && message.resourceLogs.length) {
                  object3.resourceLogs = [];
                  for (var j2 = 0; j2 < message.resourceLogs.length; ++j2)
                    object3.resourceLogs[j2] = $root.opentelemetry.proto.logs.v1.ResourceLogs.toObject(message.resourceLogs[j2], options2);
                }
                return object3;
              }, "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;
            }();
            v1.ResourceLogs = function() {
              function ResourceLogs(properties) {
                this.scopeLogs = [];
                if (properties) {
                  for (var keys = Object.keys(properties), i3 = 0; i3 < keys.length; ++i3)
                    if (properties[keys[i3]] != null)
                      this[keys[i3]] = properties[keys[i3]];
                }
              }
              __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 i3 = 0; i3 < message.scopeLogs.length; ++i3)
                    $root.opentelemetry.proto.logs.v1.ScopeLogs.encode(message.scopeLogs[i3], 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, error2) {
                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 === error2)
                    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 error2 = $root.opentelemetry.proto.resource.v1.Resource.verify(message.resource);
                  if (error2)
                    return "resource." + error2;
                }
                if (message.scopeLogs != null && message.hasOwnProperty("scopeLogs")) {
                  if (!Array.isArray(message.scopeLogs))
                    return "scopeLogs: array expected";
                  for (var i3 = 0; i3 < message.scopeLogs.length; ++i3) {
                    var error2 = $root.opentelemetry.proto.logs.v1.ScopeLogs.verify(message.scopeLogs[i3]);
                    if (error2)
                      return "scopeLogs." + error2;
                  }
                }
                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(object3) {
                if (object3 instanceof $root.opentelemetry.proto.logs.v1.ResourceLogs)
                  return object3;
                var message = new $root.opentelemetry.proto.logs.v1.ResourceLogs();
                if (object3.resource != null) {
                  if (typeof object3.resource !== "object")
                    throw TypeError(".opentelemetry.proto.logs.v1.ResourceLogs.resource: object expected");
                  message.resource = $root.opentelemetry.proto.resource.v1.Resource.fromObject(object3.resource);
                }
                if (object3.scopeLogs) {
                  if (!Array.isArray(object3.scopeLogs))
                    throw TypeError(".opentelemetry.proto.logs.v1.ResourceLogs.scopeLogs: array expected");
                  message.scopeLogs = [];
                  for (var i3 = 0; i3 < object3.scopeLogs.length; ++i3) {
                    if (typeof object3.scopeLogs[i3] !== "object")
                      throw TypeError(".opentelemetry.proto.logs.v1.ResourceLogs.scopeLogs: object expected");
                    message.scopeLogs[i3] = $root.opentelemetry.proto.logs.v1.ScopeLogs.fromObject(object3.scopeLogs[i3]);
                  }
                }
                if (object3.schemaUrl != null)
                  message.schemaUrl = String(object3.schemaUrl);
                return message;
              }, "fromObject");
              ResourceLogs.toObject = /* @__PURE__ */ __name(function toObject(message, options2) {
                if (!options2)
                  options2 = {};
                var object3 = {};
                if (options2.arrays || options2.defaults)
                  object3.scopeLogs = [];
                if (options2.defaults) {
                  object3.resource = null;
                  object3.schemaUrl = "";
                }
                if (message.resource != null && message.hasOwnProperty("resource"))
                  object3.resource = $root.opentelemetry.proto.resource.v1.Resource.toObject(message.resource, options2);
                if (message.scopeLogs && message.scopeLogs.length) {
                  object3.scopeLogs = [];
                  for (var j2 = 0; j2 < message.scopeLogs.length; ++j2)
                    object3.scopeLogs[j2] = $root.opentelemetry.proto.logs.v1.ScopeLogs.toObject(message.scopeLogs[j2], options2);
                }
                if (message.schemaUrl != null && message.hasOwnProperty("schemaUrl"))
                  object3.schemaUrl = message.schemaUrl;
                return object3;
              }, "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;
            }();
            v1.ScopeLogs = function() {
              function ScopeLogs(properties) {
                this.logRecords = [];
                if (properties) {
                  for (var keys = Object.keys(properties), i3 = 0; i3 < keys.length; ++i3)
                    if (properties[keys[i3]] != null)
                      this[keys[i3]] = properties[keys[i3]];
                }
              }
              __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 i3 = 0; i3 < message.logRecords.length; ++i3)
                    $root.opentelemetry.proto.logs.v1.LogRecord.encode(message.logRecords[i3], 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, error2) {
                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 === error2)
                    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 error2 = $root.opentelemetry.proto.common.v1.InstrumentationScope.verify(message.scope);
                  if (error2)
                    return "scope." + error2;
                }
                if (message.logRecords != null && message.hasOwnProperty("logRecords")) {
                  if (!Array.isArray(message.logRecords))
                    return "logRecords: array expected";
                  for (var i3 = 0; i3 < message.logRecords.length; ++i3) {
                    var error2 = $root.opentelemetry.proto.logs.v1.LogRecord.verify(message.logRecords[i3]);
                    if (error2)
                      return "logRecords." + error2;
                  }
                }
                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(object3) {
                if (object3 instanceof $root.opentelemetry.proto.logs.v1.ScopeLogs)
                  return object3;
                var message = new $root.opentelemetry.proto.logs.v1.ScopeLogs();
                if (object3.scope != null) {
                  if (typeof object3.scope !== "object")
                    throw TypeError(".opentelemetry.proto.logs.v1.ScopeLogs.scope: object expected");
                  message.scope = $root.opentelemetry.proto.common.v1.InstrumentationScope.fromObject(object3.scope);
                }
                if (object3.logRecords) {
                  if (!Array.isArray(object3.logRecords))
                    throw TypeError(".opentelemetry.proto.logs.v1.ScopeLogs.logRecords: array expected");
                  message.logRecords = [];
                  for (var i3 = 0; i3 < object3.logRecords.length; ++i3) {
                    if (typeof object3.logRecords[i3] !== "object")
                      throw TypeError(".opentelemetry.proto.logs.v1.ScopeLogs.logRecords: object expected");
                    message.logRecords[i3] = $root.opentelemetry.proto.logs.v1.LogRecord.fromObject(object3.logRecords[i3]);
                  }
                }
                if (object3.schemaUrl != null)
                  message.schemaUrl = String(object3.schemaUrl);
                return message;
              }, "fromObject");
              ScopeLogs.toObject = /* @__PURE__ */ __name(function toObject(message, options2) {
                if (!options2)
                  options2 = {};
                var object3 = {};
                if (options2.arrays || options2.defaults)
                  object3.logRecords = [];
                if (options2.defaults) {
                  object3.scope = null;
                  object3.schemaUrl = "";
                }
                if (message.scope != null && message.hasOwnProperty("scope"))
                  object3.scope = $root.opentelemetry.proto.common.v1.InstrumentationScope.toObject(message.scope, options2);
                if (message.logRecords && message.logRecords.length) {
                  object3.logRecords = [];
                  for (var j2 = 0; j2 < message.logRecords.length; ++j2)
                    object3.logRecords[j2] = $root.opentelemetry.proto.logs.v1.LogRecord.toObject(message.logRecords[j2], options2);
                }
                if (message.schemaUrl != null && message.hasOwnProperty("schemaUrl"))
                  object3.schemaUrl = message.schemaUrl;
                return object3;
              }, "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;
            }();
            v1.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;
            }();
            v1.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;
            }();
            v1.LogRecord = function() {
              function LogRecord(properties) {
                this.attributes = [];
                if (properties) {
                  for (var keys = Object.keys(properties), i3 = 0; i3 < keys.length; ++i3)
                    if (properties[keys[i3]] != null)
                      this[keys[i3]] = properties[keys[i3]];
                }
              }
              __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 i3 = 0; i3 < message.attributes.length; ++i3)
                    $root.opentelemetry.proto.common.v1.KeyValue.encode(message.attributes[i3], 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, error2) {
                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 === error2)
                    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 error2 = $root.opentelemetry.proto.common.v1.AnyValue.verify(message.body);
                  if (error2)
                    return "body." + error2;
                }
                if (message.attributes != null && message.hasOwnProperty("attributes")) {
                  if (!Array.isArray(message.attributes))
                    return "attributes: array expected";
                  for (var i3 = 0; i3 < message.attributes.length; ++i3) {
                    var error2 = $root.opentelemetry.proto.common.v1.KeyValue.verify(message.attributes[i3]);
                    if (error2)
                      return "attributes." + error2;
                  }
                }
                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(object3) {
                if (object3 instanceof $root.opentelemetry.proto.logs.v1.LogRecord)
                  return object3;
                var message = new $root.opentelemetry.proto.logs.v1.LogRecord();
                if (object3.timeUnixNano != null) {
                  if ($util.Long)
                    (message.timeUnixNano = $util.Long.fromValue(object3.timeUnixNano)).unsigned = false;
                  else if (typeof object3.timeUnixNano === "string")
                    message.timeUnixNano = parseInt(object3.timeUnixNano, 10);
                  else if (typeof object3.timeUnixNano === "number")
                    message.timeUnixNano = object3.timeUnixNano;
                  else if (typeof object3.timeUnixNano === "object")
                    message.timeUnixNano = new $util.LongBits(object3.timeUnixNano.low >>> 0, object3.timeUnixNano.high >>> 0).toNumber();
                }
                if (object3.observedTimeUnixNano != null) {
                  if ($util.Long)
                    (message.observedTimeUnixNano = $util.Long.fromValue(object3.observedTimeUnixNano)).unsigned = false;
                  else if (typeof object3.observedTimeUnixNano === "string")
                    message.observedTimeUnixNano = parseInt(object3.observedTimeUnixNano, 10);
                  else if (typeof object3.observedTimeUnixNano === "number")
                    message.observedTimeUnixNano = object3.observedTimeUnixNano;
                  else if (typeof object3.observedTimeUnixNano === "object")
                    message.observedTimeUnixNano = new $util.LongBits(object3.observedTimeUnixNano.low >>> 0, object3.observedTimeUnixNano.high >>> 0).toNumber();
                }
                switch (object3.severityNumber) {
                  default:
                    if (typeof object3.severityNumber === "number") {
                      message.severityNumber = object3.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 (object3.severityText != null)
                  message.severityText = String(object3.severityText);
                if (object3.body != null) {
                  if (typeof object3.body !== "object")
                    throw TypeError(".opentelemetry.proto.logs.v1.LogRecord.body: object expected");
                  message.body = $root.opentelemetry.proto.common.v1.AnyValue.fromObject(object3.body);
                }
                if (object3.attributes) {
                  if (!Array.isArray(object3.attributes))
                    throw TypeError(".opentelemetry.proto.logs.v1.LogRecord.attributes: array expected");
                  message.attributes = [];
                  for (var i3 = 0; i3 < object3.attributes.length; ++i3) {
                    if (typeof object3.attributes[i3] !== "object")
                      throw TypeError(".opentelemetry.proto.logs.v1.LogRecord.attributes: object expected");
                    message.attributes[i3] = $root.opentelemetry.proto.common.v1.KeyValue.fromObject(object3.attributes[i3]);
                  }
                }
                if (object3.droppedAttributesCount != null)
                  message.droppedAttributesCount = object3.droppedAttributesCount >>> 0;
                if (object3.flags != null)
                  message.flags = object3.flags >>> 0;
                if (object3.traceId != null) {
                  if (typeof object3.traceId === "string")
                    $util.base64.decode(object3.traceId, message.traceId = $util.newBuffer($util.base64.length(object3.traceId)), 0);
                  else if (object3.traceId.length >= 0)
                    message.traceId = object3.traceId;
                }
                if (object3.spanId != null) {
                  if (typeof object3.spanId === "string")
                    $util.base64.decode(object3.spanId, message.spanId = $util.newBuffer($util.base64.length(object3.spanId)), 0);
                  else if (object3.spanId.length >= 0)
                    message.spanId = object3.spanId;
                }
                if (object3.eventName != null)
                  message.eventName = String(object3.eventName);
                return message;
              }, "fromObject");
              LogRecord.toObject = /* @__PURE__ */ __name(function toObject(message, options2) {
                if (!options2)
                  options2 = {};
                var object3 = {};
                if (options2.arrays || options2.defaults)
                  object3.attributes = [];
                if (options2.defaults) {
                  if ($util.Long) {
                    var long = new $util.Long(0, 0, false);
                    object3.timeUnixNano = options2.longs === String ? long.toString() : options2.longs === Number ? long.toNumber() : long;
                  } else
                    object3.timeUnixNano = options2.longs === String ? "0" : 0;
                  object3.severityNumber = options2.enums === String ? "SEVERITY_NUMBER_UNSPECIFIED" : 0;
                  object3.severityText = "";
                  object3.body = null;
                  object3.droppedAttributesCount = 0;
                  object3.flags = 0;
                  if (options2.bytes === String)
                    object3.traceId = "";
                  else {
                    object3.traceId = [];
                    if (options2.bytes !== Array)
                      object3.traceId = $util.newBuffer(object3.traceId);
                  }
                  if (options2.bytes === String)
                    object3.spanId = "";
                  else {
                    object3.spanId = [];
                    if (options2.bytes !== Array)
                      object3.spanId = $util.newBuffer(object3.spanId);
                  }
                  if ($util.Long) {
                    var long = new $util.Long(0, 0, false);
                    object3.observedTimeUnixNano = options2.longs === String ? long.toString() : options2.longs === Number ? long.toNumber() : long;
                  } else
                    object3.observedTimeUnixNano = options2.longs === String ? "0" : 0;
                  object3.eventName = "";
                }
                if (message.timeUnixNano != null && message.hasOwnProperty("timeUnixNano"))
                  if (typeof message.timeUnixNano === "number")
                    object3.timeUnixNano = options2.longs === String ? String(message.timeUnixNano) : message.timeUnixNano;
                  else
                    object3.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"))
                  object3.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"))
                  object3.severityText = message.severityText;
                if (message.body != null && message.hasOwnProperty("body"))
                  object3.body = $root.opentelemetry.proto.common.v1.AnyValue.toObject(message.body, options2);
                if (message.attributes && message.attributes.length) {
                  object3.attributes = [];
                  for (var j2 = 0; j2 < message.attributes.length; ++j2)
                    object3.attributes[j2] = $root.opentelemetry.proto.common.v1.KeyValue.toObject(message.attributes[j2], options2);
                }
                if (message.droppedAttributesCount != null && message.hasOwnProperty("droppedAttributesCount"))
                  object3.droppedAttributesCount = message.droppedAttributesCount;
                if (message.flags != null && message.hasOwnProperty("flags"))
                  object3.flags = message.flags;
                if (message.traceId != null && message.hasOwnProperty("traceId"))
                  object3.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"))
                  object3.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")
                    object3.observedTimeUnixNano = options2.longs === String ? String(message.observedTimeUnixNano) : message.observedTimeUnixNano;
                  else
                    object3.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"))
                  object3.eventName = message.eventName;
                return object3;
              }, "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 v1;
          }();
          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 i3 = 0; i3 < hexStr.length; i3 += 2) {
        const hi = intValue(hexStr.charCodeAt(i3));
        const lo = intValue(hexStr.charCodeAt(i3 + 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_utils4 = __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 t5 = typeof value;
      if (t5 === "string")
        return { stringValue: value };
      if (t5 === "number") {
        if (!Number.isInteger(value))
          return { doubleValue: value };
        return { intValue: value };
      }
      if (t5 === "boolean")
        return { boolValue: value };
      if (value instanceof Uint8Array)
        return { bytesValue: value };
      if (Array.isArray(value))
        return { arrayValue: { values: value.map(toAnyValue) } };
      if (t5 === "object" && value != null)
        return {
          kvlistValue: {
            values: Object.entries(value).map(([k2, v2]) => toKeyValue(k2, v2))
          }
        };
      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_utils4();
    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 record2 of logRecords) {
        const { resource, instrumentationScope: { name: name3, version: version2 = "", schemaUrl = "" } } = record2;
        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(record2);
      }
      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_utils5 = __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(promises8) {
      return Promise.all(promises8.map(async (p2) => {
        try {
          const ret = await p2;
          return {
            status: "fulfilled",
            value: ret
          };
        } catch (e4) {
          return {
            status: "rejected",
            reason: e4
          };
        }
      }));
    }
    __name(PromiseAllSettled, "PromiseAllSettled");
    exports2.PromiseAllSettled = PromiseAllSettled;
    function isPromiseAllSettledRejectionResult(it2) {
      return it2.status === "rejected";
    }
    __name(isPromiseAllSettledRejectionResult, "isPromiseAllSettledRejectionResult");
    exports2.isPromiseAllSettledRejectionResult = isPromiseAllSettledRejectionResult;
    function FlatMap(arr, fn) {
      const result = [];
      arr.forEach((it2) => {
        result.push(...fn(it2));
      });
      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_utils5();
    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 }, (_2, i3) => this.at(i3));
      }
      /**
       * 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 i3 = 0; i3 < this.length; i3++) {
          if (this.at(i3) !== 0) {
            this.indexStart += i3;
            break;
          } else if (i3 === this.length - 1) {
            this.indexStart = this.indexEnd = this.indexBase = 0;
            return;
          }
        }
        for (let i3 = this.length - 1; i3 >= 0; i3--) {
          if (this.at(i3) !== 0) {
            this.indexEnd -= this.length - i3 - 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 i3 = mod2; i3 < each && inpos < size; i3++) {
            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 i3 = 0; i3 < num; i3++) {
          const tmp = this._counts[from + i3];
          this._counts[from + i3] = this._counts[limit2 - i3 - 1];
          this._counts[limit2 - i3 - 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_util15 = __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(v2) {
      v2--;
      v2 |= v2 >> 1;
      v2 |= v2 >> 2;
      v2 |= v2 >> 4;
      v2 |= v2 >> 8;
      v2 |= v2 >> 16;
      v2++;
      return v2;
    }
    __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 util3 = require_util15();
    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 util3.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 util3 = require_util15();
    var types_1 = require_types5();
    var LogarithmMapping = class {
      static {
        __name(this, "LogarithmMapping");
      }
      _scale;
      _scaleFactor;
      _inverseFactor;
      constructor(scale) {
        this._scale = scale;
        this._scaleFactor = util3.ldexp(Math.LOG2E, scale);
        this._inverseFactor = util3.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 }, (_2, i3) => {
      if (i3 > 10) {
        return new LogarithmMapping_1.LogarithmMapping(i3 - 10);
      }
      return new ExponentMapping_1.ExponentMapping(i3 - 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_util15();
    var HighLow = class _HighLow {
      static {
        __name(this, "HighLow");
      }
      low;
      high;
      static combine(h1, h22) {
        return new _HighLow(Math.min(h1.low, h22.low), Math.max(h1.high, h22.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, _maxSize2 = DEFAULT_MAX_SIZE, _recordMinMax = true, _sum = 0, _count = 0, _zeroCount = 0, _min = Number.POSITIVE_INFINITY, _max = Number.NEGATIVE_INFINITY, _positive2 = new Buckets_1.Buckets(), _negative2 = new Buckets_1.Buckets(), _mapping = (0, getMapping_1.getMapping)(MAX_SCALE)) {
        this.startTime = startTime;
        this._maxSize = _maxSize2;
        this._recordMinMax = _recordMinMax;
        this._sum = _sum;
        this._count = _count;
        this._zeroCount = _zeroCount;
        this._min = _min;
        this._max = _max;
        this._positive = _positive2;
        this._negative = _negative2;
        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 i3 = 0; i3 < theirs.length; i3++) {
          this._incrementIndexBy(ours, theirOffset + i3 >> theirChange, theirs.at(i3));
        }
      }
      /**
       * _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 i3 = 0; i3 < theirs.length; i3++) {
          const ourIndex = theirOffset + i3 >> theirChange;
          let bucketIndex = ourIndex - ours.indexBase;
          if (bucketIndex < 0) {
            bucketIndex += ours.backing.length;
          }
          ours.decrementBucket(bucketIndex, theirs.at(i3));
        }
        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(_maxSize2, _recordMinMax) {
        this._maxSize = _maxSize2;
        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((a2, b2) => a2 - b2);
        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(_maxSize2 = 160, _recordMinMax = true) {
        this._maxSize = _maxSize2;
        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_utils5();
    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_utils5();
    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 (e4) {
            api.diag.debug("Error while resolving async portion of resource: ", e4);
            (0, core_1.globalErrorHandler)(e4);
          }
        }
        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_utils6 = __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(_2) {
      return _2;
    }
    __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_utils6();
    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(([_2, val]) => (0, utils_1.isPromiseLike)(val)).length > 0;
        return res;
      }
      constructor(resource) {
        const attributes = resource.attributes ?? {};
        this._rawAttributes = Object.entries(attributes).map(([k2, v2]) => {
          if ((0, utils_1.isPromiseLike)(v2)) {
            this._asyncAttributesPending = true;
          }
          return [k2, v2];
        });
        this._rawAttributes = guardedRawAttributes(this._rawAttributes);
      }
      get asyncAttributesPending() {
        return this._asyncAttributesPending;
      }
      async waitForAsyncAttributes() {
        if (!this.asyncAttributesPending) {
          return;
        }
        for (let i3 = 0; i3 < this._rawAttributes.length; i3++) {
          const [k2, v2] = this._rawAttributes[i3];
          this._rawAttributes[i3] = [k2, (0, utils_1.isPromiseLike)(v2) ? await v2 : v2];
        }
        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 [k2, v2] of this._rawAttributes) {
          if ((0, utils_1.isPromiseLike)(v2)) {
            api_1.diag.debug(`Unsettled resource attribute ${k2} skipped`);
            continue;
          }
          if (v2 != null) {
            attrs[k2] ??= v2;
          }
        }
        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(([k2, v2]) => {
        if ((0, utils_1.isPromiseLike)(v2)) {
          return [
            k2,
            v2.catch((err) => {
              api_1.diag.debug("promise rejection for resource attribute: %s - %s", k2, err);
              return void 0;
            })
          ];
        }
        return [k2, v2];
      });
    }
    __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((config2 = {}) => {
      const resources = (config2.detectors || []).map((d2) => {
        try {
          const resource = (0, ResourceImpl_1.resourceFromDetectedResource)(d2.detect(config2));
          api_1.diag.debug(`${d2.constructor.name} found resource.`, resource);
          return resource;
        } catch (e4) {
          api_1.diag.debug(`${d2.constructor.name} failed: ${e4.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 (e4) {
            api_1.diag.debug(`EnvDetector failed: ${e4.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 i3 = 0; i3 < str2.length; i3++) {
          const ch = str2.charCodeAt(i3);
          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 util3 = __require("util");
    exports2.execAsync = util3.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 (e4) {
        api_1.diag.debug(`error reading machine id: ${e4}`);
      }
      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 path125 of paths) {
        try {
          const result = await fs_1.promises.readFile(path125, { encoding: "utf8" });
          return result.trim();
        } catch (e4) {
          api_1.diag.debug(`error reading machine id: ${e4}`);
        }
      }
      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 (e4) {
        api_1.diag.debug(`error reading machine id: ${e4}`);
      }
      try {
        const result = await (0, execAsync_1.execAsync)("kenv -q smbios.system.uuid");
        return result.stdout.trim();
      } catch (e4) {
        api_1.diag.debug(`error reading machine id: ${e4}`);
      }
      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 process50 = __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 (process50.arch === "ia32" && "PROCESSOR_ARCHITEW6432" in process50.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 (e4) {
        api_1.diag.debug(`error reading machine id: ${e4}`);
      }
      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 process50 = __require("process");
    var getMachineIdImpl;
    async function getMachineId() {
      if (!getMachineIdImpl) {
        switch (process50.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_utils7 = __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 normalizeArch3 = /* @__PURE__ */ __name((nodeArchString) => {
      switch (nodeArchString) {
        case "arm":
          return "arm32";
        case "ppc":
          return "ppc32";
        case "x64":
          return "amd64";
        default:
          return nodeArchString;
      }
    }, "normalizeArch");
    exports2.normalizeArch = normalizeArch3;
    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_utils7();
    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_utils7();
    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 os47 = __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 = os47.userInfo();
          attributes[semconv_1.ATTR_PROCESS_OWNER] = userInfo2.username;
        } catch (e4) {
          api_1.diag.debug(`error obtaining process owner: ${e4}`);
        }
        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_utils5();
    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(it2) {
      return it2 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_utils5();
    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_utils5();
    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 it2 of unreportedList) {
          result = _TemporalMetricProcessor.merge(result, it2, 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, record2, hash] = next.value;
          if (last2.has(key, hash)) {
            const lastAccumulation = last2.get(key, hash);
            const accumulation = aggregator.merge(lastAccumulation, record2);
            result.set(key, accumulation, hash);
          } else {
            result.set(key, record2, 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((it2) => {
          it2.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_utils5();
    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((it2) => it2.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((record2) => {
          return record2.callback === callback && record2.instrument === instrument;
        });
      }
      _findBatchCallback(callback, instruments) {
        return this._batchCallbacks.findIndex((record2) => {
          return record2.callback === callback && (0, utils_1.setEquals)(record2.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_utils5();
    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_utils5();
    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_utils5();
    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_utils4();
    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_utils4();
    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 record2 of readableSpans) {
        let ilsMap = resourceMap.get(record2.resource);
        if (!ilsMap) {
          ilsMap = /* @__PURE__ */ new Map();
          resourceMap.set(record2.resource, ilsMap);
        }
        const instrumentationScopeKey = `${record2.instrumentationScope.name}@${record2.instrumentationScope.version || ""}:${record2.instrumentationScope.schemaUrl || ""}`;
        let records = ilsMap.get(instrumentationScopeKey);
        if (!records) {
          records = [];
          ilsMap.set(instrumentationScopeKey, records);
        }
        records.push(record2);
      }
      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(config2 = {}) {
        super((0, otlp_grpc_exporter_base_1.createOtlpGrpcExportDelegate)((0, otlp_grpc_exporter_base_1.convertLegacyOtlpGrpcOptions)(config2, "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(config2 = {}) {
        super((0, otlp_grpc_exporter_base_1.createOtlpGrpcExportDelegate)((0, otlp_grpc_exporter_base_1.convertLegacyOtlpGrpcOptions)(config2, "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(config2) {
      return config2?.aggregationPreference ?? (() => DEFAULT_AGGREGATION);
    }
    __name(chooseAggregationSelector, "chooseAggregationSelector");
    var OTLPMetricExporterBase = class extends otlp_exporter_base_1.OTLPExporterBase {
      static {
        __name(this, "OTLPMetricExporterBase");
      }
      _aggregationTemporalitySelector;
      _aggregationSelector;
      constructor(delegate, config2) {
        super(delegate);
        this._aggregationSelector = chooseAggregationSelector(config2);
        this._aggregationTemporalitySelector = chooseTemporalitySelector(config2?.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(config2) {
        super((0, node_http_1.createOtlpHttpExportDelegate)((0, node_http_1.convertLegacyHttpOptions)(config2 ?? {}, "METRICS", "v1/metrics", {
          ...USER_AGENT,
          "Content-Type": "application/json"
        }), otlp_transformer_1.JsonMetricsSerializer), config2);
      }
    };
    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(config2) {
        super((0, otlp_grpc_exporter_base_1.createOtlpGrpcExportDelegate)((0, otlp_grpc_exporter_base_1.convertLegacyOtlpGrpcOptions)(config2 ?? {}, "METRICS"), otlp_transformer_1.ProtobufMetricsSerializer, "MetricsExportService", "/opentelemetry.proto.collector.metrics.v1.MetricsService/Export"), config2);
      }
    };
    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(config2 = {}) {
        super((0, node_http_1.createOtlpHttpExportDelegate)((0, node_http_1.convertLegacyHttpOptions)(config2, "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(config2 = {}) {
        super((0, node_http_1.createOtlpHttpExportDelegate)((0, node_http_1.convertLegacyHttpOptions)(config2, "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 [k2, v2] of Object.entries(attributes)) {
          this.setAttribute(k2, v2);
        }
        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(config2 = {}) {
        const mergedConfig = (0, core_1.merge)({}, (0, config_1.loadDefaultConfig)(), config2);
        const resource = config2.resource ?? (0, resources_1.defaultResource)();
        this._sharedState = new LoggerProviderSharedState_1.LoggerProviderSharedState(resource, mergedConfig.forceFlushTimeoutMillis, (0, config_1.reconfigureLimits)(mergedConfig.logRecordLimits), config2?.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, config2) {
        this._exporter = _exporter;
        this._maxExportBatchSize = config2?.maxExportBatchSize ?? (0, core_1.getNumberFromEnv)("OTEL_BLRP_MAX_EXPORT_BATCH_SIZE") ?? 512;
        this._maxQueueSize = config2?.maxQueueSize ?? (0, core_1.getNumberFromEnv)("OTEL_BLRP_MAX_QUEUE_SIZE") ?? 2048;
        this._scheduledDelayMillis = config2?.scheduledDelayMillis ?? (0, core_1.getNumberFromEnv)("OTEL_BLRP_SCHEDULE_DELAY") ?? 5e3;
        this._exportTimeoutMillis = config2?.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((resolve30, reject) => {
          const promises8 = [];
          const batchCount = Math.ceil(this._finishedLogRecords.length / this._maxExportBatchSize);
          for (let i3 = 0; i3 < batchCount; i3++) {
            promises8.push(this._flushOneBatch());
          }
          Promise.all(promises8).then(() => {
            resolve30();
          }).catch(reject);
        });
      }
      _flushOneBatch() {
        this._clearTimer();
        if (this._finishedLogRecords.length === 0) {
          return Promise.resolve();
        }
        return new Promise((resolve30, reject) => {
          (0, core_2.callWithTimeout)(this._export(this._finishedLogRecords.splice(0, this._maxExportBatchSize)), this._exportTimeoutMillis).then(() => resolve30()).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((e4) => {
            (0, core_2.globalErrorHandler)(e4);
          });
        }, 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, ee2) {
        const map2 = this._getPatchMap(ee2);
        if (map2 !== void 0)
          return ee2;
        this._createPatchMap(ee2);
        ADD_LISTENER_METHODS.forEach((methodName) => {
          if (ee2[methodName] === void 0)
            return;
          ee2[methodName] = this._patchAddListener(ee2, ee2[methodName], context2);
        });
        if (typeof ee2.removeListener === "function") {
          ee2.removeListener = this._patchRemoveListener(ee2, ee2.removeListener);
        }
        if (typeof ee2.off === "function") {
          ee2.off = this._patchRemoveListener(ee2, ee2.off);
        }
        if (typeof ee2.removeAllListeners === "function") {
          ee2.removeAllListeners = this._patchRemoveAllListeners(ee2, ee2.removeAllListeners);
        }
        return ee2;
      }
      /**
       * 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(ee2, original) {
        const contextManager = this;
        return function(event, listener) {
          const events = contextManager._getPatchMap(ee2)?.[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(ee2, original) {
        const contextManager = this;
        return function(event) {
          const map2 = contextManager._getPatchMap(ee2);
          if (map2 !== void 0) {
            if (arguments.length === 0) {
              contextManager._createPatchMap(ee2);
            } 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(ee2, original, context2) {
        const contextManager = this;
        return function(event, listener) {
          if (contextManager._wrapped) {
            return original.call(this, event, listener);
          }
          let map2 = contextManager._getPatchMap(ee2);
          if (map2 === void 0) {
            map2 = contextManager._createPatchMap(ee2);
          }
          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(ee2) {
        const map2 = /* @__PURE__ */ Object.create(null);
        ee2[this._kOtListeners] = map2;
        return map2;
      }
      _getPatchMap(ee2) {
        return ee2[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 [k2, v2] of Object.entries(attributes)) {
          this.setAttribute(k2, v2);
        }
        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, time3) {
        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, time3);
        } 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 error2 = 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}}`, error2);
        }
        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(config2) {
        this._root = config2.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 = config2.remoteParentSampled ?? new AlwaysOnSampler_1.AlwaysOnSampler();
        this._remoteParentNotSampled = config2.remoteParentNotSampled ?? new AlwaysOffSampler_1.AlwaysOffSampler();
        this._localParentSampled = config2.localParentSampled ?? new AlwaysOnSampler_1.AlwaysOnSampler();
        this._localParentNotSampled = config2.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 i3 = 0; i3 < traceId.length / 8; i3++) {
          const pos2 = i3 * 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, config2) {
        this._exporter = _exporter;
        this._maxExportBatchSize = typeof config2?.maxExportBatchSize === "number" ? config2.maxExportBatchSize : (0, core_1.getNumberFromEnv)("OTEL_BSP_MAX_EXPORT_BATCH_SIZE") ?? 512;
        this._maxQueueSize = typeof config2?.maxQueueSize === "number" ? config2.maxQueueSize : (0, core_1.getNumberFromEnv)("OTEL_BSP_MAX_QUEUE_SIZE") ?? 2048;
        this._scheduledDelayMillis = typeof config2?.scheduledDelayMillis === "number" ? config2.scheduledDelayMillis : (0, core_1.getNumberFromEnv)("OTEL_BSP_SCHEDULE_DELAY") ?? 5e3;
        this._exportTimeoutMillis = typeof config2?.exportTimeoutMillis === "number" ? config2.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((resolve30, reject) => {
          const promises8 = [];
          const count = Math.ceil(this._finishedSpans.length / this._maxExportBatchSize);
          for (let i3 = 0, j2 = count; i3 < j2; i3++) {
            promises8.push(this._flushOneBatch());
          }
          Promise.all(promises8).then(() => {
            resolve30();
          }).catch(reject);
        });
      }
      _flushOneBatch() {
        this._clearTimer();
        if (this._finishedSpans.length === 0) {
          return Promise.resolve();
        }
        return new Promise((resolve30, 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) {
                resolve30();
              } else {
                reject(result.error ?? new Error("BatchSpanProcessor: span export failed"));
              }
            }), "doExport");
            let pendingResources = null;
            for (let i3 = 0, len = spans.length; i3 < len; i3++) {
              const span = spans[i3];
              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((e4) => {
            this._isExporting = false;
            (0, core_1.globalErrorHandler)(e4);
          });
        }, "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 i3 = 0; i3 < bytes / 4; i3++) {
          SHARED_BUFFER.writeUInt32BE(Math.random() * 2 ** 32 >>> 0, i3 * 4);
        }
        for (let i3 = 0; i3 < bytes; i3++) {
          if (SHARED_BUFFER[i3] > 0) {
            break;
          } else if (i3 === 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, config2, resource, spanProcessor) {
        const localConfig = (0, utility_1.mergeConfig)(config2);
        this._sampler = localConfig.sampler;
        this._generalLimits = localConfig.generalLimits;
        this._spanLimits = localConfig.spanLimits;
        this._idGenerator = config2.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 promises8 = [];
        for (const spanProcessor of this._spanProcessors) {
          promises8.push(spanProcessor.forceFlush());
        }
        return new Promise((resolve30) => {
          Promise.all(promises8).then(() => {
            resolve30();
          }).catch((error2) => {
            (0, core_1.globalErrorHandler)(error2 || new Error("MultiSpanProcessor: forceFlush failed"));
            resolve30();
          });
        });
      }
      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 promises8 = [];
        for (const spanProcessor of this._spanProcessors) {
          promises8.push(spanProcessor.shutdown());
        }
        return new Promise((resolve30, reject) => {
          Promise.all(promises8).then(() => {
            resolve30();
          }, 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(config2 = {}) {
        const mergedConfig = (0, core_1.merge)({}, (0, config_1.loadDefaultConfig)(), (0, utility_1.reconfigureLimits)(config2));
        this._resource = mergedConfig.resource ?? (0, resources_1.defaultResource)();
        this._config = Object.assign({}, mergedConfig, {
          resource: this._resource
        });
        const spanProcessors = [];
        if (config2.spanProcessors?.length) {
          spanProcessors.push(...config2.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 promises8 = this._activeSpanProcessor["_spanProcessors"].map((spanProcessor) => {
          return new Promise((resolve30) => {
            let state;
            const timeoutInterval = setTimeout(() => {
              resolve30(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;
                resolve30(state);
              }
            }).catch((error2) => {
              clearTimeout(timeoutInterval);
              state = ForceFlushState.error;
              resolve30(error2);
            });
          });
        });
        return new Promise((resolve30, reject) => {
          Promise.all(promises8).then((results) => {
            const errors = results.filter((result) => result !== ForceFlushState.resolved);
            if (errors.length > 0) {
              reject(errors);
            } else {
              resolve30();
            }
          }).catch((error2) => reject([error2]));
        });
      }
      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(config2 = {}) {
        super(config2);
      }
      /**
       * 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(config2 = {}) {
        api_1.trace.setGlobalTracerProvider(this);
        setupContextManager(config2.contextManager);
        setupPropagator(config2.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 i3 = 0, j2 = instrumentations.length; i3 < j2; i3++) {
        const instrumentation = instrumentations[i3];
        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 r5 of ranges2) {
          if (_checkRange(parsedVersion, r5, 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 r5 of ranges2) {
          if (!_checkRange(parsedVersion, r5, 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((r5) => r5.prerelease && r5.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(s5) {
      return s5 === "*" || s5 === "x" || s5 === "X";
    }
    __name(_isWildcard, "_isWildcard");
    function _parseVersionString(v2) {
      const n3 = parseInt(v2, 10);
      return isNaN(n3) ? v2 : n3;
    }
    __name(_parseVersionString, "_parseVersionString");
    function _normalizeVersionType(a2, b2) {
      if (typeof a2 === typeof b2) {
        if (typeof a2 === "number") {
          return [a2, b2];
        } else if (typeof a2 === "string") {
          return [a2, b2];
        } else {
          throw new Error("Version segments can only be strings or numbers");
        }
      } else {
        return [String(a2), String(b2)];
      }
    }
    __name(_normalizeVersionType, "_normalizeVersionType");
    function _compareVersionStrings(v1, v2) {
      if (_isWildcard(v1) || _isWildcard(v2)) {
        return 0;
      }
      const [parsedV1, parsedV2] = _normalizeVersionType(_parseVersionString(v1), _parseVersionString(v2));
      if (parsedV1 > parsedV2) {
        return 1;
      } else if (parsedV1 < parsedV2) {
        return -1;
      }
      return 0;
    }
    __name(_compareVersionStrings, "_compareVersionStrings");
    function _compareVersionSegments(v1, v2) {
      for (let i3 = 0; i3 < Math.max(v1.length, v2.length); i3++) {
        const res = _compareVersionStrings(v1[i3] || "0", v2[i3] || "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 r5 = TILDE_REGEXP;
      return comp.replace(r5, (_2, M2, m3, p2, pr2) => {
        let ret;
        if (isX(M2)) {
          ret = "";
        } else if (isX(m3)) {
          ret = `>=${M2}.0.0 <${+M2 + 1}.0.0-0`;
        } else if (isX(p2)) {
          ret = `>=${M2}.${m3}.0 <${M2}.${+m3 + 1}.0-0`;
        } else if (pr2) {
          ret = `>=${M2}.${m3}.${p2}-${pr2} <${M2}.${+m3 + 1}.0-0`;
        } else {
          ret = `>=${M2}.${m3}.${p2} <${M2}.${+m3 + 1}.0-0`;
        }
        return ret;
      });
    }
    __name(replaceTilde, "replaceTilde");
    function replaceCaret(comp, options2) {
      const r5 = CARET_REGEXP;
      const z2 = options2?.includePrerelease ? "-0" : "";
      return comp.replace(r5, (_2, M2, m3, p2, pr2) => {
        let ret;
        if (isX(M2)) {
          ret = "";
        } else if (isX(m3)) {
          ret = `>=${M2}.0.0${z2} <${+M2 + 1}.0.0-0`;
        } else if (isX(p2)) {
          if (M2 === "0") {
            ret = `>=${M2}.${m3}.0${z2} <${M2}.${+m3 + 1}.0-0`;
          } else {
            ret = `>=${M2}.${m3}.0${z2} <${+M2 + 1}.0.0-0`;
          }
        } else if (pr2) {
          if (M2 === "0") {
            if (m3 === "0") {
              ret = `>=${M2}.${m3}.${p2}-${pr2} <${M2}.${m3}.${+p2 + 1}-0`;
            } else {
              ret = `>=${M2}.${m3}.${p2}-${pr2} <${M2}.${+m3 + 1}.0-0`;
            }
          } else {
            ret = `>=${M2}.${m3}.${p2}-${pr2} <${+M2 + 1}.0.0-0`;
          }
        } else {
          if (M2 === "0") {
            if (m3 === "0") {
              ret = `>=${M2}.${m3}.${p2}${z2} <${M2}.${m3}.${+p2 + 1}-0`;
            } else {
              ret = `>=${M2}.${m3}.${p2}${z2} <${M2}.${+m3 + 1}.0-0`;
            }
          } else {
            ret = `>=${M2}.${m3}.${p2} <${+M2 + 1}.0.0-0`;
          }
        }
        return ret;
      });
    }
    __name(replaceCaret, "replaceCaret");
    function replaceXRange(comp, options2) {
      const r5 = XRANGE_REGEXP;
      return comp.replace(r5, (ret, gtlt, M2, m3, p2, pr2) => {
        const xM = isX(M2);
        const xm = xM || isX(m3);
        const xp = xm || isX(p2);
        const anyX = xp;
        if (gtlt === "=" && anyX) {
          gtlt = "";
        }
        pr2 = options2?.includePrerelease ? "-0" : "";
        if (xM) {
          if (gtlt === ">" || gtlt === "<") {
            ret = "<0.0.0-0";
          } else {
            ret = "*";
          }
        } else if (gtlt && anyX) {
          if (xm) {
            m3 = 0;
          }
          p2 = 0;
          if (gtlt === ">") {
            gtlt = ">=";
            if (xm) {
              M2 = +M2 + 1;
              m3 = 0;
              p2 = 0;
            } else {
              m3 = +m3 + 1;
              p2 = 0;
            }
          } else if (gtlt === "<=") {
            gtlt = "<";
            if (xm) {
              M2 = +M2 + 1;
            } else {
              m3 = +m3 + 1;
            }
          }
          if (gtlt === "<") {
            pr2 = "-0";
          }
          ret = `${gtlt + M2}.${m3}.${p2}${pr2}`;
        } else if (xm) {
          ret = `>=${M2}.0.0${pr2} <${+M2 + 1}.0.0-0`;
        } else if (xp) {
          ret = `>=${M2}.${m3}.0${pr2} <${M2}.${+m3 + 1}.0-0`;
        }
        return ret;
      });
    }
    __name(replaceXRange, "replaceXRange");
    function replaceHyphen(comp, options2) {
      const r5 = HYPHENRANGE_REGEXP;
      return comp.replace(r5, (_2, 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, config2) {
        this.instrumentationName = instrumentationName;
        this.instrumentationVersion = instrumentationVersion;
        this.setConfig(config2);
        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(config2) {
        this._config = {
          enabled: true,
          ...config2
        };
      }
      /**
       * 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 (e4) {
          this._diag.error(`Error running span customization hook due to exception in handler`, { triggerName }, e4);
        }
      }
    };
    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 sep9 = __require("path").sep;
    module2.exports = function(file) {
      var segments = file.split(sep9);
      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 i3 = 0; i3 <= lastBaseDirSegmentIndex; i3++) {
        if (i3 === lastBaseDirSegmentIndex) {
          basedir += segments[i3];
        } else {
          basedir += segments[i3] + sep9;
        }
      }
      var path125 = "";
      var lastSegmentIndex = segments.length - 1;
      for (var i22 = index + offset; i22 <= lastSegmentIndex; i22++) {
        if (i22 === lastSegmentIndex) {
          path125 += segments[i22];
        } else {
          path125 += segments[i22] + sep9;
        }
      }
      return {
        name: name3,
        basedir,
        path: path125
      };
    };
  }
});

// node_modules/resolve/lib/homedir.js
var require_homedir = __commonJS({
  "node_modules/resolve/lib/homedir.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var os47 = __require("os");
    module2.exports = os47.homedir || /* @__PURE__ */ __name(function homedir24() {
      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(_2, 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 isWindows9 = 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 (isWindows9)
      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 path125 = __require("path");
    var parse14 = path125.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 = parse14(absoluteStart);
      while (parsed.dir !== paths[paths.length - 1]) {
        paths.push(parsed.dir);
        parsed = parse14(parsed.dir);
      }
      return paths.reduce(function(dirs, aPath) {
        return dirs.concat(modules.map(function(moduleDir) {
          return path125.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(x3, 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(a2, b2) {
      var arr = [];
      for (var i3 = 0; i3 < a2.length; i3 += 1) {
        arr[i3] = a2[i3];
      }
      for (var j2 = 0; j2 < b2.length; j2 += 1) {
        arr[j2 + a2.length] = b2[j2];
      }
      return arr;
    }, "concatty");
    var slicy = /* @__PURE__ */ __name(function slicy2(arrLike, offset) {
      var arr = [];
      for (var i3 = offset || 0, j2 = 0; i3 < arrLike.length; i3 += 1, j2 += 1) {
        arr[j2] = arrLike[i3];
      }
      return arr;
    }, "slicy");
    var joiny = /* @__PURE__ */ __name(function(arr, joiner) {
      var str2 = "";
      for (var i3 = 0; i3 < arr.length; i3 += 1) {
        str2 += arr[i3];
        if (i3 + 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 i3 = 0; i3 < boundLength; i3++) {
        boundArgs[i3] = "$" + i3;
      }
      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_core6 = __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 hasOwn3 = 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 i3 = 0; i3 < 3; ++i3) {
        var cur = parseInt(nodeParts[i3] || 0, 10);
        var ver = parseInt(versionParts[i3] || 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 i3 = 0; i3 < specifiers.length; ++i3) {
        if (!specifierIncluded(current, specifiers[i3])) {
          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 i3 = 0; i3 < specifierValue.length; ++i3) {
          if (matchesRange(current, specifierValue[i3])) {
            return true;
          }
        }
        return false;
      }
      return matchesRange(current, specifierValue);
    }
    __name(versionIncluded, "versionIncluded");
    var data = require_core6();
    module2.exports = /* @__PURE__ */ __name(function isCore(x3, nodeVersion2) {
      return hasOwn3(data, x3) && versionIncluded(nodeVersion2, data[x3]);
    }, "isCore");
  }
});

// node_modules/resolve/lib/async.js
var require_async = __commonJS({
  "node_modules/resolve/lib/async.js"(exports2, module2) {
    init_esbuild_shims();
    var fs113 = __require("fs");
    var getHomedir = require_homedir();
    var path125 = __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" && fs113.realpath && typeof fs113.realpath.native === "function" ? fs113.realpath.native : fs113.realpath;
    var homedir24 = getHomedir();
    var defaultPaths = /* @__PURE__ */ __name(function() {
      return [
        path125.join(homedir24, ".node_modules"),
        path125.join(homedir24, ".node_libraries")
      ];
    }, "defaultPaths");
    var defaultIsFile = /* @__PURE__ */ __name(function isFile3(file, cb) {
      fs113.stat(file, function(err, stat10) {
        if (!err) {
          return cb(null, stat10.isFile() || stat10.isFIFO());
        }
        if (err.code === "ENOENT" || err.code === "ENOTDIR") return cb(null, false);
        return cb(err);
      });
    }, "isFile");
    var defaultIsDir = /* @__PURE__ */ __name(function isDirectory(dir, cb) {
      fs113.stat(dir, function(err, stat10) {
        if (!err) {
          return cb(null, stat10.isDirectory());
        }
        if (err.code === "ENOENT" || err.code === "ENOTDIR") return cb(null, false);
        return cb(err);
      });
    }, "isDirectory");
    var defaultRealpath = /* @__PURE__ */ __name(function realpath3(x3, cb) {
      realpathFS(x3, function(realpathErr, realPath) {
        if (realpathErr && realpathErr.code !== "ENOENT") cb(realpathErr);
        else cb(null, realpathErr ? x3 : realPath);
      });
    }, "realpath");
    var maybeRealpath = /* @__PURE__ */ __name(function maybeRealpath2(realpath3, x3, opts, cb) {
      if (opts && opts.preserveSymlinks === false) {
        realpath3(x3, cb);
      } else {
        cb(null, x3);
      }
    }, "maybeRealpath");
    var defaultReadPackage = /* @__PURE__ */ __name(function defaultReadPackage2(readFile13, pkgfile, cb) {
      readFile13(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(x3, start, opts) {
      var dirs = nodeModulesPaths(start, opts, x3);
      for (var i3 = 0; i3 < dirs.length; i3++) {
        dirs[i3] = path125.join(dirs[i3], x3);
      }
      return dirs;
    }, "getPackageCandidates");
    module2.exports = /* @__PURE__ */ __name(function resolve30(x3, options2, callback) {
      var cb = callback;
      var opts = options2;
      if (typeof options2 === "function") {
        cb = opts;
        opts = {};
      }
      if (typeof x3 !== "string") {
        var err = new TypeError("Path must be a string.");
        return process.nextTick(function() {
          cb(err);
        });
      }
      opts = normalizeOptions(x3, opts);
      var isFile3 = opts.isFile || defaultIsFile;
      var isDirectory = opts.isDirectory || defaultIsDir;
      var readFile13 = opts.readFile || fs113.readFile;
      var realpath3 = 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 || path125.dirname(caller());
      var parent = opts.filename || basedir;
      opts.paths = opts.paths || defaultPaths();
      var absoluteStart = path125.resolve(basedir);
      maybeRealpath(
        realpath3,
        absoluteStart,
        opts,
        function(err2, realStart) {
          if (err2) cb(err2);
          else init(realStart);
        }
      );
      var res;
      function init(basedir2) {
        if (/^(?:\.\.?(?:\/|$)|\/|([A-Za-z]:)?[/\\])/.test(x3)) {
          res = path125.resolve(basedir2, x3);
          if (x3 === "." || x3 === ".." || x3.slice(-1) === "/") res += "/";
          if (/\/$/.test(x3) && res === basedir2) {
            loadAsDirectory(res, opts.package, onfile);
          } else loadAsFile(res, opts.package, onfile);
        } else if (includeCoreModules && isCore(x3)) {
          return cb(null, x3);
        } else loadNodeModules(x3, basedir2, function(err2, n3, pkg2) {
          if (err2) cb(err2);
          else if (n3) {
            return maybeRealpath(realpath3, n3, opts, function(err3, realN) {
              if (err3) {
                cb(err3);
              } else {
                cb(null, realN, pkg2);
              }
            });
          } else {
            var moduleError = new Error("Cannot find module '" + x3 + "' from '" + parent + "'");
            moduleError.code = "MODULE_NOT_FOUND";
            cb(moduleError);
          }
        });
      }
      __name(init, "init");
      function onfile(err2, m3, pkg2) {
        if (err2) cb(err2);
        else if (m3) cb(null, m3, pkg2);
        else loadAsDirectory(res, function(err3, d2, pkg3) {
          if (err3) cb(err3);
          else if (d2) {
            maybeRealpath(realpath3, d2, opts, function(err4, realD) {
              if (err4) {
                cb(err4);
              } else {
                cb(null, realD, pkg3);
              }
            });
          } else {
            var moduleError = new Error("Cannot find module '" + x3 + "' from '" + parent + "'");
            moduleError.code = "MODULE_NOT_FOUND";
            cb(moduleError);
          }
        });
      }
      __name(onfile, "onfile");
      function loadAsFile(x4, thePackage, callback2) {
        var loadAsFilePackage = thePackage;
        var cb2 = callback2;
        if (typeof loadAsFilePackage === "function") {
          cb2 = loadAsFilePackage;
          loadAsFilePackage = void 0;
        }
        var exts = [""].concat(extensions);
        load(exts, x4, loadAsFilePackage);
        function load(exts2, x5, loadPackage) {
          if (exts2.length === 0) return cb2(null, void 0, loadPackage);
          var file = x5 + exts2[0];
          var pkg2 = loadPackage;
          if (pkg2) onpkg(null, pkg2);
          else loadpkg(path125.dirname(file), onpkg);
          function onpkg(err2, pkg_, dir) {
            pkg2 = pkg_;
            if (err2) return cb2(err2);
            if (dir && pkg2 && opts.pathFilter) {
              var rfile = path125.relative(dir, file);
              var rel = rfile.slice(0, rfile.length - exts2[0].length);
              var r5 = opts.pathFilter(pkg2, x5, rel);
              if (r5) return load(
                [""].concat(extensions.slice()),
                path125.resolve(dir, r5),
                pkg2
              );
            }
            isFile3(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), x5, 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(realpath3, dir, opts, function(unwrapErr, pkgdir) {
          if (unwrapErr) return loadpkg(path125.dirname(dir), cb2);
          var pkgfile = path125.join(pkgdir, "package.json");
          isFile3(pkgfile, function(err2, ex) {
            if (!ex) return loadpkg(path125.dirname(dir), cb2);
            readPackage2(readFile13, 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(x4, loadAsDirectoryPackage, callback2) {
        var cb2 = callback2;
        var fpkg = loadAsDirectoryPackage;
        if (typeof fpkg === "function") {
          cb2 = fpkg;
          fpkg = opts.package;
        }
        maybeRealpath(realpath3, x4, opts, function(unwrapErr, pkgdir) {
          if (unwrapErr) return cb2(unwrapErr);
          var pkgfile = path125.join(pkgdir, "package.json");
          isFile3(pkgfile, function(err2, ex) {
            if (err2) return cb2(err2);
            if (!ex) return loadAsFile(path125.join(x4, "index"), fpkg, cb2);
            readPackage2(readFile13, 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(path125.resolve(x4, pkg2.main), pkg2, function(err4, m3, pkg3) {
                  if (err4) return cb2(err4);
                  if (m3) return cb2(null, m3, pkg3);
                  if (!pkg3) return loadAsFile(path125.join(x4, "index"), pkg3, cb2);
                  var dir = path125.resolve(x4, pkg3.main);
                  loadAsDirectory(dir, pkg3, function(err5, n3, pkg4) {
                    if (err5) return cb2(err5);
                    if (n3) return cb2(null, n3, pkg4);
                    loadAsFile(path125.join(x4, "index"), pkg4, cb2);
                  });
                });
                return;
              }
              loadAsFile(path125.join(x4, "/index"), pkg2, cb2);
            });
          });
        });
      }
      __name(loadAsDirectory, "loadAsDirectory");
      function processDirs(cb2, dirs) {
        if (dirs.length === 0) return cb2(null, void 0);
        var dir = dirs[0];
        isDirectory(path125.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, m3, pkg2) {
          if (err2) return cb2(err2);
          if (m3) return cb2(null, m3, pkg2);
          loadAsDirectory(dir, opts.package, ondir);
        }
        __name(onfile2, "onfile");
        function ondir(err2, n3, pkg2) {
          if (err2) return cb2(err2);
          if (n3) return cb2(null, n3, pkg2);
          processDirs(cb2, dirs.slice(1));
        }
        __name(ondir, "ondir");
      }
      __name(processDirs, "processDirs");
      function loadNodeModules(x4, start, cb2) {
        var thunk = /* @__PURE__ */ __name(function() {
          return getPackageCandidates(x4, start, opts);
        }, "thunk");
        processDirs(
          cb2,
          packageIterator ? packageIterator(x4, start, thunk, opts) : thunk()
        );
      }
      __name(loadNodeModules, "loadNodeModules");
    }, "resolve");
  }
});

// node_modules/resolve/lib/core.json
var require_core7 = __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_core8 = __commonJS({
  "node_modules/resolve/lib/core.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var isCoreModule = require_is_core_module();
    var data = require_core7();
    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(x3) {
      return isCoreModule(x3);
    }, "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 fs113 = __require("fs");
    var path125 = __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" && fs113.realpathSync && typeof fs113.realpathSync.native === "function" ? fs113.realpathSync.native : fs113.realpathSync;
    var homedir24 = getHomedir();
    var defaultPaths = /* @__PURE__ */ __name(function() {
      return [
        path125.join(homedir24, ".node_modules"),
        path125.join(homedir24, ".node_libraries")
      ];
    }, "defaultPaths");
    var defaultIsFile = /* @__PURE__ */ __name(function isFile3(file) {
      try {
        var stat10 = fs113.statSync(file, { throwIfNoEntry: false });
      } catch (e4) {
        if (e4 && (e4.code === "ENOENT" || e4.code === "ENOTDIR")) return false;
        throw e4;
      }
      return !!stat10 && (stat10.isFile() || stat10.isFIFO());
    }, "isFile");
    var defaultIsDir = /* @__PURE__ */ __name(function isDirectory(dir) {
      try {
        var stat10 = fs113.statSync(dir, { throwIfNoEntry: false });
      } catch (e4) {
        if (e4 && (e4.code === "ENOENT" || e4.code === "ENOTDIR")) return false;
        throw e4;
      }
      return !!stat10 && stat10.isDirectory();
    }, "isDirectory");
    var defaultRealpathSync = /* @__PURE__ */ __name(function realpathSync8(x3) {
      try {
        return realpathFS(x3);
      } catch (realpathErr) {
        if (realpathErr.code !== "ENOENT") {
          throw realpathErr;
        }
      }
      return x3;
    }, "realpathSync");
    var maybeRealpathSync = /* @__PURE__ */ __name(function maybeRealpathSync2(realpathSync8, x3, opts) {
      if (opts && opts.preserveSymlinks === false) {
        return realpathSync8(x3);
      }
      return x3;
    }, "maybeRealpathSync");
    var defaultReadPackageSync = /* @__PURE__ */ __name(function defaultReadPackageSync2(readFileSync23, pkgfile) {
      var body = readFileSync23(pkgfile);
      try {
        var pkg2 = JSON.parse(body);
        return pkg2;
      } catch (jsonErr) {
      }
    }, "defaultReadPackageSync");
    var getPackageCandidates = /* @__PURE__ */ __name(function getPackageCandidates2(x3, start, opts) {
      var dirs = nodeModulesPaths(start, opts, x3);
      for (var i3 = 0; i3 < dirs.length; i3++) {
        dirs[i3] = path125.join(dirs[i3], x3);
      }
      return dirs;
    }, "getPackageCandidates");
    module2.exports = /* @__PURE__ */ __name(function resolveSync(x3, options2) {
      if (typeof x3 !== "string") {
        throw new TypeError("Path must be a string.");
      }
      var opts = normalizeOptions(x3, options2);
      var isFile3 = opts.isFile || defaultIsFile;
      var readFileSync23 = opts.readFileSync || fs113.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 || path125.dirname(caller());
      var parent = opts.filename || basedir;
      opts.paths = opts.paths || defaultPaths();
      var absoluteStart = maybeRealpathSync(realpathSync8, path125.resolve(basedir), opts);
      if (/^(?:\.\.?(?:\/|$)|\/|([A-Za-z]:)?[/\\])/.test(x3)) {
        var res = path125.resolve(absoluteStart, x3);
        if (x3 === "." || x3 === ".." || x3.slice(-1) === "/") res += "/";
        var m3 = loadAsFileSync(res) || loadAsDirectorySync(res);
        if (m3) return maybeRealpathSync(realpathSync8, m3, opts);
      } else if (includeCoreModules && isCore(x3)) {
        return x3;
      } else {
        var n3 = loadNodeModulesSync(x3, absoluteStart);
        if (n3) return maybeRealpathSync(realpathSync8, n3, opts);
      }
      var err = new Error("Cannot find module '" + x3 + "' from '" + parent + "'");
      err.code = "MODULE_NOT_FOUND";
      throw err;
      function loadAsFileSync(x4) {
        var pkg2 = loadpkg(path125.dirname(x4));
        if (pkg2 && pkg2.dir && pkg2.pkg && opts.pathFilter) {
          var rfile = path125.relative(pkg2.dir, x4);
          var r5 = opts.pathFilter(pkg2.pkg, x4, rfile);
          if (r5) {
            x4 = path125.resolve(pkg2.dir, r5);
          }
        }
        if (isFile3(x4)) {
          return x4;
        }
        for (var i3 = 0; i3 < extensions.length; i3++) {
          var file = x4 + extensions[i3];
          if (isFile3(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 = path125.join(maybeRealpathSync(realpathSync8, dir, opts), "package.json");
        if (!isFile3(pkgfile)) {
          return loadpkg(path125.dirname(dir));
        }
        var pkg2 = readPackageSync2(readFileSync23, pkgfile);
        if (pkg2 && opts.packageFilter) {
          pkg2 = opts.packageFilter(
            pkg2,
            /*pkgfile,*/
            dir
          );
        }
        return { pkg: pkg2, dir };
      }
      __name(loadpkg, "loadpkg");
      function loadAsDirectorySync(x4) {
        var pkgfile = path125.join(maybeRealpathSync(realpathSync8, x4, opts), "/package.json");
        if (isFile3(pkgfile)) {
          try {
            var pkg2 = readPackageSync2(readFileSync23, pkgfile);
          } catch (e4) {
          }
          if (pkg2 && opts.packageFilter) {
            pkg2 = opts.packageFilter(
              pkg2,
              /*pkgfile,*/
              x4
            );
          }
          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 m4 = loadAsFileSync(path125.resolve(x4, pkg2.main));
              if (m4) return m4;
              var n4 = loadAsDirectorySync(path125.resolve(x4, pkg2.main));
              if (n4) return n4;
            } catch (e4) {
            }
          }
        }
        return loadAsFileSync(path125.join(x4, "/index"));
      }
      __name(loadAsDirectorySync, "loadAsDirectorySync");
      function loadNodeModulesSync(x4, start) {
        var thunk = /* @__PURE__ */ __name(function() {
          return getPackageCandidates(x4, start, opts);
        }, "thunk");
        var dirs = packageIterator ? packageIterator(x4, start, thunk, opts) : thunk();
        for (var i3 = 0; i3 < dirs.length; i3++) {
          var dir = dirs[i3];
          if (isDirectory(path125.dirname(dir))) {
            var m4 = loadAsFileSync(dir);
            if (m4) return m4;
            var n4 = loadAsDirectorySync(dir);
            if (n4) return n4;
          }
        }
      }
      __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_core8();
    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 path125 = __require("path");
    var Module = __require("module");
    var debug3 = 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 resolve30(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 resolve31 = require_resolve3();
          _resolve = /* @__PURE__ */ __name(function(moduleName3, basedir2) {
            return resolve31.sync(moduleName3, { basedir: basedir2 });
          }, "_resolve");
        }
      }
      return _resolve(moduleName2, basedir);
    }
    __name(resolve30, "resolve");
    var normalize12 = /([/\\]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 {
          debug3('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);
      debug3("registering require hook");
      this._require = Module.prototype.require = function(id) {
        if (self2._unhooked === true) {
          debug3("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) {
            debug3("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) {
          debug3("call to process.getBuiltinModule with unknown built-in id");
          return self2._origGetBuiltinModule.apply(this, args);
        } else {
          try {
            filename = Module._resolveFilename(id, this);
          } catch (resolveErr) {
            debug3('Module._resolveFilename("%s") threw %j, calling original Module.require', id, resolveErr.message);
            return self2._origRequire.apply(this, args);
          }
        }
        let moduleName2, basedir;
        debug3("processing %s module require('%s'): %s", core === true ? "core" : "non-core", id, filename);
        if (self2._cache.has(filename, core) === true) {
          debug3("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) {
          debug3("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) {
            debug3("ignoring core module not on whitelist: %s", filename);
            return exports3;
          }
          moduleName2 = filename;
        } else if (hasWhitelist === true && modules.includes(filename)) {
          const parsedPath = path125.parse(filename);
          moduleName2 = parsedPath.name;
          basedir = parsedPath.dir;
        } else {
          const stat10 = moduleDetailsFromPath(filename);
          if (stat10 === void 0) {
            debug3("could not parse filename: %s", filename);
            return exports3;
          }
          moduleName2 = stat10.name;
          basedir = stat10.basedir;
          const fullModuleName = resolveModuleName(stat10);
          debug3("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 = resolve30(moduleName2, basedir);
            } catch (e4) {
              debug3("could not resolve module: %s", moduleName2);
              self2._cache.set(filename, exports3, core);
              return exports3;
            }
            if (res !== filename) {
              if (internals === true) {
                moduleName2 = moduleName2 + path125.sep + path125.relative(basedir, filename);
                debug3("preparing to process require of internal file: %s", moduleName2);
              } else {
                debug3("ignoring require of non-main module file: %s", res);
                self2._cache.set(filename, exports3, core);
                return exports3;
              }
            }
          }
        }
        self2._cache.set(filename, exports3, core);
        debug3("calling require hook: %s", moduleName2);
        const patchedExports = onrequire(exports3, moduleName2, basedir);
        self2._cache.set(filename, patchedExports, core);
        debug3("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;
        debug3("require unhook successful");
      } else {
        debug3("require unhook unsuccessful");
      }
      if (process.getBuiltinModule !== void 0) {
        if (this._getBuiltinModule === process.getBuiltinModule) {
          process.getBuiltinModule = this._origGetBuiltinModule;
          debug3("process.getBuiltinModule unhook successful");
        } else {
          debug3("process.getBuiltinModule unhook unsuccessful");
        }
      }
    };
    function resolveModuleName(stat10) {
      const normalizedPath = path125.sep !== "/" ? stat10.path.split(path125.sep).join("/") : stat10.path;
      return path125.posix.join(stat10.name, normalizedPath).replace(normalize12, "");
    }
    __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((a2, b2) => a2.insertedId - b2.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 path125 = __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 path125.sep !== ModuleNameTrie_1.ModuleNameSeparator ? moduleNameOrPath.split(path125.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, get4, specifier) {
      specifiers.set(name3, specifier);
      setters.set(namespace, set);
      getters.set(namespace, get4);
      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 path125 = __require("path");
    var parse14 = require_module_details_from_path();
    var { fileURLToPath: fileURLToPath17 } = __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((resolve30) => {
          resolveFn = resolve30;
        }).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 = fileURLToPath17(name3);
            } catch (e4) {
            }
          }
          const details = parse14(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 + path125.sep + path125.relative(baseDir, fileURLToPath17(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_utils8 = __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 error2;
      let result;
      try {
        result = execute();
      } catch (e4) {
        error2 = e4;
      } finally {
        onFinish(error2, result);
        if (error2 && !preventThrowingError) {
          throw error2;
        }
        return result;
      }
    }
    __name(safeExecuteInTheMiddle, "safeExecuteInTheMiddle");
    exports2.safeExecuteInTheMiddle = safeExecuteInTheMiddle;
    async function safeExecuteInTheMiddleAsync(execute, onFinish, preventThrowingError) {
      let error2;
      let result;
      try {
        result = await execute();
      } catch (e4) {
        error2 = e4;
      } finally {
        onFinish(error2, result);
        if (error2 && !preventThrowingError) {
          throw error2;
        }
        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 path125 = __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_utils8();
    var InstrumentationBase = class extends instrumentation_1.InstrumentationAbstract {
      static {
        __name(this, "InstrumentationBase");
      }
      _modules;
      _hooks = [];
      _requireInTheMiddleSingleton = RequireInTheMiddleSingleton_1.RequireInTheMiddleSingleton.getInstance();
      _enabled = false;
      constructor(instrumentationName, instrumentationVersion, config2) {
        super(instrumentationName, instrumentationVersion, config2);
        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)(path125.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 = path125.normalize(name3);
        const supportedFileInstrumentations = files.filter((f5) => f5.name === normalizedName).filter((f5) => isSupported(f5.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 && path125.isAbsolute(name3)) {
              const parsedPath = path125.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 = path125.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((v2) => v2.trim()).filter((s5) => s5 !== "");
      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_utils8();
    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(config2 = {}) {
        super((0, node_http_1.createOtlpHttpExportDelegate)((0, node_http_1.convertLegacyHttpOptions)(config2, "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(config2) {
        super((0, node_http_1.createOtlpHttpExportDelegate)((0, node_http_1.convertLegacyHttpOptions)(config2 ?? {}, "METRICS", "v1/metrics", {
          "User-Agent": `OTel-OTLP-Exporter-JavaScript/${version_1.VERSION}`,
          "Content-Type": "application/x-protobuf"
        }), otlp_transformer_1.ProtobufMetricsSerializer), config2);
      }
    };
    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 stringify4(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(stringify4, "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((it2) => this._serializeSingularDataPoint(name3, metricData, it2)).join("");
            break;
          }
          case sdk_metrics_1.DataPointType.HISTOGRAM: {
            results = metricData.dataPoints.map((it2) => this._serializeHistogramDataPoint(name3, metricData, it2)).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 += stringify4(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 += stringify4(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 += stringify4(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 = stringify4(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(config2 = {}, 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: config2.metricProducers
        });
        this._host = config2.host || process.env.OTEL_EXPORTER_PROMETHEUS_HOST || _PrometheusExporter.DEFAULT_OPTIONS.host;
        this._port = config2.port || Number(process.env.OTEL_EXPORTER_PROMETHEUS_PORT) || _PrometheusExporter.DEFAULT_OPTIONS.port;
        this._prefix = config2.prefix || _PrometheusExporter.DEFAULT_OPTIONS.prefix;
        this._appendTimestamp = typeof config2.appendTimestamp === "boolean" ? config2.appendTimestamp : _PrometheusExporter.DEFAULT_OPTIONS.appendTimestamp;
        const _withResourceConstantLabels = config2.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 = (config2.endpoint || _PrometheusExporter.DEFAULT_OPTIONS.endpoint).replace(/^([^/])/, "/$1");
        if (config2.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((resolve30) => {
            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);
                }
              }
              resolve30();
            });
          });
        }
      }
      /**
       * Starts the Prometheus export server
       */
      startServer() {
        this._startServerPromise ??= new Promise((resolve30, 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}`);
            resolve30();
          });
        });
        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(config2 = {}) {
        super((0, node_http_1.createOtlpHttpExportDelegate)((0, node_http_1.convertLegacyHttpOptions)(config2, "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_util16 = __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 http7 = __require("http");
    var https7 = __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:" ? http7 : https7;
        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", (error2) => {
          return done({
            code: core_1.ExportResultCode.FAILED,
            error: error2
          });
        });
        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_util16();
    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_utils9 = __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_utils9();
    var ZipkinExporter = class {
      static {
        __name(this, "ZipkinExporter");
      }
      DEFAULT_SERVICE_NAME = "OpenTelemetry Service";
      _statusCodeTagName;
      _statusDescriptionTagName;
      _urlStr;
      _send;
      _getHeaders;
      _serviceName;
      _isShutdown;
      _sendingPromises = [];
      constructor(config2 = {}) {
        this._urlStr = config2.url || ((0, core_1.getStringFromEnv)("OTEL_EXPORTER_ZIPKIN_ENDPOINT") ?? "http://localhost:9411/api/v2/spans");
        this._send = (0, index_1.prepareSend)(this._urlStr, config2.headers);
        this._serviceName = config2.serviceName;
        this._statusCodeTagName = config2.statusCodeTagName || transform_1.defaultStatusCodeTagName;
        this._statusDescriptionTagName = config2.statusDescriptionTagName || transform_1.defaultStatusErrorTagName;
        this._isShutdown = false;
        if (typeof config2.getExportRequestHeaders === "function") {
          this._getHeaders = (0, utils_1.prepareGetHeaders)(config2.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((resolve30) => {
          this._sendSpans(spans, serviceName, (result) => {
            resolve30();
            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((resolve30, reject) => {
          Promise.all(this._sendingPromises).then(() => {
            resolve30();
          }, 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_constants9 = __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_constants9();
    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 debug3 = getHeaderValue(carrier, getter, constants_1.X_B3_FLAGS);
      return debug3 === "1" ? "1" : void 0;
    }
    __name(getDebug, "getDebug");
    function getTraceFlags(carrier, getter) {
      const traceFlags = getHeaderValue(carrier, getter, constants_1.X_B3_SAMPLED);
      const debug3 = getDebug(carrier, getter);
      if (debug3 === "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 debug3 = 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 (debug3 === "1") {
          setter.set(carrier, constants_1.X_B3_FLAGS, debug3);
        } 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 debug3 = 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, debug3);
          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_constants9();
    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_constants9();
    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(config2 = {}) {
        if (config2.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_constants9();
    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(config2) {
        if (typeof config2 === "string") {
          this._jaegerTraceHeader = config2;
          this._jaegerBaggageHeaderPrefix = exports2.UBER_BAGGAGE_HEADER_PREFIX;
        } else {
          this._jaegerTraceHeader = config2?.customTraceHeader || exports2.UBER_TRACE_ID_HEADER;
          this._jaegerBaggageHeaderPrefix = config2?.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_utils10 = __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((s5) => s5 !== "null" && s5 !== "");
    }
    __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 (e4) {
        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: ${e4}`);
      }
    }
    __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_utils10();
    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((r5) => readers.push(r5));
          }
          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 promises8 = [];
        if (this._tracerProvider) {
          promises8.push(this._tracerProvider.shutdown());
        }
        if (this._loggerProvider) {
          promises8.push(this._loggerProvider.shutdown());
        }
        if (this._meterProvider) {
          promises8.push(this._meterProvider.shutdown());
        }
        return Promise.all(promises8).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 util3 = __require("util");
    function ParseError2(message, input) {
      Error.captureStackTrace(this, ParseError2);
      this.name = this.constructor.name;
      this.message = message;
      this.input = input;
    }
    __name(ParseError2, "ParseError");
    util3.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 util3 = __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 util3.format(
        "Unexpected character '%s' at index %d",
        header.charAt(position),
        position
      );
    }
    __name(unexpectedCharacterMessage, "unexpectedCharacterMessage");
    function parse14(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 i3 = 0; i3 < header.length; i3++) {
        code2 = header.charCodeAt(i3);
        if (parameter === void 0) {
          if (i3 !== 0 && start === -1 && (code2 === 32 || code2 === 9)) {
            continue;
          }
          if (isTokenChar(code2)) {
            if (start === -1) start = i3;
          } else if (code2 === 61 && start !== -1) {
            parameter = header.slice(start, i3).toLowerCase();
            start = -1;
          } else {
            throw new ParseError2(unexpectedCharacterMessage(header, i3), header);
          }
        } else {
          if (isEscaping && (code2 === 9 || isPrint(code2) || isExtended(code2))) {
            isEscaping = false;
          } else if (isTokenChar(code2)) {
            if (end !== -1) {
              throw new ParseError2(unexpectedCharacterMessage(header, i3), header);
            }
            if (start === -1) start = i3;
          } else if (isDelimiter2(code2) || isExtended(code2)) {
            if (inQuotes) {
              if (code2 === 34) {
                inQuotes = false;
                end = i3;
              } else if (code2 === 92) {
                if (start === -1) start = i3;
                isEscaping = mustUnescape = true;
              } else if (start === -1) {
                start = i3;
              }
            } else if (code2 === 34 && header.charCodeAt(i3 - 1) === 61) {
              inQuotes = true;
            } else if ((code2 === 44 || code2 === 59) && (start !== -1 || end !== -1)) {
              if (start !== -1) {
                if (end === -1) end = i3;
                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, i3), header);
            }
          } else if (code2 === 32 || code2 === 9) {
            if (end !== -1) continue;
            if (inQuotes) {
              if (start === -1) start = i3;
            } else if (start !== -1) {
              end = i3;
            } else {
              throw new ParseError2(unexpectedCharacterMessage(header, i3), header);
            }
          } else {
            throw new ParseError2(unexpectedCharacterMessage(header, i3), 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 = i3;
        forwarded[parameter] = mustUnescape ? decode2(header.slice(start, end)) : header.slice(start, end);
      } else {
        forwarded[parameter] = "";
      }
      output.push(forwarded);
      return output;
    }
    __name(parse14, "parse");
    module2.exports = parse14;
  }
});

// node_modules/@opentelemetry/instrumentation-http/build/src/utils.js
var require_utils11 = __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 path125 = 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}${path125}`;
    }, "getAbsoluteUrl");
    exports2.getAbsoluteUrl = getAbsoluteUrl;
    var parseResponseStatus = /* @__PURE__ */ __name((kind2, statusCode) => {
      const upperBound = kind2 === 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, error2, semconvStability) => {
      const message = error2.message;
      if (semconvStability & instrumentation_1.SemconvStability.OLD) {
        span.setAttribute(AttributeNames_1.AttributeNames.HTTP_ERROR_NAME, error2.name);
        span.setAttribute(AttributeNames_1.AttributeNames.HTTP_ERROR_MESSAGE, message);
      }
      if (semconvStability & instrumentation_1.SemconvStability.STABLE) {
        span.setAttribute(semantic_conventions_1.ATTR_ERROR_TYPE, error2.name);
      }
      span.setStatus({ code: api_1.SpanStatusCode.ERROR, message });
      span.recordException(error2);
    }, "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: hostname4, pathname, port, username, password, search, protocol, hash, href, origin, host } = new URL(stringUrl);
      const options2 = {
        protocol,
        hostname: hostname4 && hostname4[0] === "[" ? hostname4.slice(1, -1) : hostname4,
        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 (e4) {
          invalidUrl = true;
          logger6.verbose("Unable to parse URL provided to HTTP request, using fallback to determine path. Original error:", e4);
          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 hostname4 = optionsParsed.host || (optionsParsed.port != null ? `${optionsParsed.hostname}${optionsParsed.port}` : optionsParsed.hostname);
        origin = `${optionsParsed.protocol || "http:"}//${hostname4}`;
        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 hostname4 = 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: hostname4, port };
    }, "extractHostnameAndPort");
    exports2.extractHostnameAndPort = extractHostnameAndPort;
    var getOutgoingRequestAttributes = /* @__PURE__ */ __name((requestOptions, options2, semconvStability, enableSyntheticSourceDetection) => {
      const hostname4 = 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]: hostname4,
        [semconv_1.ATTR_HTTP_HOST]: headers.host ?? `${hostname4}:${port}`
      };
      const newAttributes = {
        // Required attributes
        [semantic_conventions_1.ATTR_HTTP_REQUEST_METHOD]: normalizedMethod,
        [semantic_conventions_1.ATTR_SERVER_ADDRESS]: hostname4,
        [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((kind2, attributes) => {
      if (kind2) {
        attributes[semconv_1.ATTR_HTTP_FLAVOR] = kind2;
        if (kind2.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 (e4) {
        logger6.verbose("Unable to get URL from request", e4);
        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 hostname4 = 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]: hostname4,
        [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 i3 = 0, len = headers.length; i3 < len; i3++) {
        const capturedHeader = headers[i3].toLowerCase();
        normalizedHeaders.set(capturedHeader, capturedHeader.replace(/-/g, "_"));
      }
      return (span, getHeader2) => {
        for (const capturedHeader of normalizedHeaders.keys()) {
          const value = getHeader2(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_utils11();
    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(config2 = {}) {
        super("@opentelemetry/instrumentation-http", version_1.VERSION, config2);
        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(config2 = {}) {
        super.setConfig(config2);
        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, (error2) => {
            this._diag.debug("outgoingRequest on error()", error2);
            if (responseFinished) {
              return;
            }
            responseFinished = true;
            (0, utils_1.setSpanWithError)(span, error2, this._semconvStability);
            span.setStatus({
              code: api_1.SpanStatusCode.ERROR,
              message: error2.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, (error2) => {
          this._diag.debug("outgoingRequest on request error()", error2);
          if (responseFinished) {
            return;
          }
          responseFinished = true;
          (0, utils_1.setSpanWithError)(span, error2, 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), (e4) => {
            if (e4 != null) {
              instrumentation._diag.error("caught ignoreIncomingRequestHook error: ", e4);
            }
          }, 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]), (error2) => {
              if (error2) {
                (0, utils_1.setSpanWithError)(span, error2, instrumentation._semconvStability);
                instrumentation._closeHttpSpan(span, api_1.SpanKind.SERVER, startTime, oldMetricAttributes, stableMetricAttributes);
                throw error2;
              }
            });
          });
        }, "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), (e4) => {
            if (e4 != null) {
              instrumentation._diag.error("caught ignoreOutgoingRequestHook error: ", e4);
            }
          }, true)) {
            return original.apply(this, [optionsParsed, ...args]);
          }
          const { hostname: hostname4, port } = (0, utils_1.extractHostnameAndPort)(optionsParsed);
          const attributes = (0, utils_1.getOutgoingRequestAttributes)(optionsParsed, {
            component,
            port,
            hostname: hostname4,
            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]);
              }
            }, (error2) => {
              if (error2) {
                (0, utils_1.setSpanWithError)(span, error2, instrumentation._semconvStability);
                instrumentation._closeHttpSpan(span, api_1.SpanKind.CLIENT, startTime, oldMetricAttributes, stableMetricAttributes);
                throw error2;
              }
            });
            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, error2) {
        (0, utils_1.setSpanWithError)(span, error2, 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 duration3 = (0, core_1.hrTimeToMilliseconds)((0, core_1.hrTimeDuration)(startTime, (0, core_1.hrTime)()));
        if (spanKind === api_1.SpanKind.SERVER) {
          this._recordServerDuration(duration3, oldMetricAttributes, stableMetricAttributes);
        } else if (spanKind === api_1.SpanKind.CLIENT) {
          this._recordClientDuration(duration3, 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 config2 = this.getConfig();
        return {
          client: {
            captureRequestHeaders: (0, utils_1.headerCapture)("request", config2.headersToSpanAttributes?.client?.requestHeaders ?? []),
            captureResponseHeaders: (0, utils_1.headerCapture)("response", config2.headersToSpanAttributes?.client?.responseHeaders ?? [])
          },
          server: {
            captureRequestHeaders: (0, utils_1.headerCapture)("request", config2.headersToSpanAttributes?.server?.requestHeaders ?? []),
            captureResponseHeaders: (0, utils_1.headerCapture)("response", config2.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 fs8 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 = fs8.createWriteStream(filePath, { flags: "a" });
      }
      serialize(data) {
        return JSON.stringify(data, null, 2) + "\n";
      }
      shutdown() {
        return new Promise((resolve30) => {
          this.writeStream.end(resolve30);
        });
      }
    };
    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 (error2) {
    diag2.error("Invalid OTLP endpoint URL provided:", trimmedEndpoint, error2);
    return void 0;
  }
}
function initializeTelemetry(config2) {
  if (telemetryInitialized || !config2.getTelemetryEnabled()) {
    return;
  }
  const debugLogger124 = createDebugLogger("OTEL");
  const resource = (0, import_resources.resourceFromAttributes)({
    [SemanticResourceAttributes.SERVICE_NAME]: SERVICE_NAME,
    [SemanticResourceAttributes.SERVICE_VERSION]: process.version,
    "session.id": config2.getSessionId()
  });
  const otlpEndpoint = config2.getTelemetryOtlpEndpoint();
  const otlpProtocol = config2.getTelemetryOtlpProtocol();
  const parsedEndpoint = parseOtlpEndpoint(otlpEndpoint, otlpProtocol);
  const telemetryOutfile = config2.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();
    debugLogger124.debug("OpenTelemetry SDK started successfully.");
    telemetryInitialized = true;
    initializeMetrics(config2);
  } catch (error2) {
    debugLogger124.error("Error starting OpenTelemetry SDK:", error2);
  }
  process.on("SIGTERM", () => {
    shutdownTelemetry();
  });
  process.on("SIGINT", () => {
    shutdownTelemetry();
  });
  process.on("exit", () => {
    shutdownTelemetry();
  });
}
async function shutdownTelemetry() {
  if (!telemetryInitialized || !sdk) {
    return;
  }
  const debugLogger124 = createDebugLogger("OTEL");
  try {
    await sdk.shutdown();
    debugLogger124.debug("OpenTelemetry SDK shut down successfully.");
  } catch (error2) {
    debugLogger124.error("Error shutting down SDK:", error2);
  } 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();
    init_debugLogger();
    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 } 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();
    init_constants();
    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 EventEmitter {
      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
        });
      }
      /**
       * Resets metrics to the initial state (used when resuming a session).
       */
      reset() {
        this.#metrics = createInitialMetrics();
        this.#lastPromptTokenCount = 0;
        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(config2) {
  return {
    "session.id": config2.getSessionId()
  };
}
function logStartSession(config2, event) {
  QwenLogger.getInstance(config2)?.logStartSessionEvent(event);
  if (!isTelemetrySdkInitialized())
    return;
  const attributes = {
    ...getCommonAttributes(config2),
    "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,
    skills: event.skills,
    subagents: event.subagents
  };
  const logger6 = import_api_logs.logs.getLogger(SERVICE_NAME);
  const logRecord = {
    body: "CLI configuration loaded.",
    attributes
  };
  logger6.emit(logRecord);
}
function logUserPrompt(config2, event) {
  QwenLogger.getInstance(config2)?.logNewPromptEvent(event);
  if (!isTelemetrySdkInitialized())
    return;
  const attributes = {
    ...getCommonAttributes(config2),
    "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(config2)) {
    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(config2, event) {
  const uiEvent = {
    ...event,
    "event.name": EVENT_TOOL_CALL,
    "event.timestamp": (/* @__PURE__ */ new Date()).toISOString()
  };
  uiTelemetryService.addEvent(uiEvent);
  config2.getChatRecordingService()?.recordUiTelemetryEvent(uiEvent);
  QwenLogger.getInstance(config2)?.logToolCallEvent(event);
  if (!isTelemetrySdkInitialized())
    return;
  const attributes = {
    ...getCommonAttributes(config2),
    ...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(config2, event.duration_ms, {
    function_name: event.function_name,
    success: event.success,
    decision: event.decision,
    tool_type: event.tool_type
  });
}
function logToolOutputTruncated(config2, event) {
  QwenLogger.getInstance(config2)?.logToolOutputTruncatedEvent(event);
  if (!isTelemetrySdkInitialized())
    return;
  const attributes = {
    ...getCommonAttributes(config2),
    ...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(config2, event) {
  QwenLogger.getInstance(config2)?.logFileOperationEvent(event);
  if (!isTelemetrySdkInitialized())
    return;
  const attributes = {
    ...getCommonAttributes(config2),
    "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(config2, {
    operation: event.operation,
    lines: event.lines,
    mimetype: event.mimetype,
    extension: event.extension,
    programming_language: event.programming_language
  });
}
function logApiRequest(config2, event) {
  if (!isTelemetrySdkInitialized())
    return;
  const attributes = {
    ...getCommonAttributes(config2),
    ...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 logRipgrepFallback(config2, event) {
  QwenLogger.getInstance(config2)?.logRipgrepFallbackEvent(event);
  if (!isTelemetrySdkInitialized())
    return;
  const attributes = {
    ...getCommonAttributes(config2),
    ...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(config2, event) {
  const uiEvent = {
    ...event,
    "event.name": EVENT_API_ERROR,
    "event.timestamp": (/* @__PURE__ */ new Date()).toISOString()
  };
  uiTelemetryService.addEvent(uiEvent);
  config2.getChatRecordingService()?.recordUiTelemetryEvent(uiEvent);
  QwenLogger.getInstance(config2)?.logApiErrorEvent(event);
  if (!isTelemetrySdkInitialized())
    return;
  const attributes = {
    ...getCommonAttributes(config2),
    ...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(config2, event.duration_ms, {
    model: event.model,
    status_code: event.status_code,
    error_type: event.error_type
  });
}
function logApiCancel(config2, event) {
  const uiEvent = {
    ...event,
    "event.name": EVENT_API_CANCEL,
    "event.timestamp": (/* @__PURE__ */ new Date()).toISOString()
  };
  uiTelemetryService.addEvent(uiEvent);
  QwenLogger.getInstance(config2)?.logApiCancelEvent(event);
  if (!isTelemetrySdkInitialized())
    return;
  const attributes = {
    ...getCommonAttributes(config2),
    ...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(config2, event) {
  const uiEvent = {
    ...event,
    "event.name": EVENT_API_RESPONSE,
    "event.timestamp": (/* @__PURE__ */ new Date()).toISOString()
  };
  uiTelemetryService.addEvent(uiEvent);
  config2.getChatRecordingService()?.recordUiTelemetryEvent(uiEvent);
  QwenLogger.getInstance(config2)?.logApiResponseEvent(event);
  if (!isTelemetrySdkInitialized())
    return;
  const attributes = {
    ...getCommonAttributes(config2),
    ...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(config2, event.duration_ms, {
    model: event.model,
    status_code: event.status_code
  });
  recordTokenUsageMetrics(config2, event.input_token_count, {
    model: event.model,
    type: "input"
  });
  recordTokenUsageMetrics(config2, event.output_token_count, {
    model: event.model,
    type: "output"
  });
  recordTokenUsageMetrics(config2, event.cached_content_token_count, {
    model: event.model,
    type: "cache"
  });
  recordTokenUsageMetrics(config2, event.thoughts_token_count, {
    model: event.model,
    type: "thought"
  });
  recordTokenUsageMetrics(config2, event.tool_token_count, {
    model: event.model,
    type: "tool"
  });
}
function logLoopDetected(config2, event) {
  QwenLogger.getInstance(config2)?.logLoopDetectedEvent(event);
  if (!isTelemetrySdkInitialized())
    return;
  const attributes = {
    ...getCommonAttributes(config2),
    ...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(config2, _event) {
  QwenLogger.getInstance(config2)?.logLoopDetectionDisabledEvent();
}
function logNextSpeakerCheck(config2, event) {
  QwenLogger.getInstance(config2)?.logNextSpeakerCheck(event);
  if (!isTelemetrySdkInitialized())
    return;
  const attributes = {
    ...getCommonAttributes(config2),
    ...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(config2, event) {
  QwenLogger.getInstance(config2)?.logSlashCommandEvent(event);
  if (!isTelemetrySdkInitialized())
    return;
  const attributes = {
    ...getCommonAttributes(config2),
    ...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(config2, event) {
  QwenLogger.getInstance(config2)?.logIdeConnectionEvent(event);
  if (!isTelemetrySdkInitialized())
    return;
  const attributes = {
    ...getCommonAttributes(config2),
    ...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(config2, event) {
  QwenLogger.getInstance(config2)?.logConversationFinishedEvent(event);
  if (!isTelemetrySdkInitialized())
    return;
  const attributes = {
    ...getCommonAttributes(config2),
    ...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(config2, event) {
  QwenLogger.getInstance(config2)?.logChatCompressionEvent(event);
  const attributes = {
    ...getCommonAttributes(config2),
    ...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(config2, {
    tokens_before: event.tokens_before,
    tokens_after: event.tokens_after
  });
}
function logKittySequenceOverflow(config2, event) {
  QwenLogger.getInstance(config2)?.logKittySequenceOverflowEvent(event);
  if (!isTelemetrySdkInitialized())
    return;
  const attributes = {
    ...getCommonAttributes(config2),
    ...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(config2, event) {
  QwenLogger.getInstance(config2)?.logContentRetryEvent(event);
  if (!isTelemetrySdkInitialized())
    return;
  const attributes = {
    ...getCommonAttributes(config2),
    ...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(config2);
}
function logContentRetryFailure(config2, event) {
  QwenLogger.getInstance(config2)?.logContentRetryFailureEvent(event);
  if (!isTelemetrySdkInitialized())
    return;
  const attributes = {
    ...getCommonAttributes(config2),
    ...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(config2);
}
function logSubagentExecution(config2, event) {
  QwenLogger.getInstance(config2)?.logSubagentExecutionEvent(event);
  if (!isTelemetrySdkInitialized())
    return;
  const attributes = {
    ...getCommonAttributes(config2),
    ...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(config2, event.subagent_name, event.status, event.terminate_reason);
}
function logModelSlashCommand(config2, event) {
  QwenLogger.getInstance(config2)?.logModelSlashCommandEvent(event);
  if (!isTelemetrySdkInitialized())
    return;
  const attributes = {
    ...getCommonAttributes(config2),
    ...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(config2, event);
}
function logExtensionInstallEvent(config2, event) {
  QwenLogger.getInstance(config2)?.logExtensionInstallEvent(event);
  if (!isTelemetrySdkInitialized())
    return;
  const attributes = {
    ...getCommonAttributes(config2),
    ...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(config2, event) {
  QwenLogger.getInstance(config2)?.logExtensionUninstallEvent(event);
  if (!isTelemetrySdkInitialized())
    return;
  const attributes = {
    ...getCommonAttributes(config2),
    ...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);
}
async function logExtensionUpdateEvent(config2, event) {
  QwenLogger.getInstance(config2)?.logExtensionUpdateEvent(event);
  const attributes = {
    ...getCommonAttributes(config2),
    ...event,
    "event.name": EVENT_EXTENSION_UPDATE,
    "event.timestamp": (/* @__PURE__ */ new Date()).toISOString(),
    extension_name: event.extension_name,
    extension_id: event.extension_id,
    extension_previous_version: event.extension_previous_version,
    extension_version: event.extension_version,
    extension_source: event.extension_source
  };
  const logger6 = import_api_logs.logs.getLogger(SERVICE_NAME);
  const logRecord = {
    body: `Updated extension ${event.extension_name} from ${event.extension_previous_version} to ${event.extension_version}`,
    attributes
  };
  logger6.emit(logRecord);
}
function logExtensionEnable(config2, event) {
  QwenLogger.getInstance(config2)?.logExtensionEnableEvent(event);
  if (!isTelemetrySdkInitialized())
    return;
  const attributes = {
    ...getCommonAttributes(config2),
    ...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(config2, event) {
  QwenLogger.getInstance(config2)?.logExtensionDisableEvent(event);
  if (!isTelemetrySdkInitialized())
    return;
  const attributes = {
    ...getCommonAttributes(config2),
    ...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(config2, event) {
  QwenLogger.getInstance(config2)?.logAuthEvent(event);
  if (!isTelemetrySdkInitialized())
    return;
  const attributes = {
    ...getCommonAttributes(config2),
    ...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);
}
function logSkillLaunch(config2, event) {
  if (!isTelemetrySdkInitialized())
    return;
  const attributes = {
    ...getCommonAttributes(config2),
    ...event,
    "event.name": EVENT_SKILL_LAUNCH,
    "event.timestamp": (/* @__PURE__ */ new Date()).toISOString()
  };
  const logger6 = import_api_logs.logs.getLogger(SERVICE_NAME);
  const logRecord = {
    body: `Skill launch: ${event.skill_name}. Success: ${event.success}.`,
    attributes
  };
  logger6.emit(logRecord);
}
function logUserFeedback(config2, event) {
  const uiEvent = {
    ...event,
    "event.name": EVENT_USER_FEEDBACK,
    "event.timestamp": (/* @__PURE__ */ new Date()).toISOString()
  };
  uiTelemetryService.addEvent(uiEvent);
  config2.getChatRecordingService()?.recordUiTelemetryEvent(uiEvent);
  QwenLogger.getInstance(config2)?.logUserFeedbackEvent(event);
  if (!isTelemetrySdkInitialized())
    return;
  const attributes = {
    ...getCommonAttributes(config2),
    ...event,
    "event.name": EVENT_USER_FEEDBACK,
    "event.timestamp": (/* @__PURE__ */ new Date()).toISOString()
  };
  const logger6 = import_api_logs.logs.getLogger(SERVICE_NAME);
  const logRecord = {
    body: `User feedback: Rating ${event.rating} for session ${event.session_id}.`,
    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_constants();
    init_metrics2();
    init_qwen_logger();
    init_sdk();
    init_uiTelemetry();
    shouldLogUserPrompts = /* @__PURE__ */ __name((config2) => config2.getTelemetryLogPromptsEnabled(), "shouldLogUserPrompts");
    __name(getCommonAttributes, "getCommonAttributes");
    __name(logStartSession, "logStartSession");
    __name(logUserPrompt, "logUserPrompt");
    __name(logToolCall, "logToolCall");
    __name(logToolOutputTruncated, "logToolOutputTruncated");
    __name(logFileOperation, "logFileOperation");
    __name(logApiRequest, "logApiRequest");
    __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(logExtensionUpdateEvent, "logExtensionUpdateEvent");
    __name(logExtensionEnable, "logExtensionEnable");
    __name(logExtensionDisable, "logExtensionDisable");
    __name(logAuth, "logAuth");
    __name(logSkillLaunch, "logSkillLaunch");
    __name(logUserFeedback, "logUserFeedback");
  }
});

// packages/core/dist/src/utils/quotaErrorDetection.js
function isApiError(error2) {
  return typeof error2 === "object" && error2 !== null && "error" in error2 && typeof error2.error === "object" && "message" in error2.error;
}
function isStructuredError(error2) {
  return typeof error2 === "object" && error2 !== null && "message" in error2 && typeof error2.message === "string";
}
function isQwenQuotaExceededError(error2) {
  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 error2 === "string") {
    return checkMessage(error2);
  }
  if (isStructuredError(error2)) {
    return checkMessage(error2.message);
  }
  if (isApiError(error2)) {
    return checkMessage(error2.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(isQwenQuotaExceededError, "isQwenQuotaExceededError");
  }
});

// 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 i3 = 0;
  let output = "";
  parseMarkdownCodeBlock(["```", "[```", "{```"]);
  const processed = parseValue2();
  if (!processed) {
    throwUnexpectedEnd();
  }
  parseMarkdownCodeBlock(["```", "```]", "```}"]);
  const processedComma = parseCharacter(",");
  if (processedComma) {
    parseWhitespaceAndSkipComments();
  }
  if (isStartOfValue(text[i3]) && endsWithCommaOrNewline(output)) {
    if (!processedComma) {
      output = insertBeforeLastWhitespace(output, ",");
    }
    parseNewlineDelimitedJSON();
  } else if (processedComma) {
    output = stripLastOccurrence(output, ",");
  }
  while (text[i3] === "}" || text[i3] === "]") {
    i3++;
    parseWhitespaceAndSkipComments();
  }
  if (i3 >= 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 = i3;
    let changed = parseWhitespace(skipNewline);
    do {
      changed = parseComment();
      if (changed) {
        changed = parseWhitespace(skipNewline);
      }
    } while (changed);
    return i3 > start;
  }
  __name(parseWhitespaceAndSkipComments, "parseWhitespaceAndSkipComments");
  function parseWhitespace(skipNewline) {
    const _isWhiteSpace = skipNewline ? isWhitespace : isWhitespaceExceptNewline;
    let whitespace = "";
    while (true) {
      if (_isWhiteSpace(text, i3)) {
        whitespace += text[i3];
        i3++;
      } else if (isSpecialWhitespace(text, i3)) {
        whitespace += " ";
        i3++;
      } else {
        break;
      }
    }
    if (whitespace.length > 0) {
      output += whitespace;
      return true;
    }
    return false;
  }
  __name(parseWhitespace, "parseWhitespace");
  function parseComment() {
    if (text[i3] === "/" && text[i3 + 1] === "*") {
      while (i3 < text.length && !atEndOfBlockComment(text, i3)) {
        i3++;
      }
      i3 += 2;
      return true;
    }
    if (text[i3] === "/" && text[i3 + 1] === "/") {
      while (i3 < text.length && text[i3] !== "\n") {
        i3++;
      }
      return true;
    }
    return false;
  }
  __name(parseComment, "parseComment");
  function parseMarkdownCodeBlock(blocks) {
    if (skipMarkdownCodeBlock(blocks)) {
      if (isFunctionNameCharStart(text[i3])) {
        while (i3 < text.length && isFunctionNameChar(text[i3])) {
          i3++;
        }
      }
      parseWhitespaceAndSkipComments();
      return true;
    }
    return false;
  }
  __name(parseMarkdownCodeBlock, "parseMarkdownCodeBlock");
  function skipMarkdownCodeBlock(blocks) {
    parseWhitespace(true);
    for (const block2 of blocks) {
      const end = i3 + block2.length;
      if (text.slice(i3, end) === block2) {
        i3 = end;
        return true;
      }
    }
    return false;
  }
  __name(skipMarkdownCodeBlock, "skipMarkdownCodeBlock");
  function parseCharacter(char) {
    if (text[i3] === char) {
      output += text[i3];
      i3++;
      return true;
    }
    return false;
  }
  __name(parseCharacter, "parseCharacter");
  function skipCharacter(char) {
    if (text[i3] === char) {
      i3++;
      return true;
    }
    return false;
  }
  __name(skipCharacter, "skipCharacter");
  function skipEscapeCharacter() {
    return skipCharacter("\\");
  }
  __name(skipEscapeCharacter, "skipEscapeCharacter");
  function skipEllipsis() {
    parseWhitespaceAndSkipComments();
    if (text[i3] === "." && text[i3 + 1] === "." && text[i3 + 2] === ".") {
      i3 += 3;
      parseWhitespaceAndSkipComments();
      skipCharacter(",");
      return true;
    }
    return false;
  }
  __name(skipEllipsis, "skipEllipsis");
  function parseObject() {
    if (text[i3] === "{") {
      output += "{";
      i3++;
      parseWhitespaceAndSkipComments();
      if (skipCharacter(",")) {
        parseWhitespaceAndSkipComments();
      }
      let initial = true;
      while (i3 < text.length && text[i3] !== "}") {
        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[i3] === "}" || text[i3] === "{" || text[i3] === "]" || text[i3] === "[" || text[i3] === void 0) {
            output = stripLastOccurrence(output, ",");
          } else {
            throwObjectKeyExpected();
          }
          break;
        }
        parseWhitespaceAndSkipComments();
        const processedColon = parseCharacter(":");
        const truncatedText = i3 >= text.length;
        if (!processedColon) {
          if (isStartOfValue(text[i3]) || truncatedText) {
            output = insertBeforeLastWhitespace(output, ":");
          } else {
            throwColonExpected();
          }
        }
        const processedValue = parseValue2();
        if (!processedValue) {
          if (processedColon || truncatedText) {
            output += "null";
          } else {
            throwColonExpected();
          }
        }
      }
      if (text[i3] === "}") {
        output += "}";
        i3++;
      } else {
        output = insertBeforeLastWhitespace(output, "}");
      }
      return true;
    }
    return false;
  }
  __name(parseObject, "parseObject");
  function parseArray() {
    if (text[i3] === "[") {
      output += "[";
      i3++;
      parseWhitespaceAndSkipComments();
      if (skipCharacter(",")) {
        parseWhitespaceAndSkipComments();
      }
      let initial = true;
      while (i3 < text.length && text[i3] !== "]") {
        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[i3] === "]") {
        output += "]";
        i3++;
      } 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[i3] === "\\";
    if (skipEscapeChars) {
      i3++;
      skipEscapeChars = true;
    }
    if (isQuote(text[i3])) {
      const isEndQuote = isDoubleQuote(text[i3]) ? isDoubleQuote : isSingleQuote(text[i3]) ? isSingleQuote : isSingleQuoteLike(text[i3]) ? isSingleQuoteLike : isDoubleQuoteLike;
      const iBefore = i3;
      const oBefore = output.length;
      let str2 = '"';
      i3++;
      while (true) {
        if (i3 >= text.length) {
          const iPrev = prevNonWhitespaceIndex(i3 - 1);
          if (!stopAtDelimiter && isDelimiter(text.charAt(iPrev))) {
            i3 = iBefore;
            output = output.substring(0, oBefore);
            return parseString(true);
          }
          str2 = insertBeforeLastWhitespace(str2, '"');
          output += str2;
          return true;
        }
        if (i3 === stopAtIndex) {
          str2 = insertBeforeLastWhitespace(str2, '"');
          output += str2;
          return true;
        }
        if (isEndQuote(text[i3])) {
          const iQuote = i3;
          const oQuote = str2.length;
          str2 += '"';
          i3++;
          output += str2;
          parseWhitespaceAndSkipComments(false);
          if (stopAtDelimiter || i3 >= text.length || isDelimiter(text[i3]) || isQuote(text[i3]) || isDigit2(text[i3])) {
            parseConcatenatedString();
            return true;
          }
          const iPrevChar = prevNonWhitespaceIndex(iQuote - 1);
          const prevChar = text.charAt(iPrevChar);
          if (prevChar === ",") {
            i3 = iBefore;
            output = output.substring(0, oBefore);
            return parseString(false, iPrevChar);
          }
          if (isDelimiter(prevChar)) {
            i3 = iBefore;
            output = output.substring(0, oBefore);
            return parseString(true);
          }
          output = output.substring(0, oBefore);
          i3 = iQuote + 1;
          str2 = `${str2.substring(0, oQuote)}\\${str2.substring(oQuote)}`;
        } else if (stopAtDelimiter && isUnquotedStringDelimiter(text[i3])) {
          if (text[i3 - 1] === ":" && regexUrlStart.test(text.substring(iBefore + 1, i3 + 2))) {
            while (i3 < text.length && regexUrlChar.test(text[i3])) {
              str2 += text[i3];
              i3++;
            }
          }
          str2 = insertBeforeLastWhitespace(str2, '"');
          output += str2;
          parseConcatenatedString();
          return true;
        } else if (text[i3] === "\\") {
          const char = text.charAt(i3 + 1);
          const escapeChar = escapeCharacters[char];
          if (escapeChar !== void 0) {
            str2 += text.slice(i3, i3 + 2);
            i3 += 2;
          } else if (char === "u") {
            let j2 = 2;
            while (j2 < 6 && isHex(text[i3 + j2])) {
              j2++;
            }
            if (j2 === 6) {
              str2 += text.slice(i3, i3 + 6);
              i3 += 6;
            } else if (i3 + j2 >= text.length) {
              i3 = text.length;
            } else {
              throwInvalidUnicodeCharacter();
            }
          } else {
            str2 += char;
            i3 += 2;
          }
        } else {
          const char = text.charAt(i3);
          if (char === '"' && text[i3 - 1] !== "\\") {
            str2 += `\\${char}`;
            i3++;
          } else if (isControlCharacter(char)) {
            str2 += controlCharacters[char];
            i3++;
          } else {
            if (!isValidStringCharacter(char)) {
              throwInvalidCharacter(char);
            }
            str2 += char;
            i3++;
          }
        }
        if (skipEscapeChars) {
          skipEscapeCharacter();
        }
      }
    }
    return false;
  }
  __name(parseString, "parseString");
  function parseConcatenatedString() {
    let processed2 = false;
    parseWhitespaceAndSkipComments();
    while (text[i3] === "+") {
      processed2 = true;
      i3++;
      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 = i3;
    if (text[i3] === "-") {
      i3++;
      if (atEndOfNumber()) {
        repairNumberEndingWithNumericSymbol(start);
        return true;
      }
      if (!isDigit2(text[i3])) {
        i3 = start;
        return false;
      }
    }
    while (isDigit2(text[i3])) {
      i3++;
    }
    if (text[i3] === ".") {
      i3++;
      if (atEndOfNumber()) {
        repairNumberEndingWithNumericSymbol(start);
        return true;
      }
      if (!isDigit2(text[i3])) {
        i3 = start;
        return false;
      }
      while (isDigit2(text[i3])) {
        i3++;
      }
    }
    if (text[i3] === "e" || text[i3] === "E") {
      i3++;
      if (text[i3] === "-" || text[i3] === "+") {
        i3++;
      }
      if (atEndOfNumber()) {
        repairNumberEndingWithNumericSymbol(start);
        return true;
      }
      if (!isDigit2(text[i3])) {
        i3 = start;
        return false;
      }
      while (isDigit2(text[i3])) {
        i3++;
      }
    }
    if (!atEndOfNumber()) {
      i3 = start;
      return false;
    }
    if (i3 > start) {
      const num = text.slice(start, i3);
      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(i3, i3 + name3.length) === name3) {
      output += value;
      i3 += name3.length;
      return true;
    }
    return false;
  }
  __name(parseKeyword, "parseKeyword");
  function parseUnquotedString(isKey) {
    const start = i3;
    if (isFunctionNameCharStart(text[i3])) {
      while (i3 < text.length && isFunctionNameChar(text[i3])) {
        i3++;
      }
      let j2 = i3;
      while (isWhitespace(text, j2)) {
        j2++;
      }
      if (text[j2] === "(") {
        i3 = j2 + 1;
        parseValue2();
        if (text[i3] === ")") {
          i3++;
          if (text[i3] === ";") {
            i3++;
          }
        }
        return true;
      }
    }
    while (i3 < text.length && !isUnquotedStringDelimiter(text[i3]) && !isQuote(text[i3]) && (!isKey || text[i3] !== ":")) {
      i3++;
    }
    if (text[i3 - 1] === ":" && regexUrlStart.test(text.substring(start, i3 + 2))) {
      while (i3 < text.length && regexUrlChar.test(text[i3])) {
        i3++;
      }
    }
    if (i3 > start) {
      while (isWhitespace(text, i3 - 1) && i3 > 0) {
        i3--;
      }
      const symbol = text.slice(start, i3);
      output += symbol === "undefined" ? "null" : JSON.stringify(symbol);
      if (text[i3] === '"') {
        i3++;
      }
      return true;
    }
  }
  __name(parseUnquotedString, "parseUnquotedString");
  function parseRegex() {
    if (text[i3] === "/") {
      const start = i3;
      i3++;
      while (i3 < text.length && (text[i3] !== "/" || text[i3 - 1] === "\\")) {
        i3++;
      }
      i3++;
      output += `"${text.substring(start, i3)}"`;
      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 i3 >= text.length || isDelimiter(text[i3]) || isWhitespace(text, i3);
  }
  __name(atEndOfNumber, "atEndOfNumber");
  function repairNumberEndingWithNumericSymbol(start) {
    output += `${text.slice(start, i3)}0`;
  }
  __name(repairNumberEndingWithNumericSymbol, "repairNumberEndingWithNumericSymbol");
  function throwInvalidCharacter(char) {
    throw new JSONRepairError(`Invalid character ${JSON.stringify(char)}`, i3);
  }
  __name(throwInvalidCharacter, "throwInvalidCharacter");
  function throwUnexpectedCharacter() {
    throw new JSONRepairError(`Unexpected character ${JSON.stringify(text[i3])}`, i3);
  }
  __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", i3);
  }
  __name(throwObjectKeyExpected, "throwObjectKeyExpected");
  function throwColonExpected() {
    throw new JSONRepairError("Colon expected", i3);
  }
  __name(throwColonExpected, "throwColonExpected");
  function throwInvalidUnicodeCharacter() {
    const chars = text.slice(i3, i3 + 6);
    throw new JSONRepairError(`Invalid unicode character "${chars}"`, i3);
  }
  __name(throwInvalidUnicodeCharacter, "throwInvalidUnicodeCharacter");
}
function atEndOfBlockComment(text, i3) {
  return text[i3] === "*" && text[i3 + 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 (error2) {
    try {
      const repairedJson = jsonrepair(jsonString);
      return JSON.parse(repairedJson);
    } catch (repairError) {
      debugLogger4.error("Failed to parse JSON even with jsonrepair:", {
        originalError: error2,
        repairError,
        jsonString
      });
      return fallbackValue;
    }
  }
}
var debugLogger4;
var init_safeJsonParse = __esm({
  "packages/core/dist/src/utils/safeJsonParse.js"() {
    "use strict";
    init_esbuild_shims();
    init_esm4();
    init_debugLogger();
    debugLogger4 = createDebugLogger("JSON_PARSE");
    __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 (e4) {
            if (inString) {
              try {
                const repaired = JSON.parse(newBuffer + '"');
                return {
                  complete: true,
                  value: repaired,
                  repaired: true
                };
              } catch {
              }
            }
            return {
              complete: false,
              error: e4 instanceof Error ? e4 : new Error(String(e4))
            };
          }
        }
        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/utils/schemaConverter.js
function convertSchema(schema, mode = "auto") {
  if (mode === "openapi_30") {
    return toOpenAPI30(schema);
  }
  return schema;
}
function toOpenAPI30(schema) {
  const convert2 = /* @__PURE__ */ __name((obj) => {
    if (typeof obj !== "object" || obj === null) {
      return obj;
    }
    if (Array.isArray(obj)) {
      return obj.map(convert2);
    }
    const source2 = obj;
    const target = {};
    if (Array.isArray(source2["type"])) {
      const types7 = source2["type"];
      if (types7.length === 2 && types7.includes("null")) {
        target["type"] = types7.find((t5) => t5 !== "null");
        target["nullable"] = true;
      } else {
        target["type"] = types7[0];
      }
    } else if (source2["type"] !== void 0) {
      target["type"] = source2["type"];
    }
    if (source2["const"] !== void 0) {
      target["enum"] = [source2["const"]];
      delete target["const"];
    }
    if (typeof source2["exclusiveMinimum"] === "number") {
      target["minimum"] = source2["exclusiveMinimum"];
      target["exclusiveMinimum"] = true;
    }
    if (typeof source2["exclusiveMaximum"] === "number") {
      target["maximum"] = source2["exclusiveMaximum"];
      target["exclusiveMaximum"] = true;
    }
    if (Array.isArray(source2["items"])) {
      delete target["items"];
    } else if (typeof source2["items"] === "object" && source2["items"] !== null) {
      target["items"] = convert2(source2["items"]);
    }
    if (Array.isArray(source2["enum"])) {
      target["enum"] = source2["enum"].map(String);
    }
    for (const [key, value] of Object.entries(source2)) {
      if (key === "type" || key === "const" || key === "exclusiveMinimum" || key === "exclusiveMaximum" || key === "items" || key === "enum" || key === "$schema" || key === "$id" || key === "default" || // Optional: Gemini sometimes complains about defaults conflicting with types
      key === "dependencies" || key === "patternProperties") {
        continue;
      }
      target[key] = convert2(value);
    }
    return target;
  }, "convert");
  return convert2(schema);
}
var init_schemaConverter = __esm({
  "packages/core/dist/src/utils/schemaConverter.js"() {
    "use strict";
    init_esbuild_shims();
    __name(convertSchema, "convertSchema");
    __name(toOpenAPI30, "toOpenAPI30");
  }
});

// packages/core/dist/src/core/openaiContentGenerator/converter.js
var OpenAIContentConverter;
var init_converter = __esm({
  "packages/core/dist/src/core/openaiContentGenerator/converter.js"() {
    "use strict";
    init_esbuild_shims();
    init_node();
    init_safeJsonParse();
    init_streamingToolCallParser();
    init_schemaConverter();
    OpenAIContentConverter = class {
      static {
        __name(this, "OpenAIContentConverter");
      }
      model;
      schemaCompliance;
      streamingToolCallParser = new StreamingToolCallParser();
      constructor(model, schemaCompliance = "auto") {
        this.model = model;
        this.schemaCompliance = schemaCompliance;
      }
      /**
       * Update the model used for response metadata (modelVersion/logging) and any
       * model-specific conversion behavior.
       */
      setModel(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) {
                  const paramsCopy = {
                    ...func.parametersJsonSchema
                  };
                  parameters = paramsCopy;
                } else if (func.parameters) {
                  parameters = this.convertGeminiToolParametersToOpenAI(func.parameters);
                }
                if (parameters) {
                  parameters = convertSchema(parameters, this.schemaCompliance);
                }
                openAITools.push({
                  type: "function",
                  function: {
                    name: func.name,
                    description: func.description,
                    parameters
                  }
                });
              }
            }
          }
        }
        return openAITools;
      }
      /**
       * Convert Gemini request to OpenAI message format
       */
      convertGeminiRequestToOpenAI(request4, options2 = { cleanOrphanToolCalls: true }) {
        let messages = [];
        this.addSystemInstructionMessage(request4, messages);
        this.processContents(request4.contents, messages);
        if (options2.cleanOrphanToolCalls) {
          messages = this.cleanOrphanedToolCalls(messages);
        }
        messages = this.mergeConsecutiveAssistantMessages(messages);
        return messages;
      }
      /**
       * Convert Gemini response to OpenAI completion format (for logging).
       */
      convertGeminiResponseToOpenAI(response) {
        const candidate = response.candidates?.[0];
        const parts = candidate?.content?.parts || [];
        const thoughtParts = [];
        const contentParts = [];
        const toolCalls = [];
        let toolCallIndex = 0;
        for (const part of parts) {
          if (typeof part === "string") {
            contentParts.push(part);
          } else if ("text" in part && part.text) {
            if ("thought" in part && part.thought) {
              thoughtParts.push(part.text);
            } else {
              contentParts.push(part.text);
            }
          } else if ("functionCall" in part && part.functionCall) {
            toolCalls.push({
              id: part.functionCall.id || `call_${toolCallIndex}`,
              type: "function",
              function: {
                name: part.functionCall.name || "",
                arguments: JSON.stringify(part.functionCall.args || {})
              }
            });
            toolCallIndex += 1;
          }
        }
        const message = {
          role: "assistant",
          content: contentParts.join("") || null,
          refusal: null
        };
        const reasoningContent = thoughtParts.join("");
        if (reasoningContent) {
          message.reasoning_content = reasoningContent;
        }
        if (toolCalls.length > 0) {
          message.tool_calls = toolCalls;
        }
        const finishReason = this.mapGeminiFinishReasonToOpenAI(candidate?.finishReason);
        const usageMetadata = response.usageMetadata;
        const usage2 = {
          prompt_tokens: usageMetadata?.promptTokenCount || 0,
          completion_tokens: usageMetadata?.candidatesTokenCount || 0,
          total_tokens: usageMetadata?.totalTokenCount || 0
        };
        if (usageMetadata?.cachedContentTokenCount !== void 0) {
          usage2.prompt_tokens_details = {
            cached_tokens: usageMetadata.cachedContentTokenCount
          };
        }
        const createdMs = response.createTime ? Number(response.createTime) : Date.now();
        const createdSeconds = Number.isFinite(createdMs) ? Math.floor(createdMs / 1e3) : Math.floor(Date.now() / 1e3);
        return {
          id: response.responseId || `gemini-${Date.now()}`,
          object: "chat.completion",
          created: createdSeconds,
          model: response.modelVersion || this.model,
          choices: [
            {
              index: 0,
              message,
              finish_reason: finishReason,
              logprobs: null
            }
          ],
          usage: usage2
        };
      }
      /**
       * 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 parts = content.parts || [];
        const role = content.role === "model" ? "assistant" : "user";
        const contentParts = [];
        const reasoningParts = [];
        const toolCalls = [];
        let toolCallIndex = 0;
        for (const part of parts) {
          if (typeof part === "string") {
            contentParts.push({ type: "text", text: part });
            continue;
          }
          if ("text" in part && "thought" in part && part.thought) {
            if (role === "assistant" && part.text) {
              reasoningParts.push(part.text);
            }
          }
          if ("text" in part && part.text && !("thought" in part && part.thought)) {
            contentParts.push({ type: "text", text: part.text });
          }
          const mediaPart = this.createMediaContentPart(part);
          if (mediaPart && role === "user") {
            contentParts.push(mediaPart);
          }
          if ("functionCall" in part && part.functionCall && role === "assistant") {
            toolCalls.push({
              id: part.functionCall.id || `call_${toolCallIndex}`,
              type: "function",
              function: {
                name: part.functionCall.name || "",
                arguments: JSON.stringify(part.functionCall.args || {})
              }
            });
            toolCallIndex += 1;
          }
          if (part.functionResponse && role === "user") {
            const toolMessage = this.createToolMessage(part.functionResponse);
            if (toolMessage) {
              messages.push(toolMessage);
            }
          }
        }
        if (role === "assistant") {
          if (contentParts.length === 0 && toolCalls.length === 0 && reasoningParts.length === 0) {
            return;
          }
          const assistantTextContent = contentParts.filter((part) => part.type === "text").map((part) => part.text).join("");
          const assistantMessage = {
            role: "assistant",
            content: assistantTextContent || null
          };
          if (toolCalls.length > 0) {
            assistantMessage.tool_calls = toolCalls;
          }
          const reasoningContent = reasoningParts.join("");
          if (reasoningContent) {
            assistantMessage.reasoning_content = reasoningContent;
          }
          messages.push(assistantMessage);
          return;
        }
        if (contentParts.length > 0) {
          messages.push({
            role: "user",
            content: contentParts
          });
        }
      }
      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 error2 = responseObject["error"];
          if (typeof error2 === "string") {
            return error2;
          }
        }
        try {
          const serialized = JSON.stringify(response);
          return serialized ?? String(response);
        } catch {
          return String(response);
        }
      }
      /**
       * Create a tool message from function response (with embedded media parts)
       */
      createToolMessage(response) {
        const textContent2 = this.extractFunctionResponseContent(response.response);
        const contentParts = [];
        if (textContent2) {
          contentParts.push({ type: "text", text: textContent2 });
        }
        for (const part of response.parts || []) {
          const mediaPart = this.createMediaContentPart(part);
          if (mediaPart) {
            contentParts.push(mediaPart);
          }
        }
        if (contentParts.length === 0) {
          return {
            role: "tool",
            tool_call_id: response.id || "",
            content: ""
          };
        }
        return {
          role: "tool",
          tool_call_id: response.id || "",
          content: contentParts
        };
      }
      /**
       * Create OpenAI media content part from Gemini part
       */
      createMediaContentPart(part) {
        if (part.inlineData?.mimeType && part.inlineData?.data) {
          const mimeType = part.inlineData.mimeType;
          const mediaType = this.getMediaType(mimeType);
          if (mediaType === "image") {
            const dataUrl = `data:${mimeType};base64,${part.inlineData.data}`;
            return {
              type: "image_url",
              image_url: { url: dataUrl }
            };
          }
          if (mimeType === "application/pdf") {
            const filename = part.inlineData.displayName || "document.pdf";
            return {
              type: "file",
              file: {
                filename,
                file_data: `data:${mimeType};base64,${part.inlineData.data}`
              }
            };
          }
          if (mediaType === "audio") {
            const format4 = this.getAudioFormat(mimeType);
            if (format4) {
              return {
                type: "input_audio",
                input_audio: {
                  data: `data:${mimeType};base64,${part.inlineData.data}`,
                  format: format4
                }
              };
            }
          }
          if (mediaType === "video") {
            return {
              type: "video_url",
              video_url: {
                url: `data:${mimeType};base64,${part.inlineData.data}`
              }
            };
          }
          const displayName = part.inlineData.displayName ? ` (${part.inlineData.displayName})` : "";
          return {
            type: "text",
            text: `Unsupported inline media type: ${mimeType}${displayName}.`
          };
        }
        if (part.fileData?.mimeType && part.fileData?.fileUri) {
          const filename = part.fileData.displayName || "file";
          const fileUri = part.fileData.fileUri;
          const mimeType = part.fileData.mimeType;
          const mediaType = this.getMediaType(mimeType);
          if (mediaType === "image") {
            return {
              type: "image_url",
              image_url: { url: fileUri }
            };
          }
          if (mimeType === "application/pdf") {
            return {
              type: "file",
              file: {
                filename,
                file_data: fileUri
              }
            };
          }
          if (mediaType === "video") {
            return {
              type: "video_url",
              video_url: {
                url: fileUri
              }
            };
          }
          const displayName = part.fileData.displayName ? ` (${part.fileData.displayName})` : "";
          return {
            type: "text",
            text: `Unsupported file media type: ${mimeType}${displayName}.`
          };
        }
        return null;
      }
      /**
       * Determine media type from MIME type
       */
      getMediaType(mimeType) {
        if (mimeType.startsWith("image/"))
          return "image";
        if (mimeType.startsWith("audio/"))
          return "audio";
        if (mimeType.startsWith("video/"))
          return "video";
        return "file";
      }
      /**
       * 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 = [];
        const reasoningText = choice2.message.reasoning_content ?? choice2.message.reasoning;
        if (reasoningText) {
          parts.push({ text: reasoningText, thought: true });
        }
        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;
          const thinkingTokens = usage2.completion_tokens_details?.reasoning_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,
            thoughtsTokenCount: thinkingTokens
          };
        }
        return response;
      }
      /**
       * Convert OpenAI stream chunk to Gemini format
       */
      convertOpenAIChunkToGemini(chunk) {
        const choice2 = chunk.choices?.[0];
        const response = new GenerateContentResponse();
        if (choice2) {
          const parts = [];
          const reasoningText = choice2.delta?.reasoning_content ?? choice2.delta?.reasoning;
          if (reasoningText) {
            parts.push({ text: reasoningText, thought: true });
          }
          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 thinkingTokens = usage2.completion_tokens_details?.reasoning_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,
            thoughtsTokenCount: thinkingTokens,
            totalTokenCount: totalTokens,
            cachedContentTokenCount: cachedTokens
          };
        }
        return response;
      }
      /**
       * 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;
      }
      mapGeminiFinishReasonToOpenAI(geminiReason) {
        if (!geminiReason) {
          return "stop";
        }
        switch (geminiReason) {
          case FinishReason.STOP:
            return "stop";
          case FinishReason.MAX_TOKENS:
            return "length";
          case FinishReason.SAFETY:
            return "content_filter";
          default:
            if (geminiReason === "RECITATION") {
              return "content_filter";
            }
            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 lastToolCalls = "tool_calls" in lastMessage ? lastMessage.tool_calls || [] : [];
              const currentToolCalls = "tool_calls" in message ? message.tool_calls || [] : [];
              const lastContent = lastMessage.content;
              const currentContent = message.content;
              const useArrayFormat = Array.isArray(lastContent) || Array.isArray(currentContent);
              let combinedContent;
              if (useArrayFormat) {
                const lastParts = Array.isArray(lastContent) ? lastContent : typeof lastContent === "string" && lastContent ? [{ type: "text", text: lastContent }] : [];
                const currentParts = Array.isArray(currentContent) ? currentContent : typeof currentContent === "string" && currentContent ? [{ type: "text", text: currentContent }] : [];
                combinedContent = [
                  ...lastParts,
                  ...currentParts
                ];
              } else {
                const lastText = typeof lastContent === "string" ? lastContent : "";
                const currentText = typeof currentContent === "string" ? currentContent : "";
                const mergedText = [lastText, currentText].filter(Boolean).join("");
                combinedContent = mergedText || null;
              }
              const combinedToolCalls = [...lastToolCalls, ...currentToolCalls];
              lastMessage.content = combinedContent || null;
              if (combinedToolCalls.length > 0) {
                lastMessage.tool_calls = combinedToolCalls;
              }
              continue;
            }
          }
          merged.push(message);
        }
        return merged;
      }
    };
  }
});

// node_modules/uuid/dist/esm-node/rng.js
import crypto3 from "crypto";
function rng() {
  if (poolPtr > rnds8Pool.length - 16) {
    crypto3.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/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]];
}
var byteToHex;
var init_stringify = __esm({
  "node_modules/uuid/dist/esm-node/stringify.js"() {
    init_esbuild_shims();
    byteToHex = [];
    for (let i3 = 0; i3 < 256; ++i3) {
      byteToHex.push((i3 + 256).toString(16).slice(1));
    }
    __name(unsafeStringify, "unsafeStringify");
  }
});

// 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 i3 = 0; i3 < 16; ++i3) {
      buf[offset + i3] = rnds[i3];
    }
    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/index.js
var init_esm_node = __esm({
  "node_modules/uuid/dist/esm-node/index.js"() {
    init_esbuild_shims();
    init_v4();
  }
});

// packages/core/dist/src/utils/openaiLogger.js
import * as path6 from "node:path";
import { promises as fs9 } from "node:fs";
import * as os4 from "os";
var debugLogger5, OpenAILogger, openaiLogger;
var init_openaiLogger = __esm({
  "packages/core/dist/src/utils/openaiLogger.js"() {
    "use strict";
    init_esbuild_shims();
    init_esm_node();
    init_debugLogger();
    debugLogger5 = createDebugLogger("OPENAI_LOGGER");
    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 = path6.join(os4.homedir(), customLogDir.slice(1));
          } else if (!path6.isAbsolute(customLogDir)) {
            resolvedPath = path6.resolve(process.cwd(), customLogDir);
          }
          this.logDir = path6.normalize(resolvedPath);
        } else {
          this.logDir = path6.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 fs9.mkdir(this.logDir, { recursive: true });
          this.initialized = true;
        } catch (error2) {
          debugLogger5.error("Failed to initialize OpenAI logger:", error2);
          throw new Error(`Failed to initialize OpenAI logger: ${error2}`);
        }
      }
      /**
       * 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, error2) {
        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 = path6.join(this.logDir, filename);
        const logData = {
          timestamp: (/* @__PURE__ */ new Date()).toISOString(),
          request: request4,
          response: response || null,
          error: error2 ? {
            message: error2.message,
            stack: error2.stack
          } : null,
          system: {
            hostname: os4.hostname(),
            platform: os4.platform(),
            release: os4.release(),
            nodeVersion: process.version
          }
        };
        try {
          await fs9.writeFile(filePath, JSON.stringify(logData, null, 2), "utf-8");
          return filePath;
        } catch (writeError) {
          debugLogger5.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 fs9.readdir(this.logDir);
          const logFiles = files.filter((file) => file.startsWith("openai-") && file.endsWith(".json")).map((file) => path6.join(this.logDir, file)).sort().reverse();
          return limit2 ? logFiles.slice(0, limit2) : logFiles;
        } catch (error2) {
          if (error2.code === "ENOENT") {
            return [];
          }
          debugLogger5.error("Failed to read OpenAI log directory:", error2);
          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 fs9.readFile(filePath, "utf-8");
          return JSON.parse(content);
        } catch (error2) {
          debugLogger5.error(`Failed to read log file ${filePath}:`, error2);
          throw new Error(`Failed to read log file: ${error2}`);
        }
      }
    };
    openaiLogger = new OpenAILogger();
  }
});

// packages/core/dist/src/core/loggingContentGenerator/loggingContentGenerator.js
var LoggingContentGenerator;
var init_loggingContentGenerator = __esm({
  "packages/core/dist/src/core/loggingContentGenerator/loggingContentGenerator.js"() {
    "use strict";
    init_esbuild_shims();
    init_node();
    init_types();
    init_loggers();
    init_quotaErrorDetection();
    init_converter();
    init_openaiLogger();
    LoggingContentGenerator = class {
      static {
        __name(this, "LoggingContentGenerator");
      }
      wrapped;
      config;
      openaiLogger;
      schemaCompliance;
      constructor(wrapped, config2, generatorConfig) {
        this.wrapped = wrapped;
        this.config = config2;
        if (generatorConfig.enableOpenAILogging) {
          this.openaiLogger = new OpenAILogger(generatorConfig.openAILoggingDir);
          this.schemaCompliance = generatorConfig.schemaCompliance;
        }
      }
      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.getAuthType(), usageMetadata, responseText));
      }
      _logApiError(responseId, durationMs, error2, model, prompt_id) {
        const errorMessage = error2 instanceof Error ? error2.message : String(error2);
        const errorType = error2?.type || (error2 instanceof Error ? error2.name : "unknown");
        const errorResponseId = error2?.requestID || error2?.request_id || responseId;
        const errorStatus = error2?.code ?? error2?.status ?? (isStructuredError(error2) ? error2.status : void 0);
        logApiError(this.config, new ApiErrorEvent(errorResponseId, model, errorMessage, durationMs, prompt_id, this.config.getAuthType(), errorType, errorStatus));
      }
      async generateContent(req, userPromptId) {
        const startTime = Date.now();
        this.logApiRequest(this.toContents(req.contents), req.model, userPromptId);
        const openaiRequest = await this.buildOpenAIRequestForLogging(req);
        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));
          await this.logOpenAIInteraction(openaiRequest, response);
          return response;
        } catch (error2) {
          const durationMs = Date.now() - startTime;
          this._logApiError(void 0, durationMs, error2, req.model, userPromptId);
          await this.logOpenAIInteraction(openaiRequest, void 0, error2);
          throw error2;
        }
      }
      async generateContentStream(req, userPromptId) {
        const startTime = Date.now();
        this.logApiRequest(this.toContents(req.contents), req.model, userPromptId);
        const openaiRequest = await this.buildOpenAIRequestForLogging(req);
        let stream2;
        try {
          stream2 = await this.wrapped.generateContentStream(req, userPromptId);
        } catch (error2) {
          const durationMs = Date.now() - startTime;
          this._logApiError(void 0, durationMs, error2, req.model, userPromptId);
          await this.logOpenAIInteraction(openaiRequest, void 0, error2);
          throw error2;
        }
        return this.loggingStreamWrapper(stream2, startTime, userPromptId, req.model, openaiRequest);
      }
      async *loggingStreamWrapper(stream2, startTime, userPromptId, model, openaiRequest) {
        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));
          const consolidatedResponse = this.consolidateGeminiResponsesForLogging(responses);
          await this.logOpenAIInteraction(openaiRequest, consolidatedResponse);
        } catch (error2) {
          const durationMs = Date.now() - startTime;
          this._logApiError(void 0, durationMs, error2, responses[0]?.modelVersion || model, userPromptId);
          await this.logOpenAIInteraction(openaiRequest, void 0, error2);
          throw error2;
        }
      }
      async buildOpenAIRequestForLogging(request4) {
        if (!this.openaiLogger) {
          return void 0;
        }
        const converter = new OpenAIContentConverter(request4.model, this.schemaCompliance);
        const messages = converter.convertGeminiRequestToOpenAI(request4, {
          cleanOrphanToolCalls: false
        });
        const openaiRequest = {
          model: request4.model,
          messages
        };
        if (request4.config?.tools) {
          openaiRequest.tools = await converter.convertGeminiToolsToOpenAI(request4.config.tools);
        }
        if (request4.config?.temperature !== void 0) {
          openaiRequest.temperature = request4.config.temperature;
        }
        if (request4.config?.topP !== void 0) {
          openaiRequest.top_p = request4.config.topP;
        }
        if (request4.config?.maxOutputTokens !== void 0) {
          openaiRequest.max_tokens = request4.config.maxOutputTokens;
        }
        if (request4.config?.presencePenalty !== void 0) {
          openaiRequest.presence_penalty = request4.config.presencePenalty;
        }
        if (request4.config?.frequencyPenalty !== void 0) {
          openaiRequest.frequency_penalty = request4.config.frequencyPenalty;
        }
        return openaiRequest;
      }
      async logOpenAIInteraction(openaiRequest, response, error2) {
        if (!this.openaiLogger || !openaiRequest) {
          return;
        }
        const openaiResponse = response ? this.convertGeminiResponseToOpenAIForLogging(response, openaiRequest) : void 0;
        await this.openaiLogger.logInteraction(openaiRequest, openaiResponse, error2 instanceof Error ? error2 : error2 ? new Error(String(error2)) : void 0);
      }
      convertGeminiResponseToOpenAIForLogging(response, openaiRequest) {
        const converter = new OpenAIContentConverter(openaiRequest.model, this.schemaCompliance);
        return converter.convertGeminiResponseToOpenAI(response);
      }
      consolidateGeminiResponsesForLogging(responses) {
        if (responses.length === 0) {
          return void 0;
        }
        const consolidated = new GenerateContentResponse();
        const combinedParts = [];
        const functionCallIndex = /* @__PURE__ */ new Map();
        let finishReason;
        let usageMetadata;
        for (const response of responses) {
          if (response.usageMetadata) {
            usageMetadata = response.usageMetadata;
          }
          const candidate = response.candidates?.[0];
          if (candidate?.finishReason) {
            finishReason = candidate.finishReason;
          }
          const parts = candidate?.content?.parts ?? [];
          for (const part of parts) {
            if (typeof part === "string") {
              combinedParts.push({ text: part });
              continue;
            }
            if ("text" in part) {
              if (part.text) {
                combinedParts.push({
                  text: part.text,
                  ...part.thought ? { thought: true } : {},
                  ...part.thoughtSignature ? { thoughtSignature: part.thoughtSignature } : {}
                });
              }
              continue;
            }
            if ("functionCall" in part && part.functionCall) {
              const callKey = part.functionCall.id || part.functionCall.name || "tool_call";
              const existingIndex = functionCallIndex.get(callKey);
              const functionPart = { functionCall: part.functionCall };
              if (existingIndex !== void 0) {
                combinedParts[existingIndex] = functionPart;
              } else {
                functionCallIndex.set(callKey, combinedParts.length);
                combinedParts.push(functionPart);
              }
              continue;
            }
            if ("functionResponse" in part && part.functionResponse) {
              combinedParts.push({ functionResponse: part.functionResponse });
              continue;
            }
            combinedParts.push(part);
          }
        }
        const lastResponse = responses[responses.length - 1];
        const lastCandidate = lastResponse.candidates?.[0];
        consolidated.responseId = lastResponse.responseId;
        consolidated.createTime = lastResponse.createTime;
        consolidated.modelVersion = lastResponse.modelVersion;
        consolidated.promptFeedback = lastResponse.promptFeedback;
        consolidated.usageMetadata = usageMetadata;
        consolidated.candidates = [
          {
            content: {
              role: lastCandidate?.content?.role || "model",
              parts: combinedParts
            },
            ...finishReason ? { finishReason } : {},
            index: 0,
            safetyRatings: lastCandidate?.safetyRatings || []
          }
        ];
        return consolidated;
      }
      async countTokens(req) {
        return this.wrapped.countTokens(req);
      }
      async embedContent(req) {
        return this.wrapped.embedContent(req);
      }
      useSummarizedThinking() {
        return this.wrapped.useSummarizedThinking();
      }
      toContents(contents) {
        if (Array.isArray(contents)) {
          return contents.map((c4) => this.toContent(c4));
        }
        return [this.toContent(contents)];
      }
      toContent(content) {
        if (Array.isArray(content)) {
          return {
            role: "user",
            parts: this.toParts(content)
          };
        }
        if (typeof content === "string") {
          return {
            role: "user",
            parts: [{ text: content }]
          };
        }
        if ("parts" in content) {
          return {
            ...content,
            parts: content.parts ? this.toParts(content.parts.filter((p2) => p2 != null)) : []
          };
        }
        return {
          role: "user",
          parts: [this.toPart(content)]
        };
      }
      toParts(parts) {
        return parts.map((p2) => this.toPart(p2));
      }
      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;
      }
    };
  }
});

// packages/core/dist/src/core/loggingContentGenerator/index.js
var init_loggingContentGenerator2 = __esm({
  "packages/core/dist/src/core/loggingContentGenerator/index.js"() {
    "use strict";
    init_esbuild_shims();
    init_loggingContentGenerator();
  }
});

// packages/core/dist/src/models/modelConfigErrors.js
function getDefaultApiKeyEnvVar(authType) {
  switch (authType) {
    case "openai":
      return "OPENAI_API_KEY";
    case "anthropic":
      return "ANTHROPIC_API_KEY";
    case "gemini":
      return "GEMINI_API_KEY";
    case "vertex-ai":
      return "GOOGLE_API_KEY";
    default:
      return "API_KEY";
  }
}
function getDefaultModelEnvVar(authType) {
  switch (authType) {
    case "openai":
      return "OPENAI_MODEL";
    case "anthropic":
      return "ANTHROPIC_MODEL";
    case "gemini":
      return "GEMINI_MODEL";
    case "vertex-ai":
      return "GOOGLE_MODEL";
    default:
      return "MODEL";
  }
}
var ModelConfigError, StrictMissingCredentialsError, StrictMissingModelIdError, MissingApiKeyError, MissingModelError, MissingBaseUrlError, MissingAnthropicBaseUrlEnvError;
var init_modelConfigErrors = __esm({
  "packages/core/dist/src/models/modelConfigErrors.js"() {
    "use strict";
    init_esbuild_shims();
    __name(getDefaultApiKeyEnvVar, "getDefaultApiKeyEnvVar");
    __name(getDefaultModelEnvVar, "getDefaultModelEnvVar");
    ModelConfigError = class extends Error {
      static {
        __name(this, "ModelConfigError");
      }
      constructor(message) {
        super(message);
        this.name = new.target.name;
        Object.setPrototypeOf(this, new.target.prototype);
      }
    };
    StrictMissingCredentialsError = class extends ModelConfigError {
      static {
        __name(this, "StrictMissingCredentialsError");
      }
      code = "STRICT_MISSING_CREDENTIALS";
      constructor(authType, model, envKey) {
        const providerKey = authType || "(unknown)";
        const modelName = model || "(unknown)";
        super(`Missing credentials for modelProviders model '${modelName}'. ` + (envKey ? `Current configured envKey: '${envKey}'. Set that environment variable, or update modelProviders.${providerKey}[].envKey.` : `Configure modelProviders.${providerKey}[].envKey and set that environment variable.`));
      }
    };
    StrictMissingModelIdError = class extends ModelConfigError {
      static {
        __name(this, "StrictMissingModelIdError");
      }
      code = "STRICT_MISSING_MODEL_ID";
      constructor(authType) {
        super(`Missing model id for strict modelProviders resolution (authType: ${authType}).`);
      }
    };
    MissingApiKeyError = class extends ModelConfigError {
      static {
        __name(this, "MissingApiKeyError");
      }
      code = "MISSING_API_KEY";
      constructor(params) {
        super(`Missing API key for ${params.authType} auth. Current model: '${params.model || "(unknown)"}', baseUrl: '${params.baseUrl || "(default)"}'. Provide an API key via settings (security.auth.apiKey), or set the environment variable '${params.envKey}'.`);
      }
    };
    MissingModelError = class extends ModelConfigError {
      static {
        __name(this, "MissingModelError");
      }
      code = "MISSING_MODEL";
      constructor(params) {
        super(`Missing model for ${params.authType} auth. Set the environment variable '${params.envKey}'.`);
      }
    };
    MissingBaseUrlError = class extends ModelConfigError {
      static {
        __name(this, "MissingBaseUrlError");
      }
      code = "MISSING_BASE_URL";
      constructor(params) {
        super(`Missing baseUrl for modelProviders model '${params.model || "(unknown)"}'. Configure modelProviders.${params.authType || "(unknown)"}[].baseUrl.`);
      }
    };
    MissingAnthropicBaseUrlEnvError = class extends ModelConfigError {
      static {
        __name(this, "MissingAnthropicBaseUrlEnvError");
      }
      code = "MISSING_ANTHROPIC_BASE_URL_ENV";
      constructor() {
        super("ANTHROPIC_BASE_URL environment variable not found.");
      }
    };
  }
});

// packages/core/dist/src/config/models.js
var DEFAULT_QWEN_MODEL, DEFAULT_QWEN_FLASH_MODEL, DEFAULT_QWEN_EMBEDDING_MODEL, MAINLINE_CODER_MODEL;
var init_models = __esm({
  "packages/core/dist/src/config/models.js"() {
    "use strict";
    init_esbuild_shims();
    DEFAULT_QWEN_MODEL = "coder-model";
    DEFAULT_QWEN_FLASH_MODEL = "coder-model";
    DEFAULT_QWEN_EMBEDDING_MODEL = "text-embedding-v4";
    MAINLINE_CODER_MODEL = "qwen3.5-plus";
  }
});

// packages/core/dist/src/core/tokenLimits.js
function normalize2(model) {
  let s5 = (model ?? "").toLowerCase().trim();
  s5 = s5.replace(/^.*\//, "");
  s5 = s5.split("|").pop() ?? s5;
  s5 = s5.split(":").pop() ?? s5;
  s5 = s5.replace(/\s+/g, "-");
  s5 = s5.replace(/-preview/g, "");
  if (!s5.match(/^qwen-(?:plus|flash|vl-max)-latest$/) && !s5.match(/^kimi-k2-\d{4}$/)) {
    s5 = s5.replace(/-(?:\d{4,}|\d+x\d+b|v\d+(?:\.\d+)*|(?<=-[^-]+-)\d+(?:\.\d+)+|latest|exp)$/g, "");
  }
  s5 = s5.replace(/-(?:\d?bit|int[48]|bf16|fp16|q[45]|quantized)$/g, "");
  return s5;
}
function tokenLimit(model, type = "input") {
  const norm = normalize2(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(normalize2, "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
      // Commercial Qwen3.5-Plus: 1M token context
      [/^qwen3\.5-plus(-.*)?$/, LIMITS["1m"]],
      // catches "qwen3.5-plus" and date variants
      // Generic coder-model: same as qwen3.5-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"]],
      // -------------------
      // 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
      [/^glm-4\.7(?:-.*)?$/, LIMITS["200k"]],
      // -------------------
      // DeepSeek
      // -------------------
      [/^deepseek(?:-.*)?$/, LIMITS["128k"]],
      // -------------------
      // Moonshot / Kimi
      // -------------------
      [/^kimi-2\.5.*$/, LIMITS["256k"]],
      // Kimi-2.5: 256K context
      [/^kimi-k2.*$/, LIMITS["256k"]],
      // Kimi-k2 variants: 256K context
      // -------------------
      // GPT-OSS / Llama & Mistral examples
      // -------------------
      [/^gpt-oss.*$/, LIMITS["128k"]],
      [/^llama-4-scout.*$/, LIMITS["10m"]],
      [/^mistral-large-2.*$/, LIMITS["128k"]],
      // -------------------
      // MiniMax
      // -------------------
      [/^minimax-m2\.1.*$/i, LIMITS["200k"]]
      // MiniMax-M2.1: 200K context
    ];
    OUTPUT_PATTERNS = [
      // -------------------
      // Alibaba / Qwen - DashScope Models
      // -------------------
      // Qwen3-Coder-Plus: 65,536 max output tokens
      [/^qwen3-coder-plus(-.*)?$/, LIMITS["64k"]],
      // Qwen3.5-Plus: 65,536 max output tokens
      [/^qwen3\.5-plus(-.*)?$/, LIMITS["64k"]],
      // Generic coder-model: same as qwen3.5-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"]],
      // 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/constants.js
var DEFAULT_TIMEOUT, DEFAULT_MAX_RETRIES, DEFAULT_OPENAI_BASE_URL, 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_OPENAI_BASE_URL = "https://api.openai.com/v1";
    DEFAULT_DASHSCOPE_BASE_URL = "https://dashscope.aliyuncs.com/compatible-mode/v1";
  }
});

// packages/core/dist/src/models/types.js
var init_types4 = __esm({
  "packages/core/dist/src/models/types.js"() {
    "use strict";
    init_esbuild_shims();
  }
});

// packages/core/dist/src/models/constants.js
var MODEL_GENERATION_CONFIG_FIELDS, CREDENTIAL_FIELDS, PROVIDER_SOURCED_FIELDS, AUTH_ENV_MAPPINGS, DEFAULT_MODELS, QWEN_OAUTH_MODELS, QWEN_OAUTH_ALLOWED_MODELS;
var init_constants3 = __esm({
  "packages/core/dist/src/models/constants.js"() {
    "use strict";
    init_esbuild_shims();
    init_models();
    MODEL_GENERATION_CONFIG_FIELDS = [
      "samplingParams",
      "timeout",
      "maxRetries",
      "enableCacheControl",
      "schemaCompliance",
      "reasoning",
      "contextWindowSize",
      "customHeaders",
      "extra_body"
    ];
    CREDENTIAL_FIELDS = [
      "model",
      "apiKey",
      "apiKeyEnvKey",
      "baseUrl"
    ];
    PROVIDER_SOURCED_FIELDS = [
      ...CREDENTIAL_FIELDS,
      ...MODEL_GENERATION_CONFIG_FIELDS
    ];
    AUTH_ENV_MAPPINGS = {
      openai: {
        apiKey: ["OPENAI_API_KEY"],
        baseUrl: ["OPENAI_BASE_URL"],
        model: ["OPENAI_MODEL", "QWEN_MODEL"]
      },
      anthropic: {
        apiKey: ["ANTHROPIC_API_KEY"],
        baseUrl: ["ANTHROPIC_BASE_URL"],
        model: ["ANTHROPIC_MODEL"]
      },
      gemini: {
        apiKey: ["GEMINI_API_KEY"],
        baseUrl: [],
        model: ["GEMINI_MODEL"]
      },
      "vertex-ai": {
        apiKey: ["GOOGLE_API_KEY"],
        baseUrl: [],
        model: ["GOOGLE_MODEL"]
      },
      "qwen-oauth": {
        apiKey: [],
        baseUrl: [],
        model: []
      }
    };
    DEFAULT_MODELS = {
      openai: MAINLINE_CODER_MODEL,
      "qwen-oauth": DEFAULT_QWEN_MODEL
    };
    QWEN_OAUTH_MODELS = [
      {
        id: "coder-model",
        name: "coder-model",
        description: "Qwen 3.5 Plus \u2014 efficient hybrid model with leading coding performance",
        capabilities: { vision: true }
      }
    ];
    QWEN_OAUTH_ALLOWED_MODELS = QWEN_OAUTH_MODELS.map((model) => model.id);
  }
});

// packages/core/dist/src/models/modelRegistry.js
function validateAuthTypeKey(key) {
  if (Object.values(AuthType2).includes(key)) {
    return key;
  }
  return void 0;
}
var debugLogger6, ModelRegistry;
var init_modelRegistry = __esm({
  "packages/core/dist/src/models/modelRegistry.js"() {
    "use strict";
    init_esbuild_shims();
    init_contentGenerator();
    init_constants2();
    init_types4();
    init_models();
    init_constants3();
    init_debugLogger();
    init_constants3();
    debugLogger6 = createDebugLogger("MODEL_REGISTRY");
    __name(validateAuthTypeKey, "validateAuthTypeKey");
    ModelRegistry = class {
      static {
        __name(this, "ModelRegistry");
      }
      modelsByAuthType;
      getDefaultBaseUrl(authType) {
        switch (authType) {
          case AuthType2.QWEN_OAUTH:
            return "DYNAMIC_QWEN_OAUTH_BASE_URL";
          case AuthType2.USE_OPENAI:
            return DEFAULT_OPENAI_BASE_URL;
          default:
            return "";
        }
      }
      constructor(modelProvidersConfig) {
        this.modelsByAuthType = /* @__PURE__ */ new Map();
        this.registerAuthTypeModels(AuthType2.QWEN_OAUTH, QWEN_OAUTH_MODELS);
        if (modelProvidersConfig) {
          for (const [rawKey, models] of Object.entries(modelProvidersConfig)) {
            const authType = validateAuthTypeKey(rawKey);
            if (!authType) {
              debugLogger6.warn(`Invalid authType key "${rawKey}" in modelProviders config. Expected one of: ${Object.values(AuthType2).join(", ")}. Skipping.`);
              continue;
            }
            if (authType === AuthType2.QWEN_OAUTH) {
              continue;
            }
            this.registerAuthTypeModels(authType, models);
          }
        }
      }
      /**
       * Register models for an authType.
       * If multiple models have the same id, the first one takes precedence.
       */
      registerAuthTypeModels(authType, models) {
        const modelMap = /* @__PURE__ */ new Map();
        for (const config2 of models) {
          if (modelMap.has(config2.id)) {
            debugLogger6.warn(`Duplicate model id "${config2.id}" for authType "${authType}". Using the first registered config.`);
            continue;
          }
          const resolved = this.resolveModelConfig(config2, authType);
          modelMap.set(config2.id, resolved);
        }
        this.modelsByAuthType.set(authType, modelMap);
      }
      /**
       * Get all models for a specific authType.
       * This is used by /model command to show only relevant models.
       */
      getModelsForAuthType(authType) {
        const models = this.modelsByAuthType.get(authType);
        if (!models)
          return [];
        return Array.from(models.values()).map((model) => ({
          id: model.id,
          label: model.name,
          description: model.description,
          capabilities: model.capabilities,
          authType: model.authType,
          isVision: model.capabilities?.vision ?? false,
          contextWindowSize: model.generationConfig.contextWindowSize
        }));
      }
      /**
       * Get model configuration by authType and modelId
       */
      getModel(authType, modelId) {
        const models = this.modelsByAuthType.get(authType);
        return models?.get(modelId);
      }
      /**
       * Check if model exists for given authType
       */
      hasModel(authType, modelId) {
        const models = this.modelsByAuthType.get(authType);
        return models?.has(modelId) ?? false;
      }
      /**
       * Get default model for an authType.
       * For qwen-oauth, returns the coder model.
       * For others, returns the first configured model.
       */
      getDefaultModelForAuthType(authType) {
        if (authType === AuthType2.QWEN_OAUTH) {
          return this.getModel(authType, DEFAULT_QWEN_MODEL);
        }
        const models = this.modelsByAuthType.get(authType);
        if (!models || models.size === 0)
          return void 0;
        return Array.from(models.values())[0];
      }
      /**
       * Resolve model config by applying defaults
       */
      resolveModelConfig(config2, authType) {
        this.validateModelConfig(config2, authType);
        return {
          ...config2,
          authType,
          name: config2.name || config2.id,
          baseUrl: config2.baseUrl || this.getDefaultBaseUrl(authType),
          generationConfig: config2.generationConfig ?? {},
          capabilities: config2.capabilities || {}
        };
      }
      /**
       * Validate model configuration
       */
      validateModelConfig(config2, authType) {
        if (!config2.id) {
          throw new Error(`Model config in authType '${authType}' missing required field: id`);
        }
      }
      /**
       * Reload models from updated configuration.
       * Clears existing user-configured models and re-registers from new config.
       * Preserves hard-coded qwen-oauth models.
       */
      reloadModels(modelProvidersConfig) {
        for (const authType of this.modelsByAuthType.keys()) {
          if (authType !== AuthType2.QWEN_OAUTH) {
            this.modelsByAuthType.delete(authType);
          }
        }
        if (modelProvidersConfig) {
          for (const [rawKey, models] of Object.entries(modelProvidersConfig)) {
            const authType = validateAuthTypeKey(rawKey);
            if (!authType) {
              debugLogger6.warn(`Invalid authType key "${rawKey}" in modelProviders config. Expected one of: ${Object.values(AuthType2).join(", ")}. Skipping.`);
              continue;
            }
            if (authType === AuthType2.QWEN_OAUTH) {
              continue;
            }
            this.registerAuthTypeModels(authType, models);
          }
        }
      }
    };
  }
});

// packages/core/dist/src/models/modelsConfig.js
import process2 from "node:process";
var ModelsConfig;
var init_modelsConfig = __esm({
  "packages/core/dist/src/models/modelsConfig.js"() {
    "use strict";
    init_esbuild_shims();
    init_contentGenerator();
    init_models();
    init_tokenLimits();
    init_modelRegistry();
    init_types4();
    init_constants3();
    ModelsConfig = class _ModelsConfig {
      static {
        __name(this, "ModelsConfig");
      }
      modelRegistry;
      // Current selection state
      currentAuthType;
      // Generation config state
      _generationConfig;
      generationConfigSources;
      // Flag for strict model provider selection
      strictModelProviderSelection = false;
      // One-shot flag for qwen-oauth credential caching
      requireCachedQwenCredentialsOnce = false;
      // One-shot flag indicating credentials were manually set via updateCredentials()
      // When true, syncAfterAuthRefresh should NOT override these credentials with
      // modelProviders defaults (even if the model ID matches a registry entry).
      //
      // This must be persistent across auth refreshes, because refreshAuth() can be
      // triggered multiple times after a credential prompt flow. We only clear this
      // flag when we explicitly apply modelProvider defaults (i.e. when the user
      // switches to a registry model via switchModel).
      hasManualCredentials = false;
      // Callback for notifying Config of model changes
      onModelChange;
      // Flag indicating whether authType was explicitly provided (not defaulted)
      authTypeWasExplicitlyProvided;
      /**
       * Runtime model snapshot storage.
       *
       * These snapshots store runtime-resolved model configurations that are NOT from
       * modelProviders registry (e.g., models with manually set credentials).
       *
       * Key: snapshotId (format: `$runtime|${authType}|${modelId}`)
       *   Uses `$runtime|` prefix since `$` and `|` are unlikely to appear in real model IDs.
       *   This prevents conflicts with model IDs containing `-` or `:` characters.
       * Value: RuntimeModelSnapshot containing the model's configuration
       *
       * Note: This is different from state snapshots used for rollback during model switching.
       * RuntimeModelSnapshot stores persistent model configurations, while state snapshots
       * are temporary and used only for error recovery.
       */
      runtimeModelSnapshots = /* @__PURE__ */ new Map();
      /**
       * Currently active RuntimeModelSnapshot ID.
       *
       * When set, indicates that the current model is a runtime model (not from registry).
       * This ID is included in state snapshots for rollback purposes.
       */
      activeRuntimeModelSnapshotId;
      static deepClone(value) {
        if (value === null || typeof value !== "object") {
          return value;
        }
        if (Array.isArray(value)) {
          return value.map((v2) => _ModelsConfig.deepClone(v2));
        }
        const out = {};
        for (const key of Object.keys(value)) {
          out[key] = _ModelsConfig.deepClone(value[key]);
        }
        return out;
      }
      constructor(options2 = {}) {
        this.modelRegistry = new ModelRegistry(options2.modelProvidersConfig);
        this.onModelChange = options2.onModelChange;
        this._generationConfig = {
          ...options2.generationConfig || {}
        };
        this.generationConfigSources = options2.generationConfigSources || {};
        this.authTypeWasExplicitlyProvided = options2.initialAuthType !== void 0;
        this.currentAuthType = options2.initialAuthType;
      }
      /**
       * Create a snapshot of the current ModelsConfig state for rollback purposes.
       * Used before model switching operations to enable recovery on errors.
       *
       * Note: This is different from RuntimeModelSnapshot which stores runtime model configs.
       */
      createStateSnapshotForRollback() {
        return {
          currentAuthType: this.currentAuthType,
          generationConfig: _ModelsConfig.deepClone(this._generationConfig),
          generationConfigSources: _ModelsConfig.deepClone(this.generationConfigSources),
          strictModelProviderSelection: this.strictModelProviderSelection,
          requireCachedQwenCredentialsOnce: this.requireCachedQwenCredentialsOnce,
          hasManualCredentials: this.hasManualCredentials,
          activeRuntimeModelSnapshotId: this.activeRuntimeModelSnapshotId
        };
      }
      /**
       * Restore ModelsConfig state from a previously created state snapshot.
       * Used for rollback when model switching operations fail.
       *
       * @param snapshot - The state snapshot to restore
       */
      rollbackToStateSnapshot(snapshot) {
        this.currentAuthType = snapshot.currentAuthType;
        this._generationConfig = snapshot.generationConfig;
        this.generationConfigSources = snapshot.generationConfigSources;
        this.strictModelProviderSelection = snapshot.strictModelProviderSelection;
        this.requireCachedQwenCredentialsOnce = snapshot.requireCachedQwenCredentialsOnce;
        this.hasManualCredentials = snapshot.hasManualCredentials;
        this.activeRuntimeModelSnapshotId = snapshot.activeRuntimeModelSnapshotId;
      }
      /**
       * Get current model ID
       */
      getModel() {
        return this._generationConfig.model || DEFAULT_QWEN_MODEL;
      }
      /**
       * Get current authType
       */
      getCurrentAuthType() {
        return this.currentAuthType;
      }
      /**
       * Check if authType was explicitly provided (via CLI or settings).
       * If false, no authType was provided yet (fresh user).
       */
      wasAuthTypeExplicitlyProvided() {
        return this.authTypeWasExplicitlyProvided;
      }
      /**
       * Get available models for current authType
       */
      getAvailableModels() {
        return this.currentAuthType ? this.modelRegistry.getModelsForAuthType(this.currentAuthType) : [];
      }
      /**
       * Get available models for a specific authType
       */
      getAvailableModelsForAuthType(authType) {
        return this.modelRegistry.getModelsForAuthType(authType);
      }
      /**
       * Get all configured models across authTypes.
       *
       * Notes:
       * - By default, returns models across all authTypes.
       * - qwen-oauth models are always ordered first.
       * - Runtime model option (if active) is included before registry models of the same authType.
       */
      getAllConfiguredModels(authTypes) {
        const inputAuthTypes = authTypes && authTypes.length > 0 ? authTypes : Object.values(AuthType2);
        const seen = /* @__PURE__ */ new Set();
        const uniqueAuthTypes = [];
        for (const authType of inputAuthTypes) {
          if (!seen.has(authType)) {
            seen.add(authType);
            uniqueAuthTypes.push(authType);
          }
        }
        const orderedAuthTypes = [];
        if (uniqueAuthTypes.includes(AuthType2.QWEN_OAUTH)) {
          orderedAuthTypes.push(AuthType2.QWEN_OAUTH);
        }
        for (const authType of uniqueAuthTypes) {
          if (authType !== AuthType2.QWEN_OAUTH) {
            orderedAuthTypes.push(authType);
          }
        }
        const runtimeOption = this.getRuntimeModelOption();
        const allModels = [];
        for (const authType of orderedAuthTypes) {
          if (runtimeOption && runtimeOption.authType === authType) {
            allModels.push(runtimeOption);
          }
          allModels.push(...this.modelRegistry.getModelsForAuthType(authType));
        }
        return allModels;
      }
      /**
       * Check if a model exists for the given authType
       */
      hasModel(authType, modelId) {
        return this.modelRegistry.hasModel(authType, modelId);
      }
      /**
       * Set model programmatically (e.g., VLM auto-switch, fallback).
       * Supports both registry models and raw model IDs.
       */
      async setModel(newModel, metadata) {
        if (this.currentAuthType === AuthType2.QWEN_OAUTH && newModel === DEFAULT_QWEN_MODEL) {
          this.strictModelProviderSelection = false;
          this._generationConfig.model = newModel;
          this.generationConfigSources["model"] = {
            kind: "programmatic",
            detail: metadata?.reason || "setModel"
          };
          if (this.onModelChange) {
            await this.onModelChange(AuthType2.QWEN_OAUTH, false);
          }
          return;
        }
        if (this.currentAuthType && this.modelRegistry.hasModel(this.currentAuthType, newModel)) {
          await this.switchModel(this.currentAuthType, newModel);
          return;
        }
        this.strictModelProviderSelection = false;
        this._generationConfig.model = newModel;
        this.generationConfigSources["model"] = {
          kind: "programmatic",
          detail: metadata?.reason || "setModel"
        };
      }
      /**
       * Switch model (and optionally authType).
       * Supports both registry-backed models and RuntimeModelSnapshots.
       *
       * For runtime models, the modelId can be:
       * - A RuntimeModelSnapshot ID (format: `$runtime|${authType}|${modelId}`)
       * - With explicit `$runtime|` prefix (format: `$runtime|${authType}|${modelId}`)
       *
       * When called from ACP integration, the modelId has already been parsed
       * by parseAcpModelOption, which strips any (${authType}) suffix.
       */
      async switchModel(authType, modelId, options2) {
        const runtimeModelSnapshotId = this.extractRuntimeModelSnapshotId(modelId);
        if (runtimeModelSnapshotId) {
          await this.switchToRuntimeModel(runtimeModelSnapshotId);
          return;
        }
        const rollbackSnapshot = this.createStateSnapshotForRollback();
        if (authType === AuthType2.QWEN_OAUTH && options2?.requireCachedCredentials) {
          this.requireCachedQwenCredentialsOnce = true;
        }
        try {
          const isAuthTypeChange = authType !== this.currentAuthType;
          this.currentAuthType = authType;
          const model = this.modelRegistry.getModel(authType, modelId);
          if (!model) {
            throw new Error(`Model '${modelId}' not found for authType '${authType}'`);
          }
          this.applyResolvedModelDefaults(model);
          this.activeRuntimeModelSnapshotId = void 0;
          const requiresRefresh = isAuthTypeChange ? true : this.checkRequiresRefresh(rollbackSnapshot.generationConfig.model || "");
          if (this.onModelChange) {
            await this.onModelChange(authType, requiresRefresh);
          }
        } catch (error2) {
          this.rollbackToStateSnapshot(rollbackSnapshot);
          throw error2;
        }
      }
      /**
       * Prefix used to identify RuntimeModelSnapshot IDs.
       * Chosen to avoid conflicts with real model IDs which may contain `-` or `:`.
       */
      static RUNTIME_SNAPSHOT_PREFIX = "$runtime|";
      /**
       * Build a RuntimeModelSnapshot ID from authType and modelId.
       * The format is: `$runtime|${authType}|${modelId}`
       *
       * This is the canonical way to construct snapshot IDs, ensuring
       * consistency across creation and lookup.
       *
       * @param authType - The authentication type
       * @param modelId - The model ID
       * @returns The snapshot ID in format `$runtime|${authType}|${modelId}`
       */
      buildRuntimeModelSnapshotId(authType, modelId) {
        return `${_ModelsConfig.RUNTIME_SNAPSHOT_PREFIX}${authType}|${modelId}`;
      }
      /**
       * Extract RuntimeModelSnapshot ID from modelId if it's a runtime model reference.
       *
       * Supports the following formats:
       * - Direct snapshot ID: `$runtime|${authType}|${modelId}` → returns as-is if exists in Map
       * - Direct snapshot ID match: returns if exists in Map
       *
       * Note: When called from ACP integration via setModel, the modelId has already
       * been parsed by parseAcpModelOption which strips any (${authType}) suffix.
       * So we don't need to handle ACP format here - the ACP layer handles that.
       *
       * @param modelId - The model ID to parse
       * @returns The RuntimeModelSnapshot ID if found, undefined otherwise
       */
      extractRuntimeModelSnapshotId(modelId) {
        if (modelId.startsWith(_ModelsConfig.RUNTIME_SNAPSHOT_PREFIX)) {
          if (this.runtimeModelSnapshots.has(modelId)) {
            return modelId;
          }
          return void 0;
        }
        if (this.runtimeModelSnapshots.has(modelId)) {
          return modelId;
        }
        return void 0;
      }
      /**
       * Get generation config for ContentGenerator creation
       */
      getGenerationConfig() {
        return this._generationConfig;
      }
      /**
       * Get generation config sources for debugging/UI
       */
      getGenerationConfigSources() {
        return this.generationConfigSources;
      }
      /**
       * Merge settings generation config, preserving existing values.
       * Used when provider-sourced config is cleared but settings should still apply.
       */
      mergeSettingsGenerationConfig(settingsGenerationConfig) {
        if (!settingsGenerationConfig) {
          return;
        }
        for (const field of MODEL_GENERATION_CONFIG_FIELDS) {
          if (!(field in this._generationConfig) && field in settingsGenerationConfig) {
            this._generationConfig[field] = settingsGenerationConfig[field];
            this.generationConfigSources[field] = {
              kind: "settings",
              detail: `model.generationConfig.${field}`
            };
          }
        }
      }
      /**
       * Update credentials in generation config.
       * Sets a flag to prevent syncAfterAuthRefresh from overriding these credentials.
       *
       * When credentials are manually set, we clear all provider-sourced configuration
       * to maintain provider atomicity (either fully applied or not at all).
       * Other layers (CLI, env, settings, defaults) will participate in resolve.
       *
       * Also updates or creates a RuntimeModelSnapshot when credentials form a complete config
       * for a model not in the registry. This allows the runtime model to be reused later.
       *
       * @param settingsGenerationConfig Optional generation config from settings.json
       *                                  to merge after clearing provider-sourced config.
       *                                  This ensures settings.model.generationConfig fields
       *                                  (e.g., samplingParams, timeout) are preserved.
       */
      updateCredentials(credentials, settingsGenerationConfig) {
        if (credentials.apiKey || credentials.baseUrl || credentials.model) {
          this.hasManualCredentials = true;
          this.clearProviderSourcedConfig();
        }
        if (credentials.apiKey) {
          this._generationConfig.apiKey = credentials.apiKey;
          this.generationConfigSources["apiKey"] = {
            kind: "programmatic",
            detail: "updateCredentials"
          };
        }
        if (credentials.baseUrl) {
          this._generationConfig.baseUrl = credentials.baseUrl;
          this.generationConfigSources["baseUrl"] = {
            kind: "programmatic",
            detail: "updateCredentials"
          };
        }
        if (credentials.model) {
          this._generationConfig.model = credentials.model;
          this.generationConfigSources["model"] = {
            kind: "programmatic",
            detail: "updateCredentials"
          };
        }
        this.strictModelProviderSelection = false;
        this._generationConfig.apiKeyEnvKey = void 0;
        if (settingsGenerationConfig) {
          this.mergeSettingsGenerationConfig(settingsGenerationConfig);
        }
        this.syncRuntimeModelSnapshotWithCredentials();
      }
      /**
       * Sync RuntimeModelSnapshot with current credentials.
       *
       * Creates or updates a RuntimeModelSnapshot when current credentials form a complete
       * configuration for a model not in the registry. This enables:
       * - Reusing the runtime model configuration later
       * - Showing the runtime model as an available option in model lists
       *
       * Only creates snapshots for models NOT in the registry (to avoid duplication).
       */
      syncRuntimeModelSnapshotWithCredentials() {
        const currentAuthType = this.currentAuthType;
        const { model, apiKey, baseUrl } = this._generationConfig;
        if (!model || !currentAuthType || !apiKey || !baseUrl) {
          return;
        }
        if (this.modelRegistry.hasModel(currentAuthType, model)) {
          return;
        }
        if (this.activeRuntimeModelSnapshotId && this.runtimeModelSnapshots.has(this.activeRuntimeModelSnapshotId)) {
          const snapshot = this.runtimeModelSnapshots.get(this.activeRuntimeModelSnapshotId);
          snapshot.apiKey = apiKey;
          snapshot.baseUrl = baseUrl;
          snapshot.modelId = model;
          const newSnapshotId = this.buildRuntimeModelSnapshotId(snapshot.authType, snapshot.modelId);
          if (newSnapshotId !== snapshot.id) {
            this.runtimeModelSnapshots.delete(snapshot.id);
            snapshot.id = newSnapshotId;
            this.runtimeModelSnapshots.set(newSnapshotId, snapshot);
            this.activeRuntimeModelSnapshotId = newSnapshotId;
          }
          snapshot.createdAt = Date.now();
        } else {
          this.detectAndCaptureRuntimeModel();
        }
      }
      /**
       * Clear configuration fields that were sourced from modelProviders.
       * This ensures provider config atomicity when user manually sets credentials.
       * Other layers (CLI, env, settings, defaults) will participate in resolve.
       */
      clearProviderSourcedConfig() {
        for (const field of PROVIDER_SOURCED_FIELDS) {
          const source2 = this.generationConfigSources[field];
          if (source2?.kind === "modelProviders") {
            delete this._generationConfig[field];
            delete this.generationConfigSources[field];
          }
        }
      }
      /**
       * Get whether strict model provider selection is enabled
       */
      isStrictModelProviderSelection() {
        return this.strictModelProviderSelection;
      }
      /**
       * Reset strict model provider selection flag
       */
      resetStrictModelProviderSelection() {
        this.strictModelProviderSelection = false;
      }
      /**
       * Check and consume the one-shot cached credentials flag
       */
      consumeRequireCachedCredentialsFlag() {
        const value = this.requireCachedQwenCredentialsOnce;
        this.requireCachedQwenCredentialsOnce = false;
        return value;
      }
      /**
       * Apply resolved model config to generation config
       */
      applyResolvedModelDefaults(model) {
        this.strictModelProviderSelection = true;
        this.hasManualCredentials = false;
        this._generationConfig.model = model.id;
        this.generationConfigSources["model"] = {
          kind: "modelProviders",
          authType: model.authType,
          modelId: model.id,
          detail: "model.id"
        };
        if (this.currentAuthType === AuthType2.QWEN_OAUTH) {
          this._generationConfig.apiKey = "QWEN_OAUTH_DYNAMIC_TOKEN";
          this.generationConfigSources["apiKey"] = {
            kind: "computed",
            detail: "Qwen OAuth placeholder token"
          };
          this._generationConfig.apiKeyEnvKey = void 0;
          delete this.generationConfigSources["apiKeyEnvKey"];
        } else {
          this._generationConfig.apiKey = void 0;
          this._generationConfig.apiKeyEnvKey = void 0;
        }
        if (model.envKey !== void 0) {
          const apiKey = process2.env[model.envKey];
          if (apiKey) {
            this._generationConfig.apiKey = apiKey;
            this.generationConfigSources["apiKey"] = {
              kind: "env",
              envKey: model.envKey,
              via: {
                kind: "modelProviders",
                authType: model.authType,
                modelId: model.id,
                detail: "envKey"
              }
            };
          }
          this._generationConfig.apiKeyEnvKey = model.envKey;
          this.generationConfigSources["apiKeyEnvKey"] = {
            kind: "modelProviders",
            authType: model.authType,
            modelId: model.id,
            detail: "envKey"
          };
        }
        this._generationConfig.baseUrl = model.baseUrl;
        this.generationConfigSources["baseUrl"] = {
          kind: "modelProviders",
          authType: model.authType,
          modelId: model.id,
          detail: "baseUrl"
        };
        const gc = model.generationConfig;
        for (const field of MODEL_GENERATION_CONFIG_FIELDS) {
          this._generationConfig[field] = gc[field];
          this.generationConfigSources[field] = {
            kind: "modelProviders",
            authType: model.authType,
            modelId: model.id,
            detail: `generationConfig.${field}`
          };
        }
        if (gc.contextWindowSize === void 0) {
          this._generationConfig.contextWindowSize = tokenLimit(model.id, "input");
          this.generationConfigSources["contextWindowSize"] = {
            kind: "computed",
            detail: "auto-detected from model"
          };
        }
      }
      /**
       * Check if model switch requires ContentGenerator refresh.
       *
       * Note: This method is ONLY called by switchModel() for same-authType model switches.
       * Cross-authType switches use switchModel(authType, modelId), which always requires full refresh.
       *
       * When this method is called:
       * - this.currentAuthType is already the target authType
       * - We're checking if switching between two models within the SAME authType needs refresh
       *
       * Examples:
       * - Qwen OAuth: coder-model switches (same authType, hot-update safe)
       * - OpenAI: model-a -> model-b with same envKey (same authType, hot-update safe)
       * - OpenAI: gpt-4 -> deepseek-chat with different envKey (same authType, needs refresh)
       *
       * Cross-authType scenarios:
       * - OpenAI -> Qwen OAuth: handled by switchModel(authType, modelId), always refreshes
       * - Qwen OAuth -> OpenAI: handled by switchModel(authType, modelId), always refreshes
       */
      checkRequiresRefresh(previousModelId) {
        const authType = this.currentAuthType;
        if (!authType) {
          return true;
        }
        if (authType === AuthType2.QWEN_OAUTH) {
          return false;
        }
        const previousModel = this.modelRegistry.getModel(authType, previousModelId);
        const currentModel = this.modelRegistry.getModel(authType, this._generationConfig.model || "");
        if (!previousModel || !currentModel) {
          return true;
        }
        const criticalFieldsChanged = previousModel.envKey !== currentModel.envKey || previousModel.baseUrl !== currentModel.baseUrl;
        if (criticalFieldsChanged) {
          return true;
        }
        return false;
      }
      /**
       * Sync state after auth refresh with fallback strategy:
       * 1. If modelId can be found in modelRegistry, use the config from modelRegistry.
       * 2. Otherwise, if existing credentials exist in resolved generationConfig from other sources
       *    (not modelProviders), preserve them and update authType/modelId only.
       * 3. Otherwise, fall back to default model for the authType.
       * 4. If no default is available, leave the generationConfig incomplete and let
       *    resolveContentGeneratorConfigWithSources throw exceptions as expected.
       */
      syncAfterAuthRefresh(authType, modelId) {
        this.strictModelProviderSelection = false;
        const previousAuthType = this.currentAuthType;
        this.currentAuthType = authType;
        if (modelId && this.modelRegistry.hasModel(authType, modelId)) {
          const resolved = this.modelRegistry.getModel(authType, modelId);
          if (resolved) {
            this.applyResolvedModelDefaults(resolved);
            this.strictModelProviderSelection = true;
            this.activeRuntimeModelSnapshotId = void 0;
            return;
          }
        }
        const apiKeySource = this.generationConfigSources["apiKey"];
        const baseUrlSource = this.generationConfigSources["baseUrl"];
        const hasExistingCredentials = this._generationConfig.apiKey && apiKeySource?.kind !== "modelProviders" || this._generationConfig.baseUrl && baseUrlSource?.kind !== "modelProviders";
        const isAuthTypeChange = previousAuthType !== authType;
        const shouldPreserveCredentials = !isAuthTypeChange && (modelId === void 0 || !this.modelRegistry.hasModel(authType, modelId)) && (this.hasManualCredentials || hasExistingCredentials);
        if (shouldPreserveCredentials) {
          if (modelId) {
            this._generationConfig.model = modelId;
            if (!this.generationConfigSources["model"]) {
              this.generationConfigSources["model"] = {
                kind: "programmatic",
                detail: "auth refresh (preserved credentials)"
              };
            }
          }
          return;
        }
        const defaultModel = this.modelRegistry.getDefaultModelForAuthType(authType);
        if (defaultModel) {
          this.applyResolvedModelDefaults(defaultModel);
          this.activeRuntimeModelSnapshotId = void 0;
          return;
        }
        if (modelId) {
          this._generationConfig.model = modelId;
          if (!this.generationConfigSources["model"]) {
            this.generationConfigSources["model"] = {
              kind: "programmatic",
              detail: "auth refresh (no default model)"
            };
          }
        }
      }
      /**
       * Update callback for model changes
       */
      setOnModelChange(callback) {
        this.onModelChange = callback;
      }
      /**
       * Detect and capture RuntimeModelSnapshot during initialization.
       *
       * Checks if the current configuration represents a runtime model (not from
       * modelProviders registry) and captures it as a RuntimeModelSnapshot.
       *
       * This enables runtime models to persist across sessions and appear in model lists.
       *
       * @returns Created snapshot ID, or undefined if current config is a registry model
       */
      detectAndCaptureRuntimeModel() {
        const { model: currentModel, apiKey, baseUrl, apiKeyEnvKey, ...generationConfig } = this._generationConfig;
        const currentAuthType = this.currentAuthType;
        if (!currentModel || !currentAuthType) {
          return void 0;
        }
        if (this.modelRegistry.hasModel(currentAuthType, currentModel)) {
          this.clearRuntimeModelSnapshotForAuthType(currentAuthType);
          return void 0;
        }
        const hasValidCredentials = this._generationConfig.apiKey && this._generationConfig.baseUrl;
        if (!hasValidCredentials) {
          return void 0;
        }
        const snapshotId = this.buildRuntimeModelSnapshotId(currentAuthType, currentModel);
        const snapshot = {
          id: snapshotId,
          authType: currentAuthType,
          modelId: currentModel,
          apiKey,
          baseUrl,
          apiKeyEnvKey,
          generationConfig,
          sources: { ...this.generationConfigSources },
          createdAt: Date.now()
        };
        this.runtimeModelSnapshots.set(snapshotId, snapshot);
        this.activeRuntimeModelSnapshotId = snapshotId;
        this.cleanupOldRuntimeModelSnapshots();
        return snapshotId;
      }
      /**
       * Get the currently active RuntimeModelSnapshot.
       *
       * @returns The active RuntimeModelSnapshot, or undefined if no runtime model is active
       */
      getActiveRuntimeModelSnapshot() {
        if (!this.activeRuntimeModelSnapshotId) {
          return void 0;
        }
        return this.runtimeModelSnapshots.get(this.activeRuntimeModelSnapshotId);
      }
      /**
       * Get the ID of the currently active RuntimeModelSnapshot.
       *
       * @returns The active snapshot ID, or undefined if no runtime model is active
       */
      getActiveRuntimeModelSnapshotId() {
        return this.activeRuntimeModelSnapshotId;
      }
      /**
       * Switch to a RuntimeModelSnapshot.
       *
       * Applies the configuration from a previously captured RuntimeModelSnapshot.
       * Uses state rollback pattern: creates a state snapshot before switching and
       * restores it on error.
       *
       * @param snapshotId - The ID of the RuntimeModelSnapshot to switch to
       */
      async switchToRuntimeModel(snapshotId) {
        const runtimeModelSnapshot = this.runtimeModelSnapshots.get(snapshotId);
        if (!runtimeModelSnapshot) {
          throw new Error(`Runtime model snapshot '${snapshotId}' not found`);
        }
        const rollbackSnapshot = this.createStateSnapshotForRollback();
        try {
          const isAuthTypeChange = runtimeModelSnapshot.authType !== this.currentAuthType;
          this.currentAuthType = runtimeModelSnapshot.authType;
          this.activeRuntimeModelSnapshotId = snapshotId;
          this.strictModelProviderSelection = false;
          this.hasManualCredentials = true;
          this._generationConfig.model = runtimeModelSnapshot.modelId;
          this.generationConfigSources["model"] = {
            kind: "programmatic",
            detail: "runtimeModelSwitch"
          };
          if (runtimeModelSnapshot.apiKey) {
            this._generationConfig.apiKey = runtimeModelSnapshot.apiKey;
            this.generationConfigSources["apiKey"] = runtimeModelSnapshot.sources["apiKey"] || {
              kind: "programmatic",
              detail: "runtimeModelSwitch"
            };
          }
          if (runtimeModelSnapshot.baseUrl) {
            this._generationConfig.baseUrl = runtimeModelSnapshot.baseUrl;
            this.generationConfigSources["baseUrl"] = runtimeModelSnapshot.sources["baseUrl"] || {
              kind: "programmatic",
              detail: "runtimeModelSwitch"
            };
          }
          if (runtimeModelSnapshot.apiKeyEnvKey) {
            this._generationConfig.apiKeyEnvKey = runtimeModelSnapshot.apiKeyEnvKey;
          }
          if (runtimeModelSnapshot.generationConfig) {
            Object.assign(this._generationConfig, runtimeModelSnapshot.generationConfig);
          }
          const requiresRefresh = isAuthTypeChange;
          if (this.onModelChange) {
            await this.onModelChange(runtimeModelSnapshot.authType, requiresRefresh);
          }
        } catch (error2) {
          this.rollbackToStateSnapshot(rollbackSnapshot);
          throw error2;
        }
      }
      /**
       * Get the active RuntimeModelSnapshot as an AvailableModel option.
       *
       * Converts the active RuntimeModelSnapshot to an AvailableModel format for display
       * in model lists. Returns undefined if no runtime model is active.
       *
       * @returns The runtime model as an AvailableModel option, or undefined
       */
      getRuntimeModelOption() {
        const snapshot = this.getActiveRuntimeModelSnapshot();
        if (!snapshot) {
          return void 0;
        }
        return {
          id: snapshot.modelId,
          label: snapshot.modelId,
          authType: snapshot.authType,
          /**
           * `isVision` is for automatic switching of qwen-oauth vision model.
           * Runtime models are basically specified via CLI arguments, env variables,
           * or settings for other auth types.
           */
          isVision: false,
          contextWindowSize: snapshot.generationConfig?.contextWindowSize,
          isRuntimeModel: true,
          runtimeSnapshotId: snapshot.id
        };
      }
      /**
       * Clear all RuntimeModelSnapshots for a specific authType.
       *
       * Removes all RuntimeModelSnapshots associated with the given authType.
       * Called when switching to a registry model to avoid stale RuntimeModelSnapshots.
       *
       * @param authType - The authType whose snapshots should be cleared
       */
      clearRuntimeModelSnapshotForAuthType(authType) {
        for (const [id, snapshot] of this.runtimeModelSnapshots.entries()) {
          if (snapshot.authType === authType) {
            this.runtimeModelSnapshots.delete(id);
            if (this.activeRuntimeModelSnapshotId === id) {
              this.activeRuntimeModelSnapshotId = void 0;
            }
          }
        }
      }
      /**
       * Cleanup old RuntimeModelSnapshots to enforce per-authType limit.
       *
       * Keeps only the latest RuntimeModelSnapshot for each authType.
       * Older snapshots are removed to prevent unbounded growth.
       */
      cleanupOldRuntimeModelSnapshots() {
        const snapshotsByAuthType = /* @__PURE__ */ new Map();
        for (const snapshot of this.runtimeModelSnapshots.values()) {
          const existing = snapshotsByAuthType.get(snapshot.authType);
          if (!existing || snapshot.createdAt > existing.createdAt) {
            snapshotsByAuthType.set(snapshot.authType, snapshot);
          }
        }
        this.runtimeModelSnapshots.clear();
        for (const snapshot of snapshotsByAuthType.values()) {
          this.runtimeModelSnapshots.set(snapshot.id, snapshot);
        }
        if (this.activeRuntimeModelSnapshotId && !this.runtimeModelSnapshots.has(this.activeRuntimeModelSnapshotId)) {
          this.activeRuntimeModelSnapshotId = void 0;
        }
      }
      /**
       * Reload model providers configuration at runtime.
       * This enables hot-reloading of modelProviders settings without restarting the CLI.
       *
       * @param modelProvidersConfig - The updated model providers configuration
       */
      reloadModelProvidersConfig(modelProvidersConfig) {
        this.modelRegistry.reloadModels(modelProvidersConfig);
      }
    };
  }
});

// node_modules/openai/internal/tslib.mjs
function __classPrivateFieldSet(receiver, state, value, kind2, f5) {
  if (kind2 === "m")
    throw new TypeError("Private method is not writable");
  if (kind2 === "a" && !f5)
    throw new TypeError("Private accessor was defined without a setter");
  if (typeof state === "function" ? receiver !== state || !f5 : !state.has(receiver))
    throw new TypeError("Cannot write private member to an object whose class did not declare it");
  return kind2 === "a" ? f5.call(receiver, value) : f5 ? f5.value = value : state.set(receiver, value), value;
}
function __classPrivateFieldGet(receiver, state, kind2, f5) {
  if (kind2 === "a" && !f5)
    throw new TypeError("Private accessor was defined without a getter");
  if (typeof state === "function" ? receiver !== state || !f5 : !state.has(receiver))
    throw new TypeError("Cannot read private member from an object whose class did not declare it");
  return kind2 === "m" ? f5 : kind2 === "a" ? f5.call(receiver) : f5 ? f5.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: crypto14 } = globalThis;
      if (crypto14?.randomUUID) {
        uuid4 = crypto14.randomUUID.bind(crypto14);
        return crypto14.randomUUID();
      }
      const u8 = new Uint8Array(1);
      const randomByte = crypto14 ? () => crypto14.getRandomValues(u8)[0] : () => Math.random() * 255 & 255;
      return "10000000-1000-4000-8000-100000000000".replace(/[018]/g, (c4) => (+c4 ^ randomByte() & 15 >> +c4 / 4).toString(16));
    }, "uuid4");
  }
});

// node_modules/openai/internal/errors.mjs
function isAbortError2(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(isAbortError2, "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 error2 = new Error(err.message, err.cause ? { cause: err.cause } : {});
            if (err.stack)
              error2.stack = err.stack;
            if (err.cause && !error2.cause)
              error2.cause = err.cause;
            if (err.name)
              error2.name = err.name;
            return error2;
          }
        } 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, error2, message, headers) {
        super(`${_APIError.makeMessage(status, error2, message)}`);
        this.status = status;
        this.headers = headers;
        this.requestID = headers?.get("x-request-id");
        this.error = error2;
        const data = error2;
        this.code = data?.["code"];
        this.param = data?.["param"];
        this.type = data?.["type"];
      }
      static makeMessage(status, error2, message) {
        const msg = error2?.message ? typeof error2.message === "string" ? error2.message : JSON.stringify(error2.message) : error2 ? JSON.stringify(error2) : 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 error2 = errorResponse?.["error"];
        if (status === 400) {
          return new BadRequestError2(status, error2, message, headers);
        }
        if (status === 401) {
          return new AuthenticationError(status, error2, message, headers);
        }
        if (status === 403) {
          return new PermissionDeniedError(status, error2, message, headers);
        }
        if (status === 404) {
          return new NotFoundError(status, error2, message, headers);
        }
        if (status === 409) {
          return new ConflictError(status, error2, message, headers);
        }
        if (status === 422) {
          return new UnprocessableEntityError(status, error2, message, headers);
        }
        if (status === 429) {
          return new RateLimitError(status, error2, message, headers);
        }
        if (status >= 500) {
          return new InternalServerError(status, error2, message, headers);
        }
        return new _APIError(status, error2, 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(x3) {
  if (typeof x3 !== "object") {
    return {};
  }
  return x3 ?? {};
}
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, n3) => {
      if (typeof n3 !== "number" || !Number.isInteger(n3)) {
        throw new OpenAIError(`${name3} must be an integer`);
      }
      if (n3 < 0) {
        throw new OpenAIError(`${name3} must be a positive integer`);
      }
      return n3;
    }, "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((resolve30) => setTimeout(resolve30, ms)), "sleep");
  }
});

// node_modules/openai/version.mjs
var VERSION2;
var init_version2 = __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_version2();
    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((platform16) => {
      platform16 = platform16.toLowerCase();
      if (platform16.includes("ios"))
        return "iOS";
      if (platform16 === "android")
        return "Android";
      if (platform16 === "darwin")
        return "MacOS";
      if (platform16 === "win32")
        return "Windows";
      if (platform16 === "freebsd")
        return "FreeBSD";
      if (platform16 === "openbsd")
        return "OpenBSD";
      if (platform16 === "linux")
        return "Linux";
      if (platform16)
        return `Other:${platform16}`;
      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 ReadableStream5 = globalThis.ReadableStream;
  if (typeof ReadableStream5 === "undefined") {
    throw new Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");
  }
  return new ReadableStream5(...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 (e4) {
        reader.releaseLock();
        throw e4;
      }
    },
    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((v2) => String(v2), "default_formatter");
    formatters = {
      RFC1738: /* @__PURE__ */ __name((v2) => String(v2).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 i3 = 0; i3 < val.length; i3 += 1) {
      mapped.push(fn(val[i3]));
    }
    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 array2 = [];
      for (let i3 = 0; i3 < 256; ++i3) {
        array2.push("%" + ((i3 < 16 ? "0" : "") + i3.toString(16)).toUpperCase());
      }
      return array2;
    })();
    limit = 1024;
    encode = /* @__PURE__ */ __name((str2, _defaultEncoder, charset, _kind, format4) => {
      if (str2.length === 0) {
        return str2;
      }
      let string4 = str2;
      if (typeof str2 === "symbol") {
        string4 = Symbol.prototype.toString.call(str2);
      } else if (typeof str2 !== "string") {
        string4 = String(str2);
      }
      if (charset === "iso-8859-1") {
        return escape(string4).replace(/%u[0-9a-f]{4}/gi, function($0) {
          return "%26%23" + parseInt($0.slice(2), 16) + "%3B";
        });
      }
      let out = "";
      for (let j2 = 0; j2 < string4.length; j2 += limit) {
        const segment = string4.length >= limit ? string4.slice(j2, j2 + limit) : string4;
        const arr = [];
        for (let i3 = 0; i3 < segment.length; ++i3) {
          let c4 = segment.charCodeAt(i3);
          if (c4 === 45 || // -
          c4 === 46 || // .
          c4 === 95 || // _
          c4 === 126 || // ~
          c4 >= 48 && c4 <= 57 || // 0-9
          c4 >= 65 && c4 <= 90 || // a-z
          c4 >= 97 && c4 <= 122 || // A-Z
          format4 === RFC1738 && (c4 === 40 || c4 === 41)) {
            arr[arr.length] = segment.charAt(i3);
            continue;
          }
          if (c4 < 128) {
            arr[arr.length] = hex_table[c4];
            continue;
          }
          if (c4 < 2048) {
            arr[arr.length] = hex_table[192 | c4 >> 6] + hex_table[128 | c4 & 63];
            continue;
          }
          if (c4 < 55296 || c4 >= 57344) {
            arr[arr.length] = hex_table[224 | c4 >> 12] + hex_table[128 | c4 >> 6 & 63] + hex_table[128 | c4 & 63];
            continue;
          }
          i3 += 1;
          c4 = 65536 + ((c4 & 1023) << 10 | segment.charCodeAt(i3) & 1023);
          arr[arr.length] = hex_table[240 | c4 >> 18] + hex_table[128 | c4 >> 12 & 63] + hex_table[128 | c4 >> 6 & 63] + hex_table[128 | c4 & 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(v2) {
  return typeof v2 === "string" || typeof v2 === "number" || typeof v2 === "boolean" || typeof v2 === "symbol" || typeof v2 === "bigint";
}
function inner_stringify(object3, prefix, generateArrayPrefix, commaRoundTrip, allowEmptyArrays, strictNullHandling, skipNulls, encodeDotInKeys, encoder, filter4, sort, allowDots, serializeDate, format4, formatter, encodeValuesOnly, charset, sideChannel) {
  let obj = object3;
  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(object3);
    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 j2 = 0; j2 < obj_keys.length; ++j2) {
    const key = obj_keys[j2];
    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(object3, 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 stringify(object3, opts = {}) {
  let obj = object3;
  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 i3 = 0; i3 < obj_keys.length; ++i3) {
    const key = obj_keys[i3];
    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(date4) {
        return (toISOString ?? (toISOString = Function.prototype.call.bind(Date.prototype.toISOString)))(date4);
      },
      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(stringify, "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 i3 = startIndex ?? 0; i3 < buffer.length; i3++) {
    if (buffer[i3] === newline2) {
      return { preceding: i3, index: i3 + 1, carriage: false };
    }
    if (buffer[i3] === carriage) {
      return { preceding: i3, index: i3 + 1, carriage: true };
    }
  }
  return null;
}
function findDoubleNewlineIndex(buffer) {
  const newline2 = 10;
  const carriage = 13;
  for (let i3 = 0; i3 < buffer.length - 1; i3++) {
    if (buffer[i3] === newline2 && buffer[i3 + 1] === newline2) {
      return i3 + 2;
    }
    if (buffer[i3] === carriage && buffer[i3 + 1] === carriage) {
      return i3 + 2;
    }
    if (buffer[i3] === carriage && buffer[i3 + 1] === newline2 && i3 + 3 < buffer.length && buffer[i3 + 2] === carriage && buffer[i3 + 3] === newline2) {
      return i3 + 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, Stream3, 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();
    Stream3 = 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 (e4) {
                  logger6.error(`Could not parse message into JSON:`, sse.data);
                  logger6.error(`From chunk:`, sse.raw);
                  throw e4;
                }
                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 (e4) {
                  console.error(`Could not parse message into JSON:`, sse.data);
                  console.error(`From chunk:`, sse.raw);
                  throw e4;
                }
                if (sse.event == "error") {
                  throw new APIError(void 0, data.error, data.message, void 0);
                }
                yield { event: sse.event, data };
              }
            }
            done = true;
          } catch (e4) {
            if (isAbortError2(e4))
              return;
            throw e4;
          } 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 (e4) {
            if (isAbortError2(e4))
              return;
            throw e4;
          } 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, _2, 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 Stream3.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_parse = __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_parse();
    APIPromise = class _APIPromise extends Promise {
      static {
        __name(this, "APIPromise");
      }
      constructor(client, responsePromise, parseResponse2 = defaultParseResponse) {
        super((resolve30) => {
          resolve30(null);
        });
        this.responsePromise = responsePromise;
        this.parseResponse = parseResponse2;
        _APIPromise_client.set(this, void 0);
        __classPrivateFieldSet(this, _APIPromise_client, client, "f");
      }
      _thenUnwrap(transform2) {
        return new _APIPromise(__classPrivateFieldGet(this, _APIPromise_client, "f"), this.responsePromise, async (client, props) => addRequestID(transform2(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((p2) => p2.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_parse();
    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, Page3) {
        super(client, request4, async (client2, props) => new Page3(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 fetch5 = typeof fetchObject === "function" ? fetchObject : fetchObject.fetch;
  const cached2 = supportsFormDataMap.get(fetch5);
  if (cached2)
    return cached2;
  const promise = (async () => {
    try {
      const FetchResponse = "Response" in fetch5 ? fetch5.Response : (await fetch5("data:,")).constructor;
      const data = new FormData();
      if (data.toString() === await new FetchResponse(data).text()) {
        return false;
      }
      return true;
    } catch {
      return true;
    }
  })();
  supportsFormDataMap.set(fetch5, 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: process50 } = globalThis;
        const isOldNode = typeof process50?.versions?.node === "string" && parseInt(process50.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, fetch5) => {
      return { ...opts, body: await createForm(opts.body, fetch5) };
    }, "multipartFormRequestOptions");
    supportsFormDataMap = /* @__PURE__ */ new WeakMap();
    __name(supportsFormData, "supportsFormData");
    createForm = /* @__PURE__ */ __name(async (body, fetch5) => {
      if (!await supportsFormData(fetch5)) {
        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((p2) => `"${p2}"`).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, path7;
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 path125(statics, ...params) {
      if (statics.length === 1)
        return statics[0];
      let postPath = false;
      const invalidSegments = [];
      const path126 = 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 = path126.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((a2, b2) => a2.start - b2.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((e4) => e4.error).join("\n")}
${path126}
${underline}`);
      }
      return path126;
    }, "path"), "createPathTagFunction");
    path7 = /* @__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(path7`/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((resolve30, reject) => {
          __classPrivateFieldSet(this, _EventStream_resolveConnectedPromise, resolve30, "f");
          __classPrivateFieldSet(this, _EventStream_rejectConnectedPromise, reject, "f");
        }), "f");
        __classPrivateFieldSet(this, _EventStream_endPromise, new Promise((resolve30, reject) => {
          __classPrivateFieldSet(this, _EventStream_resolveEndPromise, resolve30, "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((l3) => l3.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((resolve30, reject) => {
          __classPrivateFieldSet(this, _EventStream_catchingPromiseCreated, true, "f");
          if (event !== "error")
            this.once("error", reject);
          this.once(event, resolve30);
        });
      }
      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((l3) => !l3.once);
          listeners.forEach(({ listener }) => listener(...args));
        }
        if (event === "abort") {
          const error2 = args[0];
          if (!__classPrivateFieldGet(this, _EventStream_catchingPromiseCreated, "f") && !listeners?.length) {
            Promise.reject(error2);
          }
          __classPrivateFieldGet(this, _EventStream_rejectConnectedPromise, "f").call(this, error2);
          __classPrivateFieldGet(this, _EventStream_rejectEndPromise, "f").call(this, error2);
          this._emit("end");
          return;
        }
        if (event === "error") {
          const error2 = args[0];
          if (!__classPrivateFieldGet(this, _EventStream_catchingPromiseCreated, "f") && !listeners?.length) {
            Promise.reject(error2);
          }
          __classPrivateFieldGet(this, _EventStream_rejectConnectedPromise, "f").call(this, error2);
          __classPrivateFieldGet(this, _EventStream_rejectEndPromise, "f").call(this, error2);
          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(error2) {
      __classPrivateFieldSet(this, _EventStream_errored, true, "f");
      if (error2 instanceof Error && error2.name === "AbortError") {
        error2 = new APIUserAbortError();
      }
      if (error2 instanceof APIUserAbortError) {
        __classPrivateFieldSet(this, _EventStream_aborted, true, "f");
        return this._emit("abort", error2);
      }
      if (error2 instanceof OpenAIError) {
        return this._emit("error", error2);
      }
      if (error2 instanceof Error) {
        const openAIError = new OpenAIError(error2.message);
        openAIError.cause = error2;
        return this._emit("error", openAIError);
      }
      return this._emit("error", new OpenAIError(String(error2)));
    }, "_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((t5) => isAutoParsableTool(t5) || t5.type === "function" && t5.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((c4) => c4.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 f5 of inputTools) {
          if (f5.type === "function") {
            functionsByName[f5.function.name || f5.function.function.name] = f5.function;
          }
        }
        const tools = "tools" in params ? inputTools.map((t5) => t5.type === "function" ? {
          type: "function",
          function: {
            name: t5.function.name || t5.function.function.name,
            parameters: t5.function.parameters,
            description: t5.function.description,
            strict: t5.function.strict
          }
        } : t5) : void 0;
        for (const message of params.messages) {
          this._addMessage(message, false);
        }
        for (let i3 = 0; i3 < maxChatCompletions; ++i3) {
          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 (error2) {
              const content2 = error2 instanceof Error ? error2.message : String(error2);
              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 i3 = this.messages.length;
      while (i3-- > 0) {
        const message = this.messages[i3];
        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 i3 = this.messages.length - 1; i3 >= 0; i3--) {
        const message = this.messages[i3];
        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 i3 = this.messages.length - 1; i3 >= 0; i3--) {
        const message = this.messages[i3];
        if (isToolMessage(message) && message.content != null && typeof message.content === "string" && this.messages.some((x3) => x3.role === "assistant" && x3.tool_calls?.some((y2) => y2.type === "function" && y2.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 (e4) {
            throwMalformedError(String(e4));
          }
        } else if (Allow.STR & allow) {
          try {
            return JSON.parse(jsonString.substring(start, index - Number(escape7)) + '"');
          } catch (e4) {
            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 (e4) {
              if (Allow.OBJ & allow)
                return obj;
              else
                throw e4;
            }
            skipBlank();
            if (jsonString[index] === ",")
              index++;
          }
        } catch (e4) {
          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 (e4) {
          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 (e4) {
            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 (e5) {
              }
            }
            throwMalformedError(String(e4));
          }
        }
        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 (e4) {
          if (jsonString.substring(start, index) === "-" && Allow.NUM & allow)
            markPartialJSON("Not sure what '-' is");
          try {
            return JSON.parse(jsonString.substring(start, jsonString.lastIndexOf("e")));
          } catch (e5) {
            throwMalformedError(String(e5));
          }
        }
      }, "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, i3) => {
              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[${i3}].id
${str(snapshot)}`);
              }
              if (type == null) {
                throw new OpenAIError(`missing choices[${index}].tool_calls[${i3}].type
${str(snapshot)}`);
              }
              if (name3 == null) {
                throw new OpenAIError(`missing choices[${index}].tool_calls[${i3}].function.name
${str(snapshot)}`);
              }
              if (args == null) {
                throw new OpenAIError(`missing choices[${index}].tool_calls[${i3}].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(x3) {
  return JSON.stringify(x3);
}
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 = Stream3.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 _a7, _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) {
                (_a7 = choice2.logprobs).content ?? (_a7.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((resolve30, reject) => readQueue.push({ resolve: resolve30, 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 Stream3(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(path7`/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(path7`/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(path7`/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_headers2 = __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_headers2();
    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(path7`/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(path7`/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_headers2();
    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(path7`/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(path7`/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(path7`/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_headers2();
    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_headers2();
    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_headers2();
    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(path7`/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(path7`/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(path7`/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(path7`/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(path7`/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_headers2();
    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(path7`/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(path7`/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 i3 = 0; i3 < len; i3++) {
          bytes[i3] = binaryStr.charCodeAt(i3);
        }
        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((resolve30, reject) => readQueue.push({ resolve: resolve30, 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 = Stream3.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 Stream3(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((x3) => typeof x3 === "string" || typeof x3 === "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_headers2();
    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(path7`/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(path7`/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(path7`/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(path7`/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(path7`/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(path7`/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_headers2();
    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(path7`/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(path7`/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(path7`/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_headers2();
    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(path7`/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_headers2();
    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(path7`/containers/${containerID}/files`, multipartFormRequestOptions({ body, ...options2 }, this._client));
      }
      /**
       * Retrieve Container File
       */
      retrieve(fileID, params, options2) {
        const { container_id } = params;
        return this._client.get(path7`/containers/${container_id}/files/${fileID}`, options2);
      }
      /**
       * List Container files
       */
      list(containerID, query = {}, options2) {
        return this._client.getAPIList(path7`/containers/${containerID}/files`, CursorPage, {
          query,
          ...options2
        });
      }
      /**
       * Delete Container File
       */
      delete(fileID, params, options2) {
        const { container_id } = params;
        return this._client.delete(path7`/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_headers2();
    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(path7`/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(path7`/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(path7`/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(path7`/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(path7`/evals/${evalID}/runs`, { body, ...options2 });
      }
      /**
       * Get an evaluation run by ID.
       */
      retrieve(runID, params, options2) {
        const { eval_id } = params;
        return this._client.get(path7`/evals/${eval_id}/runs/${runID}`, options2);
      }
      /**
       * Get a list of runs for an evaluation.
       */
      list(evalID, query = {}, options2) {
        return this._client.getAPIList(path7`/evals/${evalID}/runs`, CursorPage, {
          query,
          ...options2
        });
      }
      /**
       * Delete an eval run.
       */
      delete(runID, params, options2) {
        const { eval_id } = params;
        return this._client.delete(path7`/evals/${eval_id}/runs/${runID}`, options2);
      }
      /**
       * Cancel an ongoing evaluation run.
       */
      cancel(runID, params, options2) {
        const { eval_id } = params;
        return this._client.post(path7`/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(path7`/evals/${evalID}`, options2);
      }
      /**
       * Update certain properties of an evaluation.
       */
      update(evalID, body, options2) {
        return this._client.post(path7`/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(path7`/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_headers2();
    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(path7`/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(path7`/files/${fileID}`, options2);
      }
      /**
       * Returns the contents of the specified file.
       */
      content(fileID, options2) {
        return this._client.get(path7`/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(path7`/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(path7`/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(path7`/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(path7`/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(path7`/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(path7`/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(path7`/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(path7`/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(path7`/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(path7`/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(path7`/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((resolve30, reject) => readQueue.push({ resolve: resolve30, 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(path7`/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_headers2();
    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(path7`/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(path7`/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(path7`/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(path7`/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(path7`/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(path7`/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 (promises8) => {
      const results = await Promise.allSettled(promises8);
      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_headers2();
    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(path7`/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(path7`/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(path7`/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(path7`/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_headers2();
    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(path7`/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(path7`/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(path7`/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(path7`/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(path7`/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(path7`/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_headers2();
    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(path7`/vector_stores/${vectorStoreID}`, {
          ...options2,
          headers: buildHeaders([{ "OpenAI-Beta": "assistants=v2" }, options2?.headers])
        });
      }
      /**
       * Modifies a vector store.
       */
      update(vectorStoreID, body, options2) {
        return this._client.post(path7`/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(path7`/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(path7`/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_headers2();
    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_version2();
    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_headers2();
    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 stringify(query, { arrayFormat: "brackets" });
      }
      getUserAgent() {
        return `${this.constructor.name}/JS ${VERSION2}`;
      }
      defaultIdempotencyKey() {
        return `stainless-node-retry-${uuid4()}`;
      }
      makeStatusError(status, error2, message, headers) {
        return APIError.generate(status, error2, message, headers);
      }
      buildURL(path125, query, defaultBaseURL) {
        const baseURL = !__classPrivateFieldGet(this, _OpenAI_instances, "m", _OpenAI_baseURLOverridden).call(this) && defaultBaseURL || this.baseURL;
        const url2 = isAbsoluteURL(path125) ? new URL(path125) : new URL(baseURL + (baseURL.endsWith("/") && path125.startsWith("/") ? path125.slice(1) : path125));
        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(path125, opts) {
        return this.methodRequest("get", path125, opts);
      }
      post(path125, opts) {
        return this.methodRequest("post", path125, opts);
      }
      patch(path125, opts) {
        return this.methodRequest("patch", path125, opts);
      }
      put(path125, opts) {
        return this.methodRequest("put", path125, opts);
      }
      delete(path125, opts) {
        return this.methodRequest("delete", path125, opts);
      }
      methodRequest(method, path125, opts) {
        return this.request(Promise.resolve(opts).then((opts2) => {
          return { method, path: path125, ...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 = isAbortError2(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(path125, Page3, opts) {
        return this.requestAPIList(Page3, { method: "get", path: path125, ...opts });
      }
      requestAPIList(Page3, options2) {
        const request4 = this.makeRequest(options2, null, void 0);
        return new PagePromise(this, request4, Page3);
      }
      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: path125, query, defaultBaseURL } = options2;
        const url2 = this.buildURL(path125, 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_headers2();
  }
});

// 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/utils/runtimeFetchOptions.js
function detectRuntime() {
  if (typeof process !== "undefined" && process.versions?.["bun"]) {
    return "bun";
  }
  if (typeof process !== "undefined" && process.versions?.node) {
    return "node";
  }
  return "unknown";
}
function buildRuntimeFetchOptions(sdkType, proxyUrl) {
  const runtime = detectRuntime();
  switch (runtime) {
    case "bun": {
      if (sdkType === "openai") {
        return {
          fetchOptions: {
            timeout: false
          }
        };
      } else {
        const bunFetch = /* @__PURE__ */ __name(async (input, init) => {
          const bunFetchOptions = {
            ...init,
            // @ts-expect-error - Bun-specific timeout option
            timeout: false
          };
          return fetch(input, bunFetchOptions);
        }, "bunFetch");
        return {
          fetch: bunFetch
        };
      }
    }
    case "node": {
      return buildFetchOptionsWithDispatcher(sdkType, proxyUrl);
    }
    default: {
      return buildFetchOptionsWithDispatcher(sdkType, proxyUrl);
    }
  }
}
function buildFetchOptionsWithDispatcher(sdkType, proxyUrl) {
  try {
    const dispatcher = proxyUrl ? new import_undici.ProxyAgent({
      uri: proxyUrl,
      headersTimeout: 0,
      bodyTimeout: 0
    }) : new import_undici.Agent({
      headersTimeout: 0,
      bodyTimeout: 0
    });
    return { fetchOptions: { dispatcher } };
  } catch {
    return sdkType === "openai" ? void 0 : {};
  }
}
var import_undici;
var init_runtimeFetchOptions = __esm({
  "packages/core/dist/src/utils/runtimeFetchOptions.js"() {
    "use strict";
    init_esbuild_shims();
    import_undici = __toESM(require_undici(), 1);
    __name(detectRuntime, "detectRuntime");
    __name(buildRuntimeFetchOptions, "buildRuntimeFetchOptions");
    __name(buildFetchOptionsWithDispatcher, "buildFetchOptionsWithDispatcher");
  }
});

// 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();
    init_runtimeFetchOptions();
    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})`;
        const { customHeaders } = this.contentGeneratorConfig;
        const defaultHeaders = {
          "User-Agent": userAgent2
        };
        return customHeaders ? { ...defaultHeaders, ...customHeaders } : defaultHeaders;
      }
      buildClient() {
        const { apiKey, baseUrl, timeout: timeout2 = DEFAULT_TIMEOUT, maxRetries = DEFAULT_MAX_RETRIES } = this.contentGeneratorConfig;
        const defaultHeaders = this.buildHeaders();
        const runtimeOptions = buildRuntimeFetchOptions("openai", this.cliConfig.getProxy());
        return new OpenAI({
          apiKey,
          baseURL: baseUrl,
          timeout: timeout2,
          maxRetries,
          defaultHeaders,
          ...runtimeOptions || {}
        });
      }
      buildRequest(request4, _userPromptId) {
        const extraBody = this.contentGeneratorConfig.extra_body;
        return {
          ...request4,
          // Preserve all original parameters including sampling params
          ...extraBody ? extraBody : {}
        };
      }
      getDefaultGenerationConfig() {
        return {};
      }
    };
  }
});

// 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(config2) {
        return !!config2.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/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_runtimeFetchOptions();
    init_tokenLimits();
    DashScopeOpenAICompatibleProvider = class _DashScopeOpenAICompatibleProvider {
      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" || !baseUrl;
      }
      buildHeaders() {
        const version2 = this.cliConfig.getCliVersion() || "unknown";
        const userAgent2 = `QwenCode/${version2} (${process.platform}; ${process.arch})`;
        const { authType, customHeaders } = this.contentGeneratorConfig;
        const defaultHeaders = {
          "User-Agent": userAgent2,
          "X-DashScope-CacheControl": "enable",
          "X-DashScope-UserAgent": userAgent2,
          "X-DashScope-AuthType": authType
        };
        return customHeaders ? { ...defaultHeaders, ...customHeaders } : defaultHeaders;
      }
      buildClient() {
        const { apiKey, baseUrl = DEFAULT_DASHSCOPE_BASE_URL, timeout: timeout2 = DEFAULT_TIMEOUT, maxRetries = DEFAULT_MAX_RETRIES } = this.contentGeneratorConfig;
        const defaultHeaders = this.buildHeaders();
        const runtimeOptions = buildRuntimeFetchOptions("openai", this.cliConfig.getProxy());
        return new OpenAI({
          apiKey,
          baseURL: baseUrl,
          timeout: timeout2,
          maxRetries,
          defaultHeaders,
          ...runtimeOptions || {}
        });
      }
      /**
       * 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.shouldEnableCacheControl()) {
          const { messages: updatedMessages, tools: updatedTools } = this.addDashScopeCacheControl(request4, request4.stream ? "all" : "system_only");
          messages = updatedMessages;
          tools = updatedTools;
        }
        const requestWithTokenLimits = this.applyOutputTokenLimit(request4);
        const extraBody = this.contentGeneratorConfig.extra_body;
        if (this.isVisionModel(request4.model)) {
          return {
            ...requestWithTokenLimits,
            messages,
            ...tools ? { tools } : {},
            ...this.buildMetadata(userPromptId) || {},
            /* @ts-expect-error dashscope exclusive */
            vl_high_resolution_images: true,
            ...extraBody ? extraBody : {}
          };
        }
        return {
          ...requestWithTokenLimits,
          // Preserve all original parameters including sampling params and adjusted max_tokens
          messages,
          ...tools ? { tools } : {},
          ...this.buildMetadata(userPromptId) || {},
          ...extraBody ? extraBody : {}
        };
      }
      buildMetadata(userPromptId) {
        const channel = this.cliConfig.getChannel?.();
        return {
          metadata: {
            sessionId: this.cliConfig.getSessionId?.(),
            promptId: userPromptId,
            ...channel ? { channel } : {}
          }
        };
      }
      getDefaultGenerationConfig() {
        return {
          temperature: 0.3
        };
      }
      /**
       * 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 contentArray;
        }
        const lastItem = contentArray[contentArray.length - 1];
        contentArray[contentArray.length - 1] = {
          ...lastItem,
          cache_control: { type: "ephemeral" }
        };
        return contentArray;
      }
      /**
       * Vision-capable model patterns.
       * Supports exact matches and prefix patterns for easy extension.
       */
      static VISION_MODEL_EXACT_MATCHES = /* @__PURE__ */ new Set(["coder-model"]);
      static VISION_MODEL_PREFIX_PATTERNS = [
        "qwen-vl",
        // qwen-vl-max, qwen-vl-max-latest, etc.
        "qwen3-vl-plus",
        // qwen3-vl-plus variants
        "qwen3.5-plus"
        // qwen3.5-plus (has built-in vision capabilities)
      ];
      isVisionModel(model) {
        if (!model) {
          return false;
        }
        const normalized2 = model.toLowerCase();
        if (_DashScopeOpenAICompatibleProvider.VISION_MODEL_EXACT_MATCHES.has(normalized2)) {
          return true;
        }
        for (const prefix of _DashScopeOpenAICompatibleProvider.VISION_MODEL_PREFIX_PATTERNS) {
          if (normalized2.startsWith(prefix)) {
            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
       * @returns The request with max_tokens adjusted to respect the model's limits (if present)
       */
      applyOutputTokenLimit(request4) {
        const currentMaxTokens = request4.max_tokens;
        if (currentMaxTokens === void 0 || currentMaxTokens === null) {
          return request4;
        }
        const modelLimit = tokenLimit(request4.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 enabled, false otherwise
       */
      shouldEnableCacheControl() {
        return this.cliConfig.getContentGeneratorConfig()?.enableCacheControl !== false;
      }
    };
  }
});

// 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
        };
      }
      getDefaultGenerationConfig() {
        return {
          temperature: 0
        };
      }
    };
  }
});

// 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-OpenRouter-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();
  }
});

// packages/core/dist/src/core/openaiContentGenerator/pipeline.js
var StreamContentError, ContentGenerationPipeline;
var init_pipeline = __esm({
  "packages/core/dist/src/core/openaiContentGenerator/pipeline.js"() {
    "use strict";
    init_esbuild_shims();
    init_node();
    init_converter();
    StreamContentError = class extends Error {
      static {
        __name(this, "StreamContentError");
      }
      constructor(message) {
        super(message);
        this.name = "StreamContentError";
      }
    };
    ContentGenerationPipeline = class {
      static {
        __name(this, "ContentGenerationPipeline");
      }
      config;
      client;
      converter;
      contentGeneratorConfig;
      constructor(config2) {
        this.config = config2;
        this.contentGeneratorConfig = config2.contentGeneratorConfig;
        this.client = this.config.provider.buildClient();
        this.converter = new OpenAIContentConverter(this.contentGeneratorConfig.model, this.contentGeneratorConfig.schemaCompliance);
      }
      async execute(request4, userPromptId) {
        const effectiveModel = this.contentGeneratorConfig.model;
        this.converter.setModel(effectiveModel);
        return this.executeWithErrorHandling(request4, userPromptId, false, effectiveModel, async (openaiRequest) => {
          const openaiResponse = await this.client.chat.completions.create(openaiRequest, {
            signal: request4.config?.abortSignal
          });
          const geminiResponse = this.converter.convertOpenAIResponseToGemini(openaiResponse);
          return geminiResponse;
        });
      }
      async executeStream(request4, userPromptId) {
        const effectiveModel = this.contentGeneratorConfig.model;
        this.converter.setModel(effectiveModel);
        return this.executeWithErrorHandling(request4, userPromptId, true, effectiveModel, async (openaiRequest, context2) => {
          const stream2 = await this.client.chat.completions.create(openaiRequest, {
            signal: request4.config?.abortSignal
          });
          return this.processStreamWithLogging(stream2, context2, 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, request4) {
        const collectedGeminiResponses = [];
        this.converter.resetStreamingToolCalls();
        let pendingFinishResponse = null;
        try {
          for await (const chunk of stream2) {
            if (chunk.choices?.[0]?.finish_reason === "error_finish") {
              const errorContent = chunk.choices?.[0]?.delta?.content?.trim() || "Unknown stream error";
              throw new StreamContentError(errorContent);
            }
            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;
        } catch (error2) {
          this.converter.resetStreamingToolCalls();
          if (error2 instanceof StreamContentError) {
            throw error2;
          }
          await this.handleError(error2, 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, effectiveModel) {
        const messages = this.converter.convertGeminiRequestToOpenAI(request4);
        const baseRequest = {
          model: effectiveModel,
          messages,
          ...this.buildGenerateContentConfig(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);
      }
      buildGenerateContentConfig(request4) {
        const defaultSamplingParams = this.config.provider.getDefaultGenerationConfig();
        const configSamplingParams = this.contentGeneratorConfig.samplingParams;
        const getParameterValue = /* @__PURE__ */ __name((configKey, requestKey) => {
          const configValue = configSamplingParams?.[configKey];
          const requestValue = requestKey ? request4.config?.[requestKey] : void 0;
          const defaultValue = requestKey ? defaultSamplingParams[requestKey] : void 0;
          if (configValue !== void 0)
            return configValue;
          if (requestValue !== void 0)
            return requestValue;
          return defaultValue;
        }, "getParameterValue");
        const addParameterIfDefined = /* @__PURE__ */ __name((key, configKey, requestKey) => {
          const value = getParameterValue(configKey, requestKey);
          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", "topK"),
          ...addParameterIfDefined("repetition_penalty", "repetition_penalty"),
          ...addParameterIfDefined("presence_penalty", "presence_penalty", "presencePenalty"),
          ...addParameterIfDefined("frequency_penalty", "frequency_penalty", "frequencyPenalty"),
          ...this.buildReasoningConfig(request4)
        };
        return params;
      }
      buildReasoningConfig(request4) {
        if (request4.config?.thinkingConfig?.includeThoughts === false) {
          return {};
        }
        const reasoning = this.contentGeneratorConfig.reasoning;
        if (reasoning === false || reasoning === void 0) {
          return {};
        }
        return { reasoning };
      }
      /**
       * Common error handling wrapper for execute methods
       */
      async executeWithErrorHandling(request4, userPromptId, isStreaming, effectiveModel, executor) {
        const context2 = this.createRequestContext(userPromptId, isStreaming, effectiveModel);
        try {
          const openaiRequest = await this.buildRequest(request4, userPromptId, isStreaming, effectiveModel);
          const result = await executor(openaiRequest, context2);
          context2.duration = Date.now() - context2.startTime;
          return result;
        } catch (error2) {
          return await this.handleError(error2, context2, request4);
        }
      }
      /**
       * Shared error handling logic for both executeWithErrorHandling and processStreamWithLogging
       * This centralizes the common error processing steps to avoid duplication
       */
      async handleError(error2, context2, request4) {
        context2.duration = Date.now() - context2.startTime;
        this.config.errorHandler.handle(error2, context2, request4);
      }
      /**
       * Create request context with common properties
       */
      createRequestContext(userPromptId, isStreaming, effectiveModel) {
        return {
          userPromptId,
          model: effectiveModel,
          authType: this.contentGeneratorConfig.authType || "unknown",
          startTime: Date.now(),
          duration: 0,
          isStreaming
        };
      }
    };
  }
});

// packages/core/dist/src/core/openaiContentGenerator/errorHandler.js
var debugLogger7, EnhancedErrorHandler;
var init_errorHandler = __esm({
  "packages/core/dist/src/core/openaiContentGenerator/errorHandler.js"() {
    "use strict";
    init_esbuild_shims();
    init_debugLogger();
    debugLogger7 = createDebugLogger("OPENAI_ERROR");
    EnhancedErrorHandler = class {
      static {
        __name(this, "EnhancedErrorHandler");
      }
      shouldSuppressLogging;
      constructor(shouldSuppressLogging = () => false) {
        this.shouldSuppressLogging = shouldSuppressLogging;
      }
      handle(error2, context2, request4) {
        const isTimeoutError = this.isTimeoutError(error2);
        const errorMessage = this.buildErrorMessage(error2, context2, isTimeoutError);
        if (!this.shouldSuppressErrorLogging(error2, request4)) {
          const logPrefix = context2.isStreaming ? "OpenAI API Streaming Error:" : "OpenAI API Error:";
          debugLogger7.error(logPrefix, errorMessage);
        }
        if (isTimeoutError) {
          throw new Error(`${errorMessage}

${this.getTimeoutTroubleshootingTips(context2)}`);
        }
        throw error2;
      }
      shouldSuppressErrorLogging(error2, request4) {
        return this.shouldSuppressLogging(error2, request4);
      }
      isTimeoutError(error2) {
        if (!error2)
          return false;
        const errorMessage = error2 instanceof Error ? error2.message.toLowerCase() : String(error2).toLowerCase();
        const errorCode = error2?.code;
        const errorType = error2?.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(error2, 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 error2 instanceof Error ? error2.message : String(error2);
      }
      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
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");
      }
      /**
       * Calculate tokens for text content
       *
       * @param text - The text to estimate tokens for
       * @returns The estimated token count
       */
      async calculateTokens(text) {
        return this.calculateTokensSync(text);
      }
      /**
       * Calculate tokens for multiple text strings
       *
       * @param texts - Array of text strings to estimate tokens for
       * @returns Array of token counts corresponding to each input text
       */
      async calculateTokensBatch(texts) {
        return texts.map((text) => this.calculateTokensSync(text));
      }
      calculateTokensSync(text) {
        if (!text || text.length === 0) {
          return 0;
        }
        let asciiChars = 0;
        let nonAsciiChars = 0;
        for (let i3 = 0; i3 < text.length; i3++) {
          const charCode = text.charCodeAt(i3);
          if (charCode < 128) {
            asciiChars++;
          } else {
            nonAsciiChars++;
          }
        }
        const tokens = asciiChars / 4 + nonAsciiChars * 1.1;
        return Math.ceil(tokens);
      }
    };
  }
});

// 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 debugLogger8, ImageTokenizer;
var init_imageTokenizer = __esm({
  "packages/core/dist/src/utils/request-tokenizer/imageTokenizer.js"() {
    "use strict";
    init_esbuild_shims();
    init_supportedImageFormats();
    init_debugLogger();
    debugLogger8 = createDebugLogger("IMAGE_TOKENIZER");
    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)) {
            debugLogger8.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 (error2) {
          debugLogger8.warn("Failed to extract image metadata:", error2);
          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 (error2) {
            debugLogger8.warn("Error calculating tokens for image:", error2);
            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 i3 = 0; i3 < numEntries; i3++) {
          const entryOffset = ifdOffset + 2 + i3 * 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;
        }
        debugLogger8.warn("Could not extract HEIC dimensions, using default");
        return { width: 512, height: 512 };
      }
    };
  }
});

// packages/core/dist/src/utils/request-tokenizer/requestTokenizer.js
var debugLogger9, RequestTokenizer;
var init_requestTokenizer = __esm({
  "packages/core/dist/src/utils/request-tokenizer/requestTokenizer.js"() {
    "use strict";
    init_esbuild_shims();
    init_textTokenizer();
    init_imageTokenizer();
    init_debugLogger();
    debugLogger9 = createDebugLogger("TOKENIZER");
    RequestTokenizer = class {
      static {
        __name(this, "RequestTokenizer");
      }
      textTokenizer;
      imageTokenizer;
      constructor() {
        this.textTokenizer = new TextTokenizer();
        this.imageTokenizer = new ImageTokenizer();
      }
      /**
       * Calculate tokens for a request using serial processing
       */
      async calculateTokens(request4) {
        const startTime = performance.now();
        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 (error2) {
          debugLogger9.error("Error calculating tokens:", error2);
          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 {
          return await this.textTokenizer.calculateTokens(textContents.join(""));
        } catch (error2) {
          debugLogger9.warn("Error calculating text tokens:", error2);
          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 (error2) {
          debugLogger9.warn("Error calculating image tokens:", error2);
          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 (error2) {
            debugLogger9.warn("Error calculating audio tokens:", error2);
            totalTokens += 10;
          }
        }
        return totalTokens;
      }
      /**
       * Calculate tokens for other content types (functions, files, etc.)
       */
      async calculateOtherTokens(otherContents) {
        if (otherContents.length === 0)
          return 0;
        try {
          return await this.textTokenizer.calculateTokens(otherContents.join(""));
        } catch (error2) {
          debugLogger9.warn("Error calculating other content tokens:", error2);
          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 (error2) {
          debugLogger9.warn("Error in fallback token calculation:", error2);
          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);
          }
          return;
        }
        this.processPart(content, 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 (error2) {
          debugLogger9.warn("Failed to serialize unknown part type:", error2);
        }
      }
    };
  }
});

// packages/core/dist/src/utils/request-tokenizer/index.js
var init_request_tokenizer = __esm({
  "packages/core/dist/src/utils/request-tokenizer/index.js"() {
    "use strict";
    init_esbuild_shims();
    init_requestTokenizer();
    init_textTokenizer();
    init_imageTokenizer();
  }
});

// packages/core/dist/src/core/openaiContentGenerator/openaiContentGenerator.js
var debugLogger10, OpenAIContentGenerator;
var init_openaiContentGenerator = __esm({
  "packages/core/dist/src/core/openaiContentGenerator/openaiContentGenerator.js"() {
    "use strict";
    init_esbuild_shims();
    init_provider();
    init_pipeline();
    init_errorHandler();
    init_request_tokenizer();
    init_errors();
    init_debugLogger();
    debugLogger10 = createDebugLogger("OPENAI");
    OpenAIContentGenerator = class {
      static {
        __name(this, "OpenAIContentGenerator");
      }
      pipeline;
      constructor(contentGeneratorConfig, cliConfig, provider) {
        const pipelineConfig = {
          cliConfig,
          provider,
          contentGeneratorConfig,
          errorHandler: new EnhancedErrorHandler((error2, request4) => this.shouldSuppressErrorLogging(error2, 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(error2, request4) {
        if (isAbortError(error2) && request4.config?.abortSignal?.aborted) {
          return true;
        }
        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 estimator = new RequestTokenizer();
          const result = await estimator.calculateTokens(request4);
          return {
            totalTokens: result.totalTokens
          };
        } catch (error2) {
          debugLogger10.warn("Failed to calculate tokens with new tokenizer, falling back to simple method:", error2);
          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 (error2) {
          debugLogger10.error("OpenAI API Embedding Error:", error2);
          throw new Error(`OpenAI API error: ${error2 instanceof Error ? error2.message : String(error2)}`);
        }
      }
      useSummarizedThinking() {
        return false;
      }
    };
  }
});

// packages/core/dist/src/core/openaiContentGenerator/index.js
var openaiContentGenerator_exports = {};
__export(openaiContentGenerator_exports, {
  ContentGenerationPipeline: () => ContentGenerationPipeline,
  DashScopeOpenAICompatibleProvider: () => DashScopeOpenAICompatibleProvider,
  DeepSeekOpenAICompatibleProvider: () => DeepSeekOpenAICompatibleProvider,
  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 config2 = contentGeneratorConfig || cliConfig.getContentGeneratorConfig();
  if (DashScopeOpenAICompatibleProvider.isDashScopeProvider(config2)) {
    return new DashScopeOpenAICompatibleProvider(contentGeneratorConfig, cliConfig);
  }
  if (DeepSeekOpenAICompatibleProvider.isDeepSeekProvider(config2)) {
    return new DeepSeekOpenAICompatibleProvider(contentGeneratorConfig, cliConfig);
  }
  if (OpenRouterOpenAICompatibleProvider.isOpenRouterProvider(config2)) {
    return new OpenRouterOpenAICompatibleProvider(contentGeneratorConfig, cliConfig);
  }
  if (ModelScopeOpenAICompatibleProvider.isModelScopeProvider(config2)) {
    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_converter();
    init_errorHandler();
    __name(createOpenAIContentGenerator, "createOpenAIContentGenerator");
    __name(determineProvider, "determineProvider");
  }
});

// node_modules/is-docker/index.js
import fs10 from "node:fs";
function hasDockerEnv() {
  try {
    fs10.statSync("/.dockerenv");
    return true;
  } catch {
    return false;
  }
}
function hasDockerCGroup() {
  try {
    return fs10.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 fs11 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 {
        fs11.statSync("/run/.containerenv");
        return true;
      } catch {
        return false;
      }
    }, "hasContainerEnv");
    __name(isInsideContainer, "isInsideContainer");
  }
});

// node_modules/is-wsl/index.js
import process3 from "node:process";
import os5 from "node:os";
import fs12 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 (process3.platform !== "linux") {
        return false;
      }
      if (os5.release().toLowerCase().includes("microsoft")) {
        if (isInsideContainer()) {
          return false;
        }
        return true;
      }
      try {
        return fs12.readFileSync("/proc/version", "utf8").toLowerCase().includes("microsoft") ? !isInsideContainer() : false;
      } catch {
        return false;
      }
    }, "isWsl");
    is_wsl_default = process3.env.__IS_WSL_TEST__ ? isWsl : isWsl();
  }
});

// node_modules/wsl-utils/index.js
import process4 from "node:process";
import fs13, { constants as fsConstants } from "node:fs/promises";
var wslDrivesMountPoint, powerShellPathFromWsl, powerShellPath;
var init_wsl_utils = __esm({
  "node_modules/wsl-utils/index.js"() {
    init_esbuild_shims();
    init_is_wsl();
    init_is_wsl();
    wslDrivesMountPoint = /* @__PURE__ */ (() => {
      const defaultMountPoint = "/mnt/";
      let mountPoint;
      return async function() {
        if (mountPoint) {
          return mountPoint;
        }
        const configFilePath2 = "/etc/wsl.conf";
        let isConfigFileExists = false;
        try {
          await fs13.access(configFilePath2, fsConstants.F_OK);
          isConfigFileExists = true;
        } catch {
        }
        if (!isConfigFileExists) {
          return defaultMountPoint;
        }
        const configContent = await fs13.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;
      };
    })();
    powerShellPathFromWsl = /* @__PURE__ */ __name(async () => {
      const mountPoint = await wslDrivesMountPoint();
      return `${mountPoint}c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe`;
    }, "powerShellPathFromWsl");
    powerShellPath = /* @__PURE__ */ __name(async () => {
      if (is_wsl_default) {
        return powerShellPathFromWsl();
      }
      return `${process4.env.SYSTEMROOT || process4.env.windir || String.raw`C:\Windows`}\\System32\\WindowsPowerShell\\v1.0\\powershell.exe`;
    }, "powerShellPath");
  }
});

// node_modules/define-lazy-prop/index.js
function defineLazyProperty(object3, propertyName, valueGetter) {
  const define2 = /* @__PURE__ */ __name((value) => Object.defineProperty(object3, propertyName, { value, enumerable: true, writable: true }), "define");
  Object.defineProperty(object3, propertyName, {
    configurable: true,
    enumerable: true,
    get() {
      const result = valueGetter();
      define2(result);
      return result;
    },
    set(value) {
      define2(value);
    }
  });
  return object3;
}
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 as promisify2 } from "node:util";
import process5 from "node:process";
import { execFile } from "node:child_process";
async function defaultBrowserId() {
  if (process5.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 = promisify2(execFile);
    __name(defaultBrowserId, "defaultBrowserId");
  }
});

// node_modules/run-applescript/index.js
import process6 from "node:process";
import { promisify as promisify3 } from "node:util";
import { execFile as execFile2, execFileSync } from "node:child_process";
async function runAppleScript(script, { humanReadableOutput = true } = {}) {
  if (process6.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 = promisify3(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 promisify4 } 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 = promisify4(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 promisify5 } from "node:util";
import process7 from "node:process";
import { execFile as execFile4 } from "node:child_process";
async function defaultBrowser2() {
  if (process7.platform === "darwin") {
    const id = await defaultBrowserId();
    const name3 = await bundleName(id);
    return { name: name3, id };
  }
  if (process7.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 (process7.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 = promisify5(execFile4);
    titleize = /* @__PURE__ */ __name((string4) => string4.toLowerCase().replaceAll(/(?:^|\s|-)\S/g, (x3) => x3.toUpperCase()), "titleize");
    __name(defaultBrowser2, "defaultBrowser");
  }
});

// node_modules/open/index.js
import process8 from "node:process";
import { Buffer as Buffer5 } from "node:buffer";
import path8 from "node:path";
import { fileURLToPath as fileURLToPath2 } from "node:url";
import { promisify as promisify6 } from "node:util";
import childProcess from "node:child_process";
import fs14, { constants as fsConstants2 } from "node:fs/promises";
async function getWindowsDefaultBrowserFromWsl() {
  const powershellPath = await powerShellPath();
  const rawCommand = String.raw`(Get-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\Shell\Associations\UrlAssociations\http\UserChoice").ProgId`;
  const encodedCommand = Buffer5.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",
    BraveHTML: "com.brave.Browser",
    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({ [platform4]: platformBinary }, { wsl }) {
  if (wsl && is_wsl_default) {
    return detectArchBinary(wsl);
  }
  if (!platformBinary) {
    throw new Error(`${platform4} is not supported`);
  }
  return detectArchBinary(platformBinary);
}
var execFile5, __dirname2, localXdgOpenPath, platform4, arch, pTryEach, baseOpen, open2, apps, open_default;
var init_open = __esm({
  "node_modules/open/index.js"() {
    init_esbuild_shims();
    init_wsl_utils();
    init_define_lazy_prop();
    init_default_browser();
    init_is_inside_container();
    execFile5 = promisify6(childProcess.execFile);
    __dirname2 = path8.dirname(fileURLToPath2(import.meta.url));
    localXdgOpenPath = path8.join(__dirname2, "xdg-open");
    ({ platform: platform4, arch } = process8);
    __name(getWindowsDefaultBrowserFromWsl, "getWindowsDefaultBrowserFromWsl");
    pTryEach = /* @__PURE__ */ __name(async (array2, mapper) => {
      let latestError;
      for (const item of array2) {
        try {
          return await mapper(item);
        } catch (error2) {
          latestError = error2;
        }
      }
      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",
          "com.brave.Browser": "brave",
          "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",
          brave: "--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 (platform4 === "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 (platform4 === "win32" || is_wsl_default && !isInsideContainer() && !app) {
        command2 = await powerShellPath();
        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 = Buffer5.from(encodedArguments.join(" "), "utf16le").toString("base64");
      } else {
        if (app) {
          command2 = app;
        } else {
          const isBundled = !__dirname2 || __dirname2 === "/";
          let exeLocalXdgOpen = false;
          try {
            await fs14.access(localXdgOpenPath, fsConstants2.X_OK);
            exeLocalXdgOpen = true;
          } catch {
          }
          const useSystemXdgOpen = process8.versions.electron ?? (platform4 === "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 (platform4 === "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((resolve30, reject) => {
          subprocess.once("error", reject);
          subprocess.once("close", (exitCode) => {
            if (!options2.allowNonzeroExitCode && exitCode > 0) {
              reject(new Error(`Exited with code ${exitCode}`));
              return;
            }
            resolve30(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, "brave", () => detectPlatformBinary({
      darwin: "brave browser",
      win32: "brave",
      linux: ["brave-browser", "brave"]
    }, {
      wsl: {
        ia32: "/mnt/c/Program Files (x86)/BraveSoftware/Brave-Browser/Application/brave.exe",
        x64: ["/mnt/c/Program Files/BraveSoftware/Brave-Browser/Application/brave.exe", "/mnt/c/Program Files (x86)/BraveSoftware/Brave-Browser/Application/brave.exe"]
      }
    }));
    defineLazyProperty(apps, "firefox", () => detectPlatformBinary({
      darwin: "firefox",
      win32: String.raw`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/utils/fetch.js
import { URL as URL2 } from "node:url";
function isPrivateIp(url2) {
  try {
    const hostname4 = new URL2(url2).hostname;
    return PRIVATE_IP_RANGES.some((range) => range.test(hostname4));
  } catch (_e2) {
    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 (error2) {
    if (isNodeError(error2) && error2.code === "ABORT_ERR") {
      throw new FetchError2(`Request timed out after ${timeout2}ms`, "ETIMEDOUT");
    }
    throw new FetchError2(getErrorMessage(error2));
  } finally {
    clearTimeout(timeoutId);
  }
}
function getErrorCode(error2) {
  if (!error2 || typeof error2 !== "object") {
    return void 0;
  }
  if ("code" in error2 && typeof error2["code"] === "string") {
    return error2["code"];
  }
  return void 0;
}
function formatUnknownErrorMessage(error2) {
  if (typeof error2 === "string") {
    return error2;
  }
  if (typeof error2 === "number" || typeof error2 === "boolean" || typeof error2 === "bigint") {
    return String(error2);
  }
  if (error2 instanceof Error) {
    return error2.message;
  }
  if (!error2 || typeof error2 !== "object") {
    return void 0;
  }
  const message = error2["message"];
  if (typeof message === "string") {
    return message;
  }
  return void 0;
}
function formatErrorCause(error2) {
  if (!(error2 instanceof Error)) {
    return void 0;
  }
  const cause = error2.cause;
  if (!cause) {
    return void 0;
  }
  const causeCode = getErrorCode(cause);
  const causeMessage = formatUnknownErrorMessage(cause);
  if (!causeCode && !causeMessage) {
    return void 0;
  }
  if (causeCode && causeMessage && !causeMessage.includes(causeCode)) {
    return `${causeCode}: ${causeMessage}`;
  }
  return causeMessage ?? causeCode;
}
function formatFetchErrorForUser(error2, options2 = {}) {
  const errorMessage = getErrorMessage(error2);
  const code2 = error2 instanceof Error ? getErrorCode(error2.cause) ?? getErrorCode(error2) : getErrorCode(error2);
  const cause = formatErrorCause(error2);
  const fullErrorMessage = [
    errorMessage,
    cause ? `(cause: ${cause})` : void 0
  ].filter(Boolean).join(" ");
  const shouldShowFetchHints = errorMessage.toLowerCase().includes("fetch failed") || code2 != null && FETCH_TROUBLESHOOTING_ERROR_CODES.has(code2);
  const shouldShowTlsHint = code2 != null && TLS_ERROR_CODES.has(code2);
  if (!shouldShowFetchHints) {
    return fullErrorMessage;
  }
  const hintLines = [
    "",
    "Troubleshooting:",
    ...options2.url ? [`- Confirm you can reach ${options2.url} from this machine.`] : [],
    "- If you are behind a proxy, pass `--proxy <url>` (or set `proxy` in settings).",
    ...shouldShowTlsHint ? [
      "- If your network uses a corporate TLS inspection CA, set `NODE_EXTRA_CA_CERTS` to your CA bundle."
    ] : []
  ];
  return `${fullErrorMessage}${hintLines.join("\n")}`;
}
var PRIVATE_IP_RANGES, TLS_ERROR_CODES, FETCH_TROUBLESHOOTING_ERROR_CODES, FetchError2;
var init_fetch = __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:/
    ];
    TLS_ERROR_CODES = /* @__PURE__ */ new Set([
      "UNABLE_TO_GET_ISSUER_CERT_LOCALLY",
      "UNABLE_TO_VERIFY_LEAF_SIGNATURE",
      "SELF_SIGNED_CERT_IN_CHAIN",
      "DEPTH_ZERO_SELF_SIGNED_CERT",
      "CERT_HAS_EXPIRED",
      "ERR_TLS_CERT_ALTNAME_INVALID"
    ]);
    FETCH_TROUBLESHOOTING_ERROR_CODES = /* @__PURE__ */ new Set([
      ...TLS_ERROR_CODES,
      "ECONNRESET",
      "ETIMEDOUT",
      "ECONNREFUSED",
      "ENOTFOUND",
      "EAI_AGAIN",
      "EHOSTUNREACH",
      "ENETUNREACH"
    ]);
    FetchError2 = 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");
    __name(getErrorCode, "getErrorCode");
    __name(formatUnknownErrorMessage, "formatUnknownErrorMessage");
    __name(formatErrorCause, "formatErrorCause");
    __name(formatFetchErrorForUser, "formatFetchErrorForUser");
  }
});

// packages/core/dist/src/qwen/sharedTokenManager.js
import path9 from "node:path";
import { promises as fs15, unlinkSync } from "node:fs";
import * as os6 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 debugLogger11, QWEN_DIR3, QWEN_CREDENTIAL_FILENAME, 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();
    init_debugLogger();
    debugLogger11 = createDebugLogger("QWEN_OAUTH");
    QWEN_DIR3 = ".qwen";
    QWEN_CREDENTIAL_FILENAME = "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 (error2) {
          if (error2 instanceof TokenManagerError) {
            throw error2;
          }
          throw new TokenManagerError(TokenError.REFRESH_FAILED, `Failed to get valid credentials: ${error2 instanceof Error ? error2.message : String(error2)}`, error2);
        }
      }
      /**
       * 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((_2, 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(fs15.stat(filePath), 3e3, "File operation");
          const fileModTime = stats.mtimeMs;
          if (fileModTime > this.memoryCache.fileModTime) {
            await this.reloadCredentialsFromFile(qwenClient);
            this.memoryCache.fileModTime = fileModTime;
          }
        } catch (error2) {
          if (error2 instanceof Error && "code" in error2 && error2.code !== "ENOENT") {
            this.updateCacheState(null, 0, checkTime);
            throw new TokenManagerError(TokenError.FILE_ACCESS_ERROR, `Failed to access credentials file: ${error2.message}`, error2);
          }
          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 fs15.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 (error2) {
          if (error2 instanceof Error && "code" in error2 && error2.code !== "ENOENT") {
            this.updateCacheState(null, 0);
            throw new TokenManagerError(TokenError.FILE_ACCESS_ERROR, `Failed to access credentials file during refresh: ${error2.message}`, error2);
          }
          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 fs15.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 (error2) {
          if (error2 instanceof Error && error2.message.includes("Invalid credentials")) {
            debugLogger11.warn(`Failed to validate credentials file: ${error2.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) {
            debugLogger11.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) {
            debugLogger11.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 (error2) {
          if (error2 instanceof CredentialsClearRequiredError) {
            debugLogger11.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, error2.message, error2);
          }
          if (error2 instanceof TokenManagerError) {
            throw error2;
          }
          if (error2 instanceof Error && (error2.message.includes("fetch") || error2.message.includes("network") || error2.message.includes("timeout"))) {
            throw new TokenManagerError(TokenError.NETWORK_ERROR, `Network error during token refresh: ${error2.message}`, error2);
          }
          throw new TokenManagerError(TokenError.REFRESH_FAILED, `Unexpected error during token refresh: ${error2 instanceof Error ? error2.message : String(error2)}`, error2);
        } 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 = path9.dirname(filePath);
        const tempPath = `${filePath}.tmp.${randomUUID2()}`;
        try {
          await this.withTimeout(fs15.mkdir(dirPath, { recursive: true, mode: 448 }), 5e3, "File operation");
        } catch (error2) {
          throw new TokenManagerError(TokenError.FILE_ACCESS_ERROR, `Failed to create credentials directory: ${error2 instanceof Error ? error2.message : String(error2)}`, error2);
        }
        const credString = JSON.stringify(credentials, null, 2);
        try {
          await this.withTimeout(fs15.writeFile(tempPath, credString, { mode: 384 }), 5e3, "File operation");
          await this.withTimeout(fs15.rename(tempPath, filePath), 5e3, "File operation");
          const stats = await this.withTimeout(fs15.stat(filePath), 5e3, "File operation");
          this.memoryCache.fileModTime = stats.mtimeMs;
        } catch (error2) {
          try {
            await this.withTimeout(fs15.unlink(tempPath), 1e3, "File operation");
          } catch (_cleanupError) {
          }
          throw new TokenManagerError(TokenError.FILE_ACCESS_ERROR, `Failed to write credentials file: ${error2 instanceof Error ? error2.message : String(error2)}`, error2);
        }
      }
      /**
       * 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 path9.join(os6.homedir(), QWEN_DIR3, QWEN_CREDENTIAL_FILENAME);
      }
      /**
       * Get the full path to the lock file
       *
       * @returns The absolute path to the lock file
       */
      getLockFilePath() {
        return path9.join(os6.homedir(), QWEN_DIR3, 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 fs15.writeFile(lockPath, lockId, { flag: "wx" });
            return;
          } catch (error2) {
            if (error2.code === "EEXIST") {
              try {
                const stats = await fs15.stat(lockPath);
                const lockAge = Date.now() - stats.mtimeMs;
                if (lockAge > LOCK_TIMEOUT_MS) {
                  const tempPath = `${lockPath}.stale.${randomUUID2()}`;
                  try {
                    await fs15.rename(lockPath, tempPath);
                    await fs15.unlink(tempPath);
                    debugLogger11.warn(`Removed stale lock file: ${lockPath} (age: ${lockAge}ms)`);
                    continue;
                  } catch (renameError) {
                    debugLogger11.warn(`Failed to remove stale lock file ${lockPath}: ${renameError instanceof Error ? renameError.message : String(renameError)}`);
                  }
                }
              } catch (statError) {
                debugLogger11.warn(`Failed to stat lock file ${lockPath}: ${statError instanceof Error ? statError.message : String(statError)}`);
              }
              await new Promise((resolve30) => setTimeout(resolve30, currentInterval));
              currentInterval = Math.min(currentInterval * 1.5, maxInterval);
            } else {
              throw new TokenManagerError(TokenError.FILE_ACCESS_ERROR, `Failed to create lock file: ${error2 instanceof Error ? error2.message : String(error2)}`, error2);
            }
          }
        }
        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 fs15.unlink(lockPath);
        } catch (error2) {
          if (error2.code !== "ENOENT") {
            debugLogger11.warn(`Failed to release lock file ${lockPath}: ${error2 instanceof Error ? error2.message : String(error2)}`);
          }
        }
      }
      /**
       * 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(config2) {
        this.lockConfig = { ...DEFAULT_LOCK_CONFIG, ...config2 };
      }
      /**
       * 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/qwen/qwenOAuth2.js
var qwenOAuth2_exports = {};
__export(qwenOAuth2_exports, {
  CredentialsClearRequiredError: () => CredentialsClearRequiredError,
  QwenOAuth2Client: () => QwenOAuth2Client,
  QwenOAuth2Event: () => QwenOAuth2Event,
  clearCachedCredentialFile: () => clearCachedCredentialFile,
  clearQwenCredentials: () => clearQwenCredentials,
  generateCodeChallenge: () => generateCodeChallenge,
  generateCodeVerifier: () => generateCodeVerifier,
  generatePKCEPair: () => generatePKCEPair,
  getQwenOAuthClient: () => getQwenOAuthClient,
  isDeviceAuthorizationSuccess: () => isDeviceAuthorizationSuccess,
  isDeviceTokenPending: () => isDeviceTokenPending,
  isDeviceTokenSuccess: () => isDeviceTokenSuccess,
  isErrorResponse: () => isErrorResponse,
  qwenOAuth2Events: () => qwenOAuth2Events
});
import crypto5 from "crypto";
import path10 from "node:path";
import { promises as fs16 } from "node:fs";
import * as os7 from "os";
import { EventEmitter as EventEmitter2 } from "events";
import { randomUUID as randomUUID3 } from "node:crypto";
function generateCodeVerifier() {
  return crypto5.randomBytes(32).toString("base64url");
}
function generateCodeChallenge(codeVerifier) {
  const hash = crypto5.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(config2, options2) {
  const client = new QwenOAuth2Client();
  const sharedManager = SharedTokenManager.getInstance();
  try {
    const credentials = await sharedManager.getValidCredentials(client);
    client.setCredentials(credentials);
    return client;
  } catch (error2) {
    if (error2 instanceof TokenManagerError) {
      switch (error2.type) {
        case TokenError.NO_REFRESH_TOKEN:
          debugLogger12.debug("No refresh token available, proceeding with device flow");
          break;
        case TokenError.REFRESH_FAILED:
          debugLogger12.debug("Token refresh failed, proceeding with device flow");
          break;
        case TokenError.NETWORK_ERROR:
          debugLogger12.warn("Network error during token refresh, trying device flow");
          break;
        default:
          debugLogger12.warn("Token manager error:", error2.message);
      }
    }
    if (options2?.requireCachedCredentials) {
      throw new Error("Qwen OAuth credentials expired. Please use /auth to re-authenticate with qwen-oauth.");
    }
    const result = await authWithQwenDeviceFlow(client, config2);
    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;
  }
}
function showFallbackMessage(verificationUriComplete) {
  const title = "Qwen OAuth Device Authorization";
  const url2 = verificationUriComplete;
  const minWidth = 70;
  const maxWidth = 80;
  const boxWidth = Math.min(Math.max(title.length + 4, minWidth), maxWidth);
  const contentWidth = boxWidth - 4;
  const wrapText2 = /* @__PURE__ */ __name((text, width) => {
    if (text.startsWith("http://") || text.startsWith("https://")) {
      const lines2 = [];
      for (let i3 = 0; i3 < text.length; i3 += width) {
        lines2.push(text.substring(i3, i3 + width));
      }
      return lines2;
    }
    const words = text.split(" ");
    const lines = [];
    let currentLine = "";
    for (const word of words) {
      if (currentLine.length + word.length + 1 <= width) {
        currentLine += (currentLine ? " " : "") + word;
      } else {
        if (currentLine) {
          lines.push(currentLine);
        }
        currentLine = word.length > width ? word.substring(0, width) : word;
      }
    }
    if (currentLine) {
      lines.push(currentLine);
    }
    return lines;
  }, "wrapText");
  const titleWithSpaces = " " + title + " ";
  const totalDashes = boxWidth - 2 - titleWithSpaces.length;
  const leftDashes = Math.floor(totalDashes / 2);
  const rightDashes = totalDashes - leftDashes;
  const topBorder = "+" + "-".repeat(leftDashes) + titleWithSpaces + "-".repeat(rightDashes) + "+";
  const emptyLine = "|" + " ".repeat(boxWidth - 2) + "|";
  const bottomBorder = "+" + "-".repeat(boxWidth - 2) + "+";
  const instructionLines = wrapText2("Please visit the following URL in your browser to authorize:", contentWidth);
  const urlLines = wrapText2(url2, contentWidth);
  const waitingLine = "Waiting for authorization to complete...";
  process.stderr.write("\n" + topBorder + "\n");
  process.stderr.write(emptyLine + "\n");
  for (const line of instructionLines) {
    process.stderr.write("| " + line + " ".repeat(contentWidth - line.length) + " |\n");
  }
  process.stderr.write(emptyLine + "\n");
  for (const line of urlLines) {
    process.stderr.write("| " + line + " ".repeat(contentWidth - line.length) + " |\n");
  }
  process.stderr.write(emptyLine + "\n");
  process.stderr.write("| " + waitingLine + " ".repeat(contentWidth - waitingLine.length) + " |\n");
  process.stderr.write(emptyLine + "\n");
  process.stderr.write(bottomBorder + "\n\n");
}
async function authWithQwenDeviceFlow(client, config2) {
  let isCancelled = false;
  const cancelHandler = /* @__PURE__ */ __name(() => {
    isCancelled = true;
  }, "cancelHandler");
  qwenOAuth2Events.once(QwenOAuth2Event.AuthCancel, cancelHandler);
  const checkCancellation = /* @__PURE__ */ __name(() => {
    if (!isCancelled) {
      return null;
    }
    const message = "Authentication cancelled by user.";
    debugLogger12.debug("\n" + message);
    qwenOAuth2Events.emit(QwenOAuth2Event.AuthProgress, "error", message);
    return { success: false, reason: "cancelled", message };
  }, "checkCancellation");
  const emitAuthProgress = /* @__PURE__ */ __name((status, message) => {
    qwenOAuth2Events.emit(QwenOAuth2Event.AuthProgress, status, message);
  }, "emitAuthProgress");
  const launchBrowser = /* @__PURE__ */ __name(async (url2) => {
    try {
      const childProcess3 = await open_default(url2);
      if (childProcess3) {
        childProcess3.on("error", (err) => {
          debugLogger12.debug("Browser launch failed:", err.message || err);
        });
      }
    } catch (err) {
      debugLogger12.debug("Failed to open browser:", err instanceof Error ? err.message : "Unknown error");
    }
  }, "launchBrowser");
  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);
    if (config2.isBrowserLaunchSuppressed() || !config2.isInteractive()) {
      showFallbackMessage(deviceAuth.verification_uri_complete);
    }
    if (!config2.isBrowserLaunchSuppressed()) {
      await launchBrowser(deviceAuth.verification_uri_complete);
    }
    emitAuthProgress("polling", "Waiting for authorization...");
    debugLogger12.debug("Waiting for authorization...\n");
    let pollInterval = 2e3;
    const maxAttempts = Math.ceil(deviceAuth.expires_in / (pollInterval / 1e3));
    for (let attempt = 0; attempt < maxAttempts; attempt++) {
      const cancellationResult = checkCancellation();
      if (cancellationResult) {
        return cancellationResult;
      }
      try {
        debugLogger12.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);
          try {
            SharedTokenManager.getInstance().clearCache();
          } catch {
          }
          emitAuthProgress("success", "Authentication successful! Access token obtained.");
          debugLogger12.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);
            debugLogger12.debug(`
Server requested to slow down, increasing poll interval to ${pollInterval}ms'`);
          } else {
            pollInterval = 2e3;
          }
          emitAuthProgress("polling", `Polling... (attempt ${attempt + 1}/${maxAttempts})`);
          await new Promise((resolve30) => {
            const checkInterval = 100;
            let elapsedTime = 0;
            const intervalId = setInterval(() => {
              elapsedTime += checkInterval;
              if (isCancelled) {
                clearInterval(intervalId);
                resolve30();
                return;
              }
              if (elapsedTime >= pollInterval) {
                clearInterval(intervalId);
                resolve30();
                return;
              }
            }, checkInterval);
          });
          const cancellationResult2 = checkCancellation();
          if (cancellationResult2) {
            return cancellationResult2;
          }
          continue;
        }
        if (isErrorResponse(tokenResponse)) {
          const errorData = tokenResponse;
          throw new Error(`Token polling failed: ${errorData?.error || "Unknown error"} - ${errorData?.error_description || "No details provided"}`);
        }
      } catch (error2) {
        const errorMessage = error2 instanceof Error ? error2.message : String(error2);
        const statusCode = error2 instanceof Error ? error2.status : null;
        const handleError2 = /* @__PURE__ */ __name((reason, message2, eventType = "error") => {
          emitAuthProgress(eventType, message2);
          return { success: false, reason, message: message2 };
        }, "handleError");
        const cancellationResult2 = checkCancellation();
        if (cancellationResult2) {
          return cancellationResult2;
        }
        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}`;
        emitAuthProgress("error", message);
        await new Promise((resolve30) => setTimeout(resolve30, pollInterval));
      }
    }
    const timeoutMessage = "Authorization timeout, please restart the process.";
    emitAuthProgress("timeout", timeoutMessage);
    return { success: false, reason: "timeout", message: timeoutMessage };
  } catch (error2) {
    const fullErrorMessage = formatFetchErrorForUser(error2, {
      url: QWEN_OAUTH_BASE_URL
    });
    const message = `Device authorization flow failed: ${fullErrorMessage}`;
    emitAuthProgress("error", message);
    return { success: false, reason: "error", message };
  } finally {
    qwenOAuth2Events.off(QwenOAuth2Event.AuthCancel, cancelHandler);
  }
}
async function cacheQwenCredentials(credentials) {
  const filePath = getQwenCachedCredentialPath();
  try {
    await fs16.mkdir(path10.dirname(filePath), { recursive: true });
    const credString = JSON.stringify(credentials, null, 2);
    await fs16.writeFile(filePath, credString);
  } catch (error2) {
    const errorMessage = error2 instanceof Error ? error2.message : String(error2);
    const errorCode = error2 instanceof Error && "code" in error2 ? error2.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 \`${path10.dirname(filePath)}\` and writing to \`${filePath}\`. ${errorMessage}. Please check permissions.`);
  }
}
async function clearQwenCredentials() {
  try {
    const filePath = getQwenCachedCredentialPath();
    await fs16.unlink(filePath);
    debugLogger12.debug("Cached Qwen credentials cleared successfully.");
  } catch (error2) {
    if (error2 instanceof Error && "code" in error2 && error2.code === "ENOENT") {
      return;
    }
    debugLogger12.warn("Warning: Failed to clear cached Qwen credentials:", error2);
  } finally {
    try {
      SharedTokenManager.getInstance().clearCache();
    } catch {
    }
  }
}
function getQwenCachedCredentialPath() {
  return path10.join(os7.homedir(), QWEN_DIR4, QWEN_CREDENTIAL_FILENAME2);
}
var debugLogger12, 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_DIR4, QWEN_CREDENTIAL_FILENAME2, CredentialsClearRequiredError, QwenOAuth2Client, QwenOAuth2Event, qwenOAuth2Events, clearCachedCredentialFile;
var init_qwenOAuth2 = __esm({
  "packages/core/dist/src/qwen/qwenOAuth2.js"() {
    "use strict";
    init_esbuild_shims();
    init_open();
    init_fetch();
    init_debugLogger();
    init_sharedTokenManager();
    debugLogger12 = createDebugLogger("QWEN_OAUTH");
    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_DIR4 = ".qwen";
    QWEN_CREDENTIAL_FILENAME2 = "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 (error2) {
          debugLogger12.warn("Failed to get access token from shared manager:", error2);
          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": randomUUID3()
          },
          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();
        debugLogger12.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 error3 = new Error(`Device token poll failed: ${response.status} ${response.statusText}. Response: ${responseText}`);
            error3.status = response.status;
            throw error3;
          }
          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 error2 = new Error(`Device token poll failed: ${errorData.error || "Unknown error"} - ${errorData.error_description}`);
          error2.status = response.status;
          throw error2;
        }
        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 EventEmitter2();
    __name(getQwenOAuthClient, "getQwenOAuthClient");
    __name(showFallbackMessage, "showFallbackMessage");
    __name(authWithQwenDeviceFlow, "authWithQwenDeviceFlow");
    __name(cacheQwenCredentials, "cacheQwenCredentials");
    __name(clearQwenCredentials, "clearQwenCredentials");
    __name(getQwenCachedCredentialPath, "getQwenCachedCredentialPath");
    clearCachedCredentialFile = clearQwenCredentials;
  }
});

// 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();
    init_debugLogger();
    QwenContentGenerator = class extends OpenAIContentGenerator {
      static {
        __name(this, "QwenContentGenerator");
      }
      debugLogger = createDebugLogger("QWEN");
      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(error2, _request) {
        return this.isAuthError(error2);
      }
      /**
       * 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 (error2) {
          if (this.isAuthError(error2)) {
            throw error2;
          }
          this.debugLogger.warn("Failed to get token from shared manager:", error2);
          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 (error2) {
          if (this.isAuthError(error2)) {
            await this.sharedManager.getValidCredentials(this.qwenClient, true);
            return await attemptOperation();
          }
          throw error2;
        }
      }
      /**
       * 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(error2) {
        if (!error2)
          return false;
        const errorMessage = error2 instanceof Error ? error2.message.toLowerCase() : String(error2).toLowerCase();
        const errorWithCode = error2;
        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();
      }
    };
  }
});

// node_modules/@anthropic-ai/sdk/version.mjs
var VERSION3;
var init_version3 = __esm({
  "node_modules/@anthropic-ai/sdk/version.mjs"() {
    init_esbuild_shims();
    VERSION3 = "0.36.3";
  }
});

// node_modules/@anthropic-ai/sdk/_shims/registry.mjs
function setShims(shims, options2 = { auto: false }) {
  if (auto) {
    throw new Error(`you must \`import '@anthropic-ai/sdk/shims/${shims.kind}'\` before importing anything else from @anthropic-ai/sdk`);
  }
  if (kind) {
    throw new Error(`can't \`import '@anthropic-ai/sdk/shims/${shims.kind}'\` after \`import '@anthropic-ai/sdk/shims/${kind}'\``);
  }
  auto = options2.auto;
  kind = shims.kind;
  fetch3 = shims.fetch;
  Request3 = shims.Request;
  Response3 = shims.Response;
  Headers3 = shims.Headers;
  FormData4 = shims.FormData;
  Blob4 = shims.Blob;
  File4 = shims.File;
  ReadableStream2 = shims.ReadableStream;
  getMultipartRequestOptions = shims.getMultipartRequestOptions;
  getDefaultAgent = shims.getDefaultAgent;
  fileFromPath = shims.fileFromPath;
  isFsReadStream = shims.isFsReadStream;
}
var auto, kind, fetch3, Request3, Response3, Headers3, FormData4, Blob4, File4, ReadableStream2, getMultipartRequestOptions, getDefaultAgent, fileFromPath, isFsReadStream;
var init_registry = __esm({
  "node_modules/@anthropic-ai/sdk/_shims/registry.mjs"() {
    init_esbuild_shims();
    auto = false;
    kind = void 0;
    fetch3 = void 0;
    Request3 = void 0;
    Response3 = void 0;
    Headers3 = void 0;
    FormData4 = void 0;
    Blob4 = void 0;
    File4 = void 0;
    ReadableStream2 = void 0;
    getMultipartRequestOptions = void 0;
    getDefaultAgent = void 0;
    fileFromPath = void 0;
    isFsReadStream = void 0;
    __name(setShims, "setShims");
  }
});

// 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(x3) {
      return x3 < 0 ? -1 : 1;
    }
    __name(sign, "sign");
    function evenRound(x3) {
      if (x3 % 1 === 0.5 && (x3 & 1) === 0) {
        return Math.floor(x3);
      } else {
        return Math.round(x3);
      }
    }
    __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(V3, opts) {
        if (!opts) opts = {};
        let x3 = +V3;
        if (opts.enforceRange) {
          if (!Number.isFinite(x3)) {
            throw new TypeError("Argument is not a finite number");
          }
          x3 = sign(x3) * Math.floor(Math.abs(x3));
          if (x3 < lowerBound || x3 > upperBound) {
            throw new TypeError("Argument is not in byte range");
          }
          return x3;
        }
        if (!isNaN(x3) && opts.clamp) {
          x3 = evenRound(x3);
          if (x3 < lowerBound) x3 = lowerBound;
          if (x3 > upperBound) x3 = upperBound;
          return x3;
        }
        if (!Number.isFinite(x3) || x3 === 0) {
          return 0;
        }
        x3 = sign(x3) * Math.floor(Math.abs(x3));
        x3 = x3 % moduloVal;
        if (!typeOpts.unsigned && x3 >= moduloBound) {
          return x3 - moduloVal;
        } else if (typeOpts.unsigned) {
          if (x3 < 0) {
            x3 += moduloVal;
          } else if (x3 === -0) {
            return 0;
          }
        }
        return x3;
      };
    }
    __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(V3) {
      const x3 = +V3;
      if (!Number.isFinite(x3)) {
        throw new TypeError("Argument is not a finite floating-point value");
      }
      return x3;
    };
    conversions["unrestricted double"] = function(V3) {
      const x3 = +V3;
      if (isNaN(x3)) {
        throw new TypeError("Argument is NaN");
      }
      return x3;
    };
    conversions["float"] = conversions["double"];
    conversions["unrestricted float"] = conversions["unrestricted double"];
    conversions["DOMString"] = function(V3, opts) {
      if (!opts) opts = {};
      if (opts.treatNullAsEmptyString && V3 === null) {
        return "";
      }
      return String(V3);
    };
    conversions["ByteString"] = function(V3, opts) {
      const x3 = String(V3);
      let c4 = void 0;
      for (let i3 = 0; (c4 = x3.codePointAt(i3)) !== void 0; ++i3) {
        if (c4 > 255) {
          throw new TypeError("Argument is not a valid bytestring");
        }
      }
      return x3;
    };
    conversions["USVString"] = function(V3) {
      const S4 = String(V3);
      const n3 = S4.length;
      const U2 = [];
      for (let i3 = 0; i3 < n3; ++i3) {
        const c4 = S4.charCodeAt(i3);
        if (c4 < 55296 || c4 > 57343) {
          U2.push(String.fromCodePoint(c4));
        } else if (56320 <= c4 && c4 <= 57343) {
          U2.push(String.fromCodePoint(65533));
        } else {
          if (i3 === n3 - 1) {
            U2.push(String.fromCodePoint(65533));
          } else {
            const d2 = S4.charCodeAt(i3 + 1);
            if (56320 <= d2 && d2 <= 57343) {
              const a2 = c4 & 1023;
              const b2 = d2 & 1023;
              U2.push(String.fromCodePoint((2 << 15) + (2 << 9) * a2 + b2));
              ++i3;
            } else {
              U2.push(String.fromCodePoint(65533));
            }
          }
        }
      }
      return U2.join("");
    };
    conversions["Date"] = function(V3, opts) {
      if (!(V3 instanceof Date)) {
        throw new TypeError("Argument is not a Date object");
      }
      if (isNaN(V3)) {
        return void 0;
      }
      return V3;
    };
    conversions["RegExp"] = function(V3, opts) {
      if (!(V3 instanceof RegExp)) {
        V3 = new RegExp(V3);
      }
      return V3;
    };
  }
});

// node_modules/node-fetch/node_modules/whatwg-url/lib/utils.js
var require_utils12 = __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 i3 = 0; i3 < keys.length; ++i3) {
        Object.defineProperty(target, keys[i3], Object.getOwnPropertyDescriptor(source2, keys[i3]));
      }
    }, "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 normalize12(str2) {
      return str2.split("\0").map(function(s5) {
        return s5.normalize("NFC");
      }).join("\0");
    }
    __name(normalize12, "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(string4) {
      return string4.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 i3 = 0; i3 < len; ++i3) {
        var codePoint = domain_name.codePointAt(i3);
        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 error2 = false;
      if (normalize12(label) !== label || label[3] === "-" && label[4] === "-" || label[0] === "-" || label[label.length - 1] === "-" || label.indexOf(".") !== -1 || label.search(combiningMarksRegex) === 0) {
        error2 = true;
      }
      var len = countSymbols(label);
      for (var i3 = 0; i3 < len; ++i3) {
        var status = findStatus(label.codePointAt(i3));
        if (processing === PROCESSING_OPTIONS.TRANSITIONAL && status[1] !== "valid" || processing === PROCESSING_OPTIONS.NONTRANSITIONAL && status[1] !== "valid" && status[1] !== "deviation") {
          error2 = true;
          break;
        }
      }
      return {
        label,
        error: error2
      };
    }
    __name(validateLabel, "validateLabel");
    function processing(domain_name, useSTD3, processing_option) {
      var result = mapChars(domain_name, useSTD3, processing_option);
      result.string = normalize12(result.string);
      var labels = result.string.split(".");
      for (var i3 = 0; i3 < labels.length; ++i3) {
        try {
          var validation2 = validateLabel(labels[i3]);
          labels[i3] = validation2.label;
          result.error = result.error || validation2.error;
        } catch (e4) {
          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(l3) {
        try {
          return punycode.toASCII(l3);
        } catch (e4) {
          result.error = true;
          return l3;
        }
      });
      if (verifyDnsLength) {
        var total = labels.slice(0, labels.length - 1).join(".").length;
        if (total.length > 253 || total.length === 0) {
          result.error = true;
        }
        for (var i3 = 0; i3 < labels.length; ++i3) {
          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 at2(input, idx) {
      const c4 = input[idx];
      return isNaN(c4) ? void 0 : String.fromCodePoint(c4);
    }
    __name(at2, "at");
    function isASCIIDigit(c4) {
      return c4 >= 48 && c4 <= 57;
    }
    __name(isASCIIDigit, "isASCIIDigit");
    function isASCIIAlpha2(c4) {
      return c4 >= 65 && c4 <= 90 || c4 >= 97 && c4 <= 122;
    }
    __name(isASCIIAlpha2, "isASCIIAlpha");
    function isASCIIAlphanumeric(c4) {
      return isASCIIAlpha2(c4) || isASCIIDigit(c4);
    }
    __name(isASCIIAlphanumeric, "isASCIIAlphanumeric");
    function isASCIIHex(c4) {
      return isASCIIDigit(c4) || c4 >= 65 && c4 <= 70 || c4 >= 97 && c4 <= 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, cp22) {
      return isASCIIAlpha2(cp1) && (cp22 === 58 || cp22 === 124);
    }
    __name(isWindowsDriveLetterCodePoints, "isWindowsDriveLetterCodePoints");
    function isWindowsDriveLetterString(string4) {
      return string4.length === 2 && isASCIIAlpha2(string4.codePointAt(0)) && (string4[1] === ":" || string4[1] === "|");
    }
    __name(isWindowsDriveLetterString, "isWindowsDriveLetterString");
    function isNormalizedWindowsDriveLetterString(string4) {
      return string4.length === 2 && isASCIIAlpha2(string4.codePointAt(0)) && string4[1] === ":";
    }
    __name(isNormalizedWindowsDriveLetterString, "isNormalizedWindowsDriveLetterString");
    function containsForbiddenHostCodePoint(string4) {
      return string4.search(/\u0000|\u0009|\u000A|\u000D|\u0020|#|%|\/|:|\?|@|\[|\\|\]/) !== -1;
    }
    __name(containsForbiddenHostCodePoint, "containsForbiddenHostCodePoint");
    function containsForbiddenHostCodePointExcludingPercent(string4) {
      return string4.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(c4) {
      let hex = c4.toString(16).toUpperCase();
      if (hex.length === 1) {
        hex = "0" + hex;
      }
      return "%" + hex;
    }
    __name(percentEncode, "percentEncode");
    function utf8PercentEncode(c4) {
      const buf = new Buffer(c4);
      let str2 = "";
      for (let i3 = 0; i3 < buf.length; ++i3) {
        str2 += percentEncode(buf[i3]);
      }
      return str2;
    }
    __name(utf8PercentEncode, "utf8PercentEncode");
    function utf8PercentDecode(str2) {
      const input = new Buffer(str2);
      const output = [];
      for (let i3 = 0; i3 < input.length; ++i3) {
        if (input[i3] !== 37) {
          output.push(input[i3]);
        } else if (input[i3] === 37 && isASCIIHex(input[i3 + 1]) && isASCIIHex(input[i3 + 2])) {
          output.push(parseInt(input.slice(i3 + 1, i3 + 3).toString(), 16));
          i3 += 2;
        } else {
          output.push(input[i3]);
        }
      }
      return new Buffer(output).toString();
    }
    __name(utf8PercentDecode, "utf8PercentDecode");
    function isC0ControlPercentEncode(c4) {
      return c4 <= 31 || c4 > 126;
    }
    __name(isC0ControlPercentEncode, "isC0ControlPercentEncode");
    var extraPathPercentEncodeSet = /* @__PURE__ */ new Set([32, 34, 35, 60, 62, 63, 96, 123, 125]);
    function isPathPercentEncode(c4) {
      return isC0ControlPercentEncode(c4) || extraPathPercentEncodeSet.has(c4);
    }
    __name(isPathPercentEncode, "isPathPercentEncode");
    var extraUserinfoPercentEncodeSet = /* @__PURE__ */ new Set([47, 58, 59, 61, 64, 91, 92, 93, 94, 124]);
    function isUserinfoPercentEncode(c4) {
      return isPathPercentEncode(c4) || extraUserinfoPercentEncodeSet.has(c4);
    }
    __name(isUserinfoPercentEncode, "isUserinfoPercentEncode");
    function percentEncodeChar(c4, encodeSetPredicate) {
      const cStr = String.fromCodePoint(c4);
      if (encodeSetPredicate(c4)) {
        return utf8PercentEncode(cStr);
      }
      return cStr;
    }
    __name(percentEncodeChar, "percentEncodeChar");
    function parseIPv4Number(input) {
      let R2 = 10;
      if (input.length >= 2 && input.charAt(0) === "0" && input.charAt(1).toLowerCase() === "x") {
        input = input.substring(2);
        R2 = 16;
      } else if (input.length >= 2 && input.charAt(0) === "0") {
        input = input.substring(1);
        R2 = 8;
      }
      if (input === "") {
        return 0;
      }
      const regex3 = R2 === 10 ? /[^0-9]/ : R2 === 16 ? /[^0-9A-Fa-f]/ : /[^0-7]/;
      if (regex3.test(input)) {
        return failure;
      }
      return parseInt(input, R2);
    }
    __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 n3 = parseIPv4Number(part);
        if (n3 === failure) {
          return input;
        }
        numbers.push(n3);
      }
      for (let i3 = 0; i3 < numbers.length - 1; ++i3) {
        if (numbers[i3] > 255) {
          return failure;
        }
      }
      if (numbers[numbers.length - 1] >= Math.pow(256, 5 - numbers.length)) {
        return failure;
      }
      let ipv42 = numbers.pop();
      let counter = 0;
      for (const n3 of numbers) {
        ipv42 += n3 * Math.pow(256, 3 - counter);
        ++counter;
      }
      return ipv42;
    }
    __name(parseIPv4, "parseIPv4");
    function serializeIPv4(address) {
      let output = "";
      let n3 = address;
      for (let i3 = 1; i3 <= 4; ++i3) {
        output = String(n3 % 256) + output;
        if (i3 !== 4) {
          output = "." + output;
        }
        n3 = Math.floor(n3 / 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(at2(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 number4 = parseInt(at2(input, pointer));
              if (ipv4Piece === null) {
                ipv4Piece = number4;
              } else if (ipv4Piece === 0) {
                return failure;
              } else {
                ipv4Piece = ipv4Piece * 10 + number4;
              }
              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 i3 = 0; i3 < decoded.length; ++i3) {
        output += percentEncodeChar(decoded[i3], isC0ControlPercentEncode);
      }
      return output;
    }
    __name(parseOpaqueHost, "parseOpaqueHost");
    function findLongestZeroSequence(arr) {
      let maxIdx = null;
      let maxLen = 1;
      let currStart = null;
      let currLen = 0;
      for (let i3 = 0; i3 < arr.length; ++i3) {
        if (arr[i3] !== 0) {
          if (currLen > maxLen) {
            maxIdx = currStart;
            maxLen = currLen;
          }
          currStart = null;
          currLen = 0;
        } else {
          if (currStart === null) {
            currStart = i3;
          }
          ++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 path125 = url2.path;
      if (path125.length === 0) {
        return;
      }
      if (url2.scheme === "file" && path125.length === 1 && isNormalizedWindowsDriveLetter(path125[0])) {
        return;
      }
      path125.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(string4) {
      return /^[A-Za-z]:$/.test(string4);
    }
    __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 c4 = this.input[this.pointer];
        const cStr = isNaN(c4) ? void 0 : String.fromCodePoint(c4);
        const ret = this["parse " + this.state](c4, cStr);
        if (!ret) {
          break;
        } else if (ret === failure) {
          this.failure = true;
          break;
        }
      }
    }
    __name(URLStateMachine, "URLStateMachine");
    URLStateMachine.prototype["parse scheme start"] = /* @__PURE__ */ __name(function parseSchemeStart(c4, cStr) {
      if (isASCIIAlpha2(c4)) {
        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(c4, cStr) {
      if (isASCIIAlphanumeric(c4) || c4 === 43 || c4 === 45 || c4 === 46) {
        this.buffer += cStr.toLowerCase();
      } else if (c4 === 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(c4) {
      if (this.base === null || this.base.cannotBeABaseURL && c4 !== 35) {
        return failure;
      } else if (this.base.cannotBeABaseURL && c4 === 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(c4) {
      if (c4 === 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(c4) {
      if (c4 === 47) {
        this.state = "authority";
      } else {
        this.state = "path";
        --this.pointer;
      }
      return true;
    }, "parsePathOrAuthority");
    URLStateMachine.prototype["parse relative"] = /* @__PURE__ */ __name(function parseRelative(c4) {
      this.url.scheme = this.base.scheme;
      if (isNaN(c4)) {
        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 (c4 === 47) {
        this.state = "relative slash";
      } else if (c4 === 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 (c4 === 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) && c4 === 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(c4) {
      if (isSpecial(this.url) && (c4 === 47 || c4 === 92)) {
        if (c4 === 92) {
          this.parseError = true;
        }
        this.state = "special authority ignore slashes";
      } else if (c4 === 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(c4) {
      if (c4 === 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(c4) {
      if (c4 !== 47 && c4 !== 92) {
        this.state = "authority";
        --this.pointer;
      } else {
        this.parseError = true;
      }
      return true;
    }, "parseSpecialAuthorityIgnoreSlashes");
    URLStateMachine.prototype["parse authority"] = /* @__PURE__ */ __name(function parseAuthority(c4, cStr) {
      if (c4 === 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(c4) || c4 === 47 || c4 === 63 || c4 === 35 || isSpecial(this.url) && c4 === 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(c4, cStr) {
      if (this.stateOverride && this.url.scheme === "file") {
        --this.pointer;
        this.state = "file host";
      } else if (c4 === 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(c4) || c4 === 47 || c4 === 63 || c4 === 35 || isSpecial(this.url) && c4 === 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 (c4 === 91) {
          this.arrFlag = true;
        } else if (c4 === 93) {
          this.arrFlag = false;
        }
        this.buffer += cStr;
      }
      return true;
    }, "parseHostName");
    URLStateMachine.prototype["parse port"] = /* @__PURE__ */ __name(function parsePort(c4, cStr) {
      if (isASCIIDigit(c4)) {
        this.buffer += cStr;
      } else if (isNaN(c4) || c4 === 47 || c4 === 63 || c4 === 35 || isSpecial(this.url) && c4 === 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(c4) {
      this.url.scheme = "file";
      if (c4 === 47 || c4 === 92) {
        if (c4 === 92) {
          this.parseError = true;
        }
        this.state = "file slash";
      } else if (this.base !== null && this.base.scheme === "file") {
        if (isNaN(c4)) {
          this.url.host = this.base.host;
          this.url.path = this.base.path.slice();
          this.url.query = this.base.query;
        } else if (c4 === 63) {
          this.url.host = this.base.host;
          this.url.path = this.base.path.slice();
          this.url.query = "";
          this.state = "query";
        } else if (c4 === 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(c4, 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(c4) {
      if (c4 === 47 || c4 === 92) {
        if (c4 === 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(c4, cStr) {
      if (isNaN(c4) || c4 === 47 || c4 === 92 || c4 === 63 || c4 === 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(c4) {
      if (isSpecial(this.url)) {
        if (c4 === 92) {
          this.parseError = true;
        }
        this.state = "path";
        if (c4 !== 47 && c4 !== 92) {
          --this.pointer;
        }
      } else if (!this.stateOverride && c4 === 63) {
        this.url.query = "";
        this.state = "query";
      } else if (!this.stateOverride && c4 === 35) {
        this.url.fragment = "";
        this.state = "fragment";
      } else if (c4 !== void 0) {
        this.state = "path";
        if (c4 !== 47) {
          --this.pointer;
        }
      }
      return true;
    }, "parsePathStart");
    URLStateMachine.prototype["parse path"] = /* @__PURE__ */ __name(function parsePath(c4) {
      if (isNaN(c4) || c4 === 47 || isSpecial(this.url) && c4 === 92 || !this.stateOverride && (c4 === 63 || c4 === 35)) {
        if (isSpecial(this.url) && c4 === 92) {
          this.parseError = true;
        }
        if (isDoubleDot(this.buffer)) {
          shortenPath2(this.url);
          if (c4 !== 47 && !(isSpecial(this.url) && c4 === 92)) {
            this.url.path.push("");
          }
        } else if (isSingleDot(this.buffer) && c4 !== 47 && !(isSpecial(this.url) && c4 === 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" && (c4 === void 0 || c4 === 63 || c4 === 35)) {
          while (this.url.path.length > 1 && this.url.path[0] === "") {
            this.parseError = true;
            this.url.path.shift();
          }
        }
        if (c4 === 63) {
          this.url.query = "";
          this.state = "query";
        }
        if (c4 === 35) {
          this.url.fragment = "";
          this.state = "fragment";
        }
      } else {
        if (c4 === 37 && (!isASCIIHex(this.input[this.pointer + 1]) || !isASCIIHex(this.input[this.pointer + 2]))) {
          this.parseError = true;
        }
        this.buffer += percentEncodeChar(c4, isPathPercentEncode);
      }
      return true;
    }, "parsePath");
    URLStateMachine.prototype["parse cannot-be-a-base-URL path"] = /* @__PURE__ */ __name(function parseCannotBeABaseURLPath(c4) {
      if (c4 === 63) {
        this.url.query = "";
        this.state = "query";
      } else if (c4 === 35) {
        this.url.fragment = "";
        this.state = "fragment";
      } else {
        if (!isNaN(c4) && c4 !== 37) {
          this.parseError = true;
        }
        if (c4 === 37 && (!isASCIIHex(this.input[this.pointer + 1]) || !isASCIIHex(this.input[this.pointer + 2]))) {
          this.parseError = true;
        }
        if (!isNaN(c4)) {
          this.url.path[0] = this.url.path[0] + percentEncodeChar(c4, isC0ControlPercentEncode);
        }
      }
      return true;
    }, "parseCannotBeABaseURLPath");
    URLStateMachine.prototype["parse query"] = /* @__PURE__ */ __name(function parseQuery(c4, cStr) {
      if (isNaN(c4) || !this.stateOverride && c4 === 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 i3 = 0; i3 < buffer.length; ++i3) {
          if (buffer[i3] < 33 || buffer[i3] > 126 || buffer[i3] === 34 || buffer[i3] === 35 || buffer[i3] === 60 || buffer[i3] === 62) {
            this.url.query += percentEncode(buffer[i3]);
          } else {
            this.url.query += String.fromCodePoint(buffer[i3]);
          }
        }
        this.buffer = "";
        if (c4 === 35) {
          this.url.fragment = "";
          this.state = "fragment";
        }
      } else {
        if (c4 === 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(c4) {
      if (isNaN(c4)) {
      } else if (c4 === 0) {
        this.parseError = true;
      } else {
        if (c4 === 37 && (!isASCIIHex(this.input[this.pointer + 1]) || !isASCIIHex(this.input[this.pointer + 2]))) {
          this.parseError = true;
        }
        this.url.fragment += percentEncodeChar(c4, 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 string4 of url2.path) {
          output += "/" + string4;
        }
      }
      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 (e4) {
            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 i3 = 0; i3 < decoded.length; ++i3) {
        url2.username += percentEncodeChar(decoded[i3], isUserinfoPercentEncode);
      }
    };
    module2.exports.setThePassword = function(url2, password) {
      url2.password = "";
      const decoded = punycode.ucs2.decode(password);
      for (let i3 = 0; i3 < decoded.length; ++i3) {
        url2.password += percentEncodeChar(decoded[i3], isUserinfoPercentEncode);
      }
    };
    module2.exports.serializeHost = serializeHost;
    module2.exports.cannotHaveAUsernamePasswordPort = cannotHaveAUsernamePasswordPort;
    module2.exports.serializeInteger = function(integer2) {
      return String(integer2);
    };
    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(v2) {
        const parsedURL = usm.basicURLParse(v2);
        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(v2) {
        usm.basicURLParse(v2 + ":", { url: this._url, stateOverride: "scheme start" });
      }
      get username() {
        return this._url.username;
      }
      set username(v2) {
        if (usm.cannotHaveAUsernamePasswordPort(this._url)) {
          return;
        }
        usm.setTheUsername(this._url, v2);
      }
      get password() {
        return this._url.password;
      }
      set password(v2) {
        if (usm.cannotHaveAUsernamePasswordPort(this._url)) {
          return;
        }
        usm.setThePassword(this._url, v2);
      }
      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(v2) {
        if (this._url.cannotBeABaseURL) {
          return;
        }
        usm.basicURLParse(v2, { url: this._url, stateOverride: "host" });
      }
      get hostname() {
        if (this._url.host === null) {
          return "";
        }
        return usm.serializeHost(this._url.host);
      }
      set hostname(v2) {
        if (this._url.cannotBeABaseURL) {
          return;
        }
        usm.basicURLParse(v2, { url: this._url, stateOverride: "hostname" });
      }
      get port() {
        if (this._url.port === null) {
          return "";
        }
        return usm.serializeInteger(this._url.port);
      }
      set port(v2) {
        if (usm.cannotHaveAUsernamePasswordPort(this._url)) {
          return;
        }
        if (v2 === "") {
          this._url.port = null;
        } else {
          usm.basicURLParse(v2, { 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(v2) {
        if (this._url.cannotBeABaseURL) {
          return;
        }
        this._url.path = [];
        usm.basicURLParse(v2, { url: this._url, stateOverride: "path start" });
      }
      get search() {
        if (this._url.query === null || this._url.query === "") {
          return "";
        }
        return "?" + this._url.query;
      }
      set search(v2) {
        const url2 = this._url;
        if (v2 === "") {
          url2.query = null;
          return;
        }
        const input = v2[0] === "?" ? v2.substring(1) : v2;
        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(v2) {
        if (v2 === "") {
          this._url.fragment = null;
          return;
        }
        const input = v2[0] === "#" ? v2.substring(1) : v2;
        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_utils12();
    var Impl = require_URL_impl();
    var impl = utils.implSymbol;
    function URL5(url2) {
      if (!this || this[impl] || !(this instanceof URL5)) {
        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 i3 = 0; i3 < arguments.length && i3 < 2; ++i3) {
        args[i3] = arguments[i3];
      }
      args[0] = conversions["USVString"](args[0]);
      if (args[1] !== void 0) {
        args[1] = conversions["USVString"](args[1]);
      }
      module2.exports.setup(this, args);
    }
    __name(URL5, "URL");
    URL5.prototype.toJSON = /* @__PURE__ */ __name(function toJSON() {
      if (!this || !module2.exports.is(this)) {
        throw new TypeError("Illegal invocation");
      }
      const args = [];
      for (let i3 = 0; i3 < arguments.length && i3 < 0; ++i3) {
        args[i3] = arguments[i3];
      }
      return this[impl].toJSON.apply(this[impl], args);
    }, "toJSON");
    Object.defineProperty(URL5.prototype, "href", {
      get() {
        return this[impl].href;
      },
      set(V3) {
        V3 = conversions["USVString"](V3);
        this[impl].href = V3;
      },
      enumerable: true,
      configurable: true
    });
    URL5.prototype.toString = function() {
      if (!this || !module2.exports.is(this)) {
        throw new TypeError("Illegal invocation");
      }
      return this.href;
    };
    Object.defineProperty(URL5.prototype, "origin", {
      get() {
        return this[impl].origin;
      },
      enumerable: true,
      configurable: true
    });
    Object.defineProperty(URL5.prototype, "protocol", {
      get() {
        return this[impl].protocol;
      },
      set(V3) {
        V3 = conversions["USVString"](V3);
        this[impl].protocol = V3;
      },
      enumerable: true,
      configurable: true
    });
    Object.defineProperty(URL5.prototype, "username", {
      get() {
        return this[impl].username;
      },
      set(V3) {
        V3 = conversions["USVString"](V3);
        this[impl].username = V3;
      },
      enumerable: true,
      configurable: true
    });
    Object.defineProperty(URL5.prototype, "password", {
      get() {
        return this[impl].password;
      },
      set(V3) {
        V3 = conversions["USVString"](V3);
        this[impl].password = V3;
      },
      enumerable: true,
      configurable: true
    });
    Object.defineProperty(URL5.prototype, "host", {
      get() {
        return this[impl].host;
      },
      set(V3) {
        V3 = conversions["USVString"](V3);
        this[impl].host = V3;
      },
      enumerable: true,
      configurable: true
    });
    Object.defineProperty(URL5.prototype, "hostname", {
      get() {
        return this[impl].hostname;
      },
      set(V3) {
        V3 = conversions["USVString"](V3);
        this[impl].hostname = V3;
      },
      enumerable: true,
      configurable: true
    });
    Object.defineProperty(URL5.prototype, "port", {
      get() {
        return this[impl].port;
      },
      set(V3) {
        V3 = conversions["USVString"](V3);
        this[impl].port = V3;
      },
      enumerable: true,
      configurable: true
    });
    Object.defineProperty(URL5.prototype, "pathname", {
      get() {
        return this[impl].pathname;
      },
      set(V3) {
        V3 = conversions["USVString"](V3);
        this[impl].pathname = V3;
      },
      enumerable: true,
      configurable: true
    });
    Object.defineProperty(URL5.prototype, "search", {
      get() {
        return this[impl].search;
      },
      set(V3) {
        V3 = conversions["USVString"](V3);
        this[impl].search = V3;
      },
      enumerable: true,
      configurable: true
    });
    Object.defineProperty(URL5.prototype, "hash", {
      get() {
        return this[impl].hash;
      },
      set(V3) {
        V3 = conversions["USVString"](V3);
        this[impl].hash = V3;
      },
      enumerable: true,
      configurable: true
    });
    module2.exports = {
      is(obj) {
        return !!obj && obj[impl] instanceof Impl.implementation;
      },
      create(constructorArgs, privateData) {
        let obj = Object.create(URL5.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: URL5,
      expose: {
        Window: { URL: URL5 },
        Worker: { URL: URL5 }
      }
    };
  }
});

// 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 Stream9 = _interopDefault(__require("stream"));
    var http7 = _interopDefault(__require("http"));
    var Url = _interopDefault(__require("url"));
    var whatwgUrl = _interopDefault(require_public_api());
    var https7 = _interopDefault(__require("https"));
    var zlib4 = _interopDefault(__require("zlib"));
    var Readable6 = Stream9.Readable;
    var BUFFER3 = Symbol("buffer");
    var TYPE2 = Symbol("type");
    var Blob6 = class _Blob2 {
      static {
        __name(this, "Blob");
      }
      constructor() {
        this[TYPE2] = "";
        const blobParts = arguments[0];
        const options2 = arguments[1];
        const buffers = [];
        let size = 0;
        if (blobParts) {
          const a2 = blobParts;
          const length = Number(a2.length);
          for (let i3 = 0; i3 < length; i3++) {
            const element = a2[i3];
            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 _Blob2) {
              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 Readable6();
        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 _Blob2([], { type: arguments[2] });
        blob[BUFFER3] = slicedBuffer;
        return blob;
      }
    };
    Object.defineProperties(Blob6.prototype, {
      size: { enumerable: true },
      type: { enumerable: true },
      slice: { enumerable: true }
    });
    Object.defineProperty(Blob6.prototype, Symbol.toStringTag, {
      value: "Blob",
      writable: false,
      enumerable: false,
      configurable: true
    });
    function FetchError4(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(FetchError4, "FetchError");
    FetchError4.prototype = Object.create(Error.prototype);
    FetchError4.prototype.constructor = FetchError4;
    FetchError4.prototype.name = "FetchError";
    var convert2;
    try {
      convert2 = __require("encoding").convert;
    } catch (e4) {
    }
    var INTERNALS7 = Symbol("Body internals");
    var PassThrough8 = Stream9.PassThrough;
    function Body3(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 (isBlob4(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 Stream9) ;
      else {
        body = Buffer.from(String(body));
      }
      this[INTERNALS7] = {
        body,
        disturbed: false,
        error: null
      };
      this.size = size;
      this.timeout = timeout2;
      if (body instanceof Stream9) {
        body.on("error", function(err) {
          const error2 = err.name === "AbortError" ? err : new FetchError4(`Invalid response body while trying to fetch ${_this.url}: ${err.message}`, "system", err);
          _this[INTERNALS7].error = error2;
        });
      }
    }
    __name(Body3, "Body");
    Body3.prototype = {
      get body() {
        return this[INTERNALS7].body;
      },
      get bodyUsed() {
        return this[INTERNALS7].disturbed;
      },
      /**
       * Decode response as ArrayBuffer
       *
       * @return  Promise
       */
      arrayBuffer() {
        return consumeBody3.call(this).then(function(buf) {
          return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength);
        });
      },
      /**
       * Return raw response as Blob
       *
       * @return Promise
       */
      blob() {
        let ct2 = this.headers && this.headers.get("content-type") || "";
        return consumeBody3.call(this).then(function(buf) {
          return Object.assign(
            // Prevent copying
            new Blob6([], {
              type: ct2.toLowerCase()
            }),
            {
              [BUFFER3]: buf
            }
          );
        });
      },
      /**
       * Decode response as json
       *
       * @return  Promise
       */
      json() {
        var _this2 = this;
        return consumeBody3.call(this).then(function(buffer) {
          try {
            return JSON.parse(buffer.toString());
          } catch (err) {
            return Body3.Promise.reject(new FetchError4(`invalid json response body at ${_this2.url} reason: ${err.message}`, "invalid-json"));
          }
        });
      },
      /**
       * Decode response as text
       *
       * @return  Promise
       */
      text() {
        return consumeBody3.call(this).then(function(buffer) {
          return buffer.toString();
        });
      },
      /**
       * Decode response as buffer (non-spec api)
       *
       * @return  Promise
       */
      buffer() {
        return consumeBody3.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 consumeBody3.call(this).then(function(buffer) {
          return convertBody(buffer, _this3.headers);
        });
      }
    };
    Object.defineProperties(Body3.prototype, {
      body: { enumerable: true },
      bodyUsed: { enumerable: true },
      arrayBuffer: { enumerable: true },
      blob: { enumerable: true },
      json: { enumerable: true },
      text: { enumerable: true }
    });
    Body3.mixIn = function(proto3) {
      for (const name3 of Object.getOwnPropertyNames(Body3.prototype)) {
        if (!(name3 in proto3)) {
          const desc2 = Object.getOwnPropertyDescriptor(Body3.prototype, name3);
          Object.defineProperty(proto3, name3, desc2);
        }
      }
    };
    function consumeBody3() {
      var _this4 = this;
      if (this[INTERNALS7].disturbed) {
        return Body3.Promise.reject(new TypeError(`body used already for: ${this.url}`));
      }
      this[INTERNALS7].disturbed = true;
      if (this[INTERNALS7].error) {
        return Body3.Promise.reject(this[INTERNALS7].error);
      }
      let body = this.body;
      if (body === null) {
        return Body3.Promise.resolve(Buffer.alloc(0));
      }
      if (isBlob4(body)) {
        body = body.stream();
      }
      if (Buffer.isBuffer(body)) {
        return Body3.Promise.resolve(body);
      }
      if (!(body instanceof Stream9)) {
        return Body3.Promise.resolve(Buffer.alloc(0));
      }
      let accum = [];
      let accumBytes = 0;
      let abort = false;
      return new Body3.Promise(function(resolve30, reject) {
        let resTimeout;
        if (_this4.timeout) {
          resTimeout = setTimeout(function() {
            abort = true;
            reject(new FetchError4(`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 FetchError4(`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 FetchError4(`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 {
            resolve30(Buffer.concat(accum, accumBytes));
          } catch (err) {
            reject(new FetchError4(`Could not create Buffer from response body for ${_this4.url}: ${err.message}`, "system", err));
          }
        });
      });
    }
    __name(consumeBody3, "consumeBody");
    function convertBody(buffer, headers) {
      if (typeof convert2 !== "function") {
        throw new Error("The package `encoding` must be installed to use the textConverted() function");
      }
      const ct2 = headers.get("content-type");
      let charset = "utf-8";
      let res, str2;
      if (ct2) {
        res = /charset=([^;]*)/i.exec(ct2);
      }
      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 isBlob4(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(isBlob4, "isBlob");
    function clone4(instance) {
      let p1, p2;
      let body = instance.body;
      if (instance.bodyUsed) {
        throw new Error("cannot clone body after it is used");
      }
      if (body instanceof Stream9 && typeof body.getBoundary !== "function") {
        p1 = new PassThrough8();
        p2 = new PassThrough8();
        body.pipe(p1);
        body.pipe(p2);
        instance[INTERNALS7].body = p1;
        body = p2;
      }
      return body;
    }
    __name(clone4, "clone");
    function extractContentType3(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 (isBlob4(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 Stream9) {
        return null;
      } else {
        return "text/plain;charset=UTF-8";
      }
    }
    __name(extractContentType3, "extractContentType");
    function getTotalBytes3(instance) {
      const body = instance.body;
      if (body === null) {
        return 0;
      } else if (isBlob4(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(getTotalBytes3, "getTotalBytes");
    function writeToStream3(dest, instance) {
      const body = instance.body;
      if (body === null) {
        dest.end();
      } else if (isBlob4(body)) {
        body.stream().pipe(dest);
      } else if (Buffer.isBuffer(body)) {
        dest.write(body);
        dest.end();
      } else {
        body.pipe(dest);
      }
    }
    __name(writeToStream3, "writeToStream");
    Body3.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 Headers6 = 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 i3 = 0;
        while (i3 < pairs.length) {
          var _pairs$i = pairs[i3];
          const name3 = _pairs$i[0], value = _pairs$i[1];
          callback.call(thisArg, value, name3, this);
          pairs = getHeaders(this);
          i3++;
        }
      }
      /**
       * 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");
      }
    };
    Headers6.prototype.entries = Headers6.prototype[Symbol.iterator];
    Object.defineProperty(Headers6.prototype, Symbol.toStringTag, {
      value: "Headers",
      writable: false,
      enumerable: false,
      configurable: true
    });
    Object.defineProperties(Headers6.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 kind2 = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : "key+value";
      const keys = Object.keys(headers[MAP]).sort();
      return keys.map(kind2 === "key" ? function(k2) {
        return k2.toLowerCase();
      } : kind2 === "value" ? function(k2) {
        return headers[MAP][k2].join(", ");
      } : function(k2) {
        return [k2.toLowerCase(), headers[MAP][k2].join(", ")];
      });
    }
    __name(getHeaders, "getHeaders");
    var INTERNAL = Symbol("internal");
    function createHeadersIterator(target, kind2) {
      const iterator = Object.create(HeadersIteratorPrototype);
      iterator[INTERNAL] = {
        target,
        kind: kind2,
        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, kind2 = _INTERNAL.kind, index = _INTERNAL.index;
        const values = getHeaders(target, kind2);
        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 Headers6();
      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 = http7.STATUS_CODES;
    var Response6 = 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] : {};
        Body3.call(this, body, opts);
        const status = opts.status || 200;
        const headers = new Headers6(opts.headers);
        if (body != null && !headers.has("Content-Type")) {
          const contentType = extractContentType3(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(clone4(this), {
          url: this.url,
          status: this.status,
          statusText: this.statusText,
          headers: this.headers,
          ok: this.ok,
          redirected: this.redirected
        });
      }
    };
    Body3.mixIn(Response6.prototype);
    Object.defineProperties(Response6.prototype, {
      url: { enumerable: true },
      status: { enumerable: true },
      ok: { enumerable: true },
      redirected: { enumerable: true },
      statusText: { enumerable: true },
      headers: { enumerable: true },
      clone: { enumerable: true }
    });
    Object.defineProperty(Response6.prototype, Symbol.toStringTag, {
      value: "Response",
      writable: false,
      enumerable: false,
      configurable: true
    });
    var INTERNALS$2 = Symbol("Request internals");
    var URL5 = 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 URL5(urlStr).toString();
      }
      return parse_url(urlStr);
    }
    __name(parseURL, "parseURL");
    var streamDestructionSupported = "destroy" in Stream9.Readable.prototype;
    function isRequest3(input) {
      return typeof input === "object" && typeof input[INTERNALS$2] === "object";
    }
    __name(isRequest3, "isRequest");
    function isAbortSignal3(signal) {
      const proto3 = signal && typeof signal === "object" && Object.getPrototypeOf(signal);
      return !!(proto3 && proto3.constructor.name === "AbortSignal");
    }
    __name(isAbortSignal3, "isAbortSignal");
    var Request6 = class _Request {
      static {
        __name(this, "Request");
      }
      constructor(input) {
        let init = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {};
        let parsedURL;
        if (!isRequest3(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 || isRequest3(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 : isRequest3(input) && input.body !== null ? clone4(input) : null;
        Body3.call(this, inputBody, {
          timeout: init.timeout || input.timeout || 0,
          size: init.size || input.size || 0
        });
        const headers = new Headers6(init.headers || input.headers || {});
        if (inputBody != null && !headers.has("Content-Type")) {
          const contentType = extractContentType3(inputBody);
          if (contentType) {
            headers.append("Content-Type", contentType);
          }
        }
        let signal = isRequest3(input) ? input.signal : null;
        if ("signal" in init) signal = init.signal;
        if (signal != null && !isAbortSignal3(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);
      }
    };
    Body3.mixIn(Request6.prototype);
    Object.defineProperty(Request6.prototype, Symbol.toStringTag, {
      value: "Request",
      writable: false,
      enumerable: false,
      configurable: true
    });
    Object.defineProperties(Request6.prototype, {
      method: { enumerable: true },
      url: { enumerable: true },
      headers: { enumerable: true },
      redirect: { enumerable: true },
      clone: { enumerable: true },
      signal: { enumerable: true }
    });
    function getNodeRequestOptions3(request4) {
      const parsedURL = request4[INTERNALS$2].parsedURL;
      const headers = new Headers6(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 Stream9.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 = getTotalBytes3(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(getNodeRequestOptions3, "getNodeRequestOptions");
    function AbortError4(message) {
      Error.call(this, message);
      this.type = "aborted";
      this.message = message;
      Error.captureStackTrace(this, this.constructor);
    }
    __name(AbortError4, "AbortError");
    AbortError4.prototype = Object.create(Error.prototype);
    AbortError4.prototype.constructor = AbortError4;
    AbortError4.prototype.name = "AbortError";
    var URL$1 = Url.URL || whatwgUrl.URL;
    var PassThrough$1 = Stream9.PassThrough;
    var isDomainOrSubdomain3 = /* @__PURE__ */ __name(function isDomainOrSubdomain4(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 isSameProtocol3 = /* @__PURE__ */ __name(function isSameProtocol4(destination, original) {
      const orig = new URL$1(original).protocol;
      const dest = new URL$1(destination).protocol;
      return orig === dest;
    }, "isSameProtocol");
    function fetch5(url2, opts) {
      if (!fetch5.Promise) {
        throw new Error("native promise missing, set fetch.Promise to your favorite alternative");
      }
      Body3.Promise = fetch5.Promise;
      return new fetch5.Promise(function(resolve30, reject) {
        const request4 = new Request6(url2, opts);
        const options2 = getNodeRequestOptions3(request4);
        const send = (options2.protocol === "https:" ? https7 : http7).request;
        const signal = request4.signal;
        let response = null;
        const abort = /* @__PURE__ */ __name(function abort2() {
          let error2 = new AbortError4("The user aborted a request.");
          reject(error2);
          if (request4.body && request4.body instanceof Stream9.Readable) {
            destroyStream(request4.body, error2);
          }
          if (!response || !response.body) return;
          response.body.emit("error", error2);
        }, "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 FetchError4(`network timeout at: ${request4.url}`, "request-timeout"));
              finalize();
            }, request4.timeout);
          });
        }
        req.on("error", function(err) {
          reject(new FetchError4(`request to ${request4.url} failed, reason: ${err.message}`, "system", err));
          if (response && response.body) {
            destroyStream(response.body, err);
          }
          finalize();
        });
        fixResponseChunkedTransferBadEnding3(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(s5) {
            s5.addListener("close", function(hadError) {
              const hasDataListener = s5.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 (fetch5.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 FetchError4(`uri requested responds with an invalid redirect URL: ${location}`, "invalid-redirect"));
                finalize();
                return;
              }
            }
            switch (request4.redirect) {
              case "error":
                reject(new FetchError4(`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 FetchError4(`maximum redirect reached at: ${request4.url}`, "max-redirect"));
                  finalize();
                  return;
                }
                const requestOpts = {
                  headers: new Headers6(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 (!isDomainOrSubdomain3(request4.url, locationURL) || !isSameProtocol3(request4.url, locationURL)) {
                  for (const name3 of ["authorization", "www-authenticate", "cookie", "cookie2"]) {
                    requestOpts.headers.delete(name3);
                  }
                }
                if (res.statusCode !== 303 && request4.body && getTotalBytes3(request4) === null) {
                  reject(new FetchError4("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");
                }
                resolve30(fetch5(new Request6(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 Response6(body, response_options);
            resolve30(response);
            return;
          }
          const zlibOptions = {
            flush: zlib4.Z_SYNC_FLUSH,
            finishFlush: zlib4.Z_SYNC_FLUSH
          };
          if (codings == "gzip" || codings == "x-gzip") {
            body = body.pipe(zlib4.createGunzip(zlibOptions));
            response = new Response6(body, response_options);
            resolve30(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(zlib4.createInflate());
              } else {
                body = body.pipe(zlib4.createInflateRaw());
              }
              response = new Response6(body, response_options);
              resolve30(response);
            });
            raw2.on("end", function() {
              if (!response) {
                response = new Response6(body, response_options);
                resolve30(response);
              }
            });
            return;
          }
          if (codings == "br" && typeof zlib4.createBrotliDecompress === "function") {
            body = body.pipe(zlib4.createBrotliDecompress());
            response = new Response6(body, response_options);
            resolve30(response);
            return;
          }
          response = new Response6(body, response_options);
          resolve30(response);
        });
        writeToStream3(req, request4);
      });
    }
    __name(fetch5, "fetch");
    function fixResponseChunkedTransferBadEnding3(request4, errorCallback) {
      let socket;
      request4.on("socket", function(s5) {
        socket = s5;
      });
      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(fixResponseChunkedTransferBadEnding3, "fixResponseChunkedTransferBadEnding");
    function destroyStream(stream2, err) {
      if (stream2.destroy) {
        stream2.destroy(err);
      } else {
        stream2.emit("error", err);
        stream2.end();
      }
    }
    __name(destroyStream, "destroyStream");
    fetch5.isRedirect = function(code2) {
      return code2 === 301 || code2 === 302 || code2 === 303 || code2 === 307 || code2 === 308;
    };
    fetch5.Promise = globalThis.Promise;
    module2.exports = exports2 = fetch5;
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.default = exports2;
    exports2.Headers = Headers6;
    exports2.Request = Request6;
    exports2.Response = Response6;
    exports2.FetchError = FetchError4;
    exports2.AbortError = AbortError4;
  }
});

// node_modules/formdata-node/node_modules/web-streams-polyfill/dist/ponyfill.mjs
function t2() {
}
function r2(e4) {
  return "object" == typeof e4 && null !== e4 || "function" == typeof e4;
}
function n(e4, t5) {
  try {
    Object.defineProperty(e4, "name", { value: t5, configurable: true });
  } catch (e5) {
  }
}
function u(e4) {
  return new a(e4);
}
function c(e4) {
  return l(e4);
}
function d(e4) {
  return s2(e4);
}
function f3(e4, t5, r5) {
  return i2.call(e4, t5, r5);
}
function b(e4, t5, r5) {
  f3(f3(e4, t5, r5), void 0, o);
}
function h2(e4, t5) {
  b(e4, t5);
}
function _(e4, t5) {
  b(e4, void 0, t5);
}
function p(e4, t5, r5) {
  return f3(e4, t5, r5);
}
function m2(e4) {
  f3(e4, void 0, o);
}
function g(e4, t5, r5) {
  if ("function" != typeof e4) throw new TypeError("Argument is not a function");
  return Function.prototype.apply.call(e4, t5, r5);
}
function w(e4, t5, r5) {
  try {
    return c(g(e4, t5, r5));
  } catch (e5) {
    return d(e5);
  }
}
function E(e4, t5) {
  e4._ownerReadableStream = t5, t5._reader = e4, "readable" === t5._state ? O(e4) : "closed" === t5._state ? function(e5) {
    O(e5), j(e5);
  }(e4) : B(e4, t5._storedError);
}
function P(e4, t5) {
  return Gt(e4._ownerReadableStream, t5);
}
function W(e4) {
  const t5 = e4._ownerReadableStream;
  "readable" === t5._state ? A2(e4, new TypeError("Reader was released and can no longer be used to monitor the stream's closedness")) : function(e5, t6) {
    B(e5, t6);
  }(e4, new TypeError("Reader was released and can no longer be used to monitor the stream's closedness")), t5._readableStreamController[C](), t5._reader = void 0, e4._ownerReadableStream = void 0;
}
function k(e4) {
  return new TypeError("Cannot " + e4 + " a stream using a released reader");
}
function O(e4) {
  e4._closedPromise = u((t5, r5) => {
    e4._closedPromise_resolve = t5, e4._closedPromise_reject = r5;
  });
}
function B(e4, t5) {
  O(e4), A2(e4, t5);
}
function A2(e4, t5) {
  void 0 !== e4._closedPromise_reject && (m2(e4._closedPromise), e4._closedPromise_reject(t5), e4._closedPromise_resolve = void 0, e4._closedPromise_reject = void 0);
}
function j(e4) {
  void 0 !== e4._closedPromise_resolve && (e4._closedPromise_resolve(void 0), e4._closedPromise_resolve = void 0, e4._closedPromise_reject = void 0);
}
function F2(e4, t5) {
  if (void 0 !== e4 && ("object" != typeof (r5 = e4) && "function" != typeof r5)) throw new TypeError(`${t5} is not an object.`);
  var r5;
}
function I(e4, t5) {
  if ("function" != typeof e4) throw new TypeError(`${t5} is not a function.`);
}
function D(e4, t5) {
  if (!/* @__PURE__ */ function(e5) {
    return "object" == typeof e5 && null !== e5 || "function" == typeof e5;
  }(e4)) throw new TypeError(`${t5} is not an object.`);
}
function $(e4, t5, r5) {
  if (void 0 === e4) throw new TypeError(`Parameter ${t5} is required in '${r5}'.`);
}
function M(e4, t5, r5) {
  if (void 0 === e4) throw new TypeError(`${t5} is required in '${r5}'.`);
}
function Y(e4) {
  return Number(e4);
}
function Q(e4) {
  return 0 === e4 ? 0 : e4;
}
function N(e4, t5) {
  const r5 = Number.MAX_SAFE_INTEGER;
  let o3 = Number(e4);
  if (o3 = Q(o3), !z(o3)) throw new TypeError(`${t5} is not a finite number`);
  if (o3 = function(e5) {
    return Q(L(e5));
  }(o3), o3 < 0 || o3 > r5) throw new TypeError(`${t5} is outside the accepted range of 0 to ${r5}, inclusive`);
  return z(o3) && 0 !== o3 ? o3 : 0;
}
function H(e4) {
  if (!r2(e4)) return false;
  if ("function" != typeof e4.getReader) return false;
  try {
    return "boolean" == typeof e4.locked;
  } catch (e5) {
    return false;
  }
}
function x2(e4) {
  if (!r2(e4)) return false;
  if ("function" != typeof e4.getWriter) return false;
  try {
    return "boolean" == typeof e4.locked;
  } catch (e5) {
    return false;
  }
}
function V(e4, t5) {
  if (!Vt(e4)) throw new TypeError(`${t5} is not a ReadableStream.`);
}
function U(e4, t5) {
  e4._reader._readRequests.push(t5);
}
function G(e4, t5, r5) {
  const o3 = e4._reader._readRequests.shift();
  r5 ? o3._closeSteps() : o3._chunkSteps(t5);
}
function X(e4) {
  return e4._reader._readRequests.length;
}
function J(e4) {
  const t5 = e4._reader;
  return void 0 !== t5 && !!K(t5);
}
function K(e4) {
  return !!r2(e4) && (!!Object.prototype.hasOwnProperty.call(e4, "_readRequests") && e4 instanceof ReadableStreamDefaultReader);
}
function Z2(e4, t5) {
  const r5 = e4._readRequests;
  e4._readRequests = new S2(), r5.forEach((e5) => {
    e5._errorSteps(t5);
  });
}
function ee(e4) {
  return new TypeError(`ReadableStreamDefaultReader.prototype.${e4} can only be used on a ReadableStreamDefaultReader`);
}
function oe(e4) {
  if (!r2(e4)) return false;
  if (!Object.prototype.hasOwnProperty.call(e4, "_asyncIteratorImpl")) return false;
  try {
    return e4._asyncIteratorImpl instanceof te;
  } catch (e5) {
    return false;
  }
}
function ne(e4) {
  return new TypeError(`ReadableStreamAsyncIterator.${e4} can only be used on a ReadableSteamAsyncIterator`);
}
function ie(e4, t5, r5, o3, n3) {
  new Uint8Array(e4).set(new Uint8Array(r5, o3, n3), t5);
}
function le(e4) {
  const t5 = function(e5, t6, r5) {
    if (e5.slice) return e5.slice(t6, r5);
    const o3 = r5 - t6, n3 = new ArrayBuffer(o3);
    return ie(n3, 0, e5, t6, o3), n3;
  }(e4.buffer, e4.byteOffset, e4.byteOffset + e4.byteLength);
  return new Uint8Array(t5);
}
function se(e4) {
  const t5 = e4._queue.shift();
  return e4._queueTotalSize -= t5.size, e4._queueTotalSize < 0 && (e4._queueTotalSize = 0), t5.value;
}
function ue(e4, t5, r5) {
  if ("number" != typeof (o3 = r5) || ae(o3) || o3 < 0 || r5 === 1 / 0) throw new RangeError("Size must be a finite, non-NaN, non-negative number.");
  var o3;
  e4._queue.push({ value: t5, size: r5 }), e4._queueTotalSize += r5;
}
function ce(e4) {
  e4._queue = new S2(), e4._queueTotalSize = 0;
}
function de(e4) {
  return !!r2(e4) && (!!Object.prototype.hasOwnProperty.call(e4, "_controlledReadableByteStream") && e4 instanceof ReadableByteStreamController);
}
function fe(e4) {
  return !!r2(e4) && (!!Object.prototype.hasOwnProperty.call(e4, "_associatedReadableByteStreamController") && e4 instanceof ReadableStreamBYOBRequest);
}
function be(e4) {
  const t5 = function(e5) {
    const t6 = e5._controlledReadableByteStream;
    if ("readable" !== t6._state) return false;
    if (e5._closeRequested) return false;
    if (!e5._started) return false;
    if (J(t6) && X(t6) > 0) return true;
    if (Le(t6) && ze(t6) > 0) return true;
    if (ke(e5) > 0) return true;
    return false;
  }(e4);
  if (!t5) return;
  if (e4._pulling) return void (e4._pullAgain = true);
  e4._pulling = true;
  b(e4._pullAlgorithm(), () => (e4._pulling = false, e4._pullAgain && (e4._pullAgain = false, be(e4)), null), (t6) => (Pe(e4, t6), null));
}
function he(e4) {
  Re(e4), e4._pendingPullIntos = new S2();
}
function _e(e4, t5) {
  let r5 = false;
  "closed" === e4._state && (r5 = true);
  const o3 = pe(t5);
  "default" === t5.readerType ? G(e4, o3, r5) : function(e5, t6, r6) {
    const o4 = e5._reader._readIntoRequests.shift();
    r6 ? o4._closeSteps(t6) : o4._chunkSteps(t6);
  }(e4, o3, r5);
}
function pe(e4) {
  const t5 = e4.bytesFilled, r5 = e4.elementSize;
  return new e4.viewConstructor(e4.buffer, e4.byteOffset, t5 / r5);
}
function me(e4, t5, r5, o3) {
  e4._queue.push({ buffer: t5, byteOffset: r5, byteLength: o3 }), e4._queueTotalSize += o3;
}
function ye(e4, t5, r5, o3) {
  let n3;
  try {
    n3 = t5.slice(r5, r5 + o3);
  } catch (t6) {
    throw Pe(e4, t6), t6;
  }
  me(e4, n3, 0, o3);
}
function ge(e4, t5) {
  t5.bytesFilled > 0 && ye(e4, t5.buffer, t5.byteOffset, t5.bytesFilled), Ce(e4);
}
function we(e4, t5) {
  const r5 = t5.elementSize, o3 = t5.bytesFilled - t5.bytesFilled % r5, n3 = Math.min(e4._queueTotalSize, t5.byteLength - t5.bytesFilled), a2 = t5.bytesFilled + n3, i3 = a2 - a2 % r5;
  let l3 = n3, s5 = false;
  i3 > o3 && (l3 = i3 - t5.bytesFilled, s5 = true);
  const u2 = e4._queue;
  for (; l3 > 0; ) {
    const r6 = u2.peek(), o4 = Math.min(l3, r6.byteLength), n4 = t5.byteOffset + t5.bytesFilled;
    ie(t5.buffer, n4, r6.buffer, r6.byteOffset, o4), r6.byteLength === o4 ? u2.shift() : (r6.byteOffset += o4, r6.byteLength -= o4), e4._queueTotalSize -= o4, Se(e4, o4, t5), l3 -= o4;
  }
  return s5;
}
function Se(e4, t5, r5) {
  r5.bytesFilled += t5;
}
function ve(e4) {
  0 === e4._queueTotalSize && e4._closeRequested ? (Ee(e4), Xt(e4._controlledReadableByteStream)) : be(e4);
}
function Re(e4) {
  null !== e4._byobRequest && (e4._byobRequest._associatedReadableByteStreamController = void 0, e4._byobRequest._view = null, e4._byobRequest = null);
}
function Te(e4) {
  for (; e4._pendingPullIntos.length > 0; ) {
    if (0 === e4._queueTotalSize) return;
    const t5 = e4._pendingPullIntos.peek();
    we(e4, t5) && (Ce(e4), _e(e4._controlledReadableByteStream, t5));
  }
}
function qe(e4, t5) {
  const r5 = e4._pendingPullIntos.peek();
  Re(e4);
  "closed" === e4._controlledReadableByteStream._state ? function(e5, t6) {
    "none" === t6.readerType && Ce(e5);
    const r6 = e5._controlledReadableByteStream;
    if (Le(r6)) for (; ze(r6) > 0; ) _e(r6, Ce(e5));
  }(e4, r5) : function(e5, t6, r6) {
    if (Se(0, t6, r6), "none" === r6.readerType) return ge(e5, r6), void Te(e5);
    if (r6.bytesFilled < r6.elementSize) return;
    Ce(e5);
    const o3 = r6.bytesFilled % r6.elementSize;
    if (o3 > 0) {
      const t7 = r6.byteOffset + r6.bytesFilled;
      ye(e5, r6.buffer, t7 - o3, o3);
    }
    r6.bytesFilled -= o3, _e(e5._controlledReadableByteStream, r6), Te(e5);
  }(e4, t5, r5), be(e4);
}
function Ce(e4) {
  return e4._pendingPullIntos.shift();
}
function Ee(e4) {
  e4._pullAlgorithm = void 0, e4._cancelAlgorithm = void 0;
}
function Pe(e4, t5) {
  const r5 = e4._controlledReadableByteStream;
  "readable" === r5._state && (he(e4), ce(e4), Ee(e4), Jt(r5, t5));
}
function We(e4, t5) {
  const r5 = e4._queue.shift();
  e4._queueTotalSize -= r5.byteLength, ve(e4);
  const o3 = new Uint8Array(r5.buffer, r5.byteOffset, r5.byteLength);
  t5._chunkSteps(o3);
}
function ke(e4) {
  const t5 = e4._controlledReadableByteStream._state;
  return "errored" === t5 ? null : "closed" === t5 ? 0 : e4._strategyHWM - e4._queueTotalSize;
}
function Oe(e4, t5, r5) {
  const o3 = Object.create(ReadableByteStreamController.prototype);
  let n3, a2, i3;
  n3 = void 0 !== t5.start ? () => t5.start(o3) : () => {
  }, a2 = void 0 !== t5.pull ? () => t5.pull(o3) : () => c(void 0), i3 = void 0 !== t5.cancel ? (e5) => t5.cancel(e5) : () => c(void 0);
  const l3 = t5.autoAllocateChunkSize;
  if (0 === l3) throw new TypeError("autoAllocateChunkSize must be greater than 0");
  !function(e5, t6, r6, o4, n4, a3, i4) {
    t6._controlledReadableByteStream = e5, t6._pullAgain = false, t6._pulling = false, t6._byobRequest = null, t6._queue = t6._queueTotalSize = void 0, ce(t6), t6._closeRequested = false, t6._started = false, t6._strategyHWM = a3, t6._pullAlgorithm = o4, t6._cancelAlgorithm = n4, t6._autoAllocateChunkSize = i4, t6._pendingPullIntos = new S2(), e5._readableStreamController = t6, b(c(r6()), () => (t6._started = true, be(t6), null), (e6) => (Pe(t6, e6), null));
  }(e4, o3, n3, a2, i3, r5, l3);
}
function Be(e4) {
  return new TypeError(`ReadableStreamBYOBRequest.prototype.${e4} can only be used on a ReadableStreamBYOBRequest`);
}
function Ae(e4) {
  return new TypeError(`ReadableByteStreamController.prototype.${e4} can only be used on a ReadableByteStreamController`);
}
function je(e4, t5) {
  e4._reader._readIntoRequests.push(t5);
}
function ze(e4) {
  return e4._reader._readIntoRequests.length;
}
function Le(e4) {
  const t5 = e4._reader;
  return void 0 !== t5 && !!Fe(t5);
}
function Fe(e4) {
  return !!r2(e4) && (!!Object.prototype.hasOwnProperty.call(e4, "_readIntoRequests") && e4 instanceof ReadableStreamBYOBReader);
}
function Ie(e4, t5) {
  const r5 = e4._readIntoRequests;
  e4._readIntoRequests = new S2(), r5.forEach((e5) => {
    e5._errorSteps(t5);
  });
}
function De(e4) {
  return new TypeError(`ReadableStreamBYOBReader.prototype.${e4} can only be used on a ReadableStreamBYOBReader`);
}
function $e(e4, t5) {
  const { highWaterMark: r5 } = e4;
  if (void 0 === r5) return t5;
  if (ae(r5) || r5 < 0) throw new RangeError("Invalid highWaterMark");
  return r5;
}
function Me(e4) {
  const { size: t5 } = e4;
  return t5 || (() => 1);
}
function Ye(e4, t5) {
  F2(e4, t5);
  const r5 = null == e4 ? void 0 : e4.highWaterMark, o3 = null == e4 ? void 0 : e4.size;
  return { highWaterMark: void 0 === r5 ? void 0 : Y(r5), size: void 0 === o3 ? void 0 : Qe(o3, `${t5} has member 'size' that`) };
}
function Qe(e4, t5) {
  return I(e4, t5), (t6) => Y(e4(t6));
}
function Ne(e4, t5, r5) {
  return I(e4, r5), (r6) => w(e4, t5, [r6]);
}
function He(e4, t5, r5) {
  return I(e4, r5), () => w(e4, t5, []);
}
function xe(e4, t5, r5) {
  return I(e4, r5), (r6) => g(e4, t5, [r6]);
}
function Ve(e4, t5, r5) {
  return I(e4, r5), (r6, o3) => w(e4, t5, [r6, o3]);
}
function Ge(e4) {
  return !!r2(e4) && (!!Object.prototype.hasOwnProperty.call(e4, "_writableStreamController") && e4 instanceof WritableStream);
}
function Xe(e4) {
  return void 0 !== e4._writer;
}
function Je(e4, t5) {
  var r5;
  if ("closed" === e4._state || "errored" === e4._state) return c(void 0);
  e4._writableStreamController._abortReason = t5, null === (r5 = e4._writableStreamController._abortController) || void 0 === r5 || r5.abort(t5);
  const o3 = e4._state;
  if ("closed" === o3 || "errored" === o3) return c(void 0);
  if (void 0 !== e4._pendingAbortRequest) return e4._pendingAbortRequest._promise;
  let n3 = false;
  "erroring" === o3 && (n3 = true, t5 = void 0);
  const a2 = u((r6, o4) => {
    e4._pendingAbortRequest = { _promise: void 0, _resolve: r6, _reject: o4, _reason: t5, _wasAlreadyErroring: n3 };
  });
  return e4._pendingAbortRequest._promise = a2, n3 || et(e4, t5), a2;
}
function Ke(e4) {
  const t5 = e4._state;
  if ("closed" === t5 || "errored" === t5) return d(new TypeError(`The stream (in ${t5} state) is not in the writable state and cannot be closed`));
  const r5 = u((t6, r6) => {
    const o4 = { _resolve: t6, _reject: r6 };
    e4._closeRequest = o4;
  }), o3 = e4._writer;
  var n3;
  return void 0 !== o3 && e4._backpressure && "writable" === t5 && Et(o3), ue(n3 = e4._writableStreamController, lt, 0), dt(n3), r5;
}
function Ze(e4, t5) {
  "writable" !== e4._state ? tt(e4) : et(e4, t5);
}
function et(e4, t5) {
  const r5 = e4._writableStreamController;
  e4._state = "erroring", e4._storedError = t5;
  const o3 = e4._writer;
  void 0 !== o3 && it(o3, t5), !function(e5) {
    if (void 0 === e5._inFlightWriteRequest && void 0 === e5._inFlightCloseRequest) return false;
    return true;
  }(e4) && r5._started && tt(e4);
}
function tt(e4) {
  e4._state = "errored", e4._writableStreamController[R]();
  const t5 = e4._storedError;
  if (e4._writeRequests.forEach((e5) => {
    e5._reject(t5);
  }), e4._writeRequests = new S2(), void 0 === e4._pendingAbortRequest) return void ot(e4);
  const r5 = e4._pendingAbortRequest;
  if (e4._pendingAbortRequest = void 0, r5._wasAlreadyErroring) return r5._reject(t5), void ot(e4);
  b(e4._writableStreamController[v](r5._reason), () => (r5._resolve(), ot(e4), null), (t6) => (r5._reject(t6), ot(e4), null));
}
function rt(e4) {
  return void 0 !== e4._closeRequest || void 0 !== e4._inFlightCloseRequest;
}
function ot(e4) {
  void 0 !== e4._closeRequest && (e4._closeRequest._reject(e4._storedError), e4._closeRequest = void 0);
  const t5 = e4._writer;
  void 0 !== t5 && St(t5, e4._storedError);
}
function nt(e4, t5) {
  const r5 = e4._writer;
  void 0 !== r5 && t5 !== e4._backpressure && (t5 ? function(e5) {
    Rt(e5);
  }(r5) : Et(r5)), e4._backpressure = t5;
}
function at(e4) {
  return !!r2(e4) && (!!Object.prototype.hasOwnProperty.call(e4, "_ownerWritableStream") && e4 instanceof WritableStreamDefaultWriter);
}
function it(e4, t5) {
  "pending" === e4._readyPromiseState ? Ct(e4, t5) : function(e5, t6) {
    Tt(e5, t6);
  }(e4, t5);
}
function st(e4) {
  return !!r2(e4) && (!!Object.prototype.hasOwnProperty.call(e4, "_controlledWritableStream") && e4 instanceof WritableStreamDefaultController);
}
function ut(e4) {
  e4._writeAlgorithm = void 0, e4._closeAlgorithm = void 0, e4._abortAlgorithm = void 0, e4._strategySizeAlgorithm = void 0;
}
function ct(e4) {
  return e4._strategyHWM - e4._queueTotalSize;
}
function dt(e4) {
  const t5 = e4._controlledWritableStream;
  if (!e4._started) return;
  if (void 0 !== t5._inFlightWriteRequest) return;
  if ("erroring" === t5._state) return void tt(t5);
  if (0 === e4._queue.length) return;
  const r5 = e4._queue.peek().value;
  r5 === lt ? function(e5) {
    const t6 = e5._controlledWritableStream;
    (function(e6) {
      e6._inFlightCloseRequest = e6._closeRequest, e6._closeRequest = void 0;
    })(t6), se(e5);
    const r6 = e5._closeAlgorithm();
    ut(e5), b(r6, () => (function(e6) {
      e6._inFlightCloseRequest._resolve(void 0), e6._inFlightCloseRequest = void 0, "erroring" === e6._state && (e6._storedError = void 0, void 0 !== e6._pendingAbortRequest && (e6._pendingAbortRequest._resolve(), e6._pendingAbortRequest = void 0)), e6._state = "closed";
      const t7 = e6._writer;
      void 0 !== t7 && vt(t7);
    }(t6), null), (e6) => (function(e7, t7) {
      e7._inFlightCloseRequest._reject(t7), e7._inFlightCloseRequest = void 0, void 0 !== e7._pendingAbortRequest && (e7._pendingAbortRequest._reject(t7), e7._pendingAbortRequest = void 0), Ze(e7, t7);
    }(t6, e6), null));
  }(e4) : function(e5, t6) {
    const r6 = e5._controlledWritableStream;
    !function(e6) {
      e6._inFlightWriteRequest = e6._writeRequests.shift();
    }(r6);
    b(e5._writeAlgorithm(t6), () => {
      !function(e6) {
        e6._inFlightWriteRequest._resolve(void 0), e6._inFlightWriteRequest = void 0;
      }(r6);
      const t7 = r6._state;
      if (se(e5), !rt(r6) && "writable" === t7) {
        const t8 = bt(e5);
        nt(r6, t8);
      }
      return dt(e5), null;
    }, (t7) => ("writable" === r6._state && ut(e5), function(e6, t8) {
      e6._inFlightWriteRequest._reject(t8), e6._inFlightWriteRequest = void 0, Ze(e6, t8);
    }(r6, t7), null));
  }(e4, r5);
}
function ft(e4, t5) {
  "writable" === e4._controlledWritableStream._state && ht(e4, t5);
}
function bt(e4) {
  return ct(e4) <= 0;
}
function ht(e4, t5) {
  const r5 = e4._controlledWritableStream;
  ut(e4), et(r5, t5);
}
function _t(e4) {
  return new TypeError(`WritableStream.prototype.${e4} can only be used on a WritableStream`);
}
function pt(e4) {
  return new TypeError(`WritableStreamDefaultController.prototype.${e4} can only be used on a WritableStreamDefaultController`);
}
function mt(e4) {
  return new TypeError(`WritableStreamDefaultWriter.prototype.${e4} can only be used on a WritableStreamDefaultWriter`);
}
function yt(e4) {
  return new TypeError("Cannot " + e4 + " a stream using a released writer");
}
function gt(e4) {
  e4._closedPromise = u((t5, r5) => {
    e4._closedPromise_resolve = t5, e4._closedPromise_reject = r5, e4._closedPromiseState = "pending";
  });
}
function wt(e4, t5) {
  gt(e4), St(e4, t5);
}
function St(e4, t5) {
  void 0 !== e4._closedPromise_reject && (m2(e4._closedPromise), e4._closedPromise_reject(t5), e4._closedPromise_resolve = void 0, e4._closedPromise_reject = void 0, e4._closedPromiseState = "rejected");
}
function vt(e4) {
  void 0 !== e4._closedPromise_resolve && (e4._closedPromise_resolve(void 0), e4._closedPromise_resolve = void 0, e4._closedPromise_reject = void 0, e4._closedPromiseState = "resolved");
}
function Rt(e4) {
  e4._readyPromise = u((t5, r5) => {
    e4._readyPromise_resolve = t5, e4._readyPromise_reject = r5;
  }), e4._readyPromiseState = "pending";
}
function Tt(e4, t5) {
  Rt(e4), Ct(e4, t5);
}
function qt(e4) {
  Rt(e4), Et(e4);
}
function Ct(e4, t5) {
  void 0 !== e4._readyPromise_reject && (m2(e4._readyPromise), e4._readyPromise_reject(t5), e4._readyPromise_resolve = void 0, e4._readyPromise_reject = void 0, e4._readyPromiseState = "rejected");
}
function Et(e4) {
  void 0 !== e4._readyPromise_resolve && (e4._readyPromise_resolve(void 0), e4._readyPromise_resolve = void 0, e4._readyPromise_reject = void 0, e4._readyPromiseState = "fulfilled");
}
function kt(e4, t5, r5, o3, n3, a2) {
  const i3 = e4.getReader(), l3 = t5.getWriter();
  Vt(e4) && (e4._disturbed = true);
  let s5, _2, g2, w2 = false, S4 = false, v2 = "readable", R2 = "writable", T2 = false, q2 = false;
  const C2 = u((e5) => {
    g2 = e5;
  });
  let E2 = Promise.resolve(void 0);
  return u((P2, W2) => {
    let k2;
    function O2() {
      if (w2) return;
      const e5 = u((e6, t6) => {
        !(/* @__PURE__ */ __name(function r6(o4) {
          o4 ? e6() : f3(function() {
            if (w2) return c(true);
            return f3(l3.ready, () => f3(i3.read(), (e7) => !!e7.done || (E2 = l3.write(e7.value), m2(E2), false)));
          }(), r6, t6);
        }, "r"))(false);
      });
      m2(e5);
    }
    __name(O2, "O");
    function B2() {
      return v2 = "closed", r5 ? L2() : z2(() => (Ge(t5) && (T2 = rt(t5), R2 = t5._state), T2 || "closed" === R2 ? c(void 0) : "erroring" === R2 || "errored" === R2 ? d(_2) : (T2 = true, l3.close())), false, void 0), null;
    }
    __name(B2, "B");
    function A4(e5) {
      return w2 || (v2 = "errored", s5 = e5, o3 ? L2(true, e5) : z2(() => l3.abort(e5), true, e5)), null;
    }
    __name(A4, "A");
    function j2(e5) {
      return S4 || (R2 = "errored", _2 = e5, n3 ? L2(true, e5) : z2(() => i3.cancel(e5), true, e5)), null;
    }
    __name(j2, "j");
    if (void 0 !== a2 && (k2 = /* @__PURE__ */ __name(() => {
      const e5 = void 0 !== a2.reason ? a2.reason : new Wt("Aborted", "AbortError"), t6 = [];
      o3 || t6.push(() => "writable" === R2 ? l3.abort(e5) : c(void 0)), n3 || t6.push(() => "readable" === v2 ? i3.cancel(e5) : c(void 0)), z2(() => Promise.all(t6.map((e6) => e6())), true, e5);
    }, "k"), a2.aborted ? k2() : a2.addEventListener("abort", k2)), Vt(e4) && (v2 = e4._state, s5 = e4._storedError), Ge(t5) && (R2 = t5._state, _2 = t5._storedError, T2 = rt(t5)), Vt(e4) && Ge(t5) && (q2 = true, g2()), "errored" === v2) A4(s5);
    else if ("erroring" === R2 || "errored" === R2) j2(_2);
    else if ("closed" === v2) B2();
    else if (T2 || "closed" === R2) {
      const e5 = new TypeError("the destination writable stream closed before all data could be piped to it");
      n3 ? L2(true, e5) : z2(() => i3.cancel(e5), true, e5);
    }
    function z2(e5, t6, r6) {
      function o4() {
        return "writable" !== R2 || T2 ? n4() : h2(function() {
          let e6;
          return c((/* @__PURE__ */ __name(function t7() {
            if (e6 !== E2) return e6 = E2, p(E2, t7, t7);
          }, "t"))());
        }(), n4), null;
      }
      __name(o4, "o");
      function n4() {
        return e5 ? b(e5(), () => F4(t6, r6), (e6) => F4(true, e6)) : F4(t6, r6), null;
      }
      __name(n4, "n");
      w2 || (w2 = true, q2 ? o4() : h2(C2, o4));
    }
    __name(z2, "z");
    function L2(e5, t6) {
      z2(void 0, e5, t6);
    }
    __name(L2, "L");
    function F4(e5, t6) {
      return S4 = true, l3.releaseLock(), i3.releaseLock(), void 0 !== a2 && a2.removeEventListener("abort", k2), e5 ? W2(t6) : P2(void 0), null;
    }
    __name(F4, "F");
    w2 || (b(i3.closed, B2, A4), b(l3.closed, function() {
      return S4 || (R2 = "closed"), null;
    }, j2)), q2 ? O2() : y(() => {
      q2 = true, g2(), O2();
    });
  });
}
function Ot(e4, t5) {
  return function(e5) {
    try {
      return e5.getReader({ mode: "byob" }).releaseLock(), true;
    } catch (e6) {
      return false;
    }
  }(e4) ? function(e5) {
    let t6, r5, o3, n3, a2, i3 = e5.getReader(), l3 = false, s5 = false, d2 = false, f5 = false, h3 = false, p2 = false;
    const m3 = u((e6) => {
      a2 = e6;
    });
    function y2(e6) {
      _(e6.closed, (t7) => (e6 !== i3 || (o3.error(t7), n3.error(t7), h3 && p2 || a2(void 0)), null));
    }
    __name(y2, "y");
    function g2() {
      l3 && (i3.releaseLock(), i3 = e5.getReader(), y2(i3), l3 = false), b(i3.read(), (e6) => {
        var t7, r6;
        if (d2 = false, f5 = false, e6.done) return h3 || o3.close(), p2 || n3.close(), null === (t7 = o3.byobRequest) || void 0 === t7 || t7.respond(0), null === (r6 = n3.byobRequest) || void 0 === r6 || r6.respond(0), h3 && p2 || a2(void 0), null;
        const l4 = e6.value, u2 = l4;
        let c4 = l4;
        if (!h3 && !p2) try {
          c4 = le(l4);
        } catch (e7) {
          return o3.error(e7), n3.error(e7), a2(i3.cancel(e7)), null;
        }
        return h3 || o3.enqueue(u2), p2 || n3.enqueue(c4), s5 = false, d2 ? S4() : f5 && v2(), null;
      }, () => (s5 = false, null));
    }
    __name(g2, "g");
    function w2(t7, r6) {
      l3 || (i3.releaseLock(), i3 = e5.getReader({ mode: "byob" }), y2(i3), l3 = true);
      const u2 = r6 ? n3 : o3, c4 = r6 ? o3 : n3;
      b(i3.read(t7), (e6) => {
        var t8;
        d2 = false, f5 = false;
        const o4 = r6 ? p2 : h3, n4 = r6 ? h3 : p2;
        if (e6.done) {
          o4 || u2.close(), n4 || c4.close();
          const r7 = e6.value;
          return void 0 !== r7 && (o4 || u2.byobRequest.respondWithNewView(r7), n4 || null === (t8 = c4.byobRequest) || void 0 === t8 || t8.respond(0)), o4 && n4 || a2(void 0), null;
        }
        const l4 = e6.value;
        if (n4) o4 || u2.byobRequest.respondWithNewView(l4);
        else {
          let e7;
          try {
            e7 = le(l4);
          } catch (e8) {
            return u2.error(e8), c4.error(e8), a2(i3.cancel(e8)), null;
          }
          o4 || u2.byobRequest.respondWithNewView(l4), c4.enqueue(e7);
        }
        return s5 = false, d2 ? S4() : f5 && v2(), null;
      }, () => (s5 = false, null));
    }
    __name(w2, "w");
    function S4() {
      if (s5) return d2 = true, c(void 0);
      s5 = true;
      const e6 = o3.byobRequest;
      return null === e6 ? g2() : w2(e6.view, false), c(void 0);
    }
    __name(S4, "S");
    function v2() {
      if (s5) return f5 = true, c(void 0);
      s5 = true;
      const e6 = n3.byobRequest;
      return null === e6 ? g2() : w2(e6.view, true), c(void 0);
    }
    __name(v2, "v");
    function R2(e6) {
      if (h3 = true, t6 = e6, p2) {
        const e7 = [t6, r5], o4 = i3.cancel(e7);
        a2(o4);
      }
      return m3;
    }
    __name(R2, "R");
    function T2(e6) {
      if (p2 = true, r5 = e6, h3) {
        const e7 = [t6, r5], o4 = i3.cancel(e7);
        a2(o4);
      }
      return m3;
    }
    __name(T2, "T");
    const q2 = new ReadableStream3({ type: "bytes", start(e6) {
      o3 = e6;
    }, pull: S4, cancel: R2 }), C2 = new ReadableStream3({ type: "bytes", start(e6) {
      n3 = e6;
    }, pull: v2, cancel: T2 });
    return y2(i3), [q2, C2];
  }(e4) : function(e5, t6) {
    const r5 = e5.getReader();
    let o3, n3, a2, i3, l3, s5 = false, d2 = false, f5 = false, h3 = false;
    const p2 = u((e6) => {
      l3 = e6;
    });
    function m3() {
      return s5 ? (d2 = true, c(void 0)) : (s5 = true, b(r5.read(), (e6) => {
        if (d2 = false, e6.done) return f5 || a2.close(), h3 || i3.close(), f5 && h3 || l3(void 0), null;
        const t7 = e6.value, r6 = t7, o4 = t7;
        return f5 || a2.enqueue(r6), h3 || i3.enqueue(o4), s5 = false, d2 && m3(), null;
      }, () => (s5 = false, null)), c(void 0));
    }
    __name(m3, "m");
    function y2(e6) {
      if (f5 = true, o3 = e6, h3) {
        const e7 = [o3, n3], t7 = r5.cancel(e7);
        l3(t7);
      }
      return p2;
    }
    __name(y2, "y");
    function g2(e6) {
      if (h3 = true, n3 = e6, f5) {
        const e7 = [o3, n3], t7 = r5.cancel(e7);
        l3(t7);
      }
      return p2;
    }
    __name(g2, "g");
    const w2 = new ReadableStream3({ start(e6) {
      a2 = e6;
    }, pull: m3, cancel: y2 }), S4 = new ReadableStream3({ start(e6) {
      i3 = e6;
    }, pull: m3, cancel: g2 });
    return _(r5.closed, (e6) => (a2.error(e6), i3.error(e6), f5 && h3 || l3(void 0), null)), [w2, S4];
  }(e4);
}
function Bt(e4) {
  return !!r2(e4) && (!!Object.prototype.hasOwnProperty.call(e4, "_controlledReadableStream") && e4 instanceof ReadableStreamDefaultController);
}
function At(e4) {
  const t5 = function(e5) {
    const t6 = e5._controlledReadableStream;
    if (!Ft(e5)) return false;
    if (!e5._started) return false;
    if (Ut(t6) && X(t6) > 0) return true;
    if (Lt(e5) > 0) return true;
    return false;
  }(e4);
  if (!t5) return;
  if (e4._pulling) return void (e4._pullAgain = true);
  e4._pulling = true;
  b(e4._pullAlgorithm(), () => (e4._pulling = false, e4._pullAgain && (e4._pullAgain = false, At(e4)), null), (t6) => (zt(e4, t6), null));
}
function jt(e4) {
  e4._pullAlgorithm = void 0, e4._cancelAlgorithm = void 0, e4._strategySizeAlgorithm = void 0;
}
function zt(e4, t5) {
  const r5 = e4._controlledReadableStream;
  "readable" === r5._state && (ce(e4), jt(e4), Jt(r5, t5));
}
function Lt(e4) {
  const t5 = e4._controlledReadableStream._state;
  return "errored" === t5 ? null : "closed" === t5 ? 0 : e4._strategyHWM - e4._queueTotalSize;
}
function Ft(e4) {
  return !e4._closeRequested && "readable" === e4._controlledReadableStream._state;
}
function It(e4, t5, r5, o3) {
  const n3 = Object.create(ReadableStreamDefaultController.prototype);
  let a2, i3, l3;
  a2 = void 0 !== t5.start ? () => t5.start(n3) : () => {
  }, i3 = void 0 !== t5.pull ? () => t5.pull(n3) : () => c(void 0), l3 = void 0 !== t5.cancel ? (e5) => t5.cancel(e5) : () => c(void 0), function(e5, t6, r6, o4, n4, a3, i4) {
    t6._controlledReadableStream = e5, t6._queue = void 0, t6._queueTotalSize = void 0, ce(t6), t6._started = false, t6._closeRequested = false, t6._pullAgain = false, t6._pulling = false, t6._strategySizeAlgorithm = i4, t6._strategyHWM = a3, t6._pullAlgorithm = o4, t6._cancelAlgorithm = n4, e5._readableStreamController = t6, b(c(r6()), () => (t6._started = true, At(t6), null), (e6) => (zt(t6, e6), null));
  }(e4, n3, a2, i3, l3, r5, o3);
}
function Dt(e4) {
  return new TypeError(`ReadableStreamDefaultController.prototype.${e4} can only be used on a ReadableStreamDefaultController`);
}
function $t(e4, t5, r5) {
  return I(e4, r5), (r6) => w(e4, t5, [r6]);
}
function Mt(e4, t5, r5) {
  return I(e4, r5), (r6) => w(e4, t5, [r6]);
}
function Yt(e4, t5, r5) {
  return I(e4, r5), (r6) => g(e4, t5, [r6]);
}
function Qt(e4, t5) {
  if ("bytes" !== (e4 = `${e4}`)) throw new TypeError(`${t5} '${e4}' is not a valid enumeration value for ReadableStreamType`);
  return e4;
}
function Nt(e4, t5) {
  if ("byob" !== (e4 = `${e4}`)) throw new TypeError(`${t5} '${e4}' is not a valid enumeration value for ReadableStreamReaderMode`);
  return e4;
}
function Ht(e4, t5) {
  F2(e4, t5);
  const r5 = null == e4 ? void 0 : e4.preventAbort, o3 = null == e4 ? void 0 : e4.preventCancel, n3 = null == e4 ? void 0 : e4.preventClose, a2 = null == e4 ? void 0 : e4.signal;
  return void 0 !== a2 && function(e5, t6) {
    if (!function(e6) {
      if ("object" != typeof e6 || null === e6) return false;
      try {
        return "boolean" == typeof e6.aborted;
      } catch (e7) {
        return false;
      }
    }(e5)) throw new TypeError(`${t6} is not an AbortSignal.`);
  }(a2, `${t5} has member 'signal' that`), { preventAbort: Boolean(r5), preventCancel: Boolean(o3), preventClose: Boolean(n3), signal: a2 };
}
function xt(e4, t5) {
  F2(e4, t5);
  const r5 = null == e4 ? void 0 : e4.readable;
  M(r5, "readable", "ReadableWritablePair"), function(e5, t6) {
    if (!H(e5)) throw new TypeError(`${t6} is not a ReadableStream.`);
  }(r5, `${t5} has member 'readable' that`);
  const o3 = null == e4 ? void 0 : e4.writable;
  return M(o3, "writable", "ReadableWritablePair"), function(e5, t6) {
    if (!x2(e5)) throw new TypeError(`${t6} is not a WritableStream.`);
  }(o3, `${t5} has member 'writable' that`), { readable: r5, writable: o3 };
}
function Vt(e4) {
  return !!r2(e4) && (!!Object.prototype.hasOwnProperty.call(e4, "_readableStreamController") && e4 instanceof ReadableStream3);
}
function Ut(e4) {
  return void 0 !== e4._reader;
}
function Gt(e4, r5) {
  if (e4._disturbed = true, "closed" === e4._state) return c(void 0);
  if ("errored" === e4._state) return d(e4._storedError);
  Xt(e4);
  const o3 = e4._reader;
  if (void 0 !== o3 && Fe(o3)) {
    const e5 = o3._readIntoRequests;
    o3._readIntoRequests = new S2(), e5.forEach((e6) => {
      e6._closeSteps(void 0);
    });
  }
  return p(e4._readableStreamController[T](r5), t2);
}
function Xt(e4) {
  e4._state = "closed";
  const t5 = e4._reader;
  if (void 0 !== t5 && (j(t5), K(t5))) {
    const e5 = t5._readRequests;
    t5._readRequests = new S2(), e5.forEach((e6) => {
      e6._closeSteps();
    });
  }
}
function Jt(e4, t5) {
  e4._state = "errored", e4._storedError = t5;
  const r5 = e4._reader;
  void 0 !== r5 && (A2(r5, t5), K(r5) ? Z2(r5, t5) : Ie(r5, t5));
}
function Kt(e4) {
  return new TypeError(`ReadableStream.prototype.${e4} can only be used on a ReadableStream`);
}
function Zt(e4, t5) {
  F2(e4, t5);
  const r5 = null == e4 ? void 0 : e4.highWaterMark;
  return M(r5, "highWaterMark", "QueuingStrategyInit"), { highWaterMark: Y(r5) };
}
function tr(e4) {
  return new TypeError(`ByteLengthQueuingStrategy.prototype.${e4} can only be used on a ByteLengthQueuingStrategy`);
}
function rr(e4) {
  return !!r2(e4) && (!!Object.prototype.hasOwnProperty.call(e4, "_byteLengthQueuingStrategyHighWaterMark") && e4 instanceof ByteLengthQueuingStrategy);
}
function nr(e4) {
  return new TypeError(`CountQueuingStrategy.prototype.${e4} can only be used on a CountQueuingStrategy`);
}
function ar(e4) {
  return !!r2(e4) && (!!Object.prototype.hasOwnProperty.call(e4, "_countQueuingStrategyHighWaterMark") && e4 instanceof CountQueuingStrategy);
}
function ir(e4, t5, r5) {
  return I(e4, r5), (r6) => w(e4, t5, [r6]);
}
function lr(e4, t5, r5) {
  return I(e4, r5), (r6) => g(e4, t5, [r6]);
}
function sr(e4, t5, r5) {
  return I(e4, r5), (r6, o3) => w(e4, t5, [r6, o3]);
}
function ur(e4) {
  return !!r2(e4) && (!!Object.prototype.hasOwnProperty.call(e4, "_transformStreamController") && e4 instanceof TransformStream2);
}
function cr(e4, t5) {
  Sr(e4, t5), dr(e4, t5);
}
function dr(e4, t5) {
  hr(e4._transformStreamController), function(e5, t6) {
    e5._writableController.error(t6);
    "writable" === e5._writableState && Tr(e5, t6);
  }(e4, t5), e4._backpressure && fr(e4, false);
}
function fr(e4, t5) {
  void 0 !== e4._backpressureChangePromise && e4._backpressureChangePromise_resolve(), e4._backpressureChangePromise = u((t6) => {
    e4._backpressureChangePromise_resolve = t6;
  }), e4._backpressure = t5;
}
function br(e4) {
  return !!r2(e4) && (!!Object.prototype.hasOwnProperty.call(e4, "_controlledTransformStream") && e4 instanceof TransformStreamDefaultController);
}
function hr(e4) {
  e4._transformAlgorithm = void 0, e4._flushAlgorithm = void 0;
}
function _r(e4, t5) {
  const r5 = e4._controlledTransformStream;
  if (!gr(r5)) throw new TypeError("Readable side is not in a state that permits enqueue");
  try {
    !function(e5, t6) {
      e5._readablePulling = false;
      try {
        e5._readableController.enqueue(t6);
      } catch (t7) {
        throw Sr(e5, t7), t7;
      }
    }(r5, t5);
  } catch (e5) {
    throw dr(r5, e5), r5._readableStoredError;
  }
  const o3 = function(e5) {
    return !function(e6) {
      if (!gr(e6)) return false;
      if (e6._readablePulling) return true;
      if (vr(e6) > 0) return true;
      return false;
    }(e5);
  }(r5);
  o3 !== r5._backpressure && fr(r5, true);
}
function pr(e4, t5) {
  return p(e4._transformAlgorithm(t5), void 0, (t6) => {
    throw cr(e4._controlledTransformStream, t6), t6;
  });
}
function mr(e4) {
  return new TypeError(`TransformStreamDefaultController.prototype.${e4} can only be used on a TransformStreamDefaultController`);
}
function yr(e4) {
  return new TypeError(`TransformStream.prototype.${e4} can only be used on a TransformStream`);
}
function gr(e4) {
  return !e4._readableCloseRequested && "readable" === e4._readableState;
}
function wr(e4) {
  e4._readableState = "closed", e4._readableCloseRequested = true, e4._readableController.close();
}
function Sr(e4, t5) {
  "readable" === e4._readableState && (e4._readableState = "errored", e4._readableStoredError = t5), e4._readableController.error(t5);
}
function vr(e4) {
  return e4._readableController.desiredSize;
}
function Rr(e4, t5) {
  "writable" !== e4._writableState ? qr(e4) : Tr(e4, t5);
}
function Tr(e4, t5) {
  e4._writableState = "erroring", e4._writableStoredError = t5, !function(e5) {
    return e5._writableHasInFlightOperation;
  }(e4) && e4._writableStarted && qr(e4);
}
function qr(e4) {
  e4._writableState = "errored";
}
function Cr(e4) {
  "erroring" === e4._writableState && qr(e4);
}
var e2, o, a, i2, l, s2, y, S2, v, R, T, q, C, z, L, ReadableStreamDefaultReader, te, re2, ae, ReadableStreamBYOBRequest, ReadableByteStreamController, ReadableStreamBYOBReader, Ue, WritableStream, WritableStreamDefaultWriter, lt, WritableStreamDefaultController, Pt, Wt, ReadableStreamDefaultController, ReadableStream3, er, ByteLengthQueuingStrategy, or, CountQueuingStrategy, TransformStream2, TransformStreamDefaultController;
var init_ponyfill = __esm({
  "node_modules/formdata-node/node_modules/web-streams-polyfill/dist/ponyfill.mjs"() {
    init_esbuild_shims();
    e2 = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? Symbol : (e4) => `Symbol(${e4})`;
    __name(t2, "t");
    __name(r2, "r");
    o = t2;
    __name(n, "n");
    a = Promise;
    i2 = Promise.prototype.then;
    l = Promise.resolve.bind(a);
    s2 = Promise.reject.bind(a);
    __name(u, "u");
    __name(c, "c");
    __name(d, "d");
    __name(f3, "f");
    __name(b, "b");
    __name(h2, "h");
    __name(_, "_");
    __name(p, "p");
    __name(m2, "m");
    y = /* @__PURE__ */ __name((e4) => {
      if ("function" == typeof queueMicrotask) y = queueMicrotask;
      else {
        const e5 = c(void 0);
        y = /* @__PURE__ */ __name((t5) => f3(e5, t5), "y");
      }
      return y(e4);
    }, "y");
    __name(g, "g");
    __name(w, "w");
    S2 = class {
      static {
        __name(this, "S");
      }
      constructor() {
        this._cursor = 0, this._size = 0, this._front = { _elements: [], _next: void 0 }, this._back = this._front, this._cursor = 0, this._size = 0;
      }
      get length() {
        return this._size;
      }
      push(e4) {
        const t5 = this._back;
        let r5 = t5;
        16383 === t5._elements.length && (r5 = { _elements: [], _next: void 0 }), t5._elements.push(e4), r5 !== t5 && (this._back = r5, t5._next = r5), ++this._size;
      }
      shift() {
        const e4 = this._front;
        let t5 = e4;
        const r5 = this._cursor;
        let o3 = r5 + 1;
        const n3 = e4._elements, a2 = n3[r5];
        return 16384 === o3 && (t5 = e4._next, o3 = 0), --this._size, this._cursor = o3, e4 !== t5 && (this._front = t5), n3[r5] = void 0, a2;
      }
      forEach(e4) {
        let t5 = this._cursor, r5 = this._front, o3 = r5._elements;
        for (; !(t5 === o3.length && void 0 === r5._next || t5 === o3.length && (r5 = r5._next, o3 = r5._elements, t5 = 0, 0 === o3.length)); ) e4(o3[t5]), ++t5;
      }
      peek() {
        const e4 = this._front, t5 = this._cursor;
        return e4._elements[t5];
      }
    };
    v = e2("[[AbortSteps]]");
    R = e2("[[ErrorSteps]]");
    T = e2("[[CancelSteps]]");
    q = e2("[[PullSteps]]");
    C = e2("[[ReleaseSteps]]");
    __name(E, "E");
    __name(P, "P");
    __name(W, "W");
    __name(k, "k");
    __name(O, "O");
    __name(B, "B");
    __name(A2, "A");
    __name(j, "j");
    z = Number.isFinite || function(e4) {
      return "number" == typeof e4 && isFinite(e4);
    };
    L = Math.trunc || function(e4) {
      return e4 < 0 ? Math.ceil(e4) : Math.floor(e4);
    };
    __name(F2, "F");
    __name(I, "I");
    __name(D, "D");
    __name($, "$");
    __name(M, "M");
    __name(Y, "Y");
    __name(Q, "Q");
    __name(N, "N");
    __name(H, "H");
    __name(x2, "x");
    __name(V, "V");
    __name(U, "U");
    __name(G, "G");
    __name(X, "X");
    __name(J, "J");
    ReadableStreamDefaultReader = class {
      static {
        __name(this, "ReadableStreamDefaultReader");
      }
      constructor(e4) {
        if ($(e4, 1, "ReadableStreamDefaultReader"), V(e4, "First parameter"), Ut(e4)) throw new TypeError("This stream has already been locked for exclusive reading by another reader");
        E(this, e4), this._readRequests = new S2();
      }
      get closed() {
        return K(this) ? this._closedPromise : d(ee("closed"));
      }
      cancel(e4) {
        return K(this) ? void 0 === this._ownerReadableStream ? d(k("cancel")) : P(this, e4) : d(ee("cancel"));
      }
      read() {
        if (!K(this)) return d(ee("read"));
        if (void 0 === this._ownerReadableStream) return d(k("read from"));
        let e4, t5;
        const r5 = u((r6, o3) => {
          e4 = r6, t5 = o3;
        });
        return function(e5, t6) {
          const r6 = e5._ownerReadableStream;
          r6._disturbed = true, "closed" === r6._state ? t6._closeSteps() : "errored" === r6._state ? t6._errorSteps(r6._storedError) : r6._readableStreamController[q](t6);
        }(this, { _chunkSteps: /* @__PURE__ */ __name((t6) => e4({ value: t6, done: false }), "_chunkSteps"), _closeSteps: /* @__PURE__ */ __name(() => e4({ value: void 0, done: true }), "_closeSteps"), _errorSteps: /* @__PURE__ */ __name((e5) => t5(e5), "_errorSteps") }), r5;
      }
      releaseLock() {
        if (!K(this)) throw ee("releaseLock");
        void 0 !== this._ownerReadableStream && function(e4) {
          W(e4);
          const t5 = new TypeError("Reader was released");
          Z2(e4, t5);
        }(this);
      }
    };
    __name(K, "K");
    __name(Z2, "Z");
    __name(ee, "ee");
    Object.defineProperties(ReadableStreamDefaultReader.prototype, { cancel: { enumerable: true }, read: { enumerable: true }, releaseLock: { enumerable: true }, closed: { enumerable: true } }), n(ReadableStreamDefaultReader.prototype.cancel, "cancel"), n(ReadableStreamDefaultReader.prototype.read, "read"), n(ReadableStreamDefaultReader.prototype.releaseLock, "releaseLock"), "symbol" == typeof e2.toStringTag && Object.defineProperty(ReadableStreamDefaultReader.prototype, e2.toStringTag, { value: "ReadableStreamDefaultReader", configurable: true });
    te = class {
      static {
        __name(this, "te");
      }
      constructor(e4, t5) {
        this._ongoingPromise = void 0, this._isFinished = false, this._reader = e4, this._preventCancel = t5;
      }
      next() {
        const e4 = /* @__PURE__ */ __name(() => this._nextSteps(), "e");
        return this._ongoingPromise = this._ongoingPromise ? p(this._ongoingPromise, e4, e4) : e4(), this._ongoingPromise;
      }
      return(e4) {
        const t5 = /* @__PURE__ */ __name(() => this._returnSteps(e4), "t");
        return this._ongoingPromise ? p(this._ongoingPromise, t5, t5) : t5();
      }
      _nextSteps() {
        if (this._isFinished) return Promise.resolve({ value: void 0, done: true });
        const e4 = this._reader;
        return void 0 === e4 ? d(k("iterate")) : f3(e4.read(), (e5) => {
          var t5;
          return this._ongoingPromise = void 0, e5.done && (this._isFinished = true, null === (t5 = this._reader) || void 0 === t5 || t5.releaseLock(), this._reader = void 0), e5;
        }, (e5) => {
          var t5;
          throw this._ongoingPromise = void 0, this._isFinished = true, null === (t5 = this._reader) || void 0 === t5 || t5.releaseLock(), this._reader = void 0, e5;
        });
      }
      _returnSteps(e4) {
        if (this._isFinished) return Promise.resolve({ value: e4, done: true });
        this._isFinished = true;
        const t5 = this._reader;
        if (void 0 === t5) return d(k("finish iterating"));
        if (this._reader = void 0, !this._preventCancel) {
          const r5 = t5.cancel(e4);
          return t5.releaseLock(), p(r5, () => ({ value: e4, done: true }));
        }
        return t5.releaseLock(), c({ value: e4, done: true });
      }
    };
    re2 = { next() {
      return oe(this) ? this._asyncIteratorImpl.next() : d(ne("next"));
    }, return(e4) {
      return oe(this) ? this._asyncIteratorImpl.return(e4) : d(ne("return"));
    } };
    __name(oe, "oe");
    __name(ne, "ne");
    "symbol" == typeof e2.asyncIterator && Object.defineProperty(re2, e2.asyncIterator, { value() {
      return this;
    }, writable: true, configurable: true });
    ae = Number.isNaN || function(e4) {
      return e4 != e4;
    };
    __name(ie, "ie");
    __name(le, "le");
    __name(se, "se");
    __name(ue, "ue");
    __name(ce, "ce");
    ReadableStreamBYOBRequest = class {
      static {
        __name(this, "ReadableStreamBYOBRequest");
      }
      constructor() {
        throw new TypeError("Illegal constructor");
      }
      get view() {
        if (!fe(this)) throw Be("view");
        return this._view;
      }
      respond(e4) {
        if (!fe(this)) throw Be("respond");
        if ($(e4, 1, "respond"), e4 = N(e4, "First parameter"), void 0 === this._associatedReadableByteStreamController) throw new TypeError("This BYOB request has been invalidated");
        this._view.buffer, function(e5, t5) {
          const r5 = e5._pendingPullIntos.peek();
          if ("closed" === e5._controlledReadableByteStream._state) {
            if (0 !== t5) throw new TypeError("bytesWritten must be 0 when calling respond() on a closed stream");
          } else {
            if (0 === t5) throw new TypeError("bytesWritten must be greater than 0 when calling respond() on a readable stream");
            if (r5.bytesFilled + t5 > r5.byteLength) throw new RangeError("bytesWritten out of range");
          }
          r5.buffer = r5.buffer, qe(e5, t5);
        }(this._associatedReadableByteStreamController, e4);
      }
      respondWithNewView(e4) {
        if (!fe(this)) throw Be("respondWithNewView");
        if ($(e4, 1, "respondWithNewView"), !ArrayBuffer.isView(e4)) throw new TypeError("You can only respond with array buffer views");
        if (void 0 === this._associatedReadableByteStreamController) throw new TypeError("This BYOB request has been invalidated");
        e4.buffer, function(e5, t5) {
          const r5 = e5._pendingPullIntos.peek();
          if ("closed" === e5._controlledReadableByteStream._state) {
            if (0 !== t5.byteLength) throw new TypeError("The view's length must be 0 when calling respondWithNewView() on a closed stream");
          } else if (0 === t5.byteLength) throw new TypeError("The view's length must be greater than 0 when calling respondWithNewView() on a readable stream");
          if (r5.byteOffset + r5.bytesFilled !== t5.byteOffset) throw new RangeError("The region specified by view does not match byobRequest");
          if (r5.bufferByteLength !== t5.buffer.byteLength) throw new RangeError("The buffer of view has different capacity than byobRequest");
          if (r5.bytesFilled + t5.byteLength > r5.byteLength) throw new RangeError("The region specified by view is larger than byobRequest");
          const o3 = t5.byteLength;
          r5.buffer = t5.buffer, qe(e5, o3);
        }(this._associatedReadableByteStreamController, e4);
      }
    };
    Object.defineProperties(ReadableStreamBYOBRequest.prototype, { respond: { enumerable: true }, respondWithNewView: { enumerable: true }, view: { enumerable: true } }), n(ReadableStreamBYOBRequest.prototype.respond, "respond"), n(ReadableStreamBYOBRequest.prototype.respondWithNewView, "respondWithNewView"), "symbol" == typeof e2.toStringTag && Object.defineProperty(ReadableStreamBYOBRequest.prototype, e2.toStringTag, { value: "ReadableStreamBYOBRequest", configurable: true });
    ReadableByteStreamController = class {
      static {
        __name(this, "ReadableByteStreamController");
      }
      constructor() {
        throw new TypeError("Illegal constructor");
      }
      get byobRequest() {
        if (!de(this)) throw Ae("byobRequest");
        return function(e4) {
          if (null === e4._byobRequest && e4._pendingPullIntos.length > 0) {
            const t5 = e4._pendingPullIntos.peek(), r5 = new Uint8Array(t5.buffer, t5.byteOffset + t5.bytesFilled, t5.byteLength - t5.bytesFilled), o3 = Object.create(ReadableStreamBYOBRequest.prototype);
            !function(e5, t6, r6) {
              e5._associatedReadableByteStreamController = t6, e5._view = r6;
            }(o3, e4, r5), e4._byobRequest = o3;
          }
          return e4._byobRequest;
        }(this);
      }
      get desiredSize() {
        if (!de(this)) throw Ae("desiredSize");
        return ke(this);
      }
      close() {
        if (!de(this)) throw Ae("close");
        if (this._closeRequested) throw new TypeError("The stream has already been closed; do not close it again!");
        const e4 = this._controlledReadableByteStream._state;
        if ("readable" !== e4) throw new TypeError(`The stream (in ${e4} state) is not in the readable state and cannot be closed`);
        !function(e5) {
          const t5 = e5._controlledReadableByteStream;
          if (e5._closeRequested || "readable" !== t5._state) return;
          if (e5._queueTotalSize > 0) return void (e5._closeRequested = true);
          if (e5._pendingPullIntos.length > 0) {
            if (e5._pendingPullIntos.peek().bytesFilled > 0) {
              const t6 = new TypeError("Insufficient bytes to fill elements in the given buffer");
              throw Pe(e5, t6), t6;
            }
          }
          Ee(e5), Xt(t5);
        }(this);
      }
      enqueue(e4) {
        if (!de(this)) throw Ae("enqueue");
        if ($(e4, 1, "enqueue"), !ArrayBuffer.isView(e4)) throw new TypeError("chunk must be an array buffer view");
        if (0 === e4.byteLength) throw new TypeError("chunk must have non-zero byteLength");
        if (0 === e4.buffer.byteLength) throw new TypeError("chunk's buffer must have non-zero byteLength");
        if (this._closeRequested) throw new TypeError("stream is closed or draining");
        const t5 = this._controlledReadableByteStream._state;
        if ("readable" !== t5) throw new TypeError(`The stream (in ${t5} state) is not in the readable state and cannot be enqueued to`);
        !function(e5, t6) {
          const r5 = e5._controlledReadableByteStream;
          if (e5._closeRequested || "readable" !== r5._state) return;
          const o3 = t6.buffer, n3 = t6.byteOffset, a2 = t6.byteLength, i3 = o3;
          if (e5._pendingPullIntos.length > 0) {
            const t7 = e5._pendingPullIntos.peek();
            t7.buffer, 0, Re(e5), t7.buffer = t7.buffer, "none" === t7.readerType && ge(e5, t7);
          }
          if (J(r5)) if (function(e6) {
            const t7 = e6._controlledReadableByteStream._reader;
            for (; t7._readRequests.length > 0; ) {
              if (0 === e6._queueTotalSize) return;
              We(e6, t7._readRequests.shift());
            }
          }(e5), 0 === X(r5)) me(e5, i3, n3, a2);
          else {
            e5._pendingPullIntos.length > 0 && Ce(e5);
            G(r5, new Uint8Array(i3, n3, a2), false);
          }
          else Le(r5) ? (me(e5, i3, n3, a2), Te(e5)) : me(e5, i3, n3, a2);
          be(e5);
        }(this, e4);
      }
      error(e4) {
        if (!de(this)) throw Ae("error");
        Pe(this, e4);
      }
      [T](e4) {
        he(this), ce(this);
        const t5 = this._cancelAlgorithm(e4);
        return Ee(this), t5;
      }
      [q](e4) {
        const t5 = this._controlledReadableByteStream;
        if (this._queueTotalSize > 0) return void We(this, e4);
        const r5 = this._autoAllocateChunkSize;
        if (void 0 !== r5) {
          let t6;
          try {
            t6 = new ArrayBuffer(r5);
          } catch (t7) {
            return void e4._errorSteps(t7);
          }
          const o3 = { buffer: t6, bufferByteLength: r5, byteOffset: 0, byteLength: r5, bytesFilled: 0, elementSize: 1, viewConstructor: Uint8Array, readerType: "default" };
          this._pendingPullIntos.push(o3);
        }
        U(t5, e4), be(this);
      }
      [C]() {
        if (this._pendingPullIntos.length > 0) {
          const e4 = this._pendingPullIntos.peek();
          e4.readerType = "none", this._pendingPullIntos = new S2(), this._pendingPullIntos.push(e4);
        }
      }
    };
    __name(de, "de");
    __name(fe, "fe");
    __name(be, "be");
    __name(he, "he");
    __name(_e, "_e");
    __name(pe, "pe");
    __name(me, "me");
    __name(ye, "ye");
    __name(ge, "ge");
    __name(we, "we");
    __name(Se, "Se");
    __name(ve, "ve");
    __name(Re, "Re");
    __name(Te, "Te");
    __name(qe, "qe");
    __name(Ce, "Ce");
    __name(Ee, "Ee");
    __name(Pe, "Pe");
    __name(We, "We");
    __name(ke, "ke");
    __name(Oe, "Oe");
    __name(Be, "Be");
    __name(Ae, "Ae");
    __name(je, "je");
    __name(ze, "ze");
    __name(Le, "Le");
    Object.defineProperties(ReadableByteStreamController.prototype, { close: { enumerable: true }, enqueue: { enumerable: true }, error: { enumerable: true }, byobRequest: { enumerable: true }, desiredSize: { enumerable: true } }), n(ReadableByteStreamController.prototype.close, "close"), n(ReadableByteStreamController.prototype.enqueue, "enqueue"), n(ReadableByteStreamController.prototype.error, "error"), "symbol" == typeof e2.toStringTag && Object.defineProperty(ReadableByteStreamController.prototype, e2.toStringTag, { value: "ReadableByteStreamController", configurable: true });
    ReadableStreamBYOBReader = class {
      static {
        __name(this, "ReadableStreamBYOBReader");
      }
      constructor(e4) {
        if ($(e4, 1, "ReadableStreamBYOBReader"), V(e4, "First parameter"), Ut(e4)) throw new TypeError("This stream has already been locked for exclusive reading by another reader");
        if (!de(e4._readableStreamController)) throw new TypeError("Cannot construct a ReadableStreamBYOBReader for a stream not constructed with a byte source");
        E(this, e4), this._readIntoRequests = new S2();
      }
      get closed() {
        return Fe(this) ? this._closedPromise : d(De("closed"));
      }
      cancel(e4) {
        return Fe(this) ? void 0 === this._ownerReadableStream ? d(k("cancel")) : P(this, e4) : d(De("cancel"));
      }
      read(e4) {
        if (!Fe(this)) return d(De("read"));
        if (!ArrayBuffer.isView(e4)) return d(new TypeError("view must be an array buffer view"));
        if (0 === e4.byteLength) return d(new TypeError("view must have non-zero byteLength"));
        if (0 === e4.buffer.byteLength) return d(new TypeError("view's buffer must have non-zero byteLength"));
        if (e4.buffer, void 0 === this._ownerReadableStream) return d(k("read from"));
        let t5, r5;
        const o3 = u((e5, o4) => {
          t5 = e5, r5 = o4;
        });
        return function(e5, t6, r6) {
          const o4 = e5._ownerReadableStream;
          o4._disturbed = true, "errored" === o4._state ? r6._errorSteps(o4._storedError) : function(e6, t7, r7) {
            const o5 = e6._controlledReadableByteStream;
            let n3 = 1;
            t7.constructor !== DataView && (n3 = t7.constructor.BYTES_PER_ELEMENT);
            const a2 = t7.constructor, i3 = t7.buffer, l3 = { buffer: i3, bufferByteLength: i3.byteLength, byteOffset: t7.byteOffset, byteLength: t7.byteLength, bytesFilled: 0, elementSize: n3, viewConstructor: a2, readerType: "byob" };
            if (e6._pendingPullIntos.length > 0) return e6._pendingPullIntos.push(l3), void je(o5, r7);
            if ("closed" !== o5._state) {
              if (e6._queueTotalSize > 0) {
                if (we(e6, l3)) {
                  const t8 = pe(l3);
                  return ve(e6), void r7._chunkSteps(t8);
                }
                if (e6._closeRequested) {
                  const t8 = new TypeError("Insufficient bytes to fill elements in the given buffer");
                  return Pe(e6, t8), void r7._errorSteps(t8);
                }
              }
              e6._pendingPullIntos.push(l3), je(o5, r7), be(e6);
            } else {
              const e7 = new a2(l3.buffer, l3.byteOffset, 0);
              r7._closeSteps(e7);
            }
          }(o4._readableStreamController, t6, r6);
        }(this, e4, { _chunkSteps: /* @__PURE__ */ __name((e5) => t5({ value: e5, done: false }), "_chunkSteps"), _closeSteps: /* @__PURE__ */ __name((e5) => t5({ value: e5, done: true }), "_closeSteps"), _errorSteps: /* @__PURE__ */ __name((e5) => r5(e5), "_errorSteps") }), o3;
      }
      releaseLock() {
        if (!Fe(this)) throw De("releaseLock");
        void 0 !== this._ownerReadableStream && function(e4) {
          W(e4);
          const t5 = new TypeError("Reader was released");
          Ie(e4, t5);
        }(this);
      }
    };
    __name(Fe, "Fe");
    __name(Ie, "Ie");
    __name(De, "De");
    __name($e, "$e");
    __name(Me, "Me");
    __name(Ye, "Ye");
    __name(Qe, "Qe");
    __name(Ne, "Ne");
    __name(He, "He");
    __name(xe, "xe");
    __name(Ve, "Ve");
    Object.defineProperties(ReadableStreamBYOBReader.prototype, { cancel: { enumerable: true }, read: { enumerable: true }, releaseLock: { enumerable: true }, closed: { enumerable: true } }), n(ReadableStreamBYOBReader.prototype.cancel, "cancel"), n(ReadableStreamBYOBReader.prototype.read, "read"), n(ReadableStreamBYOBReader.prototype.releaseLock, "releaseLock"), "symbol" == typeof e2.toStringTag && Object.defineProperty(ReadableStreamBYOBReader.prototype, e2.toStringTag, { value: "ReadableStreamBYOBReader", configurable: true });
    Ue = "function" == typeof AbortController;
    WritableStream = class {
      static {
        __name(this, "WritableStream");
      }
      constructor(e4 = {}, t5 = {}) {
        void 0 === e4 ? e4 = null : D(e4, "First parameter");
        const r5 = Ye(t5, "Second parameter"), o3 = function(e5, t6) {
          F2(e5, t6);
          const r6 = null == e5 ? void 0 : e5.abort, o4 = null == e5 ? void 0 : e5.close, n4 = null == e5 ? void 0 : e5.start, a3 = null == e5 ? void 0 : e5.type, i3 = null == e5 ? void 0 : e5.write;
          return { abort: void 0 === r6 ? void 0 : Ne(r6, e5, `${t6} has member 'abort' that`), close: void 0 === o4 ? void 0 : He(o4, e5, `${t6} has member 'close' that`), start: void 0 === n4 ? void 0 : xe(n4, e5, `${t6} has member 'start' that`), write: void 0 === i3 ? void 0 : Ve(i3, e5, `${t6} has member 'write' that`), type: a3 };
        }(e4, "First parameter");
        var n3;
        (n3 = this)._state = "writable", n3._storedError = void 0, n3._writer = void 0, n3._writableStreamController = void 0, n3._writeRequests = new S2(), n3._inFlightWriteRequest = void 0, n3._closeRequest = void 0, n3._inFlightCloseRequest = void 0, n3._pendingAbortRequest = void 0, n3._backpressure = false;
        if (void 0 !== o3.type) throw new RangeError("Invalid type is specified");
        const a2 = Me(r5);
        !function(e5, t6, r6, o4) {
          const n4 = Object.create(WritableStreamDefaultController.prototype);
          let a3, i3, l3, s5;
          a3 = void 0 !== t6.start ? () => t6.start(n4) : () => {
          };
          i3 = void 0 !== t6.write ? (e6) => t6.write(e6, n4) : () => c(void 0);
          l3 = void 0 !== t6.close ? () => t6.close() : () => c(void 0);
          s5 = void 0 !== t6.abort ? (e6) => t6.abort(e6) : () => c(void 0);
          !function(e6, t7, r7, o5, n5, a4, i4, l4) {
            t7._controlledWritableStream = e6, e6._writableStreamController = t7, t7._queue = void 0, t7._queueTotalSize = void 0, ce(t7), t7._abortReason = void 0, t7._abortController = function() {
              if (Ue) return new AbortController();
            }(), t7._started = false, t7._strategySizeAlgorithm = l4, t7._strategyHWM = i4, t7._writeAlgorithm = o5, t7._closeAlgorithm = n5, t7._abortAlgorithm = a4;
            const s6 = bt(t7);
            nt(e6, s6);
            const u2 = r7();
            b(c(u2), () => (t7._started = true, dt(t7), null), (r8) => (t7._started = true, Ze(e6, r8), null));
          }(e5, n4, a3, i3, l3, s5, r6, o4);
        }(this, o3, $e(r5, 1), a2);
      }
      get locked() {
        if (!Ge(this)) throw _t("locked");
        return Xe(this);
      }
      abort(e4) {
        return Ge(this) ? Xe(this) ? d(new TypeError("Cannot abort a stream that already has a writer")) : Je(this, e4) : d(_t("abort"));
      }
      close() {
        return Ge(this) ? Xe(this) ? d(new TypeError("Cannot close a stream that already has a writer")) : rt(this) ? d(new TypeError("Cannot close an already-closing stream")) : Ke(this) : d(_t("close"));
      }
      getWriter() {
        if (!Ge(this)) throw _t("getWriter");
        return new WritableStreamDefaultWriter(this);
      }
    };
    __name(Ge, "Ge");
    __name(Xe, "Xe");
    __name(Je, "Je");
    __name(Ke, "Ke");
    __name(Ze, "Ze");
    __name(et, "et");
    __name(tt, "tt");
    __name(rt, "rt");
    __name(ot, "ot");
    __name(nt, "nt");
    Object.defineProperties(WritableStream.prototype, { abort: { enumerable: true }, close: { enumerable: true }, getWriter: { enumerable: true }, locked: { enumerable: true } }), n(WritableStream.prototype.abort, "abort"), n(WritableStream.prototype.close, "close"), n(WritableStream.prototype.getWriter, "getWriter"), "symbol" == typeof e2.toStringTag && Object.defineProperty(WritableStream.prototype, e2.toStringTag, { value: "WritableStream", configurable: true });
    WritableStreamDefaultWriter = class {
      static {
        __name(this, "WritableStreamDefaultWriter");
      }
      constructor(e4) {
        if ($(e4, 1, "WritableStreamDefaultWriter"), function(e5, t6) {
          if (!Ge(e5)) throw new TypeError(`${t6} is not a WritableStream.`);
        }(e4, "First parameter"), Xe(e4)) throw new TypeError("This stream has already been locked for exclusive writing by another writer");
        this._ownerWritableStream = e4, e4._writer = this;
        const t5 = e4._state;
        if ("writable" === t5) !rt(e4) && e4._backpressure ? Rt(this) : qt(this), gt(this);
        else if ("erroring" === t5) Tt(this, e4._storedError), gt(this);
        else if ("closed" === t5) qt(this), gt(r5 = this), vt(r5);
        else {
          const t6 = e4._storedError;
          Tt(this, t6), wt(this, t6);
        }
        var r5;
      }
      get closed() {
        return at(this) ? this._closedPromise : d(mt("closed"));
      }
      get desiredSize() {
        if (!at(this)) throw mt("desiredSize");
        if (void 0 === this._ownerWritableStream) throw yt("desiredSize");
        return function(e4) {
          const t5 = e4._ownerWritableStream, r5 = t5._state;
          if ("errored" === r5 || "erroring" === r5) return null;
          if ("closed" === r5) return 0;
          return ct(t5._writableStreamController);
        }(this);
      }
      get ready() {
        return at(this) ? this._readyPromise : d(mt("ready"));
      }
      abort(e4) {
        return at(this) ? void 0 === this._ownerWritableStream ? d(yt("abort")) : function(e5, t5) {
          return Je(e5._ownerWritableStream, t5);
        }(this, e4) : d(mt("abort"));
      }
      close() {
        if (!at(this)) return d(mt("close"));
        const e4 = this._ownerWritableStream;
        return void 0 === e4 ? d(yt("close")) : rt(e4) ? d(new TypeError("Cannot close an already-closing stream")) : Ke(this._ownerWritableStream);
      }
      releaseLock() {
        if (!at(this)) throw mt("releaseLock");
        void 0 !== this._ownerWritableStream && function(e4) {
          const t5 = e4._ownerWritableStream, r5 = new TypeError("Writer was released and can no longer be used to monitor the stream's closedness");
          it(e4, r5), function(e5, t6) {
            "pending" === e5._closedPromiseState ? St(e5, t6) : function(e6, t7) {
              wt(e6, t7);
            }(e5, t6);
          }(e4, r5), t5._writer = void 0, e4._ownerWritableStream = void 0;
        }(this);
      }
      write(e4) {
        return at(this) ? void 0 === this._ownerWritableStream ? d(yt("write to")) : function(e5, t5) {
          const r5 = e5._ownerWritableStream, o3 = r5._writableStreamController, n3 = function(e6, t6) {
            try {
              return e6._strategySizeAlgorithm(t6);
            } catch (t7) {
              return ft(e6, t7), 1;
            }
          }(o3, t5);
          if (r5 !== e5._ownerWritableStream) return d(yt("write to"));
          const a2 = r5._state;
          if ("errored" === a2) return d(r5._storedError);
          if (rt(r5) || "closed" === a2) return d(new TypeError("The stream is closing or closed and cannot be written to"));
          if ("erroring" === a2) return d(r5._storedError);
          const i3 = function(e6) {
            return u((t6, r6) => {
              const o4 = { _resolve: t6, _reject: r6 };
              e6._writeRequests.push(o4);
            });
          }(r5);
          return function(e6, t6, r6) {
            try {
              ue(e6, t6, r6);
            } catch (t7) {
              return void ft(e6, t7);
            }
            const o4 = e6._controlledWritableStream;
            if (!rt(o4) && "writable" === o4._state) {
              nt(o4, bt(e6));
            }
            dt(e6);
          }(o3, t5, n3), i3;
        }(this, e4) : d(mt("write"));
      }
    };
    __name(at, "at");
    __name(it, "it");
    Object.defineProperties(WritableStreamDefaultWriter.prototype, { abort: { enumerable: true }, close: { enumerable: true }, releaseLock: { enumerable: true }, write: { enumerable: true }, closed: { enumerable: true }, desiredSize: { enumerable: true }, ready: { enumerable: true } }), n(WritableStreamDefaultWriter.prototype.abort, "abort"), n(WritableStreamDefaultWriter.prototype.close, "close"), n(WritableStreamDefaultWriter.prototype.releaseLock, "releaseLock"), n(WritableStreamDefaultWriter.prototype.write, "write"), "symbol" == typeof e2.toStringTag && Object.defineProperty(WritableStreamDefaultWriter.prototype, e2.toStringTag, { value: "WritableStreamDefaultWriter", configurable: true });
    lt = {};
    WritableStreamDefaultController = class {
      static {
        __name(this, "WritableStreamDefaultController");
      }
      constructor() {
        throw new TypeError("Illegal constructor");
      }
      get abortReason() {
        if (!st(this)) throw pt("abortReason");
        return this._abortReason;
      }
      get signal() {
        if (!st(this)) throw pt("signal");
        if (void 0 === this._abortController) throw new TypeError("WritableStreamDefaultController.prototype.signal is not supported");
        return this._abortController.signal;
      }
      error(e4) {
        if (!st(this)) throw pt("error");
        "writable" === this._controlledWritableStream._state && ht(this, e4);
      }
      [v](e4) {
        const t5 = this._abortAlgorithm(e4);
        return ut(this), t5;
      }
      [R]() {
        ce(this);
      }
    };
    __name(st, "st");
    __name(ut, "ut");
    __name(ct, "ct");
    __name(dt, "dt");
    __name(ft, "ft");
    __name(bt, "bt");
    __name(ht, "ht");
    __name(_t, "_t");
    __name(pt, "pt");
    __name(mt, "mt");
    __name(yt, "yt");
    __name(gt, "gt");
    __name(wt, "wt");
    __name(St, "St");
    __name(vt, "vt");
    __name(Rt, "Rt");
    __name(Tt, "Tt");
    __name(qt, "qt");
    __name(Ct, "Ct");
    __name(Et, "Et");
    Object.defineProperties(WritableStreamDefaultController.prototype, { abortReason: { enumerable: true }, signal: { enumerable: true }, error: { enumerable: true } }), "symbol" == typeof e2.toStringTag && Object.defineProperty(WritableStreamDefaultController.prototype, e2.toStringTag, { value: "WritableStreamDefaultController", configurable: true });
    Pt = "undefined" != typeof DOMException ? DOMException : void 0;
    Wt = function(e4) {
      if ("function" != typeof e4 && "object" != typeof e4) return false;
      try {
        return new e4(), true;
      } catch (e5) {
        return false;
      }
    }(Pt) ? Pt : function() {
      const e4 = /* @__PURE__ */ __name(function(e5, t5) {
        this.message = e5 || "", this.name = t5 || "Error", Error.captureStackTrace && Error.captureStackTrace(this, this.constructor);
      }, "e");
      return e4.prototype = Object.create(Error.prototype), Object.defineProperty(e4.prototype, "constructor", { value: e4, writable: true, configurable: true }), e4;
    }();
    __name(kt, "kt");
    __name(Ot, "Ot");
    ReadableStreamDefaultController = class {
      static {
        __name(this, "ReadableStreamDefaultController");
      }
      constructor() {
        throw new TypeError("Illegal constructor");
      }
      get desiredSize() {
        if (!Bt(this)) throw Dt("desiredSize");
        return Lt(this);
      }
      close() {
        if (!Bt(this)) throw Dt("close");
        if (!Ft(this)) throw new TypeError("The stream is not in a state that permits close");
        !function(e4) {
          if (!Ft(e4)) return;
          const t5 = e4._controlledReadableStream;
          e4._closeRequested = true, 0 === e4._queue.length && (jt(e4), Xt(t5));
        }(this);
      }
      enqueue(e4) {
        if (!Bt(this)) throw Dt("enqueue");
        if (!Ft(this)) throw new TypeError("The stream is not in a state that permits enqueue");
        return function(e5, t5) {
          if (!Ft(e5)) return;
          const r5 = e5._controlledReadableStream;
          if (Ut(r5) && X(r5) > 0) G(r5, t5, false);
          else {
            let r6;
            try {
              r6 = e5._strategySizeAlgorithm(t5);
            } catch (t6) {
              throw zt(e5, t6), t6;
            }
            try {
              ue(e5, t5, r6);
            } catch (t6) {
              throw zt(e5, t6), t6;
            }
          }
          At(e5);
        }(this, e4);
      }
      error(e4) {
        if (!Bt(this)) throw Dt("error");
        zt(this, e4);
      }
      [T](e4) {
        ce(this);
        const t5 = this._cancelAlgorithm(e4);
        return jt(this), t5;
      }
      [q](e4) {
        const t5 = this._controlledReadableStream;
        if (this._queue.length > 0) {
          const r5 = se(this);
          this._closeRequested && 0 === this._queue.length ? (jt(this), Xt(t5)) : At(this), e4._chunkSteps(r5);
        } else U(t5, e4), At(this);
      }
      [C]() {
      }
    };
    __name(Bt, "Bt");
    __name(At, "At");
    __name(jt, "jt");
    __name(zt, "zt");
    __name(Lt, "Lt");
    __name(Ft, "Ft");
    __name(It, "It");
    __name(Dt, "Dt");
    __name($t, "$t");
    __name(Mt, "Mt");
    __name(Yt, "Yt");
    __name(Qt, "Qt");
    __name(Nt, "Nt");
    __name(Ht, "Ht");
    __name(xt, "xt");
    Object.defineProperties(ReadableStreamDefaultController.prototype, { close: { enumerable: true }, enqueue: { enumerable: true }, error: { enumerable: true }, desiredSize: { enumerable: true } }), n(ReadableStreamDefaultController.prototype.close, "close"), n(ReadableStreamDefaultController.prototype.enqueue, "enqueue"), n(ReadableStreamDefaultController.prototype.error, "error"), "symbol" == typeof e2.toStringTag && Object.defineProperty(ReadableStreamDefaultController.prototype, e2.toStringTag, { value: "ReadableStreamDefaultController", configurable: true });
    ReadableStream3 = class {
      static {
        __name(this, "ReadableStream");
      }
      constructor(e4 = {}, t5 = {}) {
        void 0 === e4 ? e4 = null : D(e4, "First parameter");
        const r5 = Ye(t5, "Second parameter"), o3 = function(e5, t6) {
          F2(e5, t6);
          const r6 = e5, o4 = null == r6 ? void 0 : r6.autoAllocateChunkSize, n4 = null == r6 ? void 0 : r6.cancel, a2 = null == r6 ? void 0 : r6.pull, i3 = null == r6 ? void 0 : r6.start, l3 = null == r6 ? void 0 : r6.type;
          return { autoAllocateChunkSize: void 0 === o4 ? void 0 : N(o4, `${t6} has member 'autoAllocateChunkSize' that`), cancel: void 0 === n4 ? void 0 : $t(n4, r6, `${t6} has member 'cancel' that`), pull: void 0 === a2 ? void 0 : Mt(a2, r6, `${t6} has member 'pull' that`), start: void 0 === i3 ? void 0 : Yt(i3, r6, `${t6} has member 'start' that`), type: void 0 === l3 ? void 0 : Qt(l3, `${t6} has member 'type' that`) };
        }(e4, "First parameter");
        var n3;
        if ((n3 = this)._state = "readable", n3._reader = void 0, n3._storedError = void 0, n3._disturbed = false, "bytes" === o3.type) {
          if (void 0 !== r5.size) throw new RangeError("The strategy for a byte stream cannot have a size function");
          Oe(this, o3, $e(r5, 0));
        } else {
          const e5 = Me(r5);
          It(this, o3, $e(r5, 1), e5);
        }
      }
      get locked() {
        if (!Vt(this)) throw Kt("locked");
        return Ut(this);
      }
      cancel(e4) {
        return Vt(this) ? Ut(this) ? d(new TypeError("Cannot cancel a stream that already has a reader")) : Gt(this, e4) : d(Kt("cancel"));
      }
      getReader(e4) {
        if (!Vt(this)) throw Kt("getReader");
        return void 0 === function(e5, t5) {
          F2(e5, t5);
          const r5 = null == e5 ? void 0 : e5.mode;
          return { mode: void 0 === r5 ? void 0 : Nt(r5, `${t5} has member 'mode' that`) };
        }(e4, "First parameter").mode ? new ReadableStreamDefaultReader(this) : function(e5) {
          return new ReadableStreamBYOBReader(e5);
        }(this);
      }
      pipeThrough(e4, t5 = {}) {
        if (!H(this)) throw Kt("pipeThrough");
        $(e4, 1, "pipeThrough");
        const r5 = xt(e4, "First parameter"), o3 = Ht(t5, "Second parameter");
        if (this.locked) throw new TypeError("ReadableStream.prototype.pipeThrough cannot be used on a locked ReadableStream");
        if (r5.writable.locked) throw new TypeError("ReadableStream.prototype.pipeThrough cannot be used on a locked WritableStream");
        return m2(kt(this, r5.writable, o3.preventClose, o3.preventAbort, o3.preventCancel, o3.signal)), r5.readable;
      }
      pipeTo(e4, t5 = {}) {
        if (!H(this)) return d(Kt("pipeTo"));
        if (void 0 === e4) return d("Parameter 1 is required in 'pipeTo'.");
        if (!x2(e4)) return d(new TypeError("ReadableStream.prototype.pipeTo's first argument must be a WritableStream"));
        let r5;
        try {
          r5 = Ht(t5, "Second parameter");
        } catch (e5) {
          return d(e5);
        }
        return this.locked ? d(new TypeError("ReadableStream.prototype.pipeTo cannot be used on a locked ReadableStream")) : e4.locked ? d(new TypeError("ReadableStream.prototype.pipeTo cannot be used on a locked WritableStream")) : kt(this, e4, r5.preventClose, r5.preventAbort, r5.preventCancel, r5.signal);
      }
      tee() {
        if (!H(this)) throw Kt("tee");
        if (this.locked) throw new TypeError("Cannot tee a stream that already has a reader");
        return Ot(this);
      }
      values(e4) {
        if (!H(this)) throw Kt("values");
        return function(e5, t5) {
          const r5 = e5.getReader(), o3 = new te(r5, t5), n3 = Object.create(re2);
          return n3._asyncIteratorImpl = o3, n3;
        }(this, function(e5, t5) {
          F2(e5, t5);
          const r5 = null == e5 ? void 0 : e5.preventCancel;
          return { preventCancel: Boolean(r5) };
        }(e4, "First parameter").preventCancel);
      }
    };
    __name(Vt, "Vt");
    __name(Ut, "Ut");
    __name(Gt, "Gt");
    __name(Xt, "Xt");
    __name(Jt, "Jt");
    __name(Kt, "Kt");
    __name(Zt, "Zt");
    Object.defineProperties(ReadableStream3.prototype, { cancel: { enumerable: true }, getReader: { enumerable: true }, pipeThrough: { enumerable: true }, pipeTo: { enumerable: true }, tee: { enumerable: true }, values: { enumerable: true }, locked: { enumerable: true } }), n(ReadableStream3.prototype.cancel, "cancel"), n(ReadableStream3.prototype.getReader, "getReader"), n(ReadableStream3.prototype.pipeThrough, "pipeThrough"), n(ReadableStream3.prototype.pipeTo, "pipeTo"), n(ReadableStream3.prototype.tee, "tee"), n(ReadableStream3.prototype.values, "values"), "symbol" == typeof e2.toStringTag && Object.defineProperty(ReadableStream3.prototype, e2.toStringTag, { value: "ReadableStream", configurable: true }), "symbol" == typeof e2.asyncIterator && Object.defineProperty(ReadableStream3.prototype, e2.asyncIterator, { value: ReadableStream3.prototype.values, writable: true, configurable: true });
    er = /* @__PURE__ */ __name((e4) => e4.byteLength, "er");
    n(er, "size");
    ByteLengthQueuingStrategy = class {
      static {
        __name(this, "ByteLengthQueuingStrategy");
      }
      constructor(e4) {
        $(e4, 1, "ByteLengthQueuingStrategy"), e4 = Zt(e4, "First parameter"), this._byteLengthQueuingStrategyHighWaterMark = e4.highWaterMark;
      }
      get highWaterMark() {
        if (!rr(this)) throw tr("highWaterMark");
        return this._byteLengthQueuingStrategyHighWaterMark;
      }
      get size() {
        if (!rr(this)) throw tr("size");
        return er;
      }
    };
    __name(tr, "tr");
    __name(rr, "rr");
    Object.defineProperties(ByteLengthQueuingStrategy.prototype, { highWaterMark: { enumerable: true }, size: { enumerable: true } }), "symbol" == typeof e2.toStringTag && Object.defineProperty(ByteLengthQueuingStrategy.prototype, e2.toStringTag, { value: "ByteLengthQueuingStrategy", configurable: true });
    or = /* @__PURE__ */ __name(() => 1, "or");
    n(or, "size");
    CountQueuingStrategy = class {
      static {
        __name(this, "CountQueuingStrategy");
      }
      constructor(e4) {
        $(e4, 1, "CountQueuingStrategy"), e4 = Zt(e4, "First parameter"), this._countQueuingStrategyHighWaterMark = e4.highWaterMark;
      }
      get highWaterMark() {
        if (!ar(this)) throw nr("highWaterMark");
        return this._countQueuingStrategyHighWaterMark;
      }
      get size() {
        if (!ar(this)) throw nr("size");
        return or;
      }
    };
    __name(nr, "nr");
    __name(ar, "ar");
    __name(ir, "ir");
    __name(lr, "lr");
    __name(sr, "sr");
    Object.defineProperties(CountQueuingStrategy.prototype, { highWaterMark: { enumerable: true }, size: { enumerable: true } }), "symbol" == typeof e2.toStringTag && Object.defineProperty(CountQueuingStrategy.prototype, e2.toStringTag, { value: "CountQueuingStrategy", configurable: true });
    TransformStream2 = class {
      static {
        __name(this, "TransformStream");
      }
      constructor(e4 = {}, t5 = {}, r5 = {}) {
        void 0 === e4 && (e4 = null);
        const o3 = Ye(t5, "Second parameter"), n3 = Ye(r5, "Third parameter"), a2 = function(e5, t6) {
          F2(e5, t6);
          const r6 = null == e5 ? void 0 : e5.flush, o4 = null == e5 ? void 0 : e5.readableType, n4 = null == e5 ? void 0 : e5.start, a3 = null == e5 ? void 0 : e5.transform, i4 = null == e5 ? void 0 : e5.writableType;
          return { flush: void 0 === r6 ? void 0 : ir(r6, e5, `${t6} has member 'flush' that`), readableType: o4, start: void 0 === n4 ? void 0 : lr(n4, e5, `${t6} has member 'start' that`), transform: void 0 === a3 ? void 0 : sr(a3, e5, `${t6} has member 'transform' that`), writableType: i4 };
        }(e4, "First parameter");
        if (void 0 !== a2.readableType) throw new RangeError("Invalid readableType specified");
        if (void 0 !== a2.writableType) throw new RangeError("Invalid writableType specified");
        const i3 = $e(n3, 0), l3 = Me(n3), s5 = $e(o3, 1), f5 = Me(o3);
        let b2;
        !function(e5, t6, r6, o4, n4, a3) {
          function i4() {
            return t6;
          }
          __name(i4, "i");
          function l4(t7) {
            return function(e6, t8) {
              const r7 = e6._transformStreamController;
              if (e6._backpressure) {
                return p(e6._backpressureChangePromise, () => {
                  if ("erroring" === (Ge(e6._writable) ? e6._writable._state : e6._writableState)) throw Ge(e6._writable) ? e6._writable._storedError : e6._writableStoredError;
                  return pr(r7, t8);
                });
              }
              return pr(r7, t8);
            }(e5, t7);
          }
          __name(l4, "l");
          function s6(t7) {
            return function(e6, t8) {
              return cr(e6, t8), c(void 0);
            }(e5, t7);
          }
          __name(s6, "s");
          function u2() {
            return function(e6) {
              const t7 = e6._transformStreamController, r7 = t7._flushAlgorithm();
              return hr(t7), p(r7, () => {
                if ("errored" === e6._readableState) throw e6._readableStoredError;
                gr(e6) && wr(e6);
              }, (t8) => {
                throw cr(e6, t8), e6._readableStoredError;
              });
            }(e5);
          }
          __name(u2, "u");
          function d2() {
            return function(e6) {
              return fr(e6, false), e6._backpressureChangePromise;
            }(e5);
          }
          __name(d2, "d");
          function f6(t7) {
            return dr(e5, t7), c(void 0);
          }
          __name(f6, "f");
          e5._writableState = "writable", e5._writableStoredError = void 0, e5._writableHasInFlightOperation = false, e5._writableStarted = false, e5._writable = function(e6, t7, r7, o5, n5, a4, i5) {
            return new WritableStream({ start(r8) {
              e6._writableController = r8;
              try {
                const t8 = r8.signal;
                void 0 !== t8 && t8.addEventListener("abort", () => {
                  "writable" === e6._writableState && (e6._writableState = "erroring", t8.reason && (e6._writableStoredError = t8.reason));
                });
              } catch (e7) {
              }
              return p(t7(), () => (e6._writableStarted = true, Cr(e6), null), (t8) => {
                throw e6._writableStarted = true, Rr(e6, t8), t8;
              });
            }, write: /* @__PURE__ */ __name((t8) => (function(e7) {
              e7._writableHasInFlightOperation = true;
            }(e6), p(r7(t8), () => (function(e7) {
              e7._writableHasInFlightOperation = false;
            }(e6), Cr(e6), null), (t9) => {
              throw function(e7, t10) {
                e7._writableHasInFlightOperation = false, Rr(e7, t10);
              }(e6, t9), t9;
            })), "write"), close: /* @__PURE__ */ __name(() => (function(e7) {
              e7._writableHasInFlightOperation = true;
            }(e6), p(o5(), () => (function(e7) {
              e7._writableHasInFlightOperation = false;
              "erroring" === e7._writableState && (e7._writableStoredError = void 0);
              e7._writableState = "closed";
            }(e6), null), (t8) => {
              throw function(e7, t9) {
                e7._writableHasInFlightOperation = false, e7._writableState, Rr(e7, t9);
              }(e6, t8), t8;
            })), "close"), abort: /* @__PURE__ */ __name((t8) => (e6._writableState = "errored", e6._writableStoredError = t8, n5(t8)), "abort") }, { highWaterMark: a4, size: i5 });
          }(e5, i4, l4, u2, s6, r6, o4), e5._readableState = "readable", e5._readableStoredError = void 0, e5._readableCloseRequested = false, e5._readablePulling = false, e5._readable = function(e6, t7, r7, o5, n5, a4) {
            return new ReadableStream3({ start: /* @__PURE__ */ __name((r8) => (e6._readableController = r8, t7().catch((t8) => {
              Sr(e6, t8);
            })), "start"), pull: /* @__PURE__ */ __name(() => (e6._readablePulling = true, r7().catch((t8) => {
              Sr(e6, t8);
            })), "pull"), cancel: /* @__PURE__ */ __name((t8) => (e6._readableState = "closed", o5(t8)), "cancel") }, { highWaterMark: n5, size: a4 });
          }(e5, i4, d2, f6, n4, a3), e5._backpressure = void 0, e5._backpressureChangePromise = void 0, e5._backpressureChangePromise_resolve = void 0, fr(e5, true), e5._transformStreamController = void 0;
        }(this, u((e5) => {
          b2 = e5;
        }), s5, f5, i3, l3), function(e5, t6) {
          const r6 = Object.create(TransformStreamDefaultController.prototype);
          let o4, n4;
          o4 = void 0 !== t6.transform ? (e6) => t6.transform(e6, r6) : (e6) => {
            try {
              return _r(r6, e6), c(void 0);
            } catch (e7) {
              return d(e7);
            }
          };
          n4 = void 0 !== t6.flush ? () => t6.flush(r6) : () => c(void 0);
          !function(e6, t7, r7, o5) {
            t7._controlledTransformStream = e6, e6._transformStreamController = t7, t7._transformAlgorithm = r7, t7._flushAlgorithm = o5;
          }(e5, r6, o4, n4);
        }(this, a2), void 0 !== a2.start ? b2(a2.start(this._transformStreamController)) : b2(void 0);
      }
      get readable() {
        if (!ur(this)) throw yr("readable");
        return this._readable;
      }
      get writable() {
        if (!ur(this)) throw yr("writable");
        return this._writable;
      }
    };
    __name(ur, "ur");
    __name(cr, "cr");
    __name(dr, "dr");
    __name(fr, "fr");
    Object.defineProperties(TransformStream2.prototype, { readable: { enumerable: true }, writable: { enumerable: true } }), "symbol" == typeof e2.toStringTag && Object.defineProperty(TransformStream2.prototype, e2.toStringTag, { value: "TransformStream", configurable: true });
    TransformStreamDefaultController = class {
      static {
        __name(this, "TransformStreamDefaultController");
      }
      constructor() {
        throw new TypeError("Illegal constructor");
      }
      get desiredSize() {
        if (!br(this)) throw mr("desiredSize");
        return vr(this._controlledTransformStream);
      }
      enqueue(e4) {
        if (!br(this)) throw mr("enqueue");
        _r(this, e4);
      }
      error(e4) {
        if (!br(this)) throw mr("error");
        var t5;
        t5 = e4, cr(this._controlledTransformStream, t5);
      }
      terminate() {
        if (!br(this)) throw mr("terminate");
        !function(e4) {
          const t5 = e4._controlledTransformStream;
          gr(t5) && wr(t5);
          const r5 = new TypeError("TransformStream terminated");
          dr(t5, r5);
        }(this);
      }
    };
    __name(br, "br");
    __name(hr, "hr");
    __name(_r, "_r");
    __name(pr, "pr");
    __name(mr, "mr");
    __name(yr, "yr");
    __name(gr, "gr");
    __name(wr, "wr");
    __name(Sr, "Sr");
    __name(vr, "vr");
    __name(Rr, "Rr");
    __name(Tr, "Tr");
    __name(qr, "qr");
    __name(Cr, "Cr");
    Object.defineProperties(TransformStreamDefaultController.prototype, { enqueue: { enumerable: true }, error: { enumerable: true }, terminate: { enumerable: true }, desiredSize: { enumerable: true } }), n(TransformStreamDefaultController.prototype.enqueue, "enqueue"), n(TransformStreamDefaultController.prototype.error, "error"), n(TransformStreamDefaultController.prototype.terminate, "terminate"), "symbol" == typeof e2.toStringTag && Object.defineProperty(TransformStreamDefaultController.prototype, e2.toStringTag, { value: "TransformStreamDefaultController", configurable: true });
  }
});

// node_modules/formdata-node/lib/esm/isFunction.js
var isFunction;
var init_isFunction = __esm({
  "node_modules/formdata-node/lib/esm/isFunction.js"() {
    init_esbuild_shims();
    isFunction = /* @__PURE__ */ __name((value) => typeof value === "function", "isFunction");
  }
});

// node_modules/formdata-node/lib/esm/blobHelpers.js
async function* clonePart(part) {
  const end = part.byteOffset + part.byteLength;
  let position = part.byteOffset;
  while (position !== end) {
    const size = Math.min(end - position, CHUNK_SIZE);
    const chunk = part.buffer.slice(position, position + size);
    position += chunk.byteLength;
    yield new Uint8Array(chunk);
  }
}
async function* consumeNodeBlob(blob) {
  let position = 0;
  while (position !== blob.size) {
    const chunk = blob.slice(position, Math.min(blob.size, position + CHUNK_SIZE));
    const buffer = await chunk.arrayBuffer();
    position += buffer.byteLength;
    yield new Uint8Array(buffer);
  }
}
async function* consumeBlobParts(parts, clone4 = false) {
  for (const part of parts) {
    if (ArrayBuffer.isView(part)) {
      if (clone4) {
        yield* clonePart(part);
      } else {
        yield part;
      }
    } else if (isFunction(part.stream)) {
      yield* part.stream();
    } else {
      yield* consumeNodeBlob(part);
    }
  }
}
function* sliceBlob(blobParts, blobSize, start = 0, end) {
  end !== null && end !== void 0 ? end : end = blobSize;
  let relativeStart = start < 0 ? Math.max(blobSize + start, 0) : Math.min(start, blobSize);
  let relativeEnd = end < 0 ? Math.max(blobSize + end, 0) : Math.min(end, blobSize);
  const span = Math.max(relativeEnd - relativeStart, 0);
  let added = 0;
  for (const part of blobParts) {
    if (added >= span) {
      break;
    }
    const partSize = ArrayBuffer.isView(part) ? part.byteLength : part.size;
    if (relativeStart && partSize <= relativeStart) {
      relativeStart -= partSize;
      relativeEnd -= partSize;
    } else {
      let chunk;
      if (ArrayBuffer.isView(part)) {
        chunk = part.subarray(relativeStart, Math.min(partSize, relativeEnd));
        added += chunk.byteLength;
      } else {
        chunk = part.slice(relativeStart, Math.min(partSize, relativeEnd));
        added += chunk.size;
      }
      relativeEnd -= partSize;
      relativeStart = 0;
      yield chunk;
    }
  }
}
var CHUNK_SIZE;
var init_blobHelpers = __esm({
  "node_modules/formdata-node/lib/esm/blobHelpers.js"() {
    init_esbuild_shims();
    init_isFunction();
    CHUNK_SIZE = 65536;
    __name(clonePart, "clonePart");
    __name(consumeNodeBlob, "consumeNodeBlob");
    __name(consumeBlobParts, "consumeBlobParts");
    __name(sliceBlob, "sliceBlob");
  }
});

// node_modules/formdata-node/lib/esm/Blob.js
var __classPrivateFieldGet2, __classPrivateFieldSet2, _Blob_parts, _Blob_type, _Blob_size, Blob5;
var init_Blob = __esm({
  "node_modules/formdata-node/lib/esm/Blob.js"() {
    init_esbuild_shims();
    init_ponyfill();
    init_isFunction();
    init_blobHelpers();
    __classPrivateFieldGet2 = function(receiver, state, kind2, f5) {
      if (kind2 === "a" && !f5) throw new TypeError("Private accessor was defined without a getter");
      if (typeof state === "function" ? receiver !== state || !f5 : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
      return kind2 === "m" ? f5 : kind2 === "a" ? f5.call(receiver) : f5 ? f5.value : state.get(receiver);
    };
    __classPrivateFieldSet2 = function(receiver, state, value, kind2, f5) {
      if (kind2 === "m") throw new TypeError("Private method is not writable");
      if (kind2 === "a" && !f5) throw new TypeError("Private accessor was defined without a setter");
      if (typeof state === "function" ? receiver !== state || !f5 : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
      return kind2 === "a" ? f5.call(receiver, value) : f5 ? f5.value = value : state.set(receiver, value), value;
    };
    Blob5 = class _Blob2 {
      static {
        __name(this, "Blob");
      }
      constructor(blobParts = [], options2 = {}) {
        _Blob_parts.set(this, []);
        _Blob_type.set(this, "");
        _Blob_size.set(this, 0);
        options2 !== null && options2 !== void 0 ? options2 : options2 = {};
        if (typeof blobParts !== "object" || blobParts === null) {
          throw new TypeError("Failed to construct 'Blob': The provided value cannot be converted to a sequence.");
        }
        if (!isFunction(blobParts[Symbol.iterator])) {
          throw new TypeError("Failed to construct 'Blob': The object must have a callable @@iterator property.");
        }
        if (typeof options2 !== "object" && !isFunction(options2)) {
          throw new TypeError("Failed to construct 'Blob': parameter 2 cannot convert to dictionary.");
        }
        const encoder = new TextEncoder();
        for (const raw2 of blobParts) {
          let part;
          if (ArrayBuffer.isView(raw2)) {
            part = new Uint8Array(raw2.buffer.slice(raw2.byteOffset, raw2.byteOffset + raw2.byteLength));
          } else if (raw2 instanceof ArrayBuffer) {
            part = new Uint8Array(raw2.slice(0));
          } else if (raw2 instanceof _Blob2) {
            part = raw2;
          } else {
            part = encoder.encode(String(raw2));
          }
          __classPrivateFieldSet2(this, _Blob_size, __classPrivateFieldGet2(this, _Blob_size, "f") + (ArrayBuffer.isView(part) ? part.byteLength : part.size), "f");
          __classPrivateFieldGet2(this, _Blob_parts, "f").push(part);
        }
        const type = options2.type === void 0 ? "" : String(options2.type);
        __classPrivateFieldSet2(this, _Blob_type, /^[\x20-\x7E]*$/.test(type) ? type : "", "f");
      }
      static [(_Blob_parts = /* @__PURE__ */ new WeakMap(), _Blob_type = /* @__PURE__ */ new WeakMap(), _Blob_size = /* @__PURE__ */ new WeakMap(), Symbol.hasInstance)](value) {
        return Boolean(value && typeof value === "object" && isFunction(value.constructor) && (isFunction(value.stream) || isFunction(value.arrayBuffer)) && /^(Blob|File)$/.test(value[Symbol.toStringTag]));
      }
      get type() {
        return __classPrivateFieldGet2(this, _Blob_type, "f");
      }
      get size() {
        return __classPrivateFieldGet2(this, _Blob_size, "f");
      }
      slice(start, end, contentType) {
        return new _Blob2(sliceBlob(__classPrivateFieldGet2(this, _Blob_parts, "f"), this.size, start, end), {
          type: contentType
        });
      }
      async text() {
        const decoder = new TextDecoder();
        let result = "";
        for await (const chunk of consumeBlobParts(__classPrivateFieldGet2(this, _Blob_parts, "f"))) {
          result += decoder.decode(chunk, { stream: true });
        }
        result += decoder.decode();
        return result;
      }
      async arrayBuffer() {
        const view = new Uint8Array(this.size);
        let offset = 0;
        for await (const chunk of consumeBlobParts(__classPrivateFieldGet2(this, _Blob_parts, "f"))) {
          view.set(chunk, offset);
          offset += chunk.length;
        }
        return view.buffer;
      }
      stream() {
        const iterator = consumeBlobParts(__classPrivateFieldGet2(this, _Blob_parts, "f"), true);
        return new ReadableStream3({
          async pull(controller) {
            const { value, done } = await iterator.next();
            if (done) {
              return queueMicrotask(() => controller.close());
            }
            controller.enqueue(value);
          },
          async cancel() {
            await iterator.return();
          }
        });
      }
      get [Symbol.toStringTag]() {
        return "Blob";
      }
    };
    Object.defineProperties(Blob5.prototype, {
      type: { enumerable: true },
      size: { enumerable: true },
      slice: { enumerable: true },
      stream: { enumerable: true },
      text: { enumerable: true },
      arrayBuffer: { enumerable: true }
    });
  }
});

// node_modules/formdata-node/lib/esm/File.js
var __classPrivateFieldSet3, __classPrivateFieldGet3, _File_name, _File_lastModified, File5;
var init_File = __esm({
  "node_modules/formdata-node/lib/esm/File.js"() {
    init_esbuild_shims();
    init_Blob();
    __classPrivateFieldSet3 = function(receiver, state, value, kind2, f5) {
      if (kind2 === "m") throw new TypeError("Private method is not writable");
      if (kind2 === "a" && !f5) throw new TypeError("Private accessor was defined without a setter");
      if (typeof state === "function" ? receiver !== state || !f5 : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
      return kind2 === "a" ? f5.call(receiver, value) : f5 ? f5.value = value : state.set(receiver, value), value;
    };
    __classPrivateFieldGet3 = function(receiver, state, kind2, f5) {
      if (kind2 === "a" && !f5) throw new TypeError("Private accessor was defined without a getter");
      if (typeof state === "function" ? receiver !== state || !f5 : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
      return kind2 === "m" ? f5 : kind2 === "a" ? f5.call(receiver) : f5 ? f5.value : state.get(receiver);
    };
    File5 = class extends Blob5 {
      static {
        __name(this, "File");
      }
      constructor(fileBits, name3, options2 = {}) {
        super(fileBits, options2);
        _File_name.set(this, void 0);
        _File_lastModified.set(this, 0);
        if (arguments.length < 2) {
          throw new TypeError(`Failed to construct 'File': 2 arguments required, but only ${arguments.length} present.`);
        }
        __classPrivateFieldSet3(this, _File_name, String(name3), "f");
        const lastModified = options2.lastModified === void 0 ? Date.now() : Number(options2.lastModified);
        if (!Number.isNaN(lastModified)) {
          __classPrivateFieldSet3(this, _File_lastModified, lastModified, "f");
        }
      }
      static [(_File_name = /* @__PURE__ */ new WeakMap(), _File_lastModified = /* @__PURE__ */ new WeakMap(), Symbol.hasInstance)](value) {
        return value instanceof Blob5 && value[Symbol.toStringTag] === "File" && typeof value.name === "string";
      }
      get name() {
        return __classPrivateFieldGet3(this, _File_name, "f");
      }
      get lastModified() {
        return __classPrivateFieldGet3(this, _File_lastModified, "f");
      }
      get webkitRelativePath() {
        return "";
      }
      get [Symbol.toStringTag]() {
        return "File";
      }
    };
  }
});

// node_modules/formdata-node/lib/esm/isFile.js
var isFile;
var init_isFile = __esm({
  "node_modules/formdata-node/lib/esm/isFile.js"() {
    init_esbuild_shims();
    init_File();
    isFile = /* @__PURE__ */ __name((value) => value instanceof File5, "isFile");
  }
});

// node_modules/formdata-node/lib/esm/isBlob.js
var isBlob2;
var init_isBlob = __esm({
  "node_modules/formdata-node/lib/esm/isBlob.js"() {
    init_esbuild_shims();
    init_Blob();
    isBlob2 = /* @__PURE__ */ __name((value) => value instanceof Blob5, "isBlob");
  }
});

// node_modules/formdata-node/lib/esm/deprecateConstructorEntries.js
import { deprecate as deprecate3 } from "util";
var deprecateConstructorEntries;
var init_deprecateConstructorEntries = __esm({
  "node_modules/formdata-node/lib/esm/deprecateConstructorEntries.js"() {
    init_esbuild_shims();
    deprecateConstructorEntries = deprecate3(() => {
    }, 'Constructor "entries" argument is not spec-compliant and will be removed in next major release.');
  }
});

// node_modules/formdata-node/lib/esm/FormData.js
import { inspect } from "util";
var __classPrivateFieldGet4, _FormData_instances, _FormData_entries, _FormData_setEntry, FormData5;
var init_FormData = __esm({
  "node_modules/formdata-node/lib/esm/FormData.js"() {
    init_esbuild_shims();
    init_File();
    init_isFile();
    init_isBlob();
    init_isFunction();
    init_deprecateConstructorEntries();
    __classPrivateFieldGet4 = function(receiver, state, kind2, f5) {
      if (kind2 === "a" && !f5) throw new TypeError("Private accessor was defined without a getter");
      if (typeof state === "function" ? receiver !== state || !f5 : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
      return kind2 === "m" ? f5 : kind2 === "a" ? f5.call(receiver) : f5 ? f5.value : state.get(receiver);
    };
    FormData5 = class {
      static {
        __name(this, "FormData");
      }
      constructor(entries) {
        _FormData_instances.add(this);
        _FormData_entries.set(this, /* @__PURE__ */ new Map());
        if (entries) {
          deprecateConstructorEntries();
          entries.forEach(({ name: name3, value, fileName }) => this.append(name3, value, fileName));
        }
      }
      static [(_FormData_entries = /* @__PURE__ */ new WeakMap(), _FormData_instances = /* @__PURE__ */ new WeakSet(), Symbol.hasInstance)](value) {
        return Boolean(value && isFunction(value.constructor) && value[Symbol.toStringTag] === "FormData" && isFunction(value.append) && isFunction(value.set) && isFunction(value.get) && isFunction(value.getAll) && isFunction(value.has) && isFunction(value.delete) && isFunction(value.entries) && isFunction(value.values) && isFunction(value.keys) && isFunction(value[Symbol.iterator]) && isFunction(value.forEach));
      }
      append(name3, value, fileName) {
        __classPrivateFieldGet4(this, _FormData_instances, "m", _FormData_setEntry).call(this, {
          name: name3,
          fileName,
          append: true,
          rawValue: value,
          argsLength: arguments.length
        });
      }
      set(name3, value, fileName) {
        __classPrivateFieldGet4(this, _FormData_instances, "m", _FormData_setEntry).call(this, {
          name: name3,
          fileName,
          append: false,
          rawValue: value,
          argsLength: arguments.length
        });
      }
      get(name3) {
        const field = __classPrivateFieldGet4(this, _FormData_entries, "f").get(String(name3));
        if (!field) {
          return null;
        }
        return field[0];
      }
      getAll(name3) {
        const field = __classPrivateFieldGet4(this, _FormData_entries, "f").get(String(name3));
        if (!field) {
          return [];
        }
        return field.slice();
      }
      has(name3) {
        return __classPrivateFieldGet4(this, _FormData_entries, "f").has(String(name3));
      }
      delete(name3) {
        __classPrivateFieldGet4(this, _FormData_entries, "f").delete(String(name3));
      }
      *keys() {
        for (const key of __classPrivateFieldGet4(this, _FormData_entries, "f").keys()) {
          yield key;
        }
      }
      *entries() {
        for (const name3 of this.keys()) {
          const values = this.getAll(name3);
          for (const value of values) {
            yield [name3, value];
          }
        }
      }
      *values() {
        for (const [, value] of this) {
          yield value;
        }
      }
      [(_FormData_setEntry = /* @__PURE__ */ __name(function _FormData_setEntry2({ name: name3, rawValue, append: append2, fileName, argsLength }) {
        const methodName = append2 ? "append" : "set";
        if (argsLength < 2) {
          throw new TypeError(`Failed to execute '${methodName}' on 'FormData': 2 arguments required, but only ${argsLength} present.`);
        }
        name3 = String(name3);
        let value;
        if (isFile(rawValue)) {
          value = fileName === void 0 ? rawValue : new File5([rawValue], fileName, {
            type: rawValue.type,
            lastModified: rawValue.lastModified
          });
        } else if (isBlob2(rawValue)) {
          value = new File5([rawValue], fileName === void 0 ? "blob" : fileName, {
            type: rawValue.type
          });
        } else if (fileName) {
          throw new TypeError(`Failed to execute '${methodName}' on 'FormData': parameter 2 is not of type 'Blob'.`);
        } else {
          value = String(rawValue);
        }
        const values = __classPrivateFieldGet4(this, _FormData_entries, "f").get(name3);
        if (!values) {
          return void __classPrivateFieldGet4(this, _FormData_entries, "f").set(name3, [value]);
        }
        if (!append2) {
          return void __classPrivateFieldGet4(this, _FormData_entries, "f").set(name3, [value]);
        }
        values.push(value);
      }, "_FormData_setEntry"), Symbol.iterator)]() {
        return this.entries();
      }
      forEach(callback, thisArg) {
        for (const [name3, value] of this) {
          callback.call(thisArg, value, name3, this);
        }
      }
      get [Symbol.toStringTag]() {
        return "FormData";
      }
      [inspect.custom]() {
        return this[Symbol.toStringTag];
      }
    };
  }
});

// node_modules/formdata-node/lib/esm/index.js
var init_esm5 = __esm({
  "node_modules/formdata-node/lib/esm/index.js"() {
    init_esbuild_shims();
    init_FormData();
    init_Blob();
    init_File();
  }
});

// node_modules/humanize-ms/index.js
var require_humanize_ms = __commonJS({
  "node_modules/humanize-ms/index.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var util3 = __require("util");
    var ms = require_ms();
    module2.exports = function(t5) {
      if (typeof t5 === "number") return t5;
      var r5 = ms(t5);
      if (r5 === void 0) {
        var err = new Error(util3.format("humanize-ms(%j) result undefined", t5));
        console.warn(err.stack);
      }
      return r5;
    };
  }
});

// node_modules/agentkeepalive/lib/constants.js
var require_constants10 = __commonJS({
  "node_modules/agentkeepalive/lib/constants.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    module2.exports = {
      // agent
      CURRENT_ID: Symbol("agentkeepalive#currentId"),
      CREATE_ID: Symbol("agentkeepalive#createId"),
      INIT_SOCKET: Symbol("agentkeepalive#initSocket"),
      CREATE_HTTPS_CONNECTION: Symbol("agentkeepalive#createHttpsConnection"),
      // socket
      SOCKET_CREATED_TIME: Symbol("agentkeepalive#socketCreatedTime"),
      SOCKET_NAME: Symbol("agentkeepalive#socketName"),
      SOCKET_REQUEST_COUNT: Symbol("agentkeepalive#socketRequestCount"),
      SOCKET_REQUEST_FINISHED_COUNT: Symbol("agentkeepalive#socketRequestFinishedCount")
    };
  }
});

// node_modules/agentkeepalive/lib/agent.js
var require_agent2 = __commonJS({
  "node_modules/agentkeepalive/lib/agent.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var OriginalAgent = __require("http").Agent;
    var ms = require_humanize_ms();
    var debug3 = __require("util").debuglog("agentkeepalive");
    var {
      INIT_SOCKET,
      CURRENT_ID,
      CREATE_ID,
      SOCKET_CREATED_TIME,
      SOCKET_NAME,
      SOCKET_REQUEST_COUNT,
      SOCKET_REQUEST_FINISHED_COUNT
    } = require_constants10();
    var defaultTimeoutListenerCount = 1;
    var majorVersion = parseInt(process.version.split(".", 1)[0].substring(1));
    if (majorVersion >= 11 && majorVersion <= 12) {
      defaultTimeoutListenerCount = 2;
    } else if (majorVersion >= 13) {
      defaultTimeoutListenerCount = 3;
    }
    function deprecate6(message) {
      console.log("[agentkeepalive:deprecated] %s", message);
    }
    __name(deprecate6, "deprecate");
    var Agent4 = class extends OriginalAgent {
      static {
        __name(this, "Agent");
      }
      constructor(options2) {
        options2 = options2 || {};
        options2.keepAlive = options2.keepAlive !== false;
        if (options2.freeSocketTimeout === void 0) {
          options2.freeSocketTimeout = 4e3;
        }
        if (options2.keepAliveTimeout) {
          deprecate6("options.keepAliveTimeout is deprecated, please use options.freeSocketTimeout instead");
          options2.freeSocketTimeout = options2.keepAliveTimeout;
          delete options2.keepAliveTimeout;
        }
        if (options2.freeSocketKeepAliveTimeout) {
          deprecate6("options.freeSocketKeepAliveTimeout is deprecated, please use options.freeSocketTimeout instead");
          options2.freeSocketTimeout = options2.freeSocketKeepAliveTimeout;
          delete options2.freeSocketKeepAliveTimeout;
        }
        if (options2.timeout === void 0) {
          options2.timeout = Math.max(options2.freeSocketTimeout * 2, 8e3);
        }
        options2.timeout = ms(options2.timeout);
        options2.freeSocketTimeout = ms(options2.freeSocketTimeout);
        options2.socketActiveTTL = options2.socketActiveTTL ? ms(options2.socketActiveTTL) : 0;
        super(options2);
        this[CURRENT_ID] = 0;
        this.createSocketCount = 0;
        this.createSocketCountLastCheck = 0;
        this.createSocketErrorCount = 0;
        this.createSocketErrorCountLastCheck = 0;
        this.closeSocketCount = 0;
        this.closeSocketCountLastCheck = 0;
        this.errorSocketCount = 0;
        this.errorSocketCountLastCheck = 0;
        this.requestCount = 0;
        this.requestCountLastCheck = 0;
        this.timeoutSocketCount = 0;
        this.timeoutSocketCountLastCheck = 0;
        this.on("free", (socket) => {
          const timeout2 = this.calcSocketTimeout(socket);
          if (timeout2 > 0 && socket.timeout !== timeout2) {
            socket.setTimeout(timeout2);
          }
        });
      }
      get freeSocketKeepAliveTimeout() {
        deprecate6("agent.freeSocketKeepAliveTimeout is deprecated, please use agent.options.freeSocketTimeout instead");
        return this.options.freeSocketTimeout;
      }
      get timeout() {
        deprecate6("agent.timeout is deprecated, please use agent.options.timeout instead");
        return this.options.timeout;
      }
      get socketActiveTTL() {
        deprecate6("agent.socketActiveTTL is deprecated, please use agent.options.socketActiveTTL instead");
        return this.options.socketActiveTTL;
      }
      calcSocketTimeout(socket) {
        let freeSocketTimeout = this.options.freeSocketTimeout;
        const socketActiveTTL = this.options.socketActiveTTL;
        if (socketActiveTTL) {
          const aliveTime = Date.now() - socket[SOCKET_CREATED_TIME];
          const diff4 = socketActiveTTL - aliveTime;
          if (diff4 <= 0) {
            return diff4;
          }
          if (freeSocketTimeout && diff4 < freeSocketTimeout) {
            freeSocketTimeout = diff4;
          }
        }
        if (freeSocketTimeout) {
          const customFreeSocketTimeout = socket.freeSocketTimeout || socket.freeSocketKeepAliveTimeout;
          return customFreeSocketTimeout || freeSocketTimeout;
        }
      }
      keepSocketAlive(socket) {
        const result = super.keepSocketAlive(socket);
        if (!result) return result;
        const customTimeout = this.calcSocketTimeout(socket);
        if (typeof customTimeout === "undefined") {
          return true;
        }
        if (customTimeout <= 0) {
          debug3(
            "%s(requests: %s, finished: %s) free but need to destroy by TTL, request count %s, diff is %s",
            socket[SOCKET_NAME],
            socket[SOCKET_REQUEST_COUNT],
            socket[SOCKET_REQUEST_FINISHED_COUNT],
            customTimeout
          );
          return false;
        }
        if (socket.timeout !== customTimeout) {
          socket.setTimeout(customTimeout);
        }
        return true;
      }
      // only call on addRequest
      reuseSocket(...args) {
        super.reuseSocket(...args);
        const socket = args[0];
        const req = args[1];
        req.reusedSocket = true;
        const agentTimeout = this.options.timeout;
        if (getSocketTimeout(socket) !== agentTimeout) {
          socket.setTimeout(agentTimeout);
          debug3("%s reset timeout to %sms", socket[SOCKET_NAME], agentTimeout);
        }
        socket[SOCKET_REQUEST_COUNT]++;
        debug3(
          "%s(requests: %s, finished: %s) reuse on addRequest, timeout %sms",
          socket[SOCKET_NAME],
          socket[SOCKET_REQUEST_COUNT],
          socket[SOCKET_REQUEST_FINISHED_COUNT],
          getSocketTimeout(socket)
        );
      }
      [CREATE_ID]() {
        const id = this[CURRENT_ID]++;
        if (this[CURRENT_ID] === Number.MAX_SAFE_INTEGER) this[CURRENT_ID] = 0;
        return id;
      }
      [INIT_SOCKET](socket, options2) {
        if (options2.timeout) {
          const timeout2 = getSocketTimeout(socket);
          if (!timeout2) {
            socket.setTimeout(options2.timeout);
          }
        }
        if (this.options.keepAlive) {
          socket.setNoDelay(true);
        }
        this.createSocketCount++;
        if (this.options.socketActiveTTL) {
          socket[SOCKET_CREATED_TIME] = Date.now();
        }
        socket[SOCKET_NAME] = `sock[${this[CREATE_ID]()}#${options2._agentKey}]`.split("-----BEGIN", 1)[0];
        socket[SOCKET_REQUEST_COUNT] = 1;
        socket[SOCKET_REQUEST_FINISHED_COUNT] = 0;
        installListeners(this, socket, options2);
      }
      createConnection(options2, oncreate) {
        let called = false;
        const onNewCreate = /* @__PURE__ */ __name((err, socket) => {
          if (called) return;
          called = true;
          if (err) {
            this.createSocketErrorCount++;
            return oncreate(err);
          }
          this[INIT_SOCKET](socket, options2);
          oncreate(err, socket);
        }, "onNewCreate");
        const newSocket = super.createConnection(options2, onNewCreate);
        if (newSocket) onNewCreate(null, newSocket);
        return newSocket;
      }
      get statusChanged() {
        const changed = this.createSocketCount !== this.createSocketCountLastCheck || this.createSocketErrorCount !== this.createSocketErrorCountLastCheck || this.closeSocketCount !== this.closeSocketCountLastCheck || this.errorSocketCount !== this.errorSocketCountLastCheck || this.timeoutSocketCount !== this.timeoutSocketCountLastCheck || this.requestCount !== this.requestCountLastCheck;
        if (changed) {
          this.createSocketCountLastCheck = this.createSocketCount;
          this.createSocketErrorCountLastCheck = this.createSocketErrorCount;
          this.closeSocketCountLastCheck = this.closeSocketCount;
          this.errorSocketCountLastCheck = this.errorSocketCount;
          this.timeoutSocketCountLastCheck = this.timeoutSocketCount;
          this.requestCountLastCheck = this.requestCount;
        }
        return changed;
      }
      getCurrentStatus() {
        return {
          createSocketCount: this.createSocketCount,
          createSocketErrorCount: this.createSocketErrorCount,
          closeSocketCount: this.closeSocketCount,
          errorSocketCount: this.errorSocketCount,
          timeoutSocketCount: this.timeoutSocketCount,
          requestCount: this.requestCount,
          freeSockets: inspect3(this.freeSockets),
          sockets: inspect3(this.sockets),
          requests: inspect3(this.requests)
        };
      }
    };
    function getSocketTimeout(socket) {
      return socket.timeout || socket._idleTimeout;
    }
    __name(getSocketTimeout, "getSocketTimeout");
    function installListeners(agent, socket, options2) {
      debug3("%s create, timeout %sms", socket[SOCKET_NAME], getSocketTimeout(socket));
      function onFree() {
        if (!socket._httpMessage && socket[SOCKET_REQUEST_COUNT] === 1) return;
        socket[SOCKET_REQUEST_FINISHED_COUNT]++;
        agent.requestCount++;
        debug3(
          "%s(requests: %s, finished: %s) free",
          socket[SOCKET_NAME],
          socket[SOCKET_REQUEST_COUNT],
          socket[SOCKET_REQUEST_FINISHED_COUNT]
        );
        const name3 = agent.getName(options2);
        if (socket.writable && agent.requests[name3] && agent.requests[name3].length) {
          socket[SOCKET_REQUEST_COUNT]++;
          debug3(
            "%s(requests: %s, finished: %s) will be reuse on agent free event",
            socket[SOCKET_NAME],
            socket[SOCKET_REQUEST_COUNT],
            socket[SOCKET_REQUEST_FINISHED_COUNT]
          );
        }
      }
      __name(onFree, "onFree");
      socket.on("free", onFree);
      function onClose(isError) {
        debug3(
          "%s(requests: %s, finished: %s) close, isError: %s",
          socket[SOCKET_NAME],
          socket[SOCKET_REQUEST_COUNT],
          socket[SOCKET_REQUEST_FINISHED_COUNT],
          isError
        );
        agent.closeSocketCount++;
      }
      __name(onClose, "onClose");
      socket.on("close", onClose);
      function onTimeout() {
        const listenerCount = socket.listeners("timeout").length;
        const timeout2 = getSocketTimeout(socket);
        const req = socket._httpMessage;
        const reqTimeoutListenerCount = req && req.listeners("timeout").length || 0;
        debug3(
          "%s(requests: %s, finished: %s) timeout after %sms, listeners %s, defaultTimeoutListenerCount %s, hasHttpRequest %s, HttpRequest timeoutListenerCount %s",
          socket[SOCKET_NAME],
          socket[SOCKET_REQUEST_COUNT],
          socket[SOCKET_REQUEST_FINISHED_COUNT],
          timeout2,
          listenerCount,
          defaultTimeoutListenerCount,
          !!req,
          reqTimeoutListenerCount
        );
        if (debug3.enabled) {
          debug3("timeout listeners: %s", socket.listeners("timeout").map((f5) => f5.name).join(", "));
        }
        agent.timeoutSocketCount++;
        const name3 = agent.getName(options2);
        if (agent.freeSockets[name3] && agent.freeSockets[name3].indexOf(socket) !== -1) {
          socket.destroy();
          agent.removeSocket(socket, options2);
          debug3("%s is free, destroy quietly", socket[SOCKET_NAME]);
        } else {
          if (reqTimeoutListenerCount === 0) {
            const error2 = new Error("Socket timeout");
            error2.code = "ERR_SOCKET_TIMEOUT";
            error2.timeout = timeout2;
            socket.destroy(error2);
            agent.removeSocket(socket, options2);
            debug3("%s destroy with timeout error", socket[SOCKET_NAME]);
          }
        }
      }
      __name(onTimeout, "onTimeout");
      socket.on("timeout", onTimeout);
      function onError2(err) {
        const listenerCount = socket.listeners("error").length;
        debug3(
          "%s(requests: %s, finished: %s) error: %s, listenerCount: %s",
          socket[SOCKET_NAME],
          socket[SOCKET_REQUEST_COUNT],
          socket[SOCKET_REQUEST_FINISHED_COUNT],
          err,
          listenerCount
        );
        agent.errorSocketCount++;
        if (listenerCount === 1) {
          debug3("%s emit uncaught error event", socket[SOCKET_NAME]);
          socket.removeListener("error", onError2);
          socket.emit("error", err);
        }
      }
      __name(onError2, "onError");
      socket.on("error", onError2);
      function onRemove() {
        debug3(
          "%s(requests: %s, finished: %s) agentRemove",
          socket[SOCKET_NAME],
          socket[SOCKET_REQUEST_COUNT],
          socket[SOCKET_REQUEST_FINISHED_COUNT]
        );
        socket.removeListener("close", onClose);
        socket.removeListener("error", onError2);
        socket.removeListener("free", onFree);
        socket.removeListener("timeout", onTimeout);
        socket.removeListener("agentRemove", onRemove);
      }
      __name(onRemove, "onRemove");
      socket.on("agentRemove", onRemove);
    }
    __name(installListeners, "installListeners");
    module2.exports = Agent4;
    function inspect3(obj) {
      const res = {};
      for (const key in obj) {
        res[key] = obj[key].length;
      }
      return res;
    }
    __name(inspect3, "inspect");
  }
});

// node_modules/agentkeepalive/lib/https_agent.js
var require_https_agent = __commonJS({
  "node_modules/agentkeepalive/lib/https_agent.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var OriginalHttpsAgent = __require("https").Agent;
    var HttpAgent = require_agent2();
    var {
      INIT_SOCKET,
      CREATE_HTTPS_CONNECTION
    } = require_constants10();
    var HttpsAgent = class extends HttpAgent {
      static {
        __name(this, "HttpsAgent");
      }
      constructor(options2) {
        super(options2);
        this.defaultPort = 443;
        this.protocol = "https:";
        this.maxCachedSessions = this.options.maxCachedSessions;
        if (this.maxCachedSessions === void 0) {
          this.maxCachedSessions = 100;
        }
        this._sessionCache = {
          map: {},
          list: []
        };
      }
      createConnection(options2, oncreate) {
        const socket = this[CREATE_HTTPS_CONNECTION](options2, oncreate);
        this[INIT_SOCKET](socket, options2);
        return socket;
      }
    };
    HttpsAgent.prototype[CREATE_HTTPS_CONNECTION] = OriginalHttpsAgent.prototype.createConnection;
    [
      "getName",
      "_getSession",
      "_cacheSession",
      // https://github.com/nodejs/node/pull/4982
      "_evictSession"
    ].forEach(function(method) {
      if (typeof OriginalHttpsAgent.prototype[method] === "function") {
        HttpsAgent.prototype[method] = OriginalHttpsAgent.prototype[method];
      }
    });
    module2.exports = HttpsAgent;
  }
});

// node_modules/agentkeepalive/index.js
var require_agentkeepalive = __commonJS({
  "node_modules/agentkeepalive/index.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var HttpAgent = require_agent2();
    module2.exports = HttpAgent;
    module2.exports.HttpAgent = HttpAgent;
    module2.exports.HttpsAgent = require_https_agent();
    module2.exports.constants = require_constants10();
  }
});

// node_modules/event-target-shim/dist/event-target-shim.js
var require_event_target_shim = __commonJS({
  "node_modules/event-target-shim/dist/event-target-shim.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    var privateData = /* @__PURE__ */ new WeakMap();
    var wrappers = /* @__PURE__ */ new WeakMap();
    function pd(event) {
      const retv = privateData.get(event);
      console.assert(
        retv != null,
        "'this' is expected an Event object, but got",
        event
      );
      return retv;
    }
    __name(pd, "pd");
    function setCancelFlag(data) {
      if (data.passiveListener != null) {
        if (typeof console !== "undefined" && typeof console.error === "function") {
          console.error(
            "Unable to preventDefault inside passive event listener invocation.",
            data.passiveListener
          );
        }
        return;
      }
      if (!data.event.cancelable) {
        return;
      }
      data.canceled = true;
      if (typeof data.event.preventDefault === "function") {
        data.event.preventDefault();
      }
    }
    __name(setCancelFlag, "setCancelFlag");
    function Event2(eventTarget, event) {
      privateData.set(this, {
        eventTarget,
        event,
        eventPhase: 2,
        currentTarget: eventTarget,
        canceled: false,
        stopped: false,
        immediateStopped: false,
        passiveListener: null,
        timeStamp: event.timeStamp || Date.now()
      });
      Object.defineProperty(this, "isTrusted", { value: false, enumerable: true });
      const keys = Object.keys(event);
      for (let i3 = 0; i3 < keys.length; ++i3) {
        const key = keys[i3];
        if (!(key in this)) {
          Object.defineProperty(this, key, defineRedirectDescriptor(key));
        }
      }
    }
    __name(Event2, "Event");
    Event2.prototype = {
      /**
       * The type of this event.
       * @type {string}
       */
      get type() {
        return pd(this).event.type;
      },
      /**
       * The target of this event.
       * @type {EventTarget}
       */
      get target() {
        return pd(this).eventTarget;
      },
      /**
       * The target of this event.
       * @type {EventTarget}
       */
      get currentTarget() {
        return pd(this).currentTarget;
      },
      /**
       * @returns {EventTarget[]} The composed path of this event.
       */
      composedPath() {
        const currentTarget = pd(this).currentTarget;
        if (currentTarget == null) {
          return [];
        }
        return [currentTarget];
      },
      /**
       * Constant of NONE.
       * @type {number}
       */
      get NONE() {
        return 0;
      },
      /**
       * Constant of CAPTURING_PHASE.
       * @type {number}
       */
      get CAPTURING_PHASE() {
        return 1;
      },
      /**
       * Constant of AT_TARGET.
       * @type {number}
       */
      get AT_TARGET() {
        return 2;
      },
      /**
       * Constant of BUBBLING_PHASE.
       * @type {number}
       */
      get BUBBLING_PHASE() {
        return 3;
      },
      /**
       * The target of this event.
       * @type {number}
       */
      get eventPhase() {
        return pd(this).eventPhase;
      },
      /**
       * Stop event bubbling.
       * @returns {void}
       */
      stopPropagation() {
        const data = pd(this);
        data.stopped = true;
        if (typeof data.event.stopPropagation === "function") {
          data.event.stopPropagation();
        }
      },
      /**
       * Stop event bubbling.
       * @returns {void}
       */
      stopImmediatePropagation() {
        const data = pd(this);
        data.stopped = true;
        data.immediateStopped = true;
        if (typeof data.event.stopImmediatePropagation === "function") {
          data.event.stopImmediatePropagation();
        }
      },
      /**
       * The flag to be bubbling.
       * @type {boolean}
       */
      get bubbles() {
        return Boolean(pd(this).event.bubbles);
      },
      /**
       * The flag to be cancelable.
       * @type {boolean}
       */
      get cancelable() {
        return Boolean(pd(this).event.cancelable);
      },
      /**
       * Cancel this event.
       * @returns {void}
       */
      preventDefault() {
        setCancelFlag(pd(this));
      },
      /**
       * The flag to indicate cancellation state.
       * @type {boolean}
       */
      get defaultPrevented() {
        return pd(this).canceled;
      },
      /**
       * The flag to be composed.
       * @type {boolean}
       */
      get composed() {
        return Boolean(pd(this).event.composed);
      },
      /**
       * The unix time of this event.
       * @type {number}
       */
      get timeStamp() {
        return pd(this).timeStamp;
      },
      /**
       * The target of this event.
       * @type {EventTarget}
       * @deprecated
       */
      get srcElement() {
        return pd(this).eventTarget;
      },
      /**
       * The flag to stop event bubbling.
       * @type {boolean}
       * @deprecated
       */
      get cancelBubble() {
        return pd(this).stopped;
      },
      set cancelBubble(value) {
        if (!value) {
          return;
        }
        const data = pd(this);
        data.stopped = true;
        if (typeof data.event.cancelBubble === "boolean") {
          data.event.cancelBubble = true;
        }
      },
      /**
       * The flag to indicate cancellation state.
       * @type {boolean}
       * @deprecated
       */
      get returnValue() {
        return !pd(this).canceled;
      },
      set returnValue(value) {
        if (!value) {
          setCancelFlag(pd(this));
        }
      },
      /**
       * Initialize this event object. But do nothing under event dispatching.
       * @param {string} type The event type.
       * @param {boolean} [bubbles=false] The flag to be possible to bubble up.
       * @param {boolean} [cancelable=false] The flag to be possible to cancel.
       * @deprecated
       */
      initEvent() {
      }
    };
    Object.defineProperty(Event2.prototype, "constructor", {
      value: Event2,
      configurable: true,
      writable: true
    });
    if (typeof window !== "undefined" && typeof window.Event !== "undefined") {
      Object.setPrototypeOf(Event2.prototype, window.Event.prototype);
      wrappers.set(window.Event.prototype, Event2);
    }
    function defineRedirectDescriptor(key) {
      return {
        get() {
          return pd(this).event[key];
        },
        set(value) {
          pd(this).event[key] = value;
        },
        configurable: true,
        enumerable: true
      };
    }
    __name(defineRedirectDescriptor, "defineRedirectDescriptor");
    function defineCallDescriptor(key) {
      return {
        value() {
          const event = pd(this).event;
          return event[key].apply(event, arguments);
        },
        configurable: true,
        enumerable: true
      };
    }
    __name(defineCallDescriptor, "defineCallDescriptor");
    function defineWrapper(BaseEvent, proto3) {
      const keys = Object.keys(proto3);
      if (keys.length === 0) {
        return BaseEvent;
      }
      function CustomEvent(eventTarget, event) {
        BaseEvent.call(this, eventTarget, event);
      }
      __name(CustomEvent, "CustomEvent");
      CustomEvent.prototype = Object.create(BaseEvent.prototype, {
        constructor: { value: CustomEvent, configurable: true, writable: true }
      });
      for (let i3 = 0; i3 < keys.length; ++i3) {
        const key = keys[i3];
        if (!(key in BaseEvent.prototype)) {
          const descriptor2 = Object.getOwnPropertyDescriptor(proto3, key);
          const isFunc = typeof descriptor2.value === "function";
          Object.defineProperty(
            CustomEvent.prototype,
            key,
            isFunc ? defineCallDescriptor(key) : defineRedirectDescriptor(key)
          );
        }
      }
      return CustomEvent;
    }
    __name(defineWrapper, "defineWrapper");
    function getWrapper(proto3) {
      if (proto3 == null || proto3 === Object.prototype) {
        return Event2;
      }
      let wrapper = wrappers.get(proto3);
      if (wrapper == null) {
        wrapper = defineWrapper(getWrapper(Object.getPrototypeOf(proto3)), proto3);
        wrappers.set(proto3, wrapper);
      }
      return wrapper;
    }
    __name(getWrapper, "getWrapper");
    function wrapEvent(eventTarget, event) {
      const Wrapper = getWrapper(Object.getPrototypeOf(event));
      return new Wrapper(eventTarget, event);
    }
    __name(wrapEvent, "wrapEvent");
    function isStopped(event) {
      return pd(event).immediateStopped;
    }
    __name(isStopped, "isStopped");
    function setEventPhase(event, eventPhase) {
      pd(event).eventPhase = eventPhase;
    }
    __name(setEventPhase, "setEventPhase");
    function setCurrentTarget(event, currentTarget) {
      pd(event).currentTarget = currentTarget;
    }
    __name(setCurrentTarget, "setCurrentTarget");
    function setPassiveListener(event, passiveListener) {
      pd(event).passiveListener = passiveListener;
    }
    __name(setPassiveListener, "setPassiveListener");
    var listenersMap = /* @__PURE__ */ new WeakMap();
    var CAPTURE = 1;
    var BUBBLE = 2;
    var ATTRIBUTE = 3;
    function isObject4(x3) {
      return x3 !== null && typeof x3 === "object";
    }
    __name(isObject4, "isObject");
    function getListeners(eventTarget) {
      const listeners = listenersMap.get(eventTarget);
      if (listeners == null) {
        throw new TypeError(
          "'this' is expected an EventTarget object, but got another value."
        );
      }
      return listeners;
    }
    __name(getListeners, "getListeners");
    function defineEventAttributeDescriptor(eventName) {
      return {
        get() {
          const listeners = getListeners(this);
          let node = listeners.get(eventName);
          while (node != null) {
            if (node.listenerType === ATTRIBUTE) {
              return node.listener;
            }
            node = node.next;
          }
          return null;
        },
        set(listener) {
          if (typeof listener !== "function" && !isObject4(listener)) {
            listener = null;
          }
          const listeners = getListeners(this);
          let prev = null;
          let node = listeners.get(eventName);
          while (node != null) {
            if (node.listenerType === ATTRIBUTE) {
              if (prev !== null) {
                prev.next = node.next;
              } else if (node.next !== null) {
                listeners.set(eventName, node.next);
              } else {
                listeners.delete(eventName);
              }
            } else {
              prev = node;
            }
            node = node.next;
          }
          if (listener !== null) {
            const newNode = {
              listener,
              listenerType: ATTRIBUTE,
              passive: false,
              once: false,
              next: null
            };
            if (prev === null) {
              listeners.set(eventName, newNode);
            } else {
              prev.next = newNode;
            }
          }
        },
        configurable: true,
        enumerable: true
      };
    }
    __name(defineEventAttributeDescriptor, "defineEventAttributeDescriptor");
    function defineEventAttribute(eventTargetPrototype, eventName) {
      Object.defineProperty(
        eventTargetPrototype,
        `on${eventName}`,
        defineEventAttributeDescriptor(eventName)
      );
    }
    __name(defineEventAttribute, "defineEventAttribute");
    function defineCustomEventTarget(eventNames) {
      function CustomEventTarget() {
        EventTarget2.call(this);
      }
      __name(CustomEventTarget, "CustomEventTarget");
      CustomEventTarget.prototype = Object.create(EventTarget2.prototype, {
        constructor: {
          value: CustomEventTarget,
          configurable: true,
          writable: true
        }
      });
      for (let i3 = 0; i3 < eventNames.length; ++i3) {
        defineEventAttribute(CustomEventTarget.prototype, eventNames[i3]);
      }
      return CustomEventTarget;
    }
    __name(defineCustomEventTarget, "defineCustomEventTarget");
    function EventTarget2() {
      if (this instanceof EventTarget2) {
        listenersMap.set(this, /* @__PURE__ */ new Map());
        return;
      }
      if (arguments.length === 1 && Array.isArray(arguments[0])) {
        return defineCustomEventTarget(arguments[0]);
      }
      if (arguments.length > 0) {
        const types7 = new Array(arguments.length);
        for (let i3 = 0; i3 < arguments.length; ++i3) {
          types7[i3] = arguments[i3];
        }
        return defineCustomEventTarget(types7);
      }
      throw new TypeError("Cannot call a class as a function");
    }
    __name(EventTarget2, "EventTarget");
    EventTarget2.prototype = {
      /**
       * Add a given listener to this event target.
       * @param {string} eventName The event name to add.
       * @param {Function} listener The listener to add.
       * @param {boolean|{capture?:boolean,passive?:boolean,once?:boolean}} [options] The options for this listener.
       * @returns {void}
       */
      addEventListener(eventName, listener, options2) {
        if (listener == null) {
          return;
        }
        if (typeof listener !== "function" && !isObject4(listener)) {
          throw new TypeError("'listener' should be a function or an object.");
        }
        const listeners = getListeners(this);
        const optionsIsObj = isObject4(options2);
        const capture = optionsIsObj ? Boolean(options2.capture) : Boolean(options2);
        const listenerType = capture ? CAPTURE : BUBBLE;
        const newNode = {
          listener,
          listenerType,
          passive: optionsIsObj && Boolean(options2.passive),
          once: optionsIsObj && Boolean(options2.once),
          next: null
        };
        let node = listeners.get(eventName);
        if (node === void 0) {
          listeners.set(eventName, newNode);
          return;
        }
        let prev = null;
        while (node != null) {
          if (node.listener === listener && node.listenerType === listenerType) {
            return;
          }
          prev = node;
          node = node.next;
        }
        prev.next = newNode;
      },
      /**
       * Remove a given listener from this event target.
       * @param {string} eventName The event name to remove.
       * @param {Function} listener The listener to remove.
       * @param {boolean|{capture?:boolean,passive?:boolean,once?:boolean}} [options] The options for this listener.
       * @returns {void}
       */
      removeEventListener(eventName, listener, options2) {
        if (listener == null) {
          return;
        }
        const listeners = getListeners(this);
        const capture = isObject4(options2) ? Boolean(options2.capture) : Boolean(options2);
        const listenerType = capture ? CAPTURE : BUBBLE;
        let prev = null;
        let node = listeners.get(eventName);
        while (node != null) {
          if (node.listener === listener && node.listenerType === listenerType) {
            if (prev !== null) {
              prev.next = node.next;
            } else if (node.next !== null) {
              listeners.set(eventName, node.next);
            } else {
              listeners.delete(eventName);
            }
            return;
          }
          prev = node;
          node = node.next;
        }
      },
      /**
       * Dispatch a given event.
       * @param {Event|{type:string}} event The event to dispatch.
       * @returns {boolean} `false` if canceled.
       */
      dispatchEvent(event) {
        if (event == null || typeof event.type !== "string") {
          throw new TypeError('"event.type" should be a string.');
        }
        const listeners = getListeners(this);
        const eventName = event.type;
        let node = listeners.get(eventName);
        if (node == null) {
          return true;
        }
        const wrappedEvent = wrapEvent(this, event);
        let prev = null;
        while (node != null) {
          if (node.once) {
            if (prev !== null) {
              prev.next = node.next;
            } else if (node.next !== null) {
              listeners.set(eventName, node.next);
            } else {
              listeners.delete(eventName);
            }
          } else {
            prev = node;
          }
          setPassiveListener(
            wrappedEvent,
            node.passive ? node.listener : null
          );
          if (typeof node.listener === "function") {
            try {
              node.listener.call(this, wrappedEvent);
            } catch (err) {
              if (typeof console !== "undefined" && typeof console.error === "function") {
                console.error(err);
              }
            }
          } else if (node.listenerType !== ATTRIBUTE && typeof node.listener.handleEvent === "function") {
            node.listener.handleEvent(wrappedEvent);
          }
          if (isStopped(wrappedEvent)) {
            break;
          }
          node = node.next;
        }
        setPassiveListener(wrappedEvent, null);
        setEventPhase(wrappedEvent, 0);
        setCurrentTarget(wrappedEvent, null);
        return !wrappedEvent.defaultPrevented;
      }
    };
    Object.defineProperty(EventTarget2.prototype, "constructor", {
      value: EventTarget2,
      configurable: true,
      writable: true
    });
    if (typeof window !== "undefined" && typeof window.EventTarget !== "undefined") {
      Object.setPrototypeOf(EventTarget2.prototype, window.EventTarget.prototype);
    }
    exports2.defineEventAttribute = defineEventAttribute;
    exports2.EventTarget = EventTarget2;
    exports2.default = EventTarget2;
    module2.exports = EventTarget2;
    module2.exports.EventTarget = module2.exports["default"] = EventTarget2;
    module2.exports.defineEventAttribute = defineEventAttribute;
  }
});

// node_modules/abort-controller/dist/abort-controller.js
var require_abort_controller = __commonJS({
  "node_modules/abort-controller/dist/abort-controller.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    var eventTargetShim = require_event_target_shim();
    var AbortSignal2 = class extends eventTargetShim.EventTarget {
      static {
        __name(this, "AbortSignal");
      }
      /**
       * AbortSignal cannot be constructed directly.
       */
      constructor() {
        super();
        throw new TypeError("AbortSignal cannot be constructed directly");
      }
      /**
       * Returns `true` if this `AbortSignal`'s `AbortController` has signaled to abort, and `false` otherwise.
       */
      get aborted() {
        const aborted2 = abortedFlags.get(this);
        if (typeof aborted2 !== "boolean") {
          throw new TypeError(`Expected 'this' to be an 'AbortSignal' object, but got ${this === null ? "null" : typeof this}`);
        }
        return aborted2;
      }
    };
    eventTargetShim.defineEventAttribute(AbortSignal2.prototype, "abort");
    function createAbortSignal() {
      const signal = Object.create(AbortSignal2.prototype);
      eventTargetShim.EventTarget.call(signal);
      abortedFlags.set(signal, false);
      return signal;
    }
    __name(createAbortSignal, "createAbortSignal");
    function abortSignal(signal) {
      if (abortedFlags.get(signal) !== false) {
        return;
      }
      abortedFlags.set(signal, true);
      signal.dispatchEvent({ type: "abort" });
    }
    __name(abortSignal, "abortSignal");
    var abortedFlags = /* @__PURE__ */ new WeakMap();
    Object.defineProperties(AbortSignal2.prototype, {
      aborted: { enumerable: true }
    });
    if (typeof Symbol === "function" && typeof Symbol.toStringTag === "symbol") {
      Object.defineProperty(AbortSignal2.prototype, Symbol.toStringTag, {
        configurable: true,
        value: "AbortSignal"
      });
    }
    var AbortController2 = class {
      static {
        __name(this, "AbortController");
      }
      /**
       * Initialize this controller.
       */
      constructor() {
        signals.set(this, createAbortSignal());
      }
      /**
       * Returns the `AbortSignal` object associated with this object.
       */
      get signal() {
        return getSignal(this);
      }
      /**
       * Abort and signal to any observers that the associated activity is to be aborted.
       */
      abort() {
        abortSignal(getSignal(this));
      }
    };
    var signals = /* @__PURE__ */ new WeakMap();
    function getSignal(controller) {
      const signal = signals.get(controller);
      if (signal == null) {
        throw new TypeError(`Expected 'this' to be an 'AbortController' object, but got ${controller === null ? "null" : typeof controller}`);
      }
      return signal;
    }
    __name(getSignal, "getSignal");
    Object.defineProperties(AbortController2.prototype, {
      signal: { enumerable: true },
      abort: { enumerable: true }
    });
    if (typeof Symbol === "function" && typeof Symbol.toStringTag === "symbol") {
      Object.defineProperty(AbortController2.prototype, Symbol.toStringTag, {
        configurable: true,
        value: "AbortController"
      });
    }
    exports2.AbortController = AbortController2;
    exports2.AbortSignal = AbortSignal2;
    exports2.default = AbortController2;
    module2.exports = AbortController2;
    module2.exports.AbortController = module2.exports["default"] = AbortController2;
    module2.exports.AbortSignal = AbortSignal2;
  }
});

// node_modules/form-data-encoder/lib/esm/util/createBoundary.js
function createBoundary() {
  let size = 16;
  let res = "";
  while (size--) {
    res += alphabet[Math.random() * alphabet.length << 0];
  }
  return res;
}
var alphabet, createBoundary_default;
var init_createBoundary = __esm({
  "node_modules/form-data-encoder/lib/esm/util/createBoundary.js"() {
    init_esbuild_shims();
    alphabet = "abcdefghijklmnopqrstuvwxyz0123456789";
    __name(createBoundary, "createBoundary");
    createBoundary_default = createBoundary;
  }
});

// node_modules/form-data-encoder/lib/esm/util/isPlainObject.js
function isPlainObject(value) {
  if (getType(value) !== "object") {
    return false;
  }
  const pp = Object.getPrototypeOf(value);
  if (pp === null || pp === void 0) {
    return true;
  }
  const Ctor = pp.constructor && pp.constructor.toString();
  return Ctor === Object.toString();
}
var getType, isPlainObject_default;
var init_isPlainObject = __esm({
  "node_modules/form-data-encoder/lib/esm/util/isPlainObject.js"() {
    init_esbuild_shims();
    getType = /* @__PURE__ */ __name((value) => Object.prototype.toString.call(value).slice(8, -1).toLowerCase(), "getType");
    __name(isPlainObject, "isPlainObject");
    isPlainObject_default = isPlainObject;
  }
});

// node_modules/form-data-encoder/lib/esm/util/normalizeValue.js
var normalizeValue, normalizeValue_default;
var init_normalizeValue = __esm({
  "node_modules/form-data-encoder/lib/esm/util/normalizeValue.js"() {
    init_esbuild_shims();
    normalizeValue = /* @__PURE__ */ __name((value) => String(value).replace(/\r|\n/g, (match2, i3, str2) => {
      if (match2 === "\r" && str2[i3 + 1] !== "\n" || match2 === "\n" && str2[i3 - 1] !== "\r") {
        return "\r\n";
      }
      return match2;
    }), "normalizeValue");
    normalizeValue_default = normalizeValue;
  }
});

// node_modules/form-data-encoder/lib/esm/util/escapeName.js
var escapeName, escapeName_default;
var init_escapeName = __esm({
  "node_modules/form-data-encoder/lib/esm/util/escapeName.js"() {
    init_esbuild_shims();
    escapeName = /* @__PURE__ */ __name((name3) => String(name3).replace(/\r/g, "%0D").replace(/\n/g, "%0A").replace(/"/g, "%22"), "escapeName");
    escapeName_default = escapeName;
  }
});

// node_modules/form-data-encoder/lib/esm/util/isFunction.js
var isFunction2, isFunction_default;
var init_isFunction2 = __esm({
  "node_modules/form-data-encoder/lib/esm/util/isFunction.js"() {
    init_esbuild_shims();
    isFunction2 = /* @__PURE__ */ __name((value) => typeof value === "function", "isFunction");
    isFunction_default = isFunction2;
  }
});

// node_modules/form-data-encoder/lib/esm/util/isFileLike.js
var isFileLike2;
var init_isFileLike = __esm({
  "node_modules/form-data-encoder/lib/esm/util/isFileLike.js"() {
    init_esbuild_shims();
    init_isFunction2();
    isFileLike2 = /* @__PURE__ */ __name((value) => Boolean(value && typeof value === "object" && isFunction_default(value.constructor) && value[Symbol.toStringTag] === "File" && isFunction_default(value.stream) && value.name != null && value.size != null && value.lastModified != null), "isFileLike");
  }
});

// node_modules/form-data-encoder/lib/esm/util/isFormData.js
var isFormData;
var init_isFormData = __esm({
  "node_modules/form-data-encoder/lib/esm/util/isFormData.js"() {
    init_esbuild_shims();
    init_isFunction2();
    isFormData = /* @__PURE__ */ __name((value) => Boolean(value && isFunction_default(value.constructor) && value[Symbol.toStringTag] === "FormData" && isFunction_default(value.append) && isFunction_default(value.getAll) && isFunction_default(value.entries) && isFunction_default(value[Symbol.iterator])), "isFormData");
  }
});

// node_modules/form-data-encoder/lib/esm/FormDataEncoder.js
var __classPrivateFieldSet4, __classPrivateFieldGet5, _FormDataEncoder_instances, _FormDataEncoder_CRLF, _FormDataEncoder_CRLF_BYTES, _FormDataEncoder_CRLF_BYTES_LENGTH, _FormDataEncoder_DASHES, _FormDataEncoder_encoder, _FormDataEncoder_footer, _FormDataEncoder_form, _FormDataEncoder_options, _FormDataEncoder_getFieldHeader, defaultOptions, FormDataEncoder;
var init_FormDataEncoder = __esm({
  "node_modules/form-data-encoder/lib/esm/FormDataEncoder.js"() {
    init_esbuild_shims();
    init_createBoundary();
    init_isPlainObject();
    init_normalizeValue();
    init_escapeName();
    init_isFileLike();
    init_isFormData();
    __classPrivateFieldSet4 = function(receiver, state, value, kind2, f5) {
      if (kind2 === "m") throw new TypeError("Private method is not writable");
      if (kind2 === "a" && !f5) throw new TypeError("Private accessor was defined without a setter");
      if (typeof state === "function" ? receiver !== state || !f5 : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
      return kind2 === "a" ? f5.call(receiver, value) : f5 ? f5.value = value : state.set(receiver, value), value;
    };
    __classPrivateFieldGet5 = function(receiver, state, kind2, f5) {
      if (kind2 === "a" && !f5) throw new TypeError("Private accessor was defined without a getter");
      if (typeof state === "function" ? receiver !== state || !f5 : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
      return kind2 === "m" ? f5 : kind2 === "a" ? f5.call(receiver) : f5 ? f5.value : state.get(receiver);
    };
    defaultOptions = {
      enableAdditionalHeaders: false
    };
    FormDataEncoder = class {
      static {
        __name(this, "FormDataEncoder");
      }
      constructor(form, boundaryOrOptions, options2) {
        _FormDataEncoder_instances.add(this);
        _FormDataEncoder_CRLF.set(this, "\r\n");
        _FormDataEncoder_CRLF_BYTES.set(this, void 0);
        _FormDataEncoder_CRLF_BYTES_LENGTH.set(this, void 0);
        _FormDataEncoder_DASHES.set(this, "-".repeat(2));
        _FormDataEncoder_encoder.set(this, new TextEncoder());
        _FormDataEncoder_footer.set(this, void 0);
        _FormDataEncoder_form.set(this, void 0);
        _FormDataEncoder_options.set(this, void 0);
        if (!isFormData(form)) {
          throw new TypeError("Expected first argument to be a FormData instance.");
        }
        let boundary;
        if (isPlainObject_default(boundaryOrOptions)) {
          options2 = boundaryOrOptions;
        } else {
          boundary = boundaryOrOptions;
        }
        if (!boundary) {
          boundary = createBoundary_default();
        }
        if (typeof boundary !== "string") {
          throw new TypeError("Expected boundary argument to be a string.");
        }
        if (options2 && !isPlainObject_default(options2)) {
          throw new TypeError("Expected options argument to be an object.");
        }
        __classPrivateFieldSet4(this, _FormDataEncoder_form, form, "f");
        __classPrivateFieldSet4(this, _FormDataEncoder_options, { ...defaultOptions, ...options2 }, "f");
        __classPrivateFieldSet4(this, _FormDataEncoder_CRLF_BYTES, __classPrivateFieldGet5(this, _FormDataEncoder_encoder, "f").encode(__classPrivateFieldGet5(this, _FormDataEncoder_CRLF, "f")), "f");
        __classPrivateFieldSet4(this, _FormDataEncoder_CRLF_BYTES_LENGTH, __classPrivateFieldGet5(this, _FormDataEncoder_CRLF_BYTES, "f").byteLength, "f");
        this.boundary = `form-data-boundary-${boundary}`;
        this.contentType = `multipart/form-data; boundary=${this.boundary}`;
        __classPrivateFieldSet4(this, _FormDataEncoder_footer, __classPrivateFieldGet5(this, _FormDataEncoder_encoder, "f").encode(`${__classPrivateFieldGet5(this, _FormDataEncoder_DASHES, "f")}${this.boundary}${__classPrivateFieldGet5(this, _FormDataEncoder_DASHES, "f")}${__classPrivateFieldGet5(this, _FormDataEncoder_CRLF, "f").repeat(2)}`), "f");
        this.contentLength = String(this.getContentLength());
        this.headers = Object.freeze({
          "Content-Type": this.contentType,
          "Content-Length": this.contentLength
        });
        Object.defineProperties(this, {
          boundary: { writable: false, configurable: false },
          contentType: { writable: false, configurable: false },
          contentLength: { writable: false, configurable: false },
          headers: { writable: false, configurable: false }
        });
      }
      getContentLength() {
        let length = 0;
        for (const [name3, raw2] of __classPrivateFieldGet5(this, _FormDataEncoder_form, "f")) {
          const value = isFileLike2(raw2) ? raw2 : __classPrivateFieldGet5(this, _FormDataEncoder_encoder, "f").encode(normalizeValue_default(raw2));
          length += __classPrivateFieldGet5(this, _FormDataEncoder_instances, "m", _FormDataEncoder_getFieldHeader).call(this, name3, value).byteLength;
          length += isFileLike2(value) ? value.size : value.byteLength;
          length += __classPrivateFieldGet5(this, _FormDataEncoder_CRLF_BYTES_LENGTH, "f");
        }
        return length + __classPrivateFieldGet5(this, _FormDataEncoder_footer, "f").byteLength;
      }
      *values() {
        for (const [name3, raw2] of __classPrivateFieldGet5(this, _FormDataEncoder_form, "f").entries()) {
          const value = isFileLike2(raw2) ? raw2 : __classPrivateFieldGet5(this, _FormDataEncoder_encoder, "f").encode(normalizeValue_default(raw2));
          yield __classPrivateFieldGet5(this, _FormDataEncoder_instances, "m", _FormDataEncoder_getFieldHeader).call(this, name3, value);
          yield value;
          yield __classPrivateFieldGet5(this, _FormDataEncoder_CRLF_BYTES, "f");
        }
        yield __classPrivateFieldGet5(this, _FormDataEncoder_footer, "f");
      }
      async *encode() {
        for (const part of this.values()) {
          if (isFileLike2(part)) {
            yield* part.stream();
          } else {
            yield part;
          }
        }
      }
      [(_FormDataEncoder_CRLF = /* @__PURE__ */ new WeakMap(), _FormDataEncoder_CRLF_BYTES = /* @__PURE__ */ new WeakMap(), _FormDataEncoder_CRLF_BYTES_LENGTH = /* @__PURE__ */ new WeakMap(), _FormDataEncoder_DASHES = /* @__PURE__ */ new WeakMap(), _FormDataEncoder_encoder = /* @__PURE__ */ new WeakMap(), _FormDataEncoder_footer = /* @__PURE__ */ new WeakMap(), _FormDataEncoder_form = /* @__PURE__ */ new WeakMap(), _FormDataEncoder_options = /* @__PURE__ */ new WeakMap(), _FormDataEncoder_instances = /* @__PURE__ */ new WeakSet(), _FormDataEncoder_getFieldHeader = /* @__PURE__ */ __name(function _FormDataEncoder_getFieldHeader2(name3, value) {
        let header = "";
        header += `${__classPrivateFieldGet5(this, _FormDataEncoder_DASHES, "f")}${this.boundary}${__classPrivateFieldGet5(this, _FormDataEncoder_CRLF, "f")}`;
        header += `Content-Disposition: form-data; name="${escapeName_default(name3)}"`;
        if (isFileLike2(value)) {
          header += `; filename="${escapeName_default(value.name)}"${__classPrivateFieldGet5(this, _FormDataEncoder_CRLF, "f")}`;
          header += `Content-Type: ${value.type || "application/octet-stream"}`;
        }
        if (__classPrivateFieldGet5(this, _FormDataEncoder_options, "f").enableAdditionalHeaders === true) {
          header += `${__classPrivateFieldGet5(this, _FormDataEncoder_CRLF, "f")}Content-Length: ${isFileLike2(value) ? value.size : value.byteLength}`;
        }
        return __classPrivateFieldGet5(this, _FormDataEncoder_encoder, "f").encode(`${header}${__classPrivateFieldGet5(this, _FormDataEncoder_CRLF, "f").repeat(2)}`);
      }, "_FormDataEncoder_getFieldHeader"), Symbol.iterator)]() {
        return this.values();
      }
      [Symbol.asyncIterator]() {
        return this.encode();
      }
    };
  }
});

// node_modules/form-data-encoder/lib/esm/FileLike.js
var init_FileLike = __esm({
  "node_modules/form-data-encoder/lib/esm/FileLike.js"() {
    init_esbuild_shims();
  }
});

// node_modules/form-data-encoder/lib/esm/FormDataLike.js
var init_FormDataLike = __esm({
  "node_modules/form-data-encoder/lib/esm/FormDataLike.js"() {
    init_esbuild_shims();
  }
});

// node_modules/form-data-encoder/lib/esm/index.js
var init_esm6 = __esm({
  "node_modules/form-data-encoder/lib/esm/index.js"() {
    init_esbuild_shims();
    init_FormDataEncoder();
    init_FileLike();
    init_FormDataLike();
    init_isFileLike();
    init_isFormData();
  }
});

// node_modules/@anthropic-ai/sdk/_shims/MultipartBody.mjs
var MultipartBody;
var init_MultipartBody = __esm({
  "node_modules/@anthropic-ai/sdk/_shims/MultipartBody.mjs"() {
    init_esbuild_shims();
    MultipartBody = class {
      static {
        __name(this, "MultipartBody");
      }
      constructor(body) {
        this.body = body;
      }
      get [Symbol.toStringTag]() {
        return "MultipartBody";
      }
    };
  }
});

// node_modules/formdata-node/lib/esm/isPlainObject.js
function isPlainObject2(value) {
  if (getType2(value) !== "object") {
    return false;
  }
  const pp = Object.getPrototypeOf(value);
  if (pp === null || pp === void 0) {
    return true;
  }
  const Ctor = pp.constructor && pp.constructor.toString();
  return Ctor === Object.toString();
}
var getType2, isPlainObject_default2;
var init_isPlainObject2 = __esm({
  "node_modules/formdata-node/lib/esm/isPlainObject.js"() {
    init_esbuild_shims();
    getType2 = /* @__PURE__ */ __name((value) => Object.prototype.toString.call(value).slice(8, -1).toLowerCase(), "getType");
    __name(isPlainObject2, "isPlainObject");
    isPlainObject_default2 = isPlainObject2;
  }
});

// node_modules/formdata-node/lib/esm/fileFromPath.js
var fileFromPath_exports = {};
__export(fileFromPath_exports, {
  fileFromPath: () => fileFromPath2,
  fileFromPathSync: () => fileFromPathSync,
  isFile: () => isFile
});
import { statSync as statSync2, createReadStream as createReadStream2, promises as fs17 } from "fs";
import { basename as basename3 } from "path";
function createFileFromPath(path125, { mtimeMs, size }, filenameOrOptions, options2 = {}) {
  let filename;
  if (isPlainObject_default2(filenameOrOptions)) {
    [options2, filename] = [filenameOrOptions, void 0];
  } else {
    filename = filenameOrOptions;
  }
  const file = new FileFromPath({ path: path125, size, lastModified: mtimeMs });
  if (!filename) {
    filename = file.name;
  }
  return new File5([file], filename, {
    ...options2,
    lastModified: file.lastModified
  });
}
function fileFromPathSync(path125, filenameOrOptions, options2 = {}) {
  const stats = statSync2(path125);
  return createFileFromPath(path125, stats, filenameOrOptions, options2);
}
async function fileFromPath2(path125, filenameOrOptions, options2) {
  const stats = await fs17.stat(path125);
  return createFileFromPath(path125, stats, filenameOrOptions, options2);
}
var import_node_domexception2, __classPrivateFieldSet5, __classPrivateFieldGet6, _FileFromPath_path, _FileFromPath_start, MESSAGE, FileFromPath;
var init_fileFromPath = __esm({
  "node_modules/formdata-node/lib/esm/fileFromPath.js"() {
    init_esbuild_shims();
    import_node_domexception2 = __toESM(require_node_domexception(), 1);
    init_File();
    init_isPlainObject2();
    init_isFile();
    __classPrivateFieldSet5 = function(receiver, state, value, kind2, f5) {
      if (kind2 === "m") throw new TypeError("Private method is not writable");
      if (kind2 === "a" && !f5) throw new TypeError("Private accessor was defined without a setter");
      if (typeof state === "function" ? receiver !== state || !f5 : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
      return kind2 === "a" ? f5.call(receiver, value) : f5 ? f5.value = value : state.set(receiver, value), value;
    };
    __classPrivateFieldGet6 = function(receiver, state, kind2, f5) {
      if (kind2 === "a" && !f5) throw new TypeError("Private accessor was defined without a getter");
      if (typeof state === "function" ? receiver !== state || !f5 : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
      return kind2 === "m" ? f5 : kind2 === "a" ? f5.call(receiver) : f5 ? f5.value : state.get(receiver);
    };
    MESSAGE = "The requested file could not be read, typically due to permission problems that have occurred after a reference to a file was acquired.";
    FileFromPath = class _FileFromPath {
      static {
        __name(this, "FileFromPath");
      }
      constructor(input) {
        _FileFromPath_path.set(this, void 0);
        _FileFromPath_start.set(this, void 0);
        __classPrivateFieldSet5(this, _FileFromPath_path, input.path, "f");
        __classPrivateFieldSet5(this, _FileFromPath_start, input.start || 0, "f");
        this.name = basename3(__classPrivateFieldGet6(this, _FileFromPath_path, "f"));
        this.size = input.size;
        this.lastModified = input.lastModified;
      }
      slice(start, end) {
        return new _FileFromPath({
          path: __classPrivateFieldGet6(this, _FileFromPath_path, "f"),
          lastModified: this.lastModified,
          size: end - start,
          start
        });
      }
      async *stream() {
        const { mtimeMs } = await fs17.stat(__classPrivateFieldGet6(this, _FileFromPath_path, "f"));
        if (mtimeMs > this.lastModified) {
          throw new import_node_domexception2.default(MESSAGE, "NotReadableError");
        }
        if (this.size) {
          yield* createReadStream2(__classPrivateFieldGet6(this, _FileFromPath_path, "f"), {
            start: __classPrivateFieldGet6(this, _FileFromPath_start, "f"),
            end: __classPrivateFieldGet6(this, _FileFromPath_start, "f") + this.size - 1
          });
        }
      }
      get [(_FileFromPath_path = /* @__PURE__ */ new WeakMap(), _FileFromPath_start = /* @__PURE__ */ new WeakMap(), Symbol.toStringTag)]() {
        return "File";
      }
    };
    __name(createFileFromPath, "createFileFromPath");
    __name(fileFromPathSync, "fileFromPathSync");
    __name(fileFromPath2, "fileFromPath");
  }
});

// node_modules/@anthropic-ai/sdk/_shims/node-runtime.mjs
import { ReadStream as FsReadStream } from "node:fs";
import { Readable as Readable3 } from "node:stream";
import { ReadableStream as ReadableStream4 } from "node:stream/web";
async function fileFromPath3(path125, ...args) {
  const { fileFromPath: _fileFromPath } = await Promise.resolve().then(() => (init_fileFromPath(), fileFromPath_exports));
  if (!fileFromPathWarned) {
    console.warn(`fileFromPath is deprecated; use fs.createReadStream(${JSON.stringify(path125)}) instead`);
    fileFromPathWarned = true;
  }
  return await _fileFromPath(path125, ...args);
}
async function getMultipartRequestOptions2(form, opts) {
  const encoder = new FormDataEncoder(form);
  const readable = Readable3.from(encoder);
  const body = new MultipartBody(readable);
  const headers = {
    ...opts.headers,
    ...encoder.headers,
    "Content-Length": encoder.contentLength
  };
  return { ...opts, body, headers };
}
function getRuntime() {
  if (typeof AbortController === "undefined") {
    globalThis.AbortController = import_abort_controller.AbortController;
  }
  return {
    kind: "node",
    fetch: nf.default,
    Request: nf.Request,
    Response: nf.Response,
    Headers: nf.Headers,
    FormData: FormData5,
    Blob: Blob5,
    File: File5,
    ReadableStream: ReadableStream4,
    getMultipartRequestOptions: getMultipartRequestOptions2,
    getDefaultAgent: /* @__PURE__ */ __name((url2) => url2.startsWith("https") ? defaultHttpsAgent : defaultHttpAgent, "getDefaultAgent"),
    fileFromPath: fileFromPath3,
    isFsReadStream: /* @__PURE__ */ __name((value) => value instanceof FsReadStream, "isFsReadStream")
  };
}
var nf, import_agentkeepalive, import_abort_controller, fileFromPathWarned, defaultHttpAgent, defaultHttpsAgent;
var init_node_runtime = __esm({
  "node_modules/@anthropic-ai/sdk/_shims/node-runtime.mjs"() {
    init_esbuild_shims();
    nf = __toESM(require_lib2(), 1);
    init_esm5();
    import_agentkeepalive = __toESM(require_agentkeepalive(), 1);
    import_abort_controller = __toESM(require_abort_controller(), 1);
    init_esm6();
    init_MultipartBody();
    fileFromPathWarned = false;
    __name(fileFromPath3, "fileFromPath");
    defaultHttpAgent = new import_agentkeepalive.default({ keepAlive: true, timeout: 5 * 60 * 1e3 });
    defaultHttpsAgent = new import_agentkeepalive.default.HttpsAgent({ keepAlive: true, timeout: 5 * 60 * 1e3 });
    __name(getMultipartRequestOptions2, "getMultipartRequestOptions");
    __name(getRuntime, "getRuntime");
  }
});

// node_modules/@anthropic-ai/sdk/_shims/auto/runtime-node.mjs
var init_runtime_node = __esm({
  "node_modules/@anthropic-ai/sdk/_shims/auto/runtime-node.mjs"() {
    init_esbuild_shims();
    init_node_runtime();
  }
});

// node_modules/@anthropic-ai/sdk/_shims/index.mjs
var init_shims2 = __esm({
  "node_modules/@anthropic-ai/sdk/_shims/index.mjs"() {
    init_esbuild_shims();
    init_registry();
    init_runtime_node();
    init_registry();
    if (!kind) setShims(getRuntime(), { auto: true });
  }
});

// node_modules/@anthropic-ai/sdk/error.mjs
var AnthropicError, APIError2, APIUserAbortError2, APIConnectionError2, APIConnectionTimeoutError2, BadRequestError3, AuthenticationError2, PermissionDeniedError2, NotFoundError2, ConflictError2, UnprocessableEntityError2, RateLimitError2, InternalServerError2;
var init_error3 = __esm({
  "node_modules/@anthropic-ai/sdk/error.mjs"() {
    init_esbuild_shims();
    init_core();
    AnthropicError = class extends Error {
      static {
        __name(this, "AnthropicError");
      }
    };
    APIError2 = class _APIError extends AnthropicError {
      static {
        __name(this, "APIError");
      }
      constructor(status, error2, message, headers) {
        super(`${_APIError.makeMessage(status, error2, message)}`);
        this.status = status;
        this.headers = headers;
        this.request_id = headers?.["request-id"];
        this.error = error2;
      }
      static makeMessage(status, error2, message) {
        const msg = error2?.message ? typeof error2.message === "string" ? error2.message : JSON.stringify(error2.message) : error2 ? JSON.stringify(error2) : 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 APIConnectionError2({ message, cause: castToError2(errorResponse) });
        }
        const error2 = errorResponse;
        if (status === 400) {
          return new BadRequestError3(status, error2, message, headers);
        }
        if (status === 401) {
          return new AuthenticationError2(status, error2, message, headers);
        }
        if (status === 403) {
          return new PermissionDeniedError2(status, error2, message, headers);
        }
        if (status === 404) {
          return new NotFoundError2(status, error2, message, headers);
        }
        if (status === 409) {
          return new ConflictError2(status, error2, message, headers);
        }
        if (status === 422) {
          return new UnprocessableEntityError2(status, error2, message, headers);
        }
        if (status === 429) {
          return new RateLimitError2(status, error2, message, headers);
        }
        if (status >= 500) {
          return new InternalServerError2(status, error2, message, headers);
        }
        return new _APIError(status, error2, message, headers);
      }
    };
    APIUserAbortError2 = class extends APIError2 {
      static {
        __name(this, "APIUserAbortError");
      }
      constructor({ message } = {}) {
        super(void 0, void 0, message || "Request was aborted.", void 0);
      }
    };
    APIConnectionError2 = class extends APIError2 {
      static {
        __name(this, "APIConnectionError");
      }
      constructor({ message, cause }) {
        super(void 0, void 0, message || "Connection error.", void 0);
        if (cause)
          this.cause = cause;
      }
    };
    APIConnectionTimeoutError2 = class extends APIConnectionError2 {
      static {
        __name(this, "APIConnectionTimeoutError");
      }
      constructor({ message } = {}) {
        super({ message: message ?? "Request timed out." });
      }
    };
    BadRequestError3 = class extends APIError2 {
      static {
        __name(this, "BadRequestError");
      }
    };
    AuthenticationError2 = class extends APIError2 {
      static {
        __name(this, "AuthenticationError");
      }
    };
    PermissionDeniedError2 = class extends APIError2 {
      static {
        __name(this, "PermissionDeniedError");
      }
    };
    NotFoundError2 = class extends APIError2 {
      static {
        __name(this, "NotFoundError");
      }
    };
    ConflictError2 = class extends APIError2 {
      static {
        __name(this, "ConflictError");
      }
    };
    UnprocessableEntityError2 = class extends APIError2 {
      static {
        __name(this, "UnprocessableEntityError");
      }
    };
    RateLimitError2 = class extends APIError2 {
      static {
        __name(this, "RateLimitError");
      }
    };
    InternalServerError2 = class extends APIError2 {
      static {
        __name(this, "InternalServerError");
      }
    };
  }
});

// node_modules/@anthropic-ai/sdk/internal/decoders/line.mjs
var LineDecoder2;
var init_line2 = __esm({
  "node_modules/@anthropic-ai/sdk/internal/decoders/line.mjs"() {
    init_esbuild_shims();
    init_error3();
    LineDecoder2 = class _LineDecoder {
      static {
        __name(this, "LineDecoder");
      }
      constructor() {
        this.buffer = [];
        this.trailingCR = false;
      }
      decode(chunk) {
        let text = this.decodeText(chunk);
        if (this.trailingCR) {
          text = "\r" + text;
          this.trailingCR = false;
        }
        if (text.endsWith("\r")) {
          this.trailingCR = true;
          text = text.slice(0, -1);
        }
        if (!text) {
          return [];
        }
        const trailingNewline = _LineDecoder.NEWLINE_CHARS.has(text[text.length - 1] || "");
        let lines = text.split(_LineDecoder.NEWLINE_REGEXP);
        if (trailingNewline) {
          lines.pop();
        }
        if (lines.length === 1 && !trailingNewline) {
          this.buffer.push(lines[0]);
          return [];
        }
        if (this.buffer.length > 0) {
          lines = [this.buffer.join("") + lines[0], ...lines.slice(1)];
          this.buffer = [];
        }
        if (!trailingNewline) {
          this.buffer = [lines.pop() || ""];
        }
        return lines;
      }
      decodeText(bytes) {
        if (bytes == null)
          return "";
        if (typeof bytes === "string")
          return bytes;
        if (typeof Buffer !== "undefined") {
          if (bytes instanceof Buffer) {
            return bytes.toString();
          }
          if (bytes instanceof Uint8Array) {
            return Buffer.from(bytes).toString();
          }
          throw new AnthropicError(`Unexpected: received non-Uint8Array (${bytes.constructor.name}) stream chunk in an environment with a global "Buffer" defined, which this library assumes to be Node. Please report this error.`);
        }
        if (typeof TextDecoder !== "undefined") {
          if (bytes instanceof Uint8Array || bytes instanceof ArrayBuffer) {
            this.textDecoder ?? (this.textDecoder = new TextDecoder("utf8"));
            return this.textDecoder.decode(bytes);
          }
          throw new AnthropicError(`Unexpected: received non-Uint8Array/ArrayBuffer (${bytes.constructor.name}) in a web platform. Please report this error.`);
        }
        throw new AnthropicError(`Unexpected: neither Buffer nor TextDecoder are available as globals. Please report this error.`);
      }
      flush() {
        if (!this.buffer.length && !this.trailingCR) {
          return [];
        }
        const lines = [this.buffer.join("")];
        this.buffer = [];
        this.trailingCR = false;
        return lines;
      }
    };
    LineDecoder2.NEWLINE_CHARS = /* @__PURE__ */ new Set(["\n", "\r"]);
    LineDecoder2.NEWLINE_REGEXP = /\r\n|[\n\r]/g;
  }
});

// node_modules/@anthropic-ai/sdk/internal/stream-utils.mjs
function ReadableStreamToAsyncIterable2(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 (e4) {
        reader.releaseLock();
        throw e4;
      }
    },
    async return() {
      const cancelPromise = reader.cancel();
      reader.releaseLock();
      await cancelPromise;
      return { done: true, value: void 0 };
    },
    [Symbol.asyncIterator]() {
      return this;
    }
  };
}
var init_stream_utils = __esm({
  "node_modules/@anthropic-ai/sdk/internal/stream-utils.mjs"() {
    init_esbuild_shims();
    __name(ReadableStreamToAsyncIterable2, "ReadableStreamToAsyncIterable");
  }
});

// node_modules/@anthropic-ai/sdk/streaming.mjs
async function* _iterSSEMessages2(response, controller) {
  if (!response.body) {
    controller.abort();
    throw new AnthropicError(`Attempted to iterate over a response with no body`);
  }
  const sseDecoder = new SSEDecoder2();
  const lineDecoder = new LineDecoder2();
  const iter = ReadableStreamToAsyncIterable2(response.body);
  for await (const sseChunk of iterSSEChunks2(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* iterSSEChunks2(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" ? new TextEncoder().encode(chunk) : chunk;
    let newData = new Uint8Array(data.length + binaryChunk.length);
    newData.set(data);
    newData.set(binaryChunk, data.length);
    data = newData;
    let patternIndex;
    while ((patternIndex = findDoubleNewlineIndex2(data)) !== -1) {
      yield data.slice(0, patternIndex);
      data = data.slice(patternIndex);
    }
  }
  if (data.length > 0) {
    yield data;
  }
}
function findDoubleNewlineIndex2(buffer) {
  const newline2 = 10;
  const carriage = 13;
  for (let i3 = 0; i3 < buffer.length - 2; i3++) {
    if (buffer[i3] === newline2 && buffer[i3 + 1] === newline2) {
      return i3 + 2;
    }
    if (buffer[i3] === carriage && buffer[i3 + 1] === carriage) {
      return i3 + 2;
    }
    if (buffer[i3] === carriage && buffer[i3 + 1] === newline2 && i3 + 3 < buffer.length && buffer[i3 + 2] === carriage && buffer[i3 + 3] === newline2) {
      return i3 + 4;
    }
  }
  return -1;
}
function partition2(str2, delimiter2) {
  const index = str2.indexOf(delimiter2);
  if (index !== -1) {
    return [str2.substring(0, index), delimiter2, str2.substring(index + delimiter2.length)];
  }
  return [str2, "", ""];
}
var Stream4, SSEDecoder2;
var init_streaming3 = __esm({
  "node_modules/@anthropic-ai/sdk/streaming.mjs"() {
    init_esbuild_shims();
    init_shims2();
    init_error3();
    init_line2();
    init_stream_utils();
    init_core();
    init_error3();
    Stream4 = class _Stream {
      static {
        __name(this, "Stream");
      }
      constructor(iterator, controller) {
        this.iterator = iterator;
        this.controller = controller;
      }
      static fromSSEResponse(response, controller) {
        let consumed = false;
        async function* iterator() {
          if (consumed) {
            throw new Error("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");
          }
          consumed = true;
          let done = false;
          try {
            for await (const sse of _iterSSEMessages2(response, controller)) {
              if (sse.event === "completion") {
                try {
                  yield JSON.parse(sse.data);
                } catch (e4) {
                  console.error(`Could not parse message into JSON:`, sse.data);
                  console.error(`From chunk:`, sse.raw);
                  throw e4;
                }
              }
              if (sse.event === "message_start" || sse.event === "message_delta" || sse.event === "message_stop" || sse.event === "content_block_start" || sse.event === "content_block_delta" || sse.event === "content_block_stop") {
                try {
                  yield JSON.parse(sse.data);
                } catch (e4) {
                  console.error(`Could not parse message into JSON:`, sse.data);
                  console.error(`From chunk:`, sse.raw);
                  throw e4;
                }
              }
              if (sse.event === "ping") {
                continue;
              }
              if (sse.event === "error") {
                throw APIError2.generate(void 0, `SSE Error: ${sse.data}`, sse.data, createResponseHeaders(response.headers));
              }
            }
            done = true;
          } catch (e4) {
            if (e4 instanceof Error && e4.name === "AbortError")
              return;
            throw e4;
          } finally {
            if (!done)
              controller.abort();
          }
        }
        __name(iterator, "iterator");
        return new _Stream(iterator, controller);
      }
      /**
       * Generates a Stream from a newline-separated ReadableStream
       * where each item is a JSON value.
       */
      static fromReadableStream(readableStream, controller) {
        let consumed = false;
        async function* iterLines() {
          const lineDecoder = new LineDecoder2();
          const iter = ReadableStreamToAsyncIterable2(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 Error("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 (e4) {
            if (e4 instanceof Error && e4.name === "AbortError")
              return;
            throw e4;
          } finally {
            if (!done)
              controller.abort();
          }
        }
        __name(iterator, "iterator");
        return new _Stream(iterator, controller);
      }
      [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),
          new _Stream(() => teeIterator(right3), this.controller)
        ];
      }
      /**
       * 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;
        const encoder = new TextEncoder();
        return new ReadableStream2({
          async start() {
            iter = self2[Symbol.asyncIterator]();
          },
          async pull(ctrl) {
            try {
              const { value, done } = await iter.next();
              if (done)
                return ctrl.close();
              const bytes = encoder.encode(JSON.stringify(value) + "\n");
              ctrl.enqueue(bytes);
            } catch (err) {
              ctrl.error(err);
            }
          },
          async cancel() {
            await iter.return?.();
          }
        });
      }
    };
    __name(_iterSSEMessages2, "_iterSSEMessages");
    __name(iterSSEChunks2, "iterSSEChunks");
    __name(findDoubleNewlineIndex2, "findDoubleNewlineIndex");
    SSEDecoder2 = 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, _2, value] = partition2(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(partition2, "partition");
  }
});

// node_modules/@anthropic-ai/sdk/uploads.mjs
async function toFile2(value, name3, options2) {
  value = await value;
  if (isFileLike3(value)) {
    return value;
  }
  if (isResponseLike2(value)) {
    const blob = await value.blob();
    name3 || (name3 = new URL(value.url).pathname.split(/[\\/]/).pop() ?? "unknown_file");
    const data = isBlobLike2(blob) ? [await blob.arrayBuffer()] : [blob];
    return new File4(data, name3, options2);
  }
  const bits = await getBytes2(value);
  name3 || (name3 = getName2(value) ?? "unknown_file");
  if (!options2?.type) {
    const type = bits[0]?.type;
    if (typeof type === "string") {
      options2 = { ...options2, type };
    }
  }
  return new File4(bits, name3, options2);
}
async function getBytes2(value) {
  let parts = [];
  if (typeof value === "string" || ArrayBuffer.isView(value) || // includes Uint8Array, Buffer, etc.
  value instanceof ArrayBuffer) {
    parts.push(value);
  } else if (isBlobLike2(value)) {
    parts.push(await value.arrayBuffer());
  } else if (isAsyncIterableIterator(value)) {
    for await (const chunk of value) {
      parts.push(chunk);
    }
  } else {
    throw new Error(`Unexpected data type: ${typeof value}; constructor: ${value?.constructor?.name}; props: ${propsForError2(value)}`);
  }
  return parts;
}
function propsForError2(value) {
  const props = Object.getOwnPropertyNames(value);
  return `[${props.map((p2) => `"${p2}"`).join(", ")}]`;
}
function getName2(value) {
  return getStringFromMaybeBuffer(value.name) || getStringFromMaybeBuffer(value.filename) || // For fs.ReadStream
  getStringFromMaybeBuffer(value.path)?.split(/[\\/]/).pop();
}
var isResponseLike2, isFileLike3, isBlobLike2, getStringFromMaybeBuffer, isAsyncIterableIterator, isMultipartBody;
var init_uploads4 = __esm({
  "node_modules/@anthropic-ai/sdk/uploads.mjs"() {
    init_esbuild_shims();
    init_shims2();
    init_shims2();
    isResponseLike2 = /* @__PURE__ */ __name((value) => value != null && typeof value === "object" && typeof value.url === "string" && typeof value.blob === "function", "isResponseLike");
    isFileLike3 = /* @__PURE__ */ __name((value) => value != null && typeof value === "object" && typeof value.name === "string" && typeof value.lastModified === "number" && isBlobLike2(value), "isFileLike");
    isBlobLike2 = /* @__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");
    __name(toFile2, "toFile");
    __name(getBytes2, "getBytes");
    __name(propsForError2, "propsForError");
    __name(getName2, "getName");
    getStringFromMaybeBuffer = /* @__PURE__ */ __name((x3) => {
      if (typeof x3 === "string")
        return x3;
      if (typeof Buffer !== "undefined" && x3 instanceof Buffer)
        return String(x3);
      return void 0;
    }, "getStringFromMaybeBuffer");
    isAsyncIterableIterator = /* @__PURE__ */ __name((value) => value != null && typeof value === "object" && typeof value[Symbol.asyncIterator] === "function", "isAsyncIterableIterator");
    isMultipartBody = /* @__PURE__ */ __name((body) => body && typeof body === "object" && body.body && body[Symbol.toStringTag] === "MultipartBody", "isMultipartBody");
  }
});

// node_modules/@anthropic-ai/sdk/core.mjs
async function defaultParseResponse2(props) {
  const { response } = props;
  if (props.options.stream) {
    debug("response", response.status, response.url, response.headers, response.body);
    if (props.options.__streamClass) {
      return props.options.__streamClass.fromSSEResponse(response, props.controller);
    }
    return Stream4.fromSSEResponse(response, props.controller);
  }
  if (response.status === 204) {
    return null;
  }
  if (props.options.__binaryResponse) {
    return response;
  }
  const contentType = response.headers.get("content-type");
  const isJSON = contentType?.includes("application/json") || contentType?.includes("application/vnd.api+json");
  if (isJSON) {
    const json2 = await response.json();
    debug("response", response.status, response.url, response.headers, json2);
    return _addRequestID(json2, response);
  }
  const text = await response.text();
  debug("response", response.status, response.url, response.headers, text);
  return text;
}
function _addRequestID(value, response) {
  if (!value || typeof value !== "object" || Array.isArray(value)) {
    return value;
  }
  return Object.defineProperty(value, "_request_id", {
    value: response.headers.get("request-id"),
    enumerable: false
  });
}
function getBrowserInfo2() {
  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;
}
function isEmptyObj2(obj) {
  if (!obj)
    return true;
  for (const _k in obj)
    return false;
  return true;
}
function hasOwn2(obj, key) {
  return Object.prototype.hasOwnProperty.call(obj, key);
}
function applyHeadersMut(targetHeaders, newHeaders) {
  for (const k2 in newHeaders) {
    if (!hasOwn2(newHeaders, k2))
      continue;
    const lowerKey = k2.toLowerCase();
    if (!lowerKey)
      continue;
    const val = newHeaders[k2];
    if (val === null) {
      delete targetHeaders[lowerKey];
    } else if (val !== void 0) {
      targetHeaders[lowerKey] = val;
    }
  }
}
function debug(action, ...args) {
  if (typeof process !== "undefined" && process?.env?.["DEBUG"] === "true") {
    console.log(`Anthropic:DEBUG:${action}`, ...args);
  }
}
var __classPrivateFieldSet6, __classPrivateFieldGet7, _AbstractPage_client2, APIPromise2, APIClient, AbstractPage2, PagePromise2, createResponseHeaders, requestOptionsKeys, isRequestOptions, getPlatformProperties2, normalizeArch2, normalizePlatform2, _platformHeaders2, getPlatformHeaders2, safeJSON2, startsWithSchemeRegexp2, isAbsoluteURL2, sleep3, validatePositiveInteger2, castToError2, readEnv2, uuid42, isRunningInBrowser2, isHeadersProtocol, getHeader;
var init_core = __esm({
  "node_modules/@anthropic-ai/sdk/core.mjs"() {
    init_esbuild_shims();
    init_version3();
    init_streaming3();
    init_error3();
    init_shims2();
    init_uploads4();
    __classPrivateFieldSet6 = function(receiver, state, value, kind2, f5) {
      if (kind2 === "m") throw new TypeError("Private method is not writable");
      if (kind2 === "a" && !f5) throw new TypeError("Private accessor was defined without a setter");
      if (typeof state === "function" ? receiver !== state || !f5 : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
      return kind2 === "a" ? f5.call(receiver, value) : f5 ? f5.value = value : state.set(receiver, value), value;
    };
    __classPrivateFieldGet7 = function(receiver, state, kind2, f5) {
      if (kind2 === "a" && !f5) throw new TypeError("Private accessor was defined without a getter");
      if (typeof state === "function" ? receiver !== state || !f5 : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
      return kind2 === "m" ? f5 : kind2 === "a" ? f5.call(receiver) : f5 ? f5.value : state.get(receiver);
    };
    __name(defaultParseResponse2, "defaultParseResponse");
    __name(_addRequestID, "_addRequestID");
    APIPromise2 = class _APIPromise extends Promise {
      static {
        __name(this, "APIPromise");
      }
      constructor(responsePromise, parseResponse2 = defaultParseResponse2) {
        super((resolve30) => {
          resolve30(null);
        });
        this.responsePromise = responsePromise;
        this.parseResponse = parseResponse2;
      }
      _thenUnwrap(transform2) {
        return new _APIPromise(this.responsePromise, async (props) => _addRequestID(transform2(await this.parseResponse(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"` if you can,
       * or add one of these imports before your first `import … from '@anthropic-ai/sdk'`:
       * - `import '@anthropic-ai/sdk/shims/node'` (if you're running on Node)
       * - `import '@anthropic-ai/sdk/shims/web'` (otherwise)
       */
      asResponse() {
        return this.responsePromise.then((p2) => p2.response);
      }
      /**
       * Gets the parsed response data, the raw `Response` instance and the ID of the request,
       * returned vie the `request-id` header which is useful for debugging requests and resporting
       * issues to Anthropic.
       *
       * 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"` if you can,
       * or add one of these imports before your first `import … from '@anthropic-ai/sdk'`:
       * - `import '@anthropic-ai/sdk/shims/node'` (if you're running on Node)
       * - `import '@anthropic-ai/sdk/shims/web'` (otherwise)
       */
      async withResponse() {
        const [data, response] = await Promise.all([this.parse(), this.asResponse()]);
        return { data, response, request_id: response.headers.get("request-id") };
      }
      parse() {
        if (!this.parsedPromise) {
          this.parsedPromise = this.responsePromise.then(this.parseResponse);
        }
        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);
      }
    };
    APIClient = class {
      static {
        __name(this, "APIClient");
      }
      constructor({
        baseURL,
        maxRetries = 2,
        timeout: timeout2 = 6e5,
        // 10 minutes
        httpAgent,
        fetch: overriddenFetch
      }) {
        this.baseURL = baseURL;
        this.maxRetries = validatePositiveInteger2("maxRetries", maxRetries);
        this.timeout = validatePositiveInteger2("timeout", timeout2);
        this.httpAgent = httpAgent;
        this.fetch = overriddenFetch ?? fetch3;
      }
      authHeaders(opts) {
        return {};
      }
      /**
       * Override this to add your own default headers, for example:
       *
       *  {
       *    ...super.defaultHeaders(),
       *    Authorization: 'Bearer 123',
       *  }
       */
      defaultHeaders(opts) {
        return {
          Accept: "application/json",
          "Content-Type": "application/json",
          "User-Agent": this.getUserAgent(),
          ...getPlatformHeaders2(),
          ...this.authHeaders(opts)
        };
      }
      /**
       * Override this to add your own headers validation:
       */
      validateHeaders(headers, customHeaders) {
      }
      defaultIdempotencyKey() {
        return `stainless-node-retry-${uuid42()}`;
      }
      get(path125, opts) {
        return this.methodRequest("get", path125, opts);
      }
      post(path125, opts) {
        return this.methodRequest("post", path125, opts);
      }
      patch(path125, opts) {
        return this.methodRequest("patch", path125, opts);
      }
      put(path125, opts) {
        return this.methodRequest("put", path125, opts);
      }
      delete(path125, opts) {
        return this.methodRequest("delete", path125, opts);
      }
      methodRequest(method, path125, opts) {
        return this.request(Promise.resolve(opts).then(async (opts2) => {
          const body = opts2 && isBlobLike2(opts2?.body) ? new DataView(await opts2.body.arrayBuffer()) : opts2?.body instanceof DataView ? opts2.body : opts2?.body instanceof ArrayBuffer ? new DataView(opts2.body) : opts2 && ArrayBuffer.isView(opts2?.body) ? new DataView(opts2.body.buffer) : opts2?.body;
          return { method, path: path125, ...opts2, body };
        }));
      }
      getAPIList(path125, Page3, opts) {
        return this.requestAPIList(Page3, { method: "get", path: path125, ...opts });
      }
      calculateContentLength(body) {
        if (typeof body === "string") {
          if (typeof Buffer !== "undefined") {
            return Buffer.byteLength(body, "utf8").toString();
          }
          if (typeof TextEncoder !== "undefined") {
            const encoder = new TextEncoder();
            const encoded = encoder.encode(body);
            return encoded.length.toString();
          }
        } else if (ArrayBuffer.isView(body)) {
          return body.byteLength.toString();
        }
        return null;
      }
      buildRequest(options2, { retryCount = 0 } = {}) {
        const { method, path: path125, query, headers = {} } = options2;
        const body = ArrayBuffer.isView(options2.body) || options2.__binaryRequest && typeof options2.body === "string" ? options2.body : isMultipartBody(options2.body) ? options2.body.body : options2.body ? JSON.stringify(options2.body, null, 2) : null;
        const contentLength = this.calculateContentLength(body);
        const url2 = this.buildURL(path125, query);
        if ("timeout" in options2)
          validatePositiveInteger2("timeout", options2.timeout);
        const timeout2 = options2.timeout ?? this.timeout;
        const httpAgent = options2.httpAgent ?? this.httpAgent ?? getDefaultAgent(url2);
        const minAgentTimeout = timeout2 + 1e3;
        if (typeof httpAgent?.options?.timeout === "number" && minAgentTimeout > (httpAgent.options.timeout ?? 0)) {
          httpAgent.options.timeout = minAgentTimeout;
        }
        if (this.idempotencyHeader && method !== "get") {
          if (!options2.idempotencyKey)
            options2.idempotencyKey = this.defaultIdempotencyKey();
          headers[this.idempotencyHeader] = options2.idempotencyKey;
        }
        const reqHeaders = this.buildHeaders({ options: options2, headers, contentLength, retryCount });
        const req = {
          method,
          ...body && { body },
          headers: reqHeaders,
          ...httpAgent && { agent: httpAgent },
          // @ts-ignore node-fetch uses a custom AbortSignal type that is
          // not compatible with standard web types
          signal: options2.signal ?? null
        };
        return { req, url: url2, timeout: timeout2 };
      }
      buildHeaders({ options: options2, headers, contentLength, retryCount }) {
        const reqHeaders = {};
        if (contentLength) {
          reqHeaders["content-length"] = contentLength;
        }
        const defaultHeaders = this.defaultHeaders(options2);
        applyHeadersMut(reqHeaders, defaultHeaders);
        applyHeadersMut(reqHeaders, headers);
        if (isMultipartBody(options2.body) && kind !== "node") {
          delete reqHeaders["content-type"];
        }
        if (getHeader(defaultHeaders, "x-stainless-retry-count") === void 0 && getHeader(headers, "x-stainless-retry-count") === void 0) {
          reqHeaders["x-stainless-retry-count"] = String(retryCount);
        }
        this.validateHeaders(reqHeaders, headers);
        return reqHeaders;
      }
      /**
       * 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 }) {
      }
      parseHeaders(headers) {
        return !headers ? {} : Symbol.iterator in headers ? Object.fromEntries(Array.from(headers).map((header) => [...header])) : { ...headers };
      }
      makeStatusError(status, error2, message, headers) {
        return APIError2.generate(status, error2, message, headers);
      }
      request(options2, remainingRetries = null) {
        return new APIPromise2(this.makeRequest(options2, remainingRetries));
      }
      async makeRequest(optionsInput, retriesRemaining) {
        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 } = this.buildRequest(options2, { retryCount: maxRetries - retriesRemaining });
        await this.prepareRequest(req, { url: url2, options: options2 });
        debug("request", url2, options2, req.headers);
        if (options2.signal?.aborted) {
          throw new APIUserAbortError2();
        }
        const controller = new AbortController();
        const response = await this.fetchWithTimeout(url2, req, timeout2, controller).catch(castToError2);
        if (response instanceof Error) {
          if (options2.signal?.aborted) {
            throw new APIUserAbortError2();
          }
          if (retriesRemaining) {
            return this.retryRequest(options2, retriesRemaining);
          }
          if (response.name === "AbortError") {
            throw new APIConnectionTimeoutError2();
          }
          throw new APIConnectionError2({ cause: response });
        }
        const responseHeaders = createResponseHeaders(response.headers);
        if (!response.ok) {
          if (retriesRemaining && this.shouldRetry(response)) {
            const retryMessage2 = `retrying, ${retriesRemaining} attempts remaining`;
            debug(`response (error; ${retryMessage2})`, response.status, url2, responseHeaders);
            return this.retryRequest(options2, retriesRemaining, responseHeaders);
          }
          const errText = await response.text().catch((e4) => castToError2(e4).message);
          const errJSON = safeJSON2(errText);
          const errMessage = errJSON ? void 0 : errText;
          const retryMessage = retriesRemaining ? `(error; no more retries left)` : `(error; not retryable)`;
          debug(`response (error; ${retryMessage})`, response.status, url2, responseHeaders, errMessage);
          const err = this.makeStatusError(response.status, errJSON, errMessage, responseHeaders);
          throw err;
        }
        return { response, options: options2, controller };
      }
      requestAPIList(Page3, options2) {
        const request4 = this.makeRequest(options2, null);
        return new PagePromise2(this, request4, Page3);
      }
      buildURL(path125, query) {
        const url2 = isAbsoluteURL2(path125) ? new URL(path125) : new URL(this.baseURL + (this.baseURL.endsWith("/") && path125.startsWith("/") ? path125.slice(1) : path125));
        const defaultQuery = this.defaultQuery();
        if (!isEmptyObj2(defaultQuery)) {
          query = { ...defaultQuery, ...query };
        }
        if (typeof query === "object" && query && !Array.isArray(query)) {
          url2.search = this.stringifyQuery(query);
        }
        return url2.toString();
      }
      stringifyQuery(query) {
        return Object.entries(query).filter(([_2, value]) => typeof value !== "undefined").map(([key, value]) => {
          if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") {
            return `${encodeURIComponent(key)}=${encodeURIComponent(value)}`;
          }
          if (value === null) {
            return `${encodeURIComponent(key)}=`;
          }
          throw new AnthropicError(`Cannot stringify type ${typeof value}; Expected string, number, boolean, or null. If you need to pass nested query parameters, you can manually encode them, e.g. { query: { 'foo[key1]': value1, 'foo[key2]': value2 } }, and please open a GitHub issue requesting better support for your use case.`);
        }).join("&");
      }
      async fetchWithTimeout(url2, init, ms, controller) {
        const { signal, ...options2 } = init || {};
        if (signal)
          signal.addEventListener("abort", () => controller.abort());
        const timeout2 = setTimeout(() => controller.abort(), ms);
        const fetchOptions = {
          signal: controller.signal,
          ...options2
        };
        if (fetchOptions.method) {
          fetchOptions.method = fetchOptions.method.toUpperCase();
        }
        return (
          // use undefined this binding; fetch errors if bound to something else in browser/cloudflare
          this.fetch.call(void 0, url2, fetchOptions).finally(() => {
            clearTimeout(timeout2);
          })
        );
      }
      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, responseHeaders) {
        let timeoutMillis;
        const retryAfterMillisHeader = responseHeaders?.["retry-after-ms"];
        if (retryAfterMillisHeader) {
          const timeoutMs = parseFloat(retryAfterMillisHeader);
          if (!Number.isNaN(timeoutMs)) {
            timeoutMillis = timeoutMs;
          }
        }
        const retryAfterHeader = responseHeaders?.["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 sleep3(timeoutMillis);
        return this.makeRequest(options2, retriesRemaining - 1);
      }
      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;
      }
      getUserAgent() {
        return `${this.constructor.name}/JS ${VERSION3}`;
      }
    };
    AbstractPage2 = class {
      static {
        __name(this, "AbstractPage");
      }
      constructor(client, response, body, options2) {
        _AbstractPage_client2.set(this, void 0);
        __classPrivateFieldSet6(this, _AbstractPage_client2, client, "f");
        this.options = options2;
        this.response = response;
        this.body = body;
      }
      hasNextPage() {
        const items = this.getPaginatedItems();
        if (!items.length)
          return false;
        return this.nextPageInfo() != null;
      }
      async getNextPage() {
        const nextInfo = this.nextPageInfo();
        if (!nextInfo) {
          throw new AnthropicError("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");
        }
        const nextOptions = { ...this.options };
        if ("params" in nextInfo && typeof nextOptions.query === "object") {
          nextOptions.query = { ...nextOptions.query, ...nextInfo.params };
        } else if ("url" in nextInfo) {
          const params = [...Object.entries(nextOptions.query || {}), ...nextInfo.url.searchParams.entries()];
          for (const [key, value] of params) {
            nextInfo.url.searchParams.set(key, value);
          }
          nextOptions.query = void 0;
          nextOptions.path = nextInfo.url.toString();
        }
        return await __classPrivateFieldGet7(this, _AbstractPage_client2, "f").requestAPIList(this.constructor, nextOptions);
      }
      async *iterPages() {
        let page = this;
        yield page;
        while (page.hasNextPage()) {
          page = await page.getNextPage();
          yield page;
        }
      }
      async *[(_AbstractPage_client2 = /* @__PURE__ */ new WeakMap(), Symbol.asyncIterator)]() {
        for await (const page of this.iterPages()) {
          for (const item of page.getPaginatedItems()) {
            yield item;
          }
        }
      }
    };
    PagePromise2 = class extends APIPromise2 {
      static {
        __name(this, "PagePromise");
      }
      constructor(client, request4, Page3) {
        super(request4, async (props) => new Page3(client, props.response, await defaultParseResponse2(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;
        }
      }
    };
    createResponseHeaders = /* @__PURE__ */ __name((headers) => {
      return new Proxy(Object.fromEntries(
        // @ts-ignore
        headers.entries()
      ), {
        get(target, name3) {
          const key = name3.toString();
          return target[key.toLowerCase()] || target[key];
        }
      });
    }, "createResponseHeaders");
    requestOptionsKeys = {
      method: true,
      path: true,
      query: true,
      body: true,
      headers: true,
      maxRetries: true,
      stream: true,
      timeout: true,
      httpAgent: true,
      signal: true,
      idempotencyKey: true,
      __binaryRequest: true,
      __binaryResponse: true,
      __streamClass: true
    };
    isRequestOptions = /* @__PURE__ */ __name((obj) => {
      return typeof obj === "object" && obj !== null && !isEmptyObj2(obj) && Object.keys(obj).every((k2) => hasOwn2(requestOptionsKeys, k2));
    }, "isRequestOptions");
    getPlatformProperties2 = /* @__PURE__ */ __name(() => {
      if (typeof Deno !== "undefined" && Deno.build != null) {
        return {
          "X-Stainless-Lang": "js",
          "X-Stainless-Package-Version": VERSION3,
          "X-Stainless-OS": normalizePlatform2(Deno.build.os),
          "X-Stainless-Arch": normalizeArch2(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": VERSION3,
          "X-Stainless-OS": "Unknown",
          "X-Stainless-Arch": `other:${EdgeRuntime}`,
          "X-Stainless-Runtime": "edge",
          "X-Stainless-Runtime-Version": process.version
        };
      }
      if (Object.prototype.toString.call(typeof process !== "undefined" ? process : 0) === "[object process]") {
        return {
          "X-Stainless-Lang": "js",
          "X-Stainless-Package-Version": VERSION3,
          "X-Stainless-OS": normalizePlatform2(process.platform),
          "X-Stainless-Arch": normalizeArch2(process.arch),
          "X-Stainless-Runtime": "node",
          "X-Stainless-Runtime-Version": process.version
        };
      }
      const browserInfo = getBrowserInfo2();
      if (browserInfo) {
        return {
          "X-Stainless-Lang": "js",
          "X-Stainless-Package-Version": VERSION3,
          "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": VERSION3,
        "X-Stainless-OS": "Unknown",
        "X-Stainless-Arch": "unknown",
        "X-Stainless-Runtime": "unknown",
        "X-Stainless-Runtime-Version": "unknown"
      };
    }, "getPlatformProperties");
    __name(getBrowserInfo2, "getBrowserInfo");
    normalizeArch2 = /* @__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");
    normalizePlatform2 = /* @__PURE__ */ __name((platform16) => {
      platform16 = platform16.toLowerCase();
      if (platform16.includes("ios"))
        return "iOS";
      if (platform16 === "android")
        return "Android";
      if (platform16 === "darwin")
        return "MacOS";
      if (platform16 === "win32")
        return "Windows";
      if (platform16 === "freebsd")
        return "FreeBSD";
      if (platform16 === "openbsd")
        return "OpenBSD";
      if (platform16 === "linux")
        return "Linux";
      if (platform16)
        return `Other:${platform16}`;
      return "Unknown";
    }, "normalizePlatform");
    getPlatformHeaders2 = /* @__PURE__ */ __name(() => {
      return _platformHeaders2 ?? (_platformHeaders2 = getPlatformProperties2());
    }, "getPlatformHeaders");
    safeJSON2 = /* @__PURE__ */ __name((text) => {
      try {
        return JSON.parse(text);
      } catch (err) {
        return void 0;
      }
    }, "safeJSON");
    startsWithSchemeRegexp2 = /^[a-z][a-z0-9+.-]*:/i;
    isAbsoluteURL2 = /* @__PURE__ */ __name((url2) => {
      return startsWithSchemeRegexp2.test(url2);
    }, "isAbsoluteURL");
    sleep3 = /* @__PURE__ */ __name((ms) => new Promise((resolve30) => setTimeout(resolve30, ms)), "sleep");
    validatePositiveInteger2 = /* @__PURE__ */ __name((name3, n3) => {
      if (typeof n3 !== "number" || !Number.isInteger(n3)) {
        throw new AnthropicError(`${name3} must be an integer`);
      }
      if (n3 < 0) {
        throw new AnthropicError(`${name3} must be a positive integer`);
      }
      return n3;
    }, "validatePositiveInteger");
    castToError2 = /* @__PURE__ */ __name((err) => {
      if (err instanceof Error)
        return err;
      if (typeof err === "object" && err !== null) {
        try {
          return new Error(JSON.stringify(err));
        } catch {
        }
      }
      return new Error(String(err));
    }, "castToError");
    readEnv2 = /* @__PURE__ */ __name((env7) => {
      if (typeof process !== "undefined") {
        return process.env?.[env7]?.trim() ?? void 0;
      }
      if (typeof Deno !== "undefined") {
        return Deno.env?.get?.(env7)?.trim();
      }
      return void 0;
    }, "readEnv");
    __name(isEmptyObj2, "isEmptyObj");
    __name(hasOwn2, "hasOwn");
    __name(applyHeadersMut, "applyHeadersMut");
    __name(debug, "debug");
    uuid42 = /* @__PURE__ */ __name(() => {
      return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (c4) => {
        const r5 = Math.random() * 16 | 0;
        const v2 = c4 === "x" ? r5 : r5 & 3 | 8;
        return v2.toString(16);
      });
    }, "uuid4");
    isRunningInBrowser2 = /* @__PURE__ */ __name(() => {
      return (
        // @ts-ignore
        typeof window !== "undefined" && // @ts-ignore
        typeof window.document !== "undefined" && // @ts-ignore
        typeof navigator !== "undefined"
      );
    }, "isRunningInBrowser");
    isHeadersProtocol = /* @__PURE__ */ __name((headers) => {
      return typeof headers?.get === "function";
    }, "isHeadersProtocol");
    getHeader = /* @__PURE__ */ __name((headers, header) => {
      const lowerCasedHeader = header.toLowerCase();
      if (isHeadersProtocol(headers)) {
        const intercapsHeader = header[0]?.toUpperCase() + header.substring(1).replace(/([^\w])(\w)/g, (_m, g1, g2) => g1 + g2.toUpperCase());
        for (const key of [header, lowerCasedHeader, header.toUpperCase(), intercapsHeader]) {
          const value = headers.get(key);
          if (value) {
            return value;
          }
        }
      }
      for (const [key, value] of Object.entries(headers)) {
        if (key.toLowerCase() === lowerCasedHeader) {
          if (Array.isArray(value)) {
            if (value.length <= 1)
              return value[0];
            console.warn(`Received ${value.length} entries for the ${header} header, using the first entry.`);
            return value[0];
          }
          return value;
        }
      }
      return void 0;
    }, "getHeader");
  }
});

// node_modules/@anthropic-ai/sdk/pagination.mjs
var Page2;
var init_pagination2 = __esm({
  "node_modules/@anthropic-ai/sdk/pagination.mjs"() {
    init_esbuild_shims();
    init_core();
    Page2 = class extends AbstractPage2 {
      static {
        __name(this, "Page");
      }
      constructor(client, response, body, options2) {
        super(client, response, body, options2);
        this.data = body.data || [];
        this.has_more = body.has_more || false;
        this.first_id = body.first_id || null;
        this.last_id = body.last_id || null;
      }
      getPaginatedItems() {
        return this.data ?? [];
      }
      // @deprecated Please use `nextPageInfo()` instead
      nextPageParams() {
        const info = this.nextPageInfo();
        if (!info)
          return null;
        if ("params" in info)
          return info.params;
        const params = Object.fromEntries(info.url.searchParams);
        if (!Object.keys(params).length)
          return null;
        return params;
      }
      nextPageInfo() {
        if (this.options.query?.["before_id"]) {
          const firstId = this.first_id;
          if (!firstId) {
            return null;
          }
          return {
            params: {
              before_id: firstId
            }
          };
        }
        const cursor = this.last_id;
        if (!cursor) {
          return null;
        }
        return {
          params: {
            after_id: cursor
          }
        };
      }
    };
  }
});

// node_modules/@anthropic-ai/sdk/resources/shared.mjs
var init_shared2 = __esm({
  "node_modules/@anthropic-ai/sdk/resources/shared.mjs"() {
    init_esbuild_shims();
  }
});

// node_modules/@anthropic-ai/sdk/resource.mjs
var APIResource2;
var init_resource3 = __esm({
  "node_modules/@anthropic-ai/sdk/resource.mjs"() {
    init_esbuild_shims();
    APIResource2 = class {
      static {
        __name(this, "APIResource");
      }
      constructor(client) {
        this._client = client;
      }
    };
  }
});

// node_modules/@anthropic-ai/sdk/resources/beta/models.mjs
var Models3, BetaModelInfosPage;
var init_models3 = __esm({
  "node_modules/@anthropic-ai/sdk/resources/beta/models.mjs"() {
    init_esbuild_shims();
    init_resource3();
    init_core();
    init_pagination2();
    Models3 = class extends APIResource2 {
      static {
        __name(this, "Models");
      }
      /**
       * Get a specific model.
       *
       * The Models API response can be used to determine information about a specific
       * model or resolve a model alias to a model ID.
       */
      retrieve(modelId, options2) {
        return this._client.get(`/v1/models/${modelId}?beta=true`, options2);
      }
      list(query = {}, options2) {
        if (isRequestOptions(query)) {
          return this.list({}, query);
        }
        return this._client.getAPIList("/v1/models?beta=true", BetaModelInfosPage, { query, ...options2 });
      }
    };
    BetaModelInfosPage = class extends Page2 {
      static {
        __name(this, "BetaModelInfosPage");
      }
    };
    Models3.BetaModelInfosPage = BetaModelInfosPage;
  }
});

// node_modules/@anthropic-ai/sdk/internal/decoders/jsonl.mjs
var JSONLDecoder;
var init_jsonl = __esm({
  "node_modules/@anthropic-ai/sdk/internal/decoders/jsonl.mjs"() {
    init_esbuild_shims();
    init_error3();
    init_stream_utils();
    init_line2();
    JSONLDecoder = class _JSONLDecoder {
      static {
        __name(this, "JSONLDecoder");
      }
      constructor(iterator, controller) {
        this.iterator = iterator;
        this.controller = controller;
      }
      async *decoder() {
        const lineDecoder = new LineDecoder2();
        for await (const chunk of this.iterator) {
          for (const line of lineDecoder.decode(chunk)) {
            yield JSON.parse(line);
          }
        }
        for (const line of lineDecoder.flush()) {
          yield JSON.parse(line);
        }
      }
      [Symbol.asyncIterator]() {
        return this.decoder();
      }
      static fromResponse(response, controller) {
        if (!response.body) {
          controller.abort();
          throw new AnthropicError(`Attempted to iterate over a response with no body`);
        }
        return new _JSONLDecoder(ReadableStreamToAsyncIterable2(response.body), controller);
      }
    };
  }
});

// node_modules/@anthropic-ai/sdk/resources/beta/messages/batches.mjs
var Batches3, BetaMessageBatchesPage;
var init_batches2 = __esm({
  "node_modules/@anthropic-ai/sdk/resources/beta/messages/batches.mjs"() {
    init_esbuild_shims();
    init_resource3();
    init_core();
    init_pagination2();
    init_jsonl();
    init_error3();
    Batches3 = class extends APIResource2 {
      static {
        __name(this, "Batches");
      }
      /**
       * Send a batch of Message creation requests.
       *
       * The Message Batches API can be used to process multiple Messages API requests at
       * once. Once a Message Batch is created, it begins processing immediately. Batches
       * can take up to 24 hours to complete.
       */
      create(params, options2) {
        const { betas, ...body } = params;
        return this._client.post("/v1/messages/batches?beta=true", {
          body,
          ...options2,
          headers: {
            "anthropic-beta": [...betas ?? [], "message-batches-2024-09-24"].toString(),
            ...options2?.headers
          }
        });
      }
      retrieve(messageBatchId, params = {}, options2) {
        if (isRequestOptions(params)) {
          return this.retrieve(messageBatchId, {}, params);
        }
        const { betas } = params;
        return this._client.get(`/v1/messages/batches/${messageBatchId}?beta=true`, {
          ...options2,
          headers: {
            "anthropic-beta": [...betas ?? [], "message-batches-2024-09-24"].toString(),
            ...options2?.headers
          }
        });
      }
      list(params = {}, options2) {
        if (isRequestOptions(params)) {
          return this.list({}, params);
        }
        const { betas, ...query } = params;
        return this._client.getAPIList("/v1/messages/batches?beta=true", BetaMessageBatchesPage, {
          query,
          ...options2,
          headers: {
            "anthropic-beta": [...betas ?? [], "message-batches-2024-09-24"].toString(),
            ...options2?.headers
          }
        });
      }
      delete(messageBatchId, params = {}, options2) {
        if (isRequestOptions(params)) {
          return this.delete(messageBatchId, {}, params);
        }
        const { betas } = params;
        return this._client.delete(`/v1/messages/batches/${messageBatchId}?beta=true`, {
          ...options2,
          headers: {
            "anthropic-beta": [...betas ?? [], "message-batches-2024-09-24"].toString(),
            ...options2?.headers
          }
        });
      }
      cancel(messageBatchId, params = {}, options2) {
        if (isRequestOptions(params)) {
          return this.cancel(messageBatchId, {}, params);
        }
        const { betas } = params;
        return this._client.post(`/v1/messages/batches/${messageBatchId}/cancel?beta=true`, {
          ...options2,
          headers: {
            "anthropic-beta": [...betas ?? [], "message-batches-2024-09-24"].toString(),
            ...options2?.headers
          }
        });
      }
      async results(messageBatchId, params = {}, options2) {
        if (isRequestOptions(params)) {
          return this.results(messageBatchId, {}, params);
        }
        const batch = await this.retrieve(messageBatchId);
        if (!batch.results_url) {
          throw new AnthropicError(`No batch \`results_url\`; Has it finished processing? ${batch.processing_status} - ${batch.id}`);
        }
        const { betas } = params;
        return this._client.get(batch.results_url, {
          ...options2,
          headers: {
            "anthropic-beta": [...betas ?? [], "message-batches-2024-09-24"].toString(),
            Accept: "application/binary",
            ...options2?.headers
          },
          __binaryResponse: true
        })._thenUnwrap((_2, props) => JSONLDecoder.fromResponse(props.response, props.controller));
      }
    };
    BetaMessageBatchesPage = class extends Page2 {
      static {
        __name(this, "BetaMessageBatchesPage");
      }
    };
    Batches3.BetaMessageBatchesPage = BetaMessageBatchesPage;
  }
});

// node_modules/@anthropic-ai/sdk/_vendor/partial-json-parser/parser.mjs
var tokenize, strip, unstrip, generate, partialParse2;
var init_parser3 = __esm({
  "node_modules/@anthropic-ai/sdk/_vendor/partial-json-parser/parser.mjs"() {
    init_esbuild_shims();
    tokenize = /* @__PURE__ */ __name((input) => {
      let current = 0;
      let tokens = [];
      while (current < input.length) {
        let char = input[current];
        if (char === "\\") {
          current++;
          continue;
        }
        if (char === "{") {
          tokens.push({
            type: "brace",
            value: "{"
          });
          current++;
          continue;
        }
        if (char === "}") {
          tokens.push({
            type: "brace",
            value: "}"
          });
          current++;
          continue;
        }
        if (char === "[") {
          tokens.push({
            type: "paren",
            value: "["
          });
          current++;
          continue;
        }
        if (char === "]") {
          tokens.push({
            type: "paren",
            value: "]"
          });
          current++;
          continue;
        }
        if (char === ":") {
          tokens.push({
            type: "separator",
            value: ":"
          });
          current++;
          continue;
        }
        if (char === ",") {
          tokens.push({
            type: "delimiter",
            value: ","
          });
          current++;
          continue;
        }
        if (char === '"') {
          let value = "";
          let danglingQuote = false;
          char = input[++current];
          while (char !== '"') {
            if (current === input.length) {
              danglingQuote = true;
              break;
            }
            if (char === "\\") {
              current++;
              if (current === input.length) {
                danglingQuote = true;
                break;
              }
              value += char + input[current];
              char = input[++current];
            } else {
              value += char;
              char = input[++current];
            }
          }
          char = input[++current];
          if (!danglingQuote) {
            tokens.push({
              type: "string",
              value
            });
          }
          continue;
        }
        let WHITESPACE = /\s/;
        if (char && WHITESPACE.test(char)) {
          current++;
          continue;
        }
        let NUMBERS = /[0-9]/;
        if (char && NUMBERS.test(char) || char === "-" || char === ".") {
          let value = "";
          if (char === "-") {
            value += char;
            char = input[++current];
          }
          while (char && NUMBERS.test(char) || char === ".") {
            value += char;
            char = input[++current];
          }
          tokens.push({
            type: "number",
            value
          });
          continue;
        }
        let LETTERS = /[a-z]/i;
        if (char && LETTERS.test(char)) {
          let value = "";
          while (char && LETTERS.test(char)) {
            if (current === input.length) {
              break;
            }
            value += char;
            char = input[++current];
          }
          if (value == "true" || value == "false" || value === "null") {
            tokens.push({
              type: "name",
              value
            });
          } else {
            current++;
            continue;
          }
          continue;
        }
        current++;
      }
      return tokens;
    }, "tokenize");
    strip = /* @__PURE__ */ __name((tokens) => {
      if (tokens.length === 0) {
        return tokens;
      }
      let lastToken = tokens[tokens.length - 1];
      switch (lastToken.type) {
        case "separator":
          tokens = tokens.slice(0, tokens.length - 1);
          return strip(tokens);
          break;
        case "number":
          let lastCharacterOfLastToken = lastToken.value[lastToken.value.length - 1];
          if (lastCharacterOfLastToken === "." || lastCharacterOfLastToken === "-") {
            tokens = tokens.slice(0, tokens.length - 1);
            return strip(tokens);
          }
        case "string":
          let tokenBeforeTheLastToken = tokens[tokens.length - 2];
          if (tokenBeforeTheLastToken?.type === "delimiter") {
            tokens = tokens.slice(0, tokens.length - 1);
            return strip(tokens);
          } else if (tokenBeforeTheLastToken?.type === "brace" && tokenBeforeTheLastToken.value === "{") {
            tokens = tokens.slice(0, tokens.length - 1);
            return strip(tokens);
          }
          break;
        case "delimiter":
          tokens = tokens.slice(0, tokens.length - 1);
          return strip(tokens);
          break;
      }
      return tokens;
    }, "strip");
    unstrip = /* @__PURE__ */ __name((tokens) => {
      let tail = [];
      tokens.map((token2) => {
        if (token2.type === "brace") {
          if (token2.value === "{") {
            tail.push("}");
          } else {
            tail.splice(tail.lastIndexOf("}"), 1);
          }
        }
        if (token2.type === "paren") {
          if (token2.value === "[") {
            tail.push("]");
          } else {
            tail.splice(tail.lastIndexOf("]"), 1);
          }
        }
      });
      if (tail.length > 0) {
        tail.reverse().map((item) => {
          if (item === "}") {
            tokens.push({
              type: "brace",
              value: "}"
            });
          } else if (item === "]") {
            tokens.push({
              type: "paren",
              value: "]"
            });
          }
        });
      }
      return tokens;
    }, "unstrip");
    generate = /* @__PURE__ */ __name((tokens) => {
      let output = "";
      tokens.map((token2) => {
        switch (token2.type) {
          case "string":
            output += '"' + token2.value + '"';
            break;
          default:
            output += token2.value;
            break;
        }
      });
      return output;
    }, "generate");
    partialParse2 = /* @__PURE__ */ __name((input) => JSON.parse(generate(unstrip(strip(tokenize(input))))), "partialParse");
  }
});

// node_modules/@anthropic-ai/sdk/lib/BetaMessageStream.mjs
function checkNever(x3) {
}
var __classPrivateFieldSet7, __classPrivateFieldGet8, _BetaMessageStream_instances, _BetaMessageStream_currentMessageSnapshot, _BetaMessageStream_connectedPromise, _BetaMessageStream_resolveConnectedPromise, _BetaMessageStream_rejectConnectedPromise, _BetaMessageStream_endPromise, _BetaMessageStream_resolveEndPromise, _BetaMessageStream_rejectEndPromise, _BetaMessageStream_listeners, _BetaMessageStream_ended, _BetaMessageStream_errored, _BetaMessageStream_aborted, _BetaMessageStream_catchingPromiseCreated, _BetaMessageStream_response, _BetaMessageStream_request_id, _BetaMessageStream_getFinalMessage, _BetaMessageStream_getFinalText, _BetaMessageStream_handleError, _BetaMessageStream_beginRequest, _BetaMessageStream_addStreamEvent, _BetaMessageStream_endRequest, _BetaMessageStream_accumulateMessage, JSON_BUF_PROPERTY, BetaMessageStream;
var init_BetaMessageStream = __esm({
  "node_modules/@anthropic-ai/sdk/lib/BetaMessageStream.mjs"() {
    init_esbuild_shims();
    init_error3();
    init_streaming3();
    init_parser3();
    __classPrivateFieldSet7 = function(receiver, state, value, kind2, f5) {
      if (kind2 === "m") throw new TypeError("Private method is not writable");
      if (kind2 === "a" && !f5) throw new TypeError("Private accessor was defined without a setter");
      if (typeof state === "function" ? receiver !== state || !f5 : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
      return kind2 === "a" ? f5.call(receiver, value) : f5 ? f5.value = value : state.set(receiver, value), value;
    };
    __classPrivateFieldGet8 = function(receiver, state, kind2, f5) {
      if (kind2 === "a" && !f5) throw new TypeError("Private accessor was defined without a getter");
      if (typeof state === "function" ? receiver !== state || !f5 : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
      return kind2 === "m" ? f5 : kind2 === "a" ? f5.call(receiver) : f5 ? f5.value : state.get(receiver);
    };
    JSON_BUF_PROPERTY = "__json_buf";
    BetaMessageStream = class _BetaMessageStream {
      static {
        __name(this, "BetaMessageStream");
      }
      constructor() {
        _BetaMessageStream_instances.add(this);
        this.messages = [];
        this.receivedMessages = [];
        _BetaMessageStream_currentMessageSnapshot.set(this, void 0);
        this.controller = new AbortController();
        _BetaMessageStream_connectedPromise.set(this, void 0);
        _BetaMessageStream_resolveConnectedPromise.set(this, () => {
        });
        _BetaMessageStream_rejectConnectedPromise.set(this, () => {
        });
        _BetaMessageStream_endPromise.set(this, void 0);
        _BetaMessageStream_resolveEndPromise.set(this, () => {
        });
        _BetaMessageStream_rejectEndPromise.set(this, () => {
        });
        _BetaMessageStream_listeners.set(this, {});
        _BetaMessageStream_ended.set(this, false);
        _BetaMessageStream_errored.set(this, false);
        _BetaMessageStream_aborted.set(this, false);
        _BetaMessageStream_catchingPromiseCreated.set(this, false);
        _BetaMessageStream_response.set(this, void 0);
        _BetaMessageStream_request_id.set(this, void 0);
        _BetaMessageStream_handleError.set(this, (error2) => {
          __classPrivateFieldSet7(this, _BetaMessageStream_errored, true, "f");
          if (error2 instanceof Error && error2.name === "AbortError") {
            error2 = new APIUserAbortError2();
          }
          if (error2 instanceof APIUserAbortError2) {
            __classPrivateFieldSet7(this, _BetaMessageStream_aborted, true, "f");
            return this._emit("abort", error2);
          }
          if (error2 instanceof AnthropicError) {
            return this._emit("error", error2);
          }
          if (error2 instanceof Error) {
            const anthropicError = new AnthropicError(error2.message);
            anthropicError.cause = error2;
            return this._emit("error", anthropicError);
          }
          return this._emit("error", new AnthropicError(String(error2)));
        });
        __classPrivateFieldSet7(this, _BetaMessageStream_connectedPromise, new Promise((resolve30, reject) => {
          __classPrivateFieldSet7(this, _BetaMessageStream_resolveConnectedPromise, resolve30, "f");
          __classPrivateFieldSet7(this, _BetaMessageStream_rejectConnectedPromise, reject, "f");
        }), "f");
        __classPrivateFieldSet7(this, _BetaMessageStream_endPromise, new Promise((resolve30, reject) => {
          __classPrivateFieldSet7(this, _BetaMessageStream_resolveEndPromise, resolve30, "f");
          __classPrivateFieldSet7(this, _BetaMessageStream_rejectEndPromise, reject, "f");
        }), "f");
        __classPrivateFieldGet8(this, _BetaMessageStream_connectedPromise, "f").catch(() => {
        });
        __classPrivateFieldGet8(this, _BetaMessageStream_endPromise, "f").catch(() => {
        });
      }
      get response() {
        return __classPrivateFieldGet8(this, _BetaMessageStream_response, "f");
      }
      get request_id() {
        return __classPrivateFieldGet8(this, _BetaMessageStream_request_id, "f");
      }
      /**
       * Returns the `MessageStream` data, the raw `Response` instance and the ID of the request,
       * returned vie the `request-id` header which is useful for debugging requests and resporting
       * issues to Anthropic.
       *
       * This is the same as the `APIPromise.withResponse()` method.
       *
       * This method will raise an error if you created the stream using `MessageStream.fromReadableStream`
       * as no `Response` is available.
       */
      async withResponse() {
        const response = await __classPrivateFieldGet8(this, _BetaMessageStream_connectedPromise, "f");
        if (!response) {
          throw new Error("Could not resolve a `Response` object");
        }
        return {
          data: this,
          response,
          request_id: response.headers.get("request-id")
        };
      }
      /**
       * 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 _BetaMessageStream();
        runner._run(() => runner._fromReadableStream(stream2));
        return runner;
      }
      static createMessage(messages, params, options2) {
        const runner = new _BetaMessageStream();
        for (const message of params.messages) {
          runner._addMessageParam(message);
        }
        runner._run(() => runner._createMessage(messages, { ...params, stream: true }, { ...options2, headers: { ...options2?.headers, "X-Stainless-Helper-Method": "stream" } }));
        return runner;
      }
      _run(executor) {
        executor().then(() => {
          this._emitFinal();
          this._emit("end");
        }, __classPrivateFieldGet8(this, _BetaMessageStream_handleError, "f"));
      }
      _addMessageParam(message) {
        this.messages.push(message);
      }
      _addMessage(message, emit = true) {
        this.receivedMessages.push(message);
        if (emit) {
          this._emit("message", message);
        }
      }
      async _createMessage(messages, params, options2) {
        const signal = options2?.signal;
        if (signal) {
          if (signal.aborted)
            this.controller.abort();
          signal.addEventListener("abort", () => this.controller.abort());
        }
        __classPrivateFieldGet8(this, _BetaMessageStream_instances, "m", _BetaMessageStream_beginRequest).call(this);
        const { response, data: stream2 } = await messages.create({ ...params, stream: true }, { ...options2, signal: this.controller.signal }).withResponse();
        this._connected(response);
        for await (const event of stream2) {
          __classPrivateFieldGet8(this, _BetaMessageStream_instances, "m", _BetaMessageStream_addStreamEvent).call(this, event);
        }
        if (stream2.controller.signal?.aborted) {
          throw new APIUserAbortError2();
        }
        __classPrivateFieldGet8(this, _BetaMessageStream_instances, "m", _BetaMessageStream_endRequest).call(this);
      }
      _connected(response) {
        if (this.ended)
          return;
        __classPrivateFieldSet7(this, _BetaMessageStream_response, response, "f");
        __classPrivateFieldSet7(this, _BetaMessageStream_request_id, response?.headers.get("request-id"), "f");
        __classPrivateFieldGet8(this, _BetaMessageStream_resolveConnectedPromise, "f").call(this, response);
        this._emit("connect");
      }
      get ended() {
        return __classPrivateFieldGet8(this, _BetaMessageStream_ended, "f");
      }
      get errored() {
        return __classPrivateFieldGet8(this, _BetaMessageStream_errored, "f");
      }
      get aborted() {
        return __classPrivateFieldGet8(this, _BetaMessageStream_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 MessageStream, so that calls can be chained
       */
      on(event, listener) {
        const listeners = __classPrivateFieldGet8(this, _BetaMessageStream_listeners, "f")[event] || (__classPrivateFieldGet8(this, _BetaMessageStream_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 MessageStream, so that calls can be chained
       */
      off(event, listener) {
        const listeners = __classPrivateFieldGet8(this, _BetaMessageStream_listeners, "f")[event];
        if (!listeners)
          return this;
        const index = listeners.findIndex((l3) => l3.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 MessageStream, so that calls can be chained
       */
      once(event, listener) {
        const listeners = __classPrivateFieldGet8(this, _BetaMessageStream_listeners, "f")[event] || (__classPrivateFieldGet8(this, _BetaMessageStream_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((resolve30, reject) => {
          __classPrivateFieldSet7(this, _BetaMessageStream_catchingPromiseCreated, true, "f");
          if (event !== "error")
            this.once("error", reject);
          this.once(event, resolve30);
        });
      }
      async done() {
        __classPrivateFieldSet7(this, _BetaMessageStream_catchingPromiseCreated, true, "f");
        await __classPrivateFieldGet8(this, _BetaMessageStream_endPromise, "f");
      }
      get currentMessage() {
        return __classPrivateFieldGet8(this, _BetaMessageStream_currentMessageSnapshot, "f");
      }
      /**
       * @returns a promise that resolves with the the final assistant Message response,
       * or rejects if an error occurred or the stream ended prematurely without producing a Message.
       */
      async finalMessage() {
        await this.done();
        return __classPrivateFieldGet8(this, _BetaMessageStream_instances, "m", _BetaMessageStream_getFinalMessage).call(this);
      }
      /**
       * @returns a promise that resolves with the the final assistant Message's text response, concatenated
       * together if there are more than one text blocks.
       * Rejects if an error occurred or the stream ended prematurely without producing a Message.
       */
      async finalText() {
        await this.done();
        return __classPrivateFieldGet8(this, _BetaMessageStream_instances, "m", _BetaMessageStream_getFinalText).call(this);
      }
      _emit(event, ...args) {
        if (__classPrivateFieldGet8(this, _BetaMessageStream_ended, "f"))
          return;
        if (event === "end") {
          __classPrivateFieldSet7(this, _BetaMessageStream_ended, true, "f");
          __classPrivateFieldGet8(this, _BetaMessageStream_resolveEndPromise, "f").call(this);
        }
        const listeners = __classPrivateFieldGet8(this, _BetaMessageStream_listeners, "f")[event];
        if (listeners) {
          __classPrivateFieldGet8(this, _BetaMessageStream_listeners, "f")[event] = listeners.filter((l3) => !l3.once);
          listeners.forEach(({ listener }) => listener(...args));
        }
        if (event === "abort") {
          const error2 = args[0];
          if (!__classPrivateFieldGet8(this, _BetaMessageStream_catchingPromiseCreated, "f") && !listeners?.length) {
            Promise.reject(error2);
          }
          __classPrivateFieldGet8(this, _BetaMessageStream_rejectConnectedPromise, "f").call(this, error2);
          __classPrivateFieldGet8(this, _BetaMessageStream_rejectEndPromise, "f").call(this, error2);
          this._emit("end");
          return;
        }
        if (event === "error") {
          const error2 = args[0];
          if (!__classPrivateFieldGet8(this, _BetaMessageStream_catchingPromiseCreated, "f") && !listeners?.length) {
            Promise.reject(error2);
          }
          __classPrivateFieldGet8(this, _BetaMessageStream_rejectConnectedPromise, "f").call(this, error2);
          __classPrivateFieldGet8(this, _BetaMessageStream_rejectEndPromise, "f").call(this, error2);
          this._emit("end");
        }
      }
      _emitFinal() {
        const finalMessage = this.receivedMessages.at(-1);
        if (finalMessage) {
          this._emit("finalMessage", __classPrivateFieldGet8(this, _BetaMessageStream_instances, "m", _BetaMessageStream_getFinalMessage).call(this));
        }
      }
      async _fromReadableStream(readableStream, options2) {
        const signal = options2?.signal;
        if (signal) {
          if (signal.aborted)
            this.controller.abort();
          signal.addEventListener("abort", () => this.controller.abort());
        }
        __classPrivateFieldGet8(this, _BetaMessageStream_instances, "m", _BetaMessageStream_beginRequest).call(this);
        this._connected(null);
        const stream2 = Stream4.fromReadableStream(readableStream, this.controller);
        for await (const event of stream2) {
          __classPrivateFieldGet8(this, _BetaMessageStream_instances, "m", _BetaMessageStream_addStreamEvent).call(this, event);
        }
        if (stream2.controller.signal?.aborted) {
          throw new APIUserAbortError2();
        }
        __classPrivateFieldGet8(this, _BetaMessageStream_instances, "m", _BetaMessageStream_endRequest).call(this);
      }
      [(_BetaMessageStream_currentMessageSnapshot = /* @__PURE__ */ new WeakMap(), _BetaMessageStream_connectedPromise = /* @__PURE__ */ new WeakMap(), _BetaMessageStream_resolveConnectedPromise = /* @__PURE__ */ new WeakMap(), _BetaMessageStream_rejectConnectedPromise = /* @__PURE__ */ new WeakMap(), _BetaMessageStream_endPromise = /* @__PURE__ */ new WeakMap(), _BetaMessageStream_resolveEndPromise = /* @__PURE__ */ new WeakMap(), _BetaMessageStream_rejectEndPromise = /* @__PURE__ */ new WeakMap(), _BetaMessageStream_listeners = /* @__PURE__ */ new WeakMap(), _BetaMessageStream_ended = /* @__PURE__ */ new WeakMap(), _BetaMessageStream_errored = /* @__PURE__ */ new WeakMap(), _BetaMessageStream_aborted = /* @__PURE__ */ new WeakMap(), _BetaMessageStream_catchingPromiseCreated = /* @__PURE__ */ new WeakMap(), _BetaMessageStream_response = /* @__PURE__ */ new WeakMap(), _BetaMessageStream_request_id = /* @__PURE__ */ new WeakMap(), _BetaMessageStream_handleError = /* @__PURE__ */ new WeakMap(), _BetaMessageStream_instances = /* @__PURE__ */ new WeakSet(), _BetaMessageStream_getFinalMessage = /* @__PURE__ */ __name(function _BetaMessageStream_getFinalMessage2() {
        if (this.receivedMessages.length === 0) {
          throw new AnthropicError("stream ended without producing a Message with role=assistant");
        }
        return this.receivedMessages.at(-1);
      }, "_BetaMessageStream_getFinalMessage"), _BetaMessageStream_getFinalText = /* @__PURE__ */ __name(function _BetaMessageStream_getFinalText2() {
        if (this.receivedMessages.length === 0) {
          throw new AnthropicError("stream ended without producing a Message with role=assistant");
        }
        const textBlocks = this.receivedMessages.at(-1).content.filter((block2) => block2.type === "text").map((block2) => block2.text);
        if (textBlocks.length === 0) {
          throw new AnthropicError("stream ended without producing a content block with type=text");
        }
        return textBlocks.join(" ");
      }, "_BetaMessageStream_getFinalText"), _BetaMessageStream_beginRequest = /* @__PURE__ */ __name(function _BetaMessageStream_beginRequest2() {
        if (this.ended)
          return;
        __classPrivateFieldSet7(this, _BetaMessageStream_currentMessageSnapshot, void 0, "f");
      }, "_BetaMessageStream_beginRequest"), _BetaMessageStream_addStreamEvent = /* @__PURE__ */ __name(function _BetaMessageStream_addStreamEvent2(event) {
        if (this.ended)
          return;
        const messageSnapshot = __classPrivateFieldGet8(this, _BetaMessageStream_instances, "m", _BetaMessageStream_accumulateMessage).call(this, event);
        this._emit("streamEvent", event, messageSnapshot);
        switch (event.type) {
          case "content_block_delta": {
            const content = messageSnapshot.content.at(-1);
            switch (event.delta.type) {
              case "text_delta": {
                if (content.type === "text") {
                  this._emit("text", event.delta.text, content.text || "");
                }
                break;
              }
              case "citations_delta": {
                if (content.type === "text") {
                  this._emit("citation", event.delta.citation, content.citations ?? []);
                }
                break;
              }
              case "input_json_delta": {
                if (content.type === "tool_use" && content.input) {
                  this._emit("inputJson", event.delta.partial_json, content.input);
                }
                break;
              }
              default:
                checkNever(event.delta);
            }
            break;
          }
          case "message_stop": {
            this._addMessageParam(messageSnapshot);
            this._addMessage(messageSnapshot, true);
            break;
          }
          case "content_block_stop": {
            this._emit("contentBlock", messageSnapshot.content.at(-1));
            break;
          }
          case "message_start": {
            __classPrivateFieldSet7(this, _BetaMessageStream_currentMessageSnapshot, messageSnapshot, "f");
            break;
          }
          case "content_block_start":
          case "message_delta":
            break;
        }
      }, "_BetaMessageStream_addStreamEvent"), _BetaMessageStream_endRequest = /* @__PURE__ */ __name(function _BetaMessageStream_endRequest2() {
        if (this.ended) {
          throw new AnthropicError(`stream has ended, this shouldn't happen`);
        }
        const snapshot = __classPrivateFieldGet8(this, _BetaMessageStream_currentMessageSnapshot, "f");
        if (!snapshot) {
          throw new AnthropicError(`request ended without sending any chunks`);
        }
        __classPrivateFieldSet7(this, _BetaMessageStream_currentMessageSnapshot, void 0, "f");
        return snapshot;
      }, "_BetaMessageStream_endRequest"), _BetaMessageStream_accumulateMessage = /* @__PURE__ */ __name(function _BetaMessageStream_accumulateMessage2(event) {
        let snapshot = __classPrivateFieldGet8(this, _BetaMessageStream_currentMessageSnapshot, "f");
        if (event.type === "message_start") {
          if (snapshot) {
            throw new AnthropicError(`Unexpected event order, got ${event.type} before receiving "message_stop"`);
          }
          return event.message;
        }
        if (!snapshot) {
          throw new AnthropicError(`Unexpected event order, got ${event.type} before "message_start"`);
        }
        switch (event.type) {
          case "message_stop":
            return snapshot;
          case "message_delta":
            snapshot.stop_reason = event.delta.stop_reason;
            snapshot.stop_sequence = event.delta.stop_sequence;
            snapshot.usage.output_tokens = event.usage.output_tokens;
            return snapshot;
          case "content_block_start":
            snapshot.content.push(event.content_block);
            return snapshot;
          case "content_block_delta": {
            const snapshotContent = snapshot.content.at(event.index);
            switch (event.delta.type) {
              case "text_delta": {
                if (snapshotContent?.type === "text") {
                  snapshotContent.text += event.delta.text;
                }
                break;
              }
              case "citations_delta": {
                if (snapshotContent?.type === "text") {
                  snapshotContent.citations ?? (snapshotContent.citations = []);
                  snapshotContent.citations.push(event.delta.citation);
                }
                break;
              }
              case "input_json_delta": {
                if (snapshotContent?.type === "tool_use") {
                  let jsonBuf = snapshotContent[JSON_BUF_PROPERTY] || "";
                  jsonBuf += event.delta.partial_json;
                  Object.defineProperty(snapshotContent, JSON_BUF_PROPERTY, {
                    value: jsonBuf,
                    enumerable: false,
                    writable: true
                  });
                  if (jsonBuf) {
                    snapshotContent.input = partialParse2(jsonBuf);
                  }
                }
                break;
              }
              default:
                checkNever(event.delta);
            }
            return snapshot;
          }
          case "content_block_stop":
            return snapshot;
        }
      }, "_BetaMessageStream_accumulateMessage"), Symbol.asyncIterator)]() {
        const pushQueue = [];
        const readQueue = [];
        let done = false;
        this.on("streamEvent", (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((resolve30, reject) => readQueue.push({ resolve: resolve30, 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 Stream4(this[Symbol.asyncIterator].bind(this), this.controller);
        return stream2.toReadableStream();
      }
    };
    __name(checkNever, "checkNever");
  }
});

// node_modules/@anthropic-ai/sdk/resources/beta/messages/messages.mjs
var DEPRECATED_MODELS, Messages3;
var init_messages3 = __esm({
  "node_modules/@anthropic-ai/sdk/resources/beta/messages/messages.mjs"() {
    init_esbuild_shims();
    init_resource3();
    init_batches2();
    init_batches2();
    init_BetaMessageStream();
    DEPRECATED_MODELS = {
      "claude-1.3": "November 6th, 2024",
      "claude-1.3-100k": "November 6th, 2024",
      "claude-instant-1.1": "November 6th, 2024",
      "claude-instant-1.1-100k": "November 6th, 2024",
      "claude-instant-1.2": "November 6th, 2024",
      "claude-3-sonnet-20240229": "July 21st, 2025",
      "claude-2.1": "July 21st, 2025",
      "claude-2.0": "July 21st, 2025"
    };
    Messages3 = class extends APIResource2 {
      static {
        __name(this, "Messages");
      }
      constructor() {
        super(...arguments);
        this.batches = new Batches3(this._client);
      }
      create(params, options2) {
        const { betas, ...body } = params;
        if (body.model in DEPRECATED_MODELS) {
          console.warn(`The model '${body.model}' is deprecated and will reach end-of-life on ${DEPRECATED_MODELS[body.model]}
Please migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`);
        }
        return this._client.post("/v1/messages?beta=true", {
          body,
          timeout: this._client._options.timeout ?? 6e5,
          ...options2,
          headers: {
            ...betas?.toString() != null ? { "anthropic-beta": betas?.toString() } : void 0,
            ...options2?.headers
          },
          stream: params.stream ?? false
        });
      }
      /**
       * Create a Message stream
       */
      stream(body, options2) {
        return BetaMessageStream.createMessage(this, body, options2);
      }
      /**
       * Count the number of tokens in a Message.
       *
       * The Token Count API can be used to count the number of tokens in a Message,
       * including tools, images, and documents, without creating it.
       */
      countTokens(params, options2) {
        const { betas, ...body } = params;
        return this._client.post("/v1/messages/count_tokens?beta=true", {
          body,
          ...options2,
          headers: {
            "anthropic-beta": [...betas ?? [], "token-counting-2024-11-01"].toString(),
            ...options2?.headers
          }
        });
      }
    };
    Messages3.Batches = Batches3;
    Messages3.BetaMessageBatchesPage = BetaMessageBatchesPage;
  }
});

// node_modules/@anthropic-ai/sdk/resources/beta/beta.mjs
var Beta2;
var init_beta2 = __esm({
  "node_modules/@anthropic-ai/sdk/resources/beta/beta.mjs"() {
    init_esbuild_shims();
    init_resource3();
    init_models3();
    init_models3();
    init_messages3();
    init_messages3();
    Beta2 = class extends APIResource2 {
      static {
        __name(this, "Beta");
      }
      constructor() {
        super(...arguments);
        this.models = new Models3(this._client);
        this.messages = new Messages3(this._client);
      }
    };
    Beta2.Models = Models3;
    Beta2.BetaModelInfosPage = BetaModelInfosPage;
    Beta2.Messages = Messages3;
  }
});

// node_modules/@anthropic-ai/sdk/resources/completions.mjs
var Completions3;
var init_completions4 = __esm({
  "node_modules/@anthropic-ai/sdk/resources/completions.mjs"() {
    init_esbuild_shims();
    init_resource3();
    Completions3 = class extends APIResource2 {
      static {
        __name(this, "Completions");
      }
      create(body, options2) {
        return this._client.post("/v1/complete", {
          body,
          timeout: this._client._options.timeout ?? 6e5,
          ...options2,
          stream: body.stream ?? false
        });
      }
    };
  }
});

// node_modules/@anthropic-ai/sdk/resources/messages/batches.mjs
var Batches4, MessageBatchesPage;
var init_batches3 = __esm({
  "node_modules/@anthropic-ai/sdk/resources/messages/batches.mjs"() {
    init_esbuild_shims();
    init_resource3();
    init_core();
    init_pagination2();
    init_jsonl();
    init_error3();
    Batches4 = class extends APIResource2 {
      static {
        __name(this, "Batches");
      }
      /**
       * Send a batch of Message creation requests.
       *
       * The Message Batches API can be used to process multiple Messages API requests at
       * once. Once a Message Batch is created, it begins processing immediately. Batches
       * can take up to 24 hours to complete.
       */
      create(body, options2) {
        return this._client.post("/v1/messages/batches", { body, ...options2 });
      }
      /**
       * This endpoint is idempotent and can be used to poll for Message Batch
       * completion. To access the results of a Message Batch, make a request to the
       * `results_url` field in the response.
       */
      retrieve(messageBatchId, options2) {
        return this._client.get(`/v1/messages/batches/${messageBatchId}`, options2);
      }
      list(query = {}, options2) {
        if (isRequestOptions(query)) {
          return this.list({}, query);
        }
        return this._client.getAPIList("/v1/messages/batches", MessageBatchesPage, { query, ...options2 });
      }
      /**
       * Delete a Message Batch.
       *
       * Message Batches can only be deleted once they've finished processing. If you'd
       * like to delete an in-progress batch, you must first cancel it.
       */
      delete(messageBatchId, options2) {
        return this._client.delete(`/v1/messages/batches/${messageBatchId}`, options2);
      }
      /**
       * Batches may be canceled any time before processing ends. Once cancellation is
       * initiated, the batch enters a `canceling` state, at which time the system may
       * complete any in-progress, non-interruptible requests before finalizing
       * cancellation.
       *
       * The number of canceled requests is specified in `request_counts`. To determine
       * which requests were canceled, check the individual results within the batch.
       * Note that cancellation may not result in any canceled requests if they were
       * non-interruptible.
       */
      cancel(messageBatchId, options2) {
        return this._client.post(`/v1/messages/batches/${messageBatchId}/cancel`, options2);
      }
      /**
       * Streams the results of a Message Batch as a `.jsonl` file.
       *
       * Each line in the file is a JSON object containing the result of a single request
       * in the Message Batch. Results are not guaranteed to be in the same order as
       * requests. Use the `custom_id` field to match results to requests.
       */
      async results(messageBatchId, options2) {
        const batch = await this.retrieve(messageBatchId);
        if (!batch.results_url) {
          throw new AnthropicError(`No batch \`results_url\`; Has it finished processing? ${batch.processing_status} - ${batch.id}`);
        }
        return this._client.get(batch.results_url, {
          ...options2,
          headers: {
            Accept: "application/binary",
            ...options2?.headers
          },
          __binaryResponse: true
        })._thenUnwrap((_2, props) => JSONLDecoder.fromResponse(props.response, props.controller));
      }
    };
    MessageBatchesPage = class extends Page2 {
      static {
        __name(this, "MessageBatchesPage");
      }
    };
    Batches4.MessageBatchesPage = MessageBatchesPage;
  }
});

// node_modules/@anthropic-ai/sdk/lib/MessageStream.mjs
function checkNever2(x3) {
}
var __classPrivateFieldSet8, __classPrivateFieldGet9, _MessageStream_instances, _MessageStream_currentMessageSnapshot, _MessageStream_connectedPromise, _MessageStream_resolveConnectedPromise, _MessageStream_rejectConnectedPromise, _MessageStream_endPromise, _MessageStream_resolveEndPromise, _MessageStream_rejectEndPromise, _MessageStream_listeners, _MessageStream_ended, _MessageStream_errored, _MessageStream_aborted, _MessageStream_catchingPromiseCreated, _MessageStream_response, _MessageStream_request_id, _MessageStream_getFinalMessage, _MessageStream_getFinalText, _MessageStream_handleError, _MessageStream_beginRequest, _MessageStream_addStreamEvent, _MessageStream_endRequest, _MessageStream_accumulateMessage, JSON_BUF_PROPERTY2, MessageStream;
var init_MessageStream = __esm({
  "node_modules/@anthropic-ai/sdk/lib/MessageStream.mjs"() {
    init_esbuild_shims();
    init_error3();
    init_streaming3();
    init_parser3();
    __classPrivateFieldSet8 = function(receiver, state, value, kind2, f5) {
      if (kind2 === "m") throw new TypeError("Private method is not writable");
      if (kind2 === "a" && !f5) throw new TypeError("Private accessor was defined without a setter");
      if (typeof state === "function" ? receiver !== state || !f5 : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
      return kind2 === "a" ? f5.call(receiver, value) : f5 ? f5.value = value : state.set(receiver, value), value;
    };
    __classPrivateFieldGet9 = function(receiver, state, kind2, f5) {
      if (kind2 === "a" && !f5) throw new TypeError("Private accessor was defined without a getter");
      if (typeof state === "function" ? receiver !== state || !f5 : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
      return kind2 === "m" ? f5 : kind2 === "a" ? f5.call(receiver) : f5 ? f5.value : state.get(receiver);
    };
    JSON_BUF_PROPERTY2 = "__json_buf";
    MessageStream = class _MessageStream {
      static {
        __name(this, "MessageStream");
      }
      constructor() {
        _MessageStream_instances.add(this);
        this.messages = [];
        this.receivedMessages = [];
        _MessageStream_currentMessageSnapshot.set(this, void 0);
        this.controller = new AbortController();
        _MessageStream_connectedPromise.set(this, void 0);
        _MessageStream_resolveConnectedPromise.set(this, () => {
        });
        _MessageStream_rejectConnectedPromise.set(this, () => {
        });
        _MessageStream_endPromise.set(this, void 0);
        _MessageStream_resolveEndPromise.set(this, () => {
        });
        _MessageStream_rejectEndPromise.set(this, () => {
        });
        _MessageStream_listeners.set(this, {});
        _MessageStream_ended.set(this, false);
        _MessageStream_errored.set(this, false);
        _MessageStream_aborted.set(this, false);
        _MessageStream_catchingPromiseCreated.set(this, false);
        _MessageStream_response.set(this, void 0);
        _MessageStream_request_id.set(this, void 0);
        _MessageStream_handleError.set(this, (error2) => {
          __classPrivateFieldSet8(this, _MessageStream_errored, true, "f");
          if (error2 instanceof Error && error2.name === "AbortError") {
            error2 = new APIUserAbortError2();
          }
          if (error2 instanceof APIUserAbortError2) {
            __classPrivateFieldSet8(this, _MessageStream_aborted, true, "f");
            return this._emit("abort", error2);
          }
          if (error2 instanceof AnthropicError) {
            return this._emit("error", error2);
          }
          if (error2 instanceof Error) {
            const anthropicError = new AnthropicError(error2.message);
            anthropicError.cause = error2;
            return this._emit("error", anthropicError);
          }
          return this._emit("error", new AnthropicError(String(error2)));
        });
        __classPrivateFieldSet8(this, _MessageStream_connectedPromise, new Promise((resolve30, reject) => {
          __classPrivateFieldSet8(this, _MessageStream_resolveConnectedPromise, resolve30, "f");
          __classPrivateFieldSet8(this, _MessageStream_rejectConnectedPromise, reject, "f");
        }), "f");
        __classPrivateFieldSet8(this, _MessageStream_endPromise, new Promise((resolve30, reject) => {
          __classPrivateFieldSet8(this, _MessageStream_resolveEndPromise, resolve30, "f");
          __classPrivateFieldSet8(this, _MessageStream_rejectEndPromise, reject, "f");
        }), "f");
        __classPrivateFieldGet9(this, _MessageStream_connectedPromise, "f").catch(() => {
        });
        __classPrivateFieldGet9(this, _MessageStream_endPromise, "f").catch(() => {
        });
      }
      get response() {
        return __classPrivateFieldGet9(this, _MessageStream_response, "f");
      }
      get request_id() {
        return __classPrivateFieldGet9(this, _MessageStream_request_id, "f");
      }
      /**
       * Returns the `MessageStream` data, the raw `Response` instance and the ID of the request,
       * returned vie the `request-id` header which is useful for debugging requests and resporting
       * issues to Anthropic.
       *
       * This is the same as the `APIPromise.withResponse()` method.
       *
       * This method will raise an error if you created the stream using `MessageStream.fromReadableStream`
       * as no `Response` is available.
       */
      async withResponse() {
        const response = await __classPrivateFieldGet9(this, _MessageStream_connectedPromise, "f");
        if (!response) {
          throw new Error("Could not resolve a `Response` object");
        }
        return {
          data: this,
          response,
          request_id: response.headers.get("request-id")
        };
      }
      /**
       * 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 _MessageStream();
        runner._run(() => runner._fromReadableStream(stream2));
        return runner;
      }
      static createMessage(messages, params, options2) {
        const runner = new _MessageStream();
        for (const message of params.messages) {
          runner._addMessageParam(message);
        }
        runner._run(() => runner._createMessage(messages, { ...params, stream: true }, { ...options2, headers: { ...options2?.headers, "X-Stainless-Helper-Method": "stream" } }));
        return runner;
      }
      _run(executor) {
        executor().then(() => {
          this._emitFinal();
          this._emit("end");
        }, __classPrivateFieldGet9(this, _MessageStream_handleError, "f"));
      }
      _addMessageParam(message) {
        this.messages.push(message);
      }
      _addMessage(message, emit = true) {
        this.receivedMessages.push(message);
        if (emit) {
          this._emit("message", message);
        }
      }
      async _createMessage(messages, params, options2) {
        const signal = options2?.signal;
        if (signal) {
          if (signal.aborted)
            this.controller.abort();
          signal.addEventListener("abort", () => this.controller.abort());
        }
        __classPrivateFieldGet9(this, _MessageStream_instances, "m", _MessageStream_beginRequest).call(this);
        const { response, data: stream2 } = await messages.create({ ...params, stream: true }, { ...options2, signal: this.controller.signal }).withResponse();
        this._connected(response);
        for await (const event of stream2) {
          __classPrivateFieldGet9(this, _MessageStream_instances, "m", _MessageStream_addStreamEvent).call(this, event);
        }
        if (stream2.controller.signal?.aborted) {
          throw new APIUserAbortError2();
        }
        __classPrivateFieldGet9(this, _MessageStream_instances, "m", _MessageStream_endRequest).call(this);
      }
      _connected(response) {
        if (this.ended)
          return;
        __classPrivateFieldSet8(this, _MessageStream_response, response, "f");
        __classPrivateFieldSet8(this, _MessageStream_request_id, response?.headers.get("request-id"), "f");
        __classPrivateFieldGet9(this, _MessageStream_resolveConnectedPromise, "f").call(this, response);
        this._emit("connect");
      }
      get ended() {
        return __classPrivateFieldGet9(this, _MessageStream_ended, "f");
      }
      get errored() {
        return __classPrivateFieldGet9(this, _MessageStream_errored, "f");
      }
      get aborted() {
        return __classPrivateFieldGet9(this, _MessageStream_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 MessageStream, so that calls can be chained
       */
      on(event, listener) {
        const listeners = __classPrivateFieldGet9(this, _MessageStream_listeners, "f")[event] || (__classPrivateFieldGet9(this, _MessageStream_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 MessageStream, so that calls can be chained
       */
      off(event, listener) {
        const listeners = __classPrivateFieldGet9(this, _MessageStream_listeners, "f")[event];
        if (!listeners)
          return this;
        const index = listeners.findIndex((l3) => l3.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 MessageStream, so that calls can be chained
       */
      once(event, listener) {
        const listeners = __classPrivateFieldGet9(this, _MessageStream_listeners, "f")[event] || (__classPrivateFieldGet9(this, _MessageStream_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((resolve30, reject) => {
          __classPrivateFieldSet8(this, _MessageStream_catchingPromiseCreated, true, "f");
          if (event !== "error")
            this.once("error", reject);
          this.once(event, resolve30);
        });
      }
      async done() {
        __classPrivateFieldSet8(this, _MessageStream_catchingPromiseCreated, true, "f");
        await __classPrivateFieldGet9(this, _MessageStream_endPromise, "f");
      }
      get currentMessage() {
        return __classPrivateFieldGet9(this, _MessageStream_currentMessageSnapshot, "f");
      }
      /**
       * @returns a promise that resolves with the the final assistant Message response,
       * or rejects if an error occurred or the stream ended prematurely without producing a Message.
       */
      async finalMessage() {
        await this.done();
        return __classPrivateFieldGet9(this, _MessageStream_instances, "m", _MessageStream_getFinalMessage).call(this);
      }
      /**
       * @returns a promise that resolves with the the final assistant Message's text response, concatenated
       * together if there are more than one text blocks.
       * Rejects if an error occurred or the stream ended prematurely without producing a Message.
       */
      async finalText() {
        await this.done();
        return __classPrivateFieldGet9(this, _MessageStream_instances, "m", _MessageStream_getFinalText).call(this);
      }
      _emit(event, ...args) {
        if (__classPrivateFieldGet9(this, _MessageStream_ended, "f"))
          return;
        if (event === "end") {
          __classPrivateFieldSet8(this, _MessageStream_ended, true, "f");
          __classPrivateFieldGet9(this, _MessageStream_resolveEndPromise, "f").call(this);
        }
        const listeners = __classPrivateFieldGet9(this, _MessageStream_listeners, "f")[event];
        if (listeners) {
          __classPrivateFieldGet9(this, _MessageStream_listeners, "f")[event] = listeners.filter((l3) => !l3.once);
          listeners.forEach(({ listener }) => listener(...args));
        }
        if (event === "abort") {
          const error2 = args[0];
          if (!__classPrivateFieldGet9(this, _MessageStream_catchingPromiseCreated, "f") && !listeners?.length) {
            Promise.reject(error2);
          }
          __classPrivateFieldGet9(this, _MessageStream_rejectConnectedPromise, "f").call(this, error2);
          __classPrivateFieldGet9(this, _MessageStream_rejectEndPromise, "f").call(this, error2);
          this._emit("end");
          return;
        }
        if (event === "error") {
          const error2 = args[0];
          if (!__classPrivateFieldGet9(this, _MessageStream_catchingPromiseCreated, "f") && !listeners?.length) {
            Promise.reject(error2);
          }
          __classPrivateFieldGet9(this, _MessageStream_rejectConnectedPromise, "f").call(this, error2);
          __classPrivateFieldGet9(this, _MessageStream_rejectEndPromise, "f").call(this, error2);
          this._emit("end");
        }
      }
      _emitFinal() {
        const finalMessage = this.receivedMessages.at(-1);
        if (finalMessage) {
          this._emit("finalMessage", __classPrivateFieldGet9(this, _MessageStream_instances, "m", _MessageStream_getFinalMessage).call(this));
        }
      }
      async _fromReadableStream(readableStream, options2) {
        const signal = options2?.signal;
        if (signal) {
          if (signal.aborted)
            this.controller.abort();
          signal.addEventListener("abort", () => this.controller.abort());
        }
        __classPrivateFieldGet9(this, _MessageStream_instances, "m", _MessageStream_beginRequest).call(this);
        this._connected(null);
        const stream2 = Stream4.fromReadableStream(readableStream, this.controller);
        for await (const event of stream2) {
          __classPrivateFieldGet9(this, _MessageStream_instances, "m", _MessageStream_addStreamEvent).call(this, event);
        }
        if (stream2.controller.signal?.aborted) {
          throw new APIUserAbortError2();
        }
        __classPrivateFieldGet9(this, _MessageStream_instances, "m", _MessageStream_endRequest).call(this);
      }
      [(_MessageStream_currentMessageSnapshot = /* @__PURE__ */ new WeakMap(), _MessageStream_connectedPromise = /* @__PURE__ */ new WeakMap(), _MessageStream_resolveConnectedPromise = /* @__PURE__ */ new WeakMap(), _MessageStream_rejectConnectedPromise = /* @__PURE__ */ new WeakMap(), _MessageStream_endPromise = /* @__PURE__ */ new WeakMap(), _MessageStream_resolveEndPromise = /* @__PURE__ */ new WeakMap(), _MessageStream_rejectEndPromise = /* @__PURE__ */ new WeakMap(), _MessageStream_listeners = /* @__PURE__ */ new WeakMap(), _MessageStream_ended = /* @__PURE__ */ new WeakMap(), _MessageStream_errored = /* @__PURE__ */ new WeakMap(), _MessageStream_aborted = /* @__PURE__ */ new WeakMap(), _MessageStream_catchingPromiseCreated = /* @__PURE__ */ new WeakMap(), _MessageStream_response = /* @__PURE__ */ new WeakMap(), _MessageStream_request_id = /* @__PURE__ */ new WeakMap(), _MessageStream_handleError = /* @__PURE__ */ new WeakMap(), _MessageStream_instances = /* @__PURE__ */ new WeakSet(), _MessageStream_getFinalMessage = /* @__PURE__ */ __name(function _MessageStream_getFinalMessage2() {
        if (this.receivedMessages.length === 0) {
          throw new AnthropicError("stream ended without producing a Message with role=assistant");
        }
        return this.receivedMessages.at(-1);
      }, "_MessageStream_getFinalMessage"), _MessageStream_getFinalText = /* @__PURE__ */ __name(function _MessageStream_getFinalText2() {
        if (this.receivedMessages.length === 0) {
          throw new AnthropicError("stream ended without producing a Message with role=assistant");
        }
        const textBlocks = this.receivedMessages.at(-1).content.filter((block2) => block2.type === "text").map((block2) => block2.text);
        if (textBlocks.length === 0) {
          throw new AnthropicError("stream ended without producing a content block with type=text");
        }
        return textBlocks.join(" ");
      }, "_MessageStream_getFinalText"), _MessageStream_beginRequest = /* @__PURE__ */ __name(function _MessageStream_beginRequest2() {
        if (this.ended)
          return;
        __classPrivateFieldSet8(this, _MessageStream_currentMessageSnapshot, void 0, "f");
      }, "_MessageStream_beginRequest"), _MessageStream_addStreamEvent = /* @__PURE__ */ __name(function _MessageStream_addStreamEvent2(event) {
        if (this.ended)
          return;
        const messageSnapshot = __classPrivateFieldGet9(this, _MessageStream_instances, "m", _MessageStream_accumulateMessage).call(this, event);
        this._emit("streamEvent", event, messageSnapshot);
        switch (event.type) {
          case "content_block_delta": {
            const content = messageSnapshot.content.at(-1);
            switch (event.delta.type) {
              case "text_delta": {
                if (content.type === "text") {
                  this._emit("text", event.delta.text, content.text || "");
                }
                break;
              }
              case "citations_delta": {
                if (content.type === "text") {
                  this._emit("citation", event.delta.citation, content.citations ?? []);
                }
                break;
              }
              case "input_json_delta": {
                if (content.type === "tool_use" && content.input) {
                  this._emit("inputJson", event.delta.partial_json, content.input);
                }
                break;
              }
              default:
                checkNever2(event.delta);
            }
            break;
          }
          case "message_stop": {
            this._addMessageParam(messageSnapshot);
            this._addMessage(messageSnapshot, true);
            break;
          }
          case "content_block_stop": {
            this._emit("contentBlock", messageSnapshot.content.at(-1));
            break;
          }
          case "message_start": {
            __classPrivateFieldSet8(this, _MessageStream_currentMessageSnapshot, messageSnapshot, "f");
            break;
          }
          case "content_block_start":
          case "message_delta":
            break;
        }
      }, "_MessageStream_addStreamEvent"), _MessageStream_endRequest = /* @__PURE__ */ __name(function _MessageStream_endRequest2() {
        if (this.ended) {
          throw new AnthropicError(`stream has ended, this shouldn't happen`);
        }
        const snapshot = __classPrivateFieldGet9(this, _MessageStream_currentMessageSnapshot, "f");
        if (!snapshot) {
          throw new AnthropicError(`request ended without sending any chunks`);
        }
        __classPrivateFieldSet8(this, _MessageStream_currentMessageSnapshot, void 0, "f");
        return snapshot;
      }, "_MessageStream_endRequest"), _MessageStream_accumulateMessage = /* @__PURE__ */ __name(function _MessageStream_accumulateMessage2(event) {
        let snapshot = __classPrivateFieldGet9(this, _MessageStream_currentMessageSnapshot, "f");
        if (event.type === "message_start") {
          if (snapshot) {
            throw new AnthropicError(`Unexpected event order, got ${event.type} before receiving "message_stop"`);
          }
          return event.message;
        }
        if (!snapshot) {
          throw new AnthropicError(`Unexpected event order, got ${event.type} before "message_start"`);
        }
        switch (event.type) {
          case "message_stop":
            return snapshot;
          case "message_delta":
            snapshot.stop_reason = event.delta.stop_reason;
            snapshot.stop_sequence = event.delta.stop_sequence;
            snapshot.usage.output_tokens = event.usage.output_tokens;
            return snapshot;
          case "content_block_start":
            snapshot.content.push(event.content_block);
            return snapshot;
          case "content_block_delta": {
            const snapshotContent = snapshot.content.at(event.index);
            switch (event.delta.type) {
              case "text_delta": {
                if (snapshotContent?.type === "text") {
                  snapshotContent.text += event.delta.text;
                }
                break;
              }
              case "citations_delta": {
                if (snapshotContent?.type === "text") {
                  snapshotContent.citations ?? (snapshotContent.citations = []);
                  snapshotContent.citations.push(event.delta.citation);
                }
                break;
              }
              case "input_json_delta": {
                if (snapshotContent?.type === "tool_use") {
                  let jsonBuf = snapshotContent[JSON_BUF_PROPERTY2] || "";
                  jsonBuf += event.delta.partial_json;
                  Object.defineProperty(snapshotContent, JSON_BUF_PROPERTY2, {
                    value: jsonBuf,
                    enumerable: false,
                    writable: true
                  });
                  if (jsonBuf) {
                    snapshotContent.input = partialParse2(jsonBuf);
                  }
                }
                break;
              }
              default:
                checkNever2(event.delta);
            }
            return snapshot;
          }
          case "content_block_stop":
            return snapshot;
        }
      }, "_MessageStream_accumulateMessage"), Symbol.asyncIterator)]() {
        const pushQueue = [];
        const readQueue = [];
        let done = false;
        this.on("streamEvent", (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((resolve30, reject) => readQueue.push({ resolve: resolve30, 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 Stream4(this[Symbol.asyncIterator].bind(this), this.controller);
        return stream2.toReadableStream();
      }
    };
    __name(checkNever2, "checkNever");
  }
});

// node_modules/@anthropic-ai/sdk/resources/messages/messages.mjs
var Messages4, DEPRECATED_MODELS2;
var init_messages4 = __esm({
  "node_modules/@anthropic-ai/sdk/resources/messages/messages.mjs"() {
    init_esbuild_shims();
    init_resource3();
    init_batches3();
    init_batches3();
    init_MessageStream();
    Messages4 = class extends APIResource2 {
      static {
        __name(this, "Messages");
      }
      constructor() {
        super(...arguments);
        this.batches = new Batches4(this._client);
      }
      create(body, options2) {
        if (body.model in DEPRECATED_MODELS2) {
          console.warn(`The model '${body.model}' is deprecated and will reach end-of-life on ${DEPRECATED_MODELS2[body.model]}
Please migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`);
        }
        return this._client.post("/v1/messages", {
          body,
          timeout: this._client._options.timeout ?? 6e5,
          ...options2,
          stream: body.stream ?? false
        });
      }
      /**
       * Create a Message stream
       */
      stream(body, options2) {
        return MessageStream.createMessage(this, body, options2);
      }
      /**
       * Count the number of tokens in a Message.
       *
       * The Token Count API can be used to count the number of tokens in a Message,
       * including tools, images, and documents, without creating it.
       */
      countTokens(body, options2) {
        return this._client.post("/v1/messages/count_tokens", { body, ...options2 });
      }
    };
    DEPRECATED_MODELS2 = {
      "claude-1.3": "November 6th, 2024",
      "claude-1.3-100k": "November 6th, 2024",
      "claude-instant-1.1": "November 6th, 2024",
      "claude-instant-1.1-100k": "November 6th, 2024",
      "claude-instant-1.2": "November 6th, 2024",
      "claude-3-sonnet-20240229": "July 21st, 2025",
      "claude-2.1": "July 21st, 2025",
      "claude-2.0": "July 21st, 2025"
    };
    Messages4.Batches = Batches4;
    Messages4.MessageBatchesPage = MessageBatchesPage;
  }
});

// node_modules/@anthropic-ai/sdk/resources/models.mjs
var Models4, ModelInfosPage;
var init_models4 = __esm({
  "node_modules/@anthropic-ai/sdk/resources/models.mjs"() {
    init_esbuild_shims();
    init_resource3();
    init_core();
    init_pagination2();
    Models4 = class extends APIResource2 {
      static {
        __name(this, "Models");
      }
      /**
       * Get a specific model.
       *
       * The Models API response can be used to determine information about a specific
       * model or resolve a model alias to a model ID.
       */
      retrieve(modelId, options2) {
        return this._client.get(`/v1/models/${modelId}`, options2);
      }
      list(query = {}, options2) {
        if (isRequestOptions(query)) {
          return this.list({}, query);
        }
        return this._client.getAPIList("/v1/models", ModelInfosPage, { query, ...options2 });
      }
    };
    ModelInfosPage = class extends Page2 {
      static {
        __name(this, "ModelInfosPage");
      }
    };
    Models4.ModelInfosPage = ModelInfosPage;
  }
});

// node_modules/@anthropic-ai/sdk/resources/index.mjs
var init_resources2 = __esm({
  "node_modules/@anthropic-ai/sdk/resources/index.mjs"() {
    init_esbuild_shims();
    init_shared2();
    init_beta2();
    init_completions4();
    init_messages4();
    init_models4();
  }
});

// node_modules/@anthropic-ai/sdk/index.mjs
var _a3, Anthropic, HUMAN_PROMPT, AI_PROMPT, sdk_default;
var init_sdk2 = __esm({
  "node_modules/@anthropic-ai/sdk/index.mjs"() {
    init_esbuild_shims();
    init_core();
    init_error3();
    init_uploads4();
    init_resources2();
    init_completions4();
    init_models4();
    init_beta2();
    init_messages4();
    Anthropic = class extends APIClient {
      static {
        __name(this, "Anthropic");
      }
      /**
       * API Client for interfacing with the Anthropic API.
       *
       * @param {string | null | undefined} [opts.apiKey=process.env['ANTHROPIC_API_KEY'] ?? null]
       * @param {string | null | undefined} [opts.authToken=process.env['ANTHROPIC_AUTH_TOKEN'] ?? null]
       * @param {string} [opts.baseURL=process.env['ANTHROPIC_BASE_URL'] ?? https://api.anthropic.com] - 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 {number} [opts.httpAgent] - An HTTP agent used to manage HTTP(s) connections.
       * @param {Core.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 {Core.Headers} opts.defaultHeaders - Default headers to include with every request to the API.
       * @param {Core.DefaultQuery} 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 = readEnv2("ANTHROPIC_BASE_URL"), apiKey = readEnv2("ANTHROPIC_API_KEY") ?? null, authToken = readEnv2("ANTHROPIC_AUTH_TOKEN") ?? null, ...opts } = {}) {
        const options2 = {
          apiKey,
          authToken,
          ...opts,
          baseURL: baseURL || `https://api.anthropic.com`
        };
        if (!options2.dangerouslyAllowBrowser && isRunningInBrowser2()) {
          throw new AnthropicError("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 Anthropic({ apiKey, dangerouslyAllowBrowser: true });\n");
        }
        super({
          baseURL: options2.baseURL,
          timeout: options2.timeout ?? 6e5,
          httpAgent: options2.httpAgent,
          maxRetries: options2.maxRetries,
          fetch: options2.fetch
        });
        this.completions = new Completions3(this);
        this.messages = new Messages4(this);
        this.models = new Models4(this);
        this.beta = new Beta2(this);
        this._options = options2;
        this.apiKey = apiKey;
        this.authToken = authToken;
      }
      defaultQuery() {
        return this._options.defaultQuery;
      }
      defaultHeaders(opts) {
        return {
          ...super.defaultHeaders(opts),
          ...this._options.dangerouslyAllowBrowser ? { "anthropic-dangerous-direct-browser-access": "true" } : void 0,
          "anthropic-version": "2023-06-01",
          ...this._options.defaultHeaders
        };
      }
      validateHeaders(headers, customHeaders) {
        if (this.apiKey && headers["x-api-key"]) {
          return;
        }
        if (customHeaders["x-api-key"] === null) {
          return;
        }
        if (this.authToken && headers["authorization"]) {
          return;
        }
        if (customHeaders["authorization"] === null) {
          return;
        }
        throw new Error('Could not resolve authentication method. Expected either apiKey or authToken to be set. Or for one of the "X-Api-Key" or "Authorization" headers to be explicitly omitted');
      }
      authHeaders(opts) {
        const apiKeyAuth = this.apiKeyAuth(opts);
        const bearerAuth = this.bearerAuth(opts);
        if (apiKeyAuth != null && !isEmptyObj2(apiKeyAuth)) {
          return apiKeyAuth;
        }
        if (bearerAuth != null && !isEmptyObj2(bearerAuth)) {
          return bearerAuth;
        }
        return {};
      }
      apiKeyAuth(opts) {
        if (this.apiKey == null) {
          return {};
        }
        return { "X-Api-Key": this.apiKey };
      }
      bearerAuth(opts) {
        if (this.authToken == null) {
          return {};
        }
        return { Authorization: `Bearer ${this.authToken}` };
      }
    };
    _a3 = Anthropic;
    Anthropic.Anthropic = _a3;
    Anthropic.HUMAN_PROMPT = "\n\nHuman:";
    Anthropic.AI_PROMPT = "\n\nAssistant:";
    Anthropic.DEFAULT_TIMEOUT = 6e5;
    Anthropic.AnthropicError = AnthropicError;
    Anthropic.APIError = APIError2;
    Anthropic.APIConnectionError = APIConnectionError2;
    Anthropic.APIConnectionTimeoutError = APIConnectionTimeoutError2;
    Anthropic.APIUserAbortError = APIUserAbortError2;
    Anthropic.NotFoundError = NotFoundError2;
    Anthropic.ConflictError = ConflictError2;
    Anthropic.RateLimitError = RateLimitError2;
    Anthropic.BadRequestError = BadRequestError3;
    Anthropic.AuthenticationError = AuthenticationError2;
    Anthropic.InternalServerError = InternalServerError2;
    Anthropic.PermissionDeniedError = PermissionDeniedError2;
    Anthropic.UnprocessableEntityError = UnprocessableEntityError2;
    Anthropic.toFile = toFile2;
    Anthropic.fileFromPath = fileFromPath;
    Anthropic.Completions = Completions3;
    Anthropic.Messages = Messages4;
    Anthropic.Models = Models4;
    Anthropic.ModelInfosPage = ModelInfosPage;
    Anthropic.Beta = Beta2;
    ({ HUMAN_PROMPT, AI_PROMPT } = Anthropic);
    sdk_default = Anthropic;
  }
});

// packages/core/dist/src/core/anthropicContentGenerator/converter.js
var AnthropicContentConverter;
var init_converter2 = __esm({
  "packages/core/dist/src/core/anthropicContentGenerator/converter.js"() {
    "use strict";
    init_esbuild_shims();
    init_node();
    init_safeJsonParse();
    init_schemaConverter();
    AnthropicContentConverter = class {
      static {
        __name(this, "AnthropicContentConverter");
      }
      model;
      schemaCompliance;
      enableCacheControl;
      constructor(model, schemaCompliance = "auto", enableCacheControl = true) {
        this.model = model;
        this.schemaCompliance = schemaCompliance;
        this.enableCacheControl = enableCacheControl;
      }
      convertGeminiRequestToAnthropic(request4) {
        const messages = [];
        const systemText = this.extractTextFromContentUnion(request4.config?.systemInstruction);
        this.processContents(request4.contents, messages);
        const system = this.enableCacheControl ? this.buildSystemWithCacheControl(systemText) : systemText;
        if (this.enableCacheControl) {
          this.addCacheControlToMessages(messages);
        }
        return {
          system,
          messages
        };
      }
      async convertGeminiToolsToAnthropic(geminiTools) {
        const tools = [];
        for (const tool of geminiTools) {
          let actualTool;
          if ("tool" in tool) {
            actualTool = await tool.tool();
          } else {
            actualTool = tool;
          }
          if (!actualTool.functionDeclarations) {
            continue;
          }
          for (const func of actualTool.functionDeclarations) {
            if (!func.name)
              continue;
            let inputSchema;
            if (func.parametersJsonSchema) {
              inputSchema = {
                ...func.parametersJsonSchema
              };
            } else if (func.parameters) {
              inputSchema = func.parameters;
            }
            if (!inputSchema) {
              inputSchema = { type: "object", properties: {} };
            }
            inputSchema = convertSchema(inputSchema, this.schemaCompliance);
            if (typeof inputSchema["type"] !== "string") {
              inputSchema["type"] = "object";
            }
            tools.push({
              name: func.name,
              description: func.description,
              input_schema: inputSchema
            });
          }
        }
        if (this.enableCacheControl && tools.length > 0) {
          const lastToolIndex = tools.length - 1;
          tools[lastToolIndex] = {
            ...tools[lastToolIndex],
            cache_control: { type: "ephemeral" }
          };
        }
        return tools;
      }
      convertAnthropicResponseToGemini(response) {
        const geminiResponse = new GenerateContentResponse();
        const parts = [];
        for (const block2 of response.content || []) {
          const blockType = String(block2["type"] || "");
          if (blockType === "text") {
            const text = typeof block2.text === "string" ? block2.text : "";
            if (text) {
              parts.push({ text });
            }
          } else if (blockType === "tool_use") {
            const toolUse = block2;
            parts.push({
              functionCall: {
                id: typeof toolUse.id === "string" ? toolUse.id : void 0,
                name: typeof toolUse.name === "string" ? toolUse.name : void 0,
                args: this.safeInputToArgs(toolUse.input)
              }
            });
          } else if (blockType === "thinking") {
            const thinking = typeof block2.thinking === "string" ? block2.thinking : "";
            const signature = typeof block2.signature === "string" ? block2.signature : "";
            if (thinking || signature) {
              const thoughtPart = {
                text: thinking,
                thought: true,
                thoughtSignature: signature
              };
              parts.push(thoughtPart);
            }
          } else if (blockType === "redacted_thinking") {
            parts.push({ text: "", thought: true });
          }
        }
        const candidate = {
          content: {
            parts,
            role: "model"
          },
          index: 0,
          safetyRatings: []
        };
        const finishReason = this.mapAnthropicFinishReasonToGemini(response.stop_reason);
        if (finishReason) {
          candidate.finishReason = finishReason;
        }
        geminiResponse.candidates = [candidate];
        geminiResponse.responseId = response.id;
        geminiResponse.createTime = Date.now().toString();
        geminiResponse.modelVersion = response.model || this.model;
        geminiResponse.promptFeedback = { safetyRatings: [] };
        if (response.usage) {
          const promptTokens = response.usage.input_tokens || 0;
          const completionTokens = response.usage.output_tokens || 0;
          geminiResponse.usageMetadata = {
            promptTokenCount: promptTokens,
            candidatesTokenCount: completionTokens,
            totalTokenCount: promptTokens + completionTokens
          };
        }
        return geminiResponse;
      }
      processContents(contents, messages) {
        if (Array.isArray(contents)) {
          for (const content of contents) {
            this.processContent(content, messages);
          }
        } else if (contents) {
          this.processContent(contents, messages);
        }
      }
      processContent(content, messages) {
        if (typeof content === "string") {
          messages.push({
            role: "user",
            content: [{ type: "text", text: content }]
          });
          return;
        }
        if (!this.isContentObject(content))
          return;
        const parts = content.parts || [];
        const role = content.role === "model" ? "assistant" : "user";
        const contentBlocks = [];
        let toolCallIndex = 0;
        for (const part of parts) {
          if (typeof part === "string") {
            contentBlocks.push({ type: "text", text: part });
            continue;
          }
          if ("text" in part && "thought" in part && part.thought) {
            if (role === "assistant") {
              const thinkingBlock = {
                type: "thinking",
                thinking: part.text || ""
              };
              if ("thoughtSignature" in part && typeof part.thoughtSignature === "string") {
                thinkingBlock.signature = part.thoughtSignature;
              }
              contentBlocks.push(thinkingBlock);
            }
          }
          if ("text" in part && part.text && !("thought" in part && part.thought)) {
            contentBlocks.push({ type: "text", text: part.text });
          }
          const mediaBlock = this.createMediaBlockFromPart(part);
          if (mediaBlock) {
            contentBlocks.push(mediaBlock);
          }
          if ("functionCall" in part && part.functionCall) {
            if (role === "assistant") {
              contentBlocks.push({
                type: "tool_use",
                id: part.functionCall.id || `tool_${toolCallIndex}`,
                name: part.functionCall.name || "",
                input: part.functionCall.args || {}
              });
              toolCallIndex += 1;
            }
          }
          if (part.functionResponse) {
            const toolResultBlock = this.createToolResultBlock(part.functionResponse);
            if (toolResultBlock && role === "user") {
              contentBlocks.push(toolResultBlock);
            }
          }
        }
        if (contentBlocks.length > 0) {
          messages.push({ role, content: contentBlocks });
        }
      }
      createToolResultBlock(response) {
        const textContent2 = this.extractFunctionResponseContent(response.response);
        const partBlocks = [];
        for (const part of response.parts || []) {
          const block2 = this.createMediaBlockFromPart(part);
          if (block2) {
            partBlocks.push(block2);
          }
        }
        let content;
        if (partBlocks.length > 0) {
          const blocks = [];
          if (textContent2) {
            blocks.push({ type: "text", text: textContent2 });
          }
          blocks.push(...partBlocks);
          content = blocks;
        } else {
          content = textContent2;
        }
        return {
          type: "tool_result",
          tool_use_id: response.id || "",
          content
        };
      }
      createMediaBlockFromPart(part) {
        if (part.inlineData?.mimeType && part.inlineData?.data) {
          if (this.isSupportedAnthropicImageMimeType(part.inlineData.mimeType)) {
            return {
              type: "image",
              source: {
                type: "base64",
                media_type: part.inlineData.mimeType,
                data: part.inlineData.data
              }
            };
          }
          if (part.inlineData.mimeType === "application/pdf") {
            return {
              type: "document",
              source: {
                type: "base64",
                media_type: "application/pdf",
                data: part.inlineData.data
              }
            };
          }
          const displayName = part.inlineData.displayName ? ` (${part.inlineData.displayName})` : "";
          return {
            type: "text",
            text: `Unsupported inline media type: ${part.inlineData.mimeType}${displayName}.`
          };
        }
        if (part.fileData?.mimeType && part.fileData?.fileUri) {
          const displayName = part.fileData.displayName ? ` (${part.fileData.displayName})` : "";
          const fileUri = part.fileData.fileUri;
          if (this.isSupportedAnthropicImageMimeType(part.fileData.mimeType)) {
            return {
              type: "image",
              source: {
                type: "url",
                url: fileUri
              }
            };
          }
          if (part.fileData.mimeType === "application/pdf") {
            return {
              type: "document",
              source: {
                type: "url",
                url: fileUri
              }
            };
          }
          return {
            type: "text",
            text: `Unsupported file media type: ${part.fileData.mimeType}${displayName}.`
          };
        }
        return null;
      }
      isSupportedAnthropicImageMimeType(mimeType) {
        return mimeType === "image/jpeg" || mimeType === "image/png" || mimeType === "image/gif" || mimeType === "image/webp";
      }
      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 "";
      }
      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 error2 = responseObject["error"];
          if (typeof error2 === "string") {
            return error2;
          }
        }
        try {
          const serialized = JSON.stringify(response);
          return serialized ?? String(response);
        } catch {
          return String(response);
        }
      }
      safeInputToArgs(input) {
        if (input && typeof input === "object") {
          return input;
        }
        if (typeof input === "string") {
          return safeJsonParse(input, {});
        }
        return {};
      }
      mapAnthropicFinishReasonToGemini(reason) {
        if (!reason)
          return void 0;
        const mapping = {
          end_turn: FinishReason.STOP,
          stop_sequence: FinishReason.STOP,
          tool_use: FinishReason.STOP,
          max_tokens: FinishReason.MAX_TOKENS,
          content_filter: FinishReason.SAFETY
        };
        return mapping[reason] || FinishReason.FINISH_REASON_UNSPECIFIED;
      }
      isContentObject(content) {
        return typeof content === "object" && content !== null && "role" in content && "parts" in content && Array.isArray(content["parts"]);
      }
      /**
       * Build system content blocks with cache_control.
       * Anthropic prompt caching requires cache_control on system content.
       */
      buildSystemWithCacheControl(systemText) {
        if (!systemText) {
          return systemText;
        }
        return [
          {
            type: "text",
            text: systemText,
            cache_control: { type: "ephemeral" }
          }
        ];
      }
      /**
       * Add cache_control to the last user message's content.
       * This enables prompt caching for the conversation context.
       */
      addCacheControlToMessages(messages) {
        for (let i3 = messages.length - 1; i3 >= 0; i3--) {
          const msg = messages[i3];
          if (msg.role === "user") {
            const content = Array.isArray(msg.content) ? msg.content : [{ type: "text", text: msg.content }];
            if (content.length > 0) {
              const lastContent = content[content.length - 1];
              if (typeof lastContent === "object" && "type" in lastContent && lastContent.type === "text" && "text" in lastContent && lastContent.text) {
                lastContent.cache_control = {
                  type: "ephemeral"
                };
              }
              msg.content = content;
            }
            break;
          }
        }
      }
    };
  }
});

// packages/core/dist/src/core/anthropicContentGenerator/anthropicContentGenerator.js
var debugLogger13, AnthropicContentGenerator;
var init_anthropicContentGenerator = __esm({
  "packages/core/dist/src/core/anthropicContentGenerator/anthropicContentGenerator.js"() {
    "use strict";
    init_esbuild_shims();
    init_sdk2();
    init_node();
    init_request_tokenizer();
    init_safeJsonParse();
    init_converter2();
    init_runtimeFetchOptions();
    init_constants2();
    init_debugLogger();
    debugLogger13 = createDebugLogger("ANTHROPIC");
    AnthropicContentGenerator = class {
      static {
        __name(this, "AnthropicContentGenerator");
      }
      contentGeneratorConfig;
      cliConfig;
      client;
      converter;
      constructor(contentGeneratorConfig, cliConfig) {
        this.contentGeneratorConfig = contentGeneratorConfig;
        this.cliConfig = cliConfig;
        const defaultHeaders = this.buildHeaders();
        const baseURL = contentGeneratorConfig.baseUrl;
        const runtimeOptions = buildRuntimeFetchOptions("anthropic", this.cliConfig.getProxy());
        this.client = new sdk_default({
          apiKey: contentGeneratorConfig.apiKey,
          baseURL,
          timeout: contentGeneratorConfig.timeout || DEFAULT_TIMEOUT,
          maxRetries: contentGeneratorConfig.maxRetries,
          defaultHeaders,
          ...runtimeOptions
        });
        this.converter = new AnthropicContentConverter(contentGeneratorConfig.model, contentGeneratorConfig.schemaCompliance, contentGeneratorConfig.enableCacheControl);
      }
      async generateContent(request4) {
        const anthropicRequest = await this.buildRequest(request4);
        const response = await this.client.messages.create(anthropicRequest, {
          signal: request4.config?.abortSignal
        });
        return this.converter.convertAnthropicResponseToGemini(response);
      }
      async generateContentStream(request4) {
        const anthropicRequest = await this.buildRequest(request4);
        const streamingRequest = {
          ...anthropicRequest,
          stream: true
        };
        const stream2 = await this.client.messages.create(streamingRequest, {
          signal: request4.config?.abortSignal
        });
        return this.processStream(stream2);
      }
      async countTokens(request4) {
        try {
          const estimator = new RequestTokenizer();
          const result = await estimator.calculateTokens(request4);
          return {
            totalTokens: result.totalTokens
          };
        } catch (error2) {
          debugLogger13.warn("Failed to calculate tokens with tokenizer, falling back to simple method:", error2);
          const content = JSON.stringify(request4.contents);
          const totalTokens = Math.ceil(content.length / 4);
          return {
            totalTokens
          };
        }
      }
      async embedContent(_request) {
        throw new Error("Anthropic does not support embeddings.");
      }
      useSummarizedThinking() {
        return false;
      }
      buildHeaders() {
        const version2 = this.cliConfig.getCliVersion() || "unknown";
        const userAgent2 = `QwenCode/${version2} (${process.platform}; ${process.arch})`;
        const { customHeaders } = this.contentGeneratorConfig;
        const betas = [];
        const reasoning = this.contentGeneratorConfig.reasoning;
        if (reasoning !== false) {
          betas.push("interleaved-thinking-2025-05-14");
        }
        if (reasoning !== false && reasoning?.effort !== void 0) {
          betas.push("effort-2025-11-24");
        }
        const headers = {
          "User-Agent": userAgent2
        };
        if (betas.length) {
          headers["anthropic-beta"] = betas.join(",");
        }
        return customHeaders ? { ...headers, ...customHeaders } : headers;
      }
      async buildRequest(request4) {
        const { system, messages } = this.converter.convertGeminiRequestToAnthropic(request4);
        const tools = request4.config?.tools ? await this.converter.convertGeminiToolsToAnthropic(request4.config.tools) : void 0;
        const sampling = this.buildSamplingParameters(request4);
        const thinking = this.buildThinkingConfig(request4);
        const outputConfig = this.buildOutputConfig();
        return {
          model: this.contentGeneratorConfig.model,
          system,
          messages,
          tools,
          ...sampling,
          ...thinking ? { thinking } : {},
          ...outputConfig ? { output_config: outputConfig } : {}
        };
      }
      buildSamplingParameters(request4) {
        const configSamplingParams = this.contentGeneratorConfig.samplingParams;
        const requestConfig = request4.config || {};
        const getParam = /* @__PURE__ */ __name((configKey, requestKey) => {
          const configValue = configSamplingParams?.[configKey];
          const requestValue = requestKey ? requestConfig[requestKey] : void 0;
          return configValue !== void 0 ? configValue : requestValue;
        }, "getParam");
        const maxTokens = getParam("max_tokens", "maxOutputTokens") ?? 1e4;
        return {
          max_tokens: maxTokens,
          temperature: getParam("temperature", "temperature") ?? 1,
          top_p: getParam("top_p", "topP"),
          top_k: getParam("top_k", "topK")
        };
      }
      buildThinkingConfig(request4) {
        if (request4.config?.thinkingConfig?.includeThoughts === false) {
          return void 0;
        }
        const reasoning = this.contentGeneratorConfig.reasoning;
        if (reasoning === false) {
          return void 0;
        }
        if (reasoning?.budget_tokens !== void 0) {
          return {
            type: "enabled",
            budget_tokens: reasoning.budget_tokens
          };
        }
        const effort = reasoning?.effort;
        const budgetTokens = effort === "low" ? 16e3 : effort === "high" ? 64e3 : 32e3;
        return {
          type: "enabled",
          budget_tokens: budgetTokens
        };
      }
      buildOutputConfig() {
        const reasoning = this.contentGeneratorConfig.reasoning;
        if (reasoning === false || reasoning === void 0) {
          return void 0;
        }
        if (reasoning.effort === void 0) {
          return void 0;
        }
        return { effort: reasoning.effort };
      }
      async *processStream(stream2) {
        let messageId;
        let model = this.contentGeneratorConfig.model;
        let cachedTokens = 0;
        let promptTokens = 0;
        let completionTokens = 0;
        let finishReason;
        const blocks = /* @__PURE__ */ new Map();
        const collectedResponses = [];
        for await (const event of stream2) {
          switch (event.type) {
            case "message_start": {
              messageId = event.message.id ?? messageId;
              model = event.message.model ?? model;
              cachedTokens = event.message.usage?.cache_read_input_tokens ?? cachedTokens;
              promptTokens = event.message.usage?.input_tokens ?? promptTokens;
              break;
            }
            case "content_block_start": {
              const index = event.index ?? 0;
              const type = String(event.content_block.type || "text");
              const initialInput = type === "tool_use" && "input" in event.content_block ? JSON.stringify(event.content_block.input) : "";
              blocks.set(index, {
                type,
                id: "id" in event.content_block ? event.content_block.id : void 0,
                name: "name" in event.content_block ? event.content_block.name : void 0,
                inputJson: initialInput !== "{}" ? initialInput : "",
                signature: type === "thinking" && "signature" in event.content_block && typeof event.content_block.signature === "string" ? event.content_block.signature : ""
              });
              break;
            }
            case "content_block_delta": {
              const index = event.index ?? 0;
              const deltaType = event.delta.type || "";
              const blockState = blocks.get(index);
              if (deltaType === "text_delta") {
                const text = "text" in event.delta ? event.delta.text : "";
                if (text) {
                  const chunk = this.buildGeminiChunk({ text }, messageId, model);
                  collectedResponses.push(chunk);
                  yield chunk;
                }
              } else if (deltaType === "thinking_delta") {
                const thinking = event.delta.thinking || "";
                if (thinking) {
                  const chunk = this.buildGeminiChunk({ text: thinking, thought: true }, messageId, model);
                  collectedResponses.push(chunk);
                  yield chunk;
                }
              } else if (deltaType === "signature_delta" && blockState) {
                const signature = event.delta.signature || "";
                if (signature) {
                  blockState.signature += signature;
                  const chunk = this.buildGeminiChunk({ thought: true, thoughtSignature: signature }, messageId, model);
                  collectedResponses.push(chunk);
                  yield chunk;
                }
              } else if (deltaType === "input_json_delta" && blockState) {
                const jsonDelta = event.delta.partial_json || "";
                if (jsonDelta) {
                  blockState.inputJson += jsonDelta;
                }
              }
              break;
            }
            case "content_block_stop": {
              const index = event.index ?? 0;
              const blockState = blocks.get(index);
              if (blockState?.type === "tool_use") {
                const args = safeJsonParse(blockState.inputJson || "{}", {});
                const chunk = this.buildGeminiChunk({
                  functionCall: {
                    id: blockState.id,
                    name: blockState.name,
                    args
                  }
                }, messageId, model);
                collectedResponses.push(chunk);
                yield chunk;
              }
              blocks.delete(index);
              break;
            }
            case "message_delta": {
              const stopReasonValue = event.delta.stop_reason;
              if (stopReasonValue) {
                finishReason = stopReasonValue;
              }
              const usageUnknown = event.usage;
              const usageRecord = usageUnknown && typeof usageUnknown === "object" ? usageUnknown : void 0;
              if (event.usage?.output_tokens !== void 0) {
                completionTokens = event.usage.output_tokens;
              }
              if (usageRecord?.["input_tokens"] !== void 0) {
                const inputTokens = usageRecord["input_tokens"];
                if (typeof inputTokens === "number") {
                  promptTokens = inputTokens;
                }
              }
              if (usageRecord?.["cache_read_input_tokens"] !== void 0) {
                const cacheRead = usageRecord["cache_read_input_tokens"];
                if (typeof cacheRead === "number") {
                  cachedTokens = cacheRead;
                }
              }
              if (finishReason || event.usage) {
                const chunk = this.buildGeminiChunk(void 0, messageId, model, finishReason, {
                  cachedContentTokenCount: cachedTokens,
                  promptTokenCount: cachedTokens + promptTokens,
                  candidatesTokenCount: completionTokens,
                  totalTokenCount: cachedTokens + promptTokens + completionTokens
                });
                collectedResponses.push(chunk);
                yield chunk;
              }
              break;
            }
            case "message_stop": {
              if (promptTokens || completionTokens) {
                const chunk = this.buildGeminiChunk(void 0, messageId, model, finishReason, {
                  cachedContentTokenCount: cachedTokens,
                  promptTokenCount: cachedTokens + promptTokens,
                  candidatesTokenCount: completionTokens,
                  totalTokenCount: cachedTokens + promptTokens + completionTokens
                });
                collectedResponses.push(chunk);
                yield chunk;
              }
              break;
            }
            default:
              break;
          }
        }
      }
      buildGeminiChunk(part, responseId, model, finishReason, usageMetadata) {
        const response = new GenerateContentResponse();
        response.responseId = responseId;
        response.createTime = Date.now().toString();
        response.modelVersion = model || this.contentGeneratorConfig.model;
        response.promptFeedback = { safetyRatings: [] };
        const candidateParts = part ? [part] : [];
        const mappedFinishReason = finishReason !== void 0 ? this.converter.mapAnthropicFinishReasonToGemini(finishReason) : void 0;
        response.candidates = [
          {
            content: {
              parts: candidateParts,
              role: "model"
            },
            index: 0,
            safetyRatings: [],
            ...mappedFinishReason ? { finishReason: mappedFinishReason } : {}
          }
        ];
        if (usageMetadata) {
          response.usageMetadata = usageMetadata;
        }
        return response;
      }
    };
  }
});

// packages/core/dist/src/core/anthropicContentGenerator/index.js
var anthropicContentGenerator_exports = {};
__export(anthropicContentGenerator_exports, {
  AnthropicContentGenerator: () => AnthropicContentGenerator,
  createAnthropicContentGenerator: () => createAnthropicContentGenerator
});
function createAnthropicContentGenerator(contentGeneratorConfig, cliConfig) {
  return new AnthropicContentGenerator(contentGeneratorConfig, cliConfig);
}
var init_anthropicContentGenerator2 = __esm({
  "packages/core/dist/src/core/anthropicContentGenerator/index.js"() {
    "use strict";
    init_esbuild_shims();
    init_anthropicContentGenerator();
    init_anthropicContentGenerator();
    __name(createAnthropicContentGenerator, "createAnthropicContentGenerator");
  }
});

// packages/core/dist/src/core/geminiContentGenerator/geminiContentGenerator.js
var GeminiContentGenerator;
var init_geminiContentGenerator = __esm({
  "packages/core/dist/src/core/geminiContentGenerator/geminiContentGenerator.js"() {
    "use strict";
    init_esbuild_shims();
    init_node();
    GeminiContentGenerator = class {
      static {
        __name(this, "GeminiContentGenerator");
      }
      googleGenAI;
      contentGeneratorConfig;
      constructor(options2, contentGeneratorConfig) {
        const customHeaders = contentGeneratorConfig?.customHeaders;
        const finalOptions = customHeaders ? (() => {
          const baseHttpOptions = options2.httpOptions;
          const baseHeaders = baseHttpOptions?.headers ?? {};
          return {
            ...options2,
            httpOptions: {
              ...baseHttpOptions ?? {},
              headers: {
                ...baseHeaders,
                ...customHeaders
              }
            }
          };
        })() : options2;
        this.googleGenAI = new GoogleGenAI(finalOptions);
        this.contentGeneratorConfig = contentGeneratorConfig;
      }
      buildGenerateContentConfig(request4) {
        const configSamplingParams = this.contentGeneratorConfig?.samplingParams;
        const requestConfig = request4.config || {};
        const getParameterValue = /* @__PURE__ */ __name((configValue, requestKey, defaultValue) => {
          const requestValue = requestConfig[requestKey];
          if (configValue !== void 0)
            return configValue;
          if (requestValue !== void 0)
            return requestValue;
          return defaultValue;
        }, "getParameterValue");
        return {
          ...requestConfig,
          temperature: getParameterValue(configSamplingParams?.temperature, "temperature", 1),
          topP: getParameterValue(configSamplingParams?.top_p, "topP", 0.95),
          topK: getParameterValue(configSamplingParams?.top_k, "topK", 64),
          maxOutputTokens: getParameterValue(configSamplingParams?.max_tokens, "maxOutputTokens"),
          presencePenalty: getParameterValue(configSamplingParams?.presence_penalty, "presencePenalty"),
          frequencyPenalty: getParameterValue(configSamplingParams?.frequency_penalty, "frequencyPenalty"),
          thinkingConfig: getParameterValue(this.buildThinkingConfig(), "thinkingConfig", {
            includeThoughts: true,
            thinkingLevel: "THINKING_LEVEL_UNSPECIFIED"
          })
        };
      }
      buildThinkingConfig() {
        const reasoning = this.contentGeneratorConfig?.reasoning;
        if (reasoning === false) {
          return { includeThoughts: false };
        }
        if (reasoning) {
          const thinkingLevel = reasoning.effort === "low" ? "LOW" : reasoning.effort === "high" ? "HIGH" : "THINKING_LEVEL_UNSPECIFIED";
          return {
            includeThoughts: true,
            thinkingLevel
          };
        }
        return void 0;
      }
      async generateContent(request4, _userPromptId) {
        const finalRequest = {
          ...request4,
          contents: this.stripUnsupportedFields(request4.contents),
          config: this.buildGenerateContentConfig(request4)
        };
        return this.googleGenAI.models.generateContent(finalRequest);
      }
      async generateContentStream(request4, _userPromptId) {
        const finalRequest = {
          ...request4,
          contents: this.stripUnsupportedFields(request4.contents),
          config: this.buildGenerateContentConfig(request4)
        };
        return this.googleGenAI.models.generateContentStream(finalRequest);
      }
      /**
       * Strip fields not supported by Gemini API (e.g., displayName in inlineData/fileData)
       */
      stripUnsupportedFields(contents) {
        if (!contents)
          return contents;
        if (typeof contents === "string")
          return contents;
        if (Array.isArray(contents)) {
          return contents.map((content) => this.stripContentFields(content));
        }
        return this.stripContentFields(contents);
      }
      stripContentFields(content) {
        if (typeof content === "string") {
          return content;
        }
        if (!("role" in content) && !("parts" in content)) {
          return this.stripPartFields(content);
        }
        const contentObj = content;
        if (!contentObj.parts)
          return contentObj;
        return {
          ...contentObj,
          parts: contentObj.parts.map((part) => this.stripPartFields(part))
        };
      }
      stripPartFields(part) {
        if (typeof part === "string") {
          return part;
        }
        const result = { ...part };
        if (result.inlineData) {
          const { displayName: _2, ...inlineDataWithoutDisplayName } = result.inlineData;
          result.inlineData = inlineDataWithoutDisplayName;
        }
        if (result.fileData) {
          const { displayName: _2, ...fileDataWithoutDisplayName } = result.fileData;
          result.fileData = fileDataWithoutDisplayName;
        }
        if (result.functionResponse?.parts) {
          const processedParts = result.functionResponse.parts.map((p2) => {
            const converted = this.convertUnsupportedMediaToText(p2);
            return this.stripPartFields(converted);
          });
          result.functionResponse = {
            ...result.functionResponse,
            parts: processedParts
          };
        }
        return result;
      }
      /**
       * Convert unsupported media types (audio, video) to explanatory text for Gemini API
       */
      convertUnsupportedMediaToText(part) {
        if (typeof part === "string")
          return part;
        const inlineMimeType = part.inlineData?.mimeType || "";
        const fileMimeType = part.fileData?.mimeType || "";
        if (inlineMimeType.startsWith("audio/") || inlineMimeType.startsWith("video/")) {
          const displayName = part.inlineData?.displayName;
          const displayNameText = displayName ? ` (${displayName})` : "";
          return {
            text: `Unsupported media type for Gemini: ${inlineMimeType}${displayNameText}.`
          };
        }
        if (fileMimeType.startsWith("audio/") || fileMimeType.startsWith("video/")) {
          const displayName = part.fileData?.displayName;
          const displayNameText = displayName ? ` (${displayName})` : "";
          return {
            text: `Unsupported media type for Gemini: ${fileMimeType}${displayNameText}.`
          };
        }
        return part;
      }
      async countTokens(request4) {
        return this.googleGenAI.models.countTokens(request4);
      }
      async embedContent(request4) {
        return this.googleGenAI.models.embedContent(request4);
      }
      useSummarizedThinking() {
        return true;
      }
    };
  }
});

// packages/core/dist/src/core/geminiContentGenerator/index.js
var geminiContentGenerator_exports = {};
__export(geminiContentGenerator_exports, {
  GeminiContentGenerator: () => GeminiContentGenerator,
  createGeminiContentGenerator: () => createGeminiContentGenerator
});
function createGeminiContentGenerator(config2, gcConfig) {
  const version2 = "0.11.0";
  const userAgent2 = config2.userAgent || `QwenCode/${version2} (${process.platform}; ${process.arch})`;
  const baseHeaders = {
    "User-Agent": userAgent2
  };
  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 geminiContentGenerator = new GeminiContentGenerator({
    apiKey: config2.apiKey === "" ? void 0 : config2.apiKey,
    vertexai: config2.vertexai,
    httpOptions
  }, config2);
  return geminiContentGenerator;
}
var init_geminiContentGenerator2 = __esm({
  "packages/core/dist/src/core/geminiContentGenerator/index.js"() {
    "use strict";
    init_esbuild_shims();
    init_geminiContentGenerator();
    init_installationManager();
    init_geminiContentGenerator();
    __name(createGeminiContentGenerator, "createGeminiContentGenerator");
  }
});

// packages/core/dist/src/core/contentGenerator.js
function setSource(sources, path125, source2) {
  sources[path125] = source2;
}
function getSeedSource(seed, path125) {
  return seed?.[path125];
}
function resolveContentGeneratorConfigWithSources(config2, authType, generationConfig, seedSources, options2) {
  const sources = { ...seedSources || {} };
  const strictModelProvider = options2?.strictModelProvider === true;
  const newContentGeneratorConfig = {
    ...generationConfig || {},
    authType,
    proxy: config2?.getProxy()
  };
  setSource(sources, "authType", {
    kind: "computed",
    detail: "provided by caller"
  });
  if (config2?.getProxy()) {
    setSource(sources, "proxy", {
      kind: "computed",
      detail: "Config.getProxy()"
    });
  }
  const seedOrUnknown = /* @__PURE__ */ __name((path125) => getSeedSource(seedSources, path125) ?? { kind: "unknown" }, "seedOrUnknown");
  for (const field of PROVIDER_SOURCED_FIELDS) {
    if (generationConfig && field in generationConfig && !sources[field]) {
      setSource(sources, field, seedOrUnknown(field));
    }
  }
  const validation2 = validateModelConfig(newContentGeneratorConfig, strictModelProvider);
  if (!validation2.valid) {
    throw new Error(validation2.errors.map((e4) => e4.message).join("\n"));
  }
  return {
    config: newContentGeneratorConfig,
    sources
  };
}
function validateModelConfig(config2, isStrictModelProvider = false) {
  const errors = [];
  if (config2.authType === AuthType2.QWEN_OAUTH) {
    return { valid: true, errors: [] };
  }
  if (!config2.apiKey) {
    if (isStrictModelProvider) {
      errors.push(new StrictMissingCredentialsError(config2.authType, config2.model, config2.apiKeyEnvKey));
    } else {
      const envKey = config2.apiKeyEnvKey || getDefaultApiKeyEnvVar(config2.authType);
      errors.push(new MissingApiKeyError({
        authType: config2.authType,
        model: config2.model,
        baseUrl: config2.baseUrl,
        envKey
      }));
    }
  }
  if (!config2.model) {
    if (isStrictModelProvider) {
      errors.push(new StrictMissingModelIdError(config2.authType));
    } else {
      const envKey = getDefaultModelEnvVar(config2.authType);
      errors.push(new MissingModelError({ authType: config2.authType, envKey }));
    }
  }
  if (config2.authType === AuthType2.USE_ANTHROPIC && !config2.baseUrl) {
    if (isStrictModelProvider) {
      errors.push(new MissingBaseUrlError({
        authType: config2.authType,
        model: config2.model
      }));
    } else if (config2.authType === AuthType2.USE_ANTHROPIC) {
      errors.push(new MissingAnthropicBaseUrlEnvError());
    }
  }
  return { valid: errors.length === 0, errors };
}
async function createContentGenerator(generatorConfig, config2, isInitialAuth) {
  const validation2 = validateModelConfig(generatorConfig, false);
  if (!validation2.valid) {
    throw new Error(validation2.errors.map((e4) => e4.message).join("\n"));
  }
  const authType = generatorConfig.authType;
  if (!authType) {
    throw new Error("ContentGeneratorConfig must have an authType");
  }
  let baseGenerator;
  if (authType === AuthType2.USE_OPENAI) {
    const { createOpenAIContentGenerator: createOpenAIContentGenerator2 } = await Promise.resolve().then(() => (init_openaiContentGenerator2(), openaiContentGenerator_exports));
    baseGenerator = createOpenAIContentGenerator2(generatorConfig, config2);
  } else if (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(config2, isInitialAuth ? { requireCachedCredentials: true } : void 0);
      baseGenerator = new QwenContentGenerator2(qwenClient, generatorConfig, config2);
    } catch (error2) {
      throw new Error(`${error2 instanceof Error ? error2.message : String(error2)}`);
    }
  } else if (authType === AuthType2.USE_ANTHROPIC) {
    const { createAnthropicContentGenerator: createAnthropicContentGenerator2 } = await Promise.resolve().then(() => (init_anthropicContentGenerator2(), anthropicContentGenerator_exports));
    baseGenerator = createAnthropicContentGenerator2(generatorConfig, config2);
  } else if (authType === AuthType2.USE_GEMINI || authType === AuthType2.USE_VERTEX_AI) {
    const { createGeminiContentGenerator: createGeminiContentGenerator2 } = await Promise.resolve().then(() => (init_geminiContentGenerator2(), geminiContentGenerator_exports));
    baseGenerator = createGeminiContentGenerator2(generatorConfig, config2);
  } else {
    throw new Error(`Error creating contentGenerator: Unsupported authType: ${authType}`);
  }
  return new LoggingContentGenerator(baseGenerator, config2, generatorConfig);
}
var AuthType2;
var init_contentGenerator = __esm({
  "packages/core/dist/src/core/contentGenerator.js"() {
    "use strict";
    init_esbuild_shims();
    init_loggingContentGenerator2();
    init_modelConfigErrors();
    init_modelsConfig();
    (function(AuthType4) {
      AuthType4["USE_OPENAI"] = "openai";
      AuthType4["QWEN_OAUTH"] = "qwen-oauth";
      AuthType4["USE_GEMINI"] = "gemini";
      AuthType4["USE_VERTEX_AI"] = "vertex-ai";
      AuthType4["USE_ANTHROPIC"] = "anthropic";
    })(AuthType2 || (AuthType2 = {}));
    __name(setSource, "setSource");
    __name(getSeedSource, "getSeedSource");
    __name(resolveContentGeneratorConfigWithSources, "resolveContentGeneratorConfigWithSources");
    __name(validateModelConfig, "validateModelConfig");
    __name(createContentGenerator, "createContentGenerator");
  }
});

// packages/core/dist/src/utils/retry.js
function defaultShouldRetry(error2) {
  const status = getErrorStatus(error2);
  return status === 429 || status !== void 0 && status >= 500 && status < 600;
}
function delay(ms) {
  return new Promise((resolve30) => setTimeout(resolve30, 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(([_2, v2]) => v2 != null)) : {};
  const { maxAttempts, initialDelayMs, maxDelayMs, authType, shouldRetryOnError, shouldRetryOnContent } = {
    ...DEFAULT_RETRY_OPTIONS,
    ...cleanOptions
  };
  let attempt = 0;
  let currentDelay = initialDelayMs;
  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 (error2) {
      const errorStatus = getErrorStatus(error2);
      if (authType === AuthType2.QWEN_OAUTH && isQwenQuotaExceededError(error2)) {
        throw new Error(`Qwen API quota exceeded: Your Qwen API quota has been exhausted. Please wait for your quota to reset.`);
      }
      if (attempt >= maxAttempts || !shouldRetryOnError(error2)) {
        throw error2;
      }
      const retryAfterMs = errorStatus === 429 ? getRetryAfterDelayMs(error2) : 0;
      if (retryAfterMs > 0) {
        debugLogger14.warn(`Attempt ${attempt} failed with status ${errorStatus ?? "unknown"}. Retrying after explicit delay of ${retryAfterMs}ms...`, error2);
        await delay(retryAfterMs);
        currentDelay = initialDelayMs;
      } else {
        logRetryAttempt(attempt, error2, 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(error2) {
  if (typeof error2 !== "object" || error2 === null) {
    return void 0;
  }
  const err = error2;
  const value = err.status ?? err.statusCode ?? err.response?.status ?? err.error?.code;
  return typeof value === "number" && value >= 100 && value <= 599 ? value : void 0;
}
function getRetryAfterDelayMs(error2) {
  if (typeof error2 === "object" && error2 !== null) {
    if ("response" in error2 && typeof error2.response === "object" && error2.response !== null) {
      const response = error2.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 logRetryAttempt(attempt, error2, errorStatus) {
  const message = errorStatus ? `Attempt ${attempt} failed with status ${errorStatus}. Retrying with backoff...` : `Attempt ${attempt} failed. Retrying with backoff...`;
  if (errorStatus === 429) {
    debugLogger14.warn(message, error2);
  } else if (errorStatus && errorStatus >= 500 && errorStatus < 600) {
    debugLogger14.error(message, error2);
  } else {
    debugLogger14.warn(message, error2);
  }
}
var debugLogger14, DEFAULT_RETRY_OPTIONS;
var init_retry = __esm({
  "packages/core/dist/src/utils/retry.js"() {
    "use strict";
    init_esbuild_shims();
    init_contentGenerator();
    init_quotaErrorDetection();
    init_debugLogger();
    debugLogger14 = createDebugLogger("RETRY");
    DEFAULT_RETRY_OPTIONS = {
      maxAttempts: 7,
      initialDelayMs: 1500,
      maxDelayMs: 3e4,
      // 30 seconds
      shouldRetryOnError: defaultShouldRetry
    };
    __name(defaultShouldRetry, "defaultShouldRetry");
    __name(delay, "delay");
    __name(retryWithBackoff, "retryWithBackoff");
    __name(getErrorStatus, "getErrorStatus");
    __name(getRetryAfterDelayMs, "getRetryAfterDelayMs");
    __name(logRetryAttempt, "logRetryAttempt");
  }
});

// packages/core/dist/src/utils/partUtils.js
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 && !part.thought).map((part) => part.text).join("");
    }
  }
  return null;
}
async function flatMapTextParts(parts, transform2) {
  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 transform2(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(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);
  if (functionCallParts.length === 2) {
    const [first2, second] = functionCallParts;
    const firstHasNameOnly = first2.name && (!first2.args || Object.keys(first2.args).length === 0);
    const secondHasArgsOnly = !second.name && second.args && Object.keys(second.args).length > 0;
    if (firstHasNameOnly && secondHasArgsOnly) {
      return [
        {
          name: first2.name,
          args: second.args
        }
      ];
    }
  }
  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 = 7;
    BaseLlmClient = class {
      static {
        __name(this, "BaseLlmClient");
      }
      contentGenerator;
      config;
      constructor(contentGenerator, config2) {
        this.contentGenerator = contentGenerator;
        this.config = config2;
      }
      async generateJson(options2) {
        const { contents, schema, model, abortSignal, systemInstruction, promptId, maxAttempts } = options2;
        const requestConfig = {
          abortSignal,
          ...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 (error2) {
          if (abortSignal.aborted) {
            throw error2;
          }
          if (error2 instanceof Error && error2.message === "API returned an empty response for generateJson.") {
            throw error2;
          }
          await reportError2(error2, "Error generating JSON content via API.", contents, "generateJson-api");
          throw new Error(`Failed to generate JSON content: ${getErrorMessage(error2)}`);
        }
      }
      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/errorParsing.js
function getRateLimitMessage(authType) {
  switch (authType) {
    case AuthType2.USE_GEMINI:
      return RATE_LIMIT_ERROR_MESSAGE_USE_GEMINI;
    case AuthType2.USE_VERTEX_AI:
      return RATE_LIMIT_ERROR_MESSAGE_VERTEX;
    default:
      return RATE_LIMIT_ERROR_MESSAGE_DEFAULT;
  }
}
function parseAndFormatApiError(error2, authType) {
  if (isStructuredError(error2)) {
    let text = `[API Error: ${error2.message}]`;
    if (error2.status === 429) {
      text += getRateLimitMessage(authType);
    }
    return text;
  }
  if (typeof error2 === "string") {
    const jsonStart = error2.indexOf("{");
    if (jsonStart === -1) {
      return `[API Error: ${error2}]`;
    }
    const jsonString = error2.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 (_e2) {
        }
        const statusText = parsedError.error.status ? ` (Status: ${parsedError.error.status})` : "";
        let text = `[API Error: ${finalMessage}${statusText}]`;
        if (parsedError.error.code === 429) {
          text += getRateLimitMessage(authType);
        }
        return text;
      }
    } catch (_e2) {
    }
    return `[API Error: ${error2}]`;
  }
  return "[API Error: An unknown error occurred.]";
}
var RATE_LIMIT_ERROR_MESSAGE_USE_GEMINI, RATE_LIMIT_ERROR_MESSAGE_VERTEX, RATE_LIMIT_ERROR_MESSAGE_DEFAULT;
var init_errorParsing = __esm({
  "packages/core/dist/src/utils/errorParsing.js"() {
    "use strict";
    init_esbuild_shims();
    init_quotaErrorDetection();
    init_contentGenerator();
    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";
    RATE_LIMIT_ERROR_MESSAGE_DEFAULT = "\nPossible quota limitations in place or slow response times detected. Please wait and try again later.";
    __name(getRateLimitMessage, "getRateLimitMessage");
    __name(parseAndFormatApiError, "parseAndFormatApiError");
  }
});

// packages/core/dist/src/utils/rateLimit.js
function isRateLimitError(error2) {
  const code2 = getErrorCode2(error2);
  return code2 !== null && RATE_LIMIT_ERROR_CODES.has(code2);
}
function getErrorCode2(error2) {
  if (isApiError(error2))
    return Number(error2.error.code) || null;
  const msg = error2 instanceof Error ? error2.message : typeof error2 === "string" ? error2 : null;
  if (msg) {
    const i3 = msg.indexOf("{");
    if (i3 !== -1) {
      try {
        const p2 = JSON.parse(msg.substring(i3));
        if (isApiError(p2))
          return Number(p2.error.code) || null;
      } catch {
      }
    }
  }
  if (isStructuredError(error2)) {
    return typeof error2.status === "number" ? error2.status : null;
  }
  if (error2 instanceof Error && "status" in error2) {
    const s5 = error2.status;
    if (typeof s5 === "number")
      return s5;
  }
  return null;
}
var RATE_LIMIT_ERROR_CODES;
var init_rateLimit = __esm({
  "packages/core/dist/src/utils/rateLimit.js"() {
    "use strict";
    init_esbuild_shims();
    init_quotaErrorDetection();
    RATE_LIMIT_ERROR_CODES = /* @__PURE__ */ new Set([429, 503, 1302]);
    __name(isRateLimitError, "isRateLimitError");
    __name(getErrorCode2, "getErrorCode");
  }
});

// node_modules/async-mutex/index.mjs
var E_TIMEOUT, E_ALREADY_LOCKED, E_CANCELED;
var init_async_mutex = __esm({
  "node_modules/async-mutex/index.mjs"() {
    init_esbuild_shims();
    E_TIMEOUT = new Error("timeout while waiting for mutex to become available");
    E_ALREADY_LOCKED = new Error("mutex already locked");
    E_CANCELED = new Error("request for lock canceled");
  }
});

// packages/core/dist/src/utils/jsonl-utils.js
import fs18 from "node:fs";
import path11 from "node:path";
import readline from "node:readline";
async function readLines(filePath, count) {
  try {
    const fileStream = fs18.createReadStream(filePath);
    const rl = readline.createInterface({
      input: fileStream,
      crlfDelay: Infinity
    });
    const results = [];
    for await (const line of rl) {
      if (results.length >= count)
        break;
      const trimmed2 = line.trim();
      if (trimmed2.length > 0) {
        results.push(JSON.parse(trimmed2));
      }
    }
    return results;
  } catch (error2) {
    if (error2.code !== "ENOENT") {
      debugLogger15.error(`Error reading first ${count} lines from ${filePath}:`, error2);
    }
    return [];
  }
}
async function read(filePath) {
  try {
    const fileStream = fs18.createReadStream(filePath);
    const rl = readline.createInterface({
      input: fileStream,
      crlfDelay: Infinity
    });
    const results = [];
    for await (const line of rl) {
      const trimmed2 = line.trim();
      if (trimmed2.length > 0) {
        results.push(JSON.parse(trimmed2));
      }
    }
    return results;
  } catch (error2) {
    if (error2.code !== "ENOENT") {
      debugLogger15.error(`Error reading ${filePath}:`, error2);
    }
    return [];
  }
}
function writeLineSync(filePath, data) {
  const line = `${JSON.stringify(data)}
`;
  const dir = path11.dirname(filePath);
  if (!fs18.existsSync(dir)) {
    fs18.mkdirSync(dir, { recursive: true });
  }
  fs18.appendFileSync(filePath, line, "utf8");
}
var debugLogger15;
var init_jsonl_utils = __esm({
  "packages/core/dist/src/utils/jsonl-utils.js"() {
    "use strict";
    init_esbuild_shims();
    init_async_mutex();
    init_debugLogger();
    debugLogger15 = createDebugLogger("JSONL");
    __name(readLines, "readLines");
    __name(read, "read");
    __name(writeLineSync, "writeLineSync");
  }
});

// packages/core/dist/src/utils/gitUtils.js
import * as fs19 from "node:fs";
import * as path12 from "node:path";
import { execSync } from "node:child_process";
function isGitRepository(directory) {
  try {
    let currentDir = path12.resolve(directory);
    while (true) {
      const gitDir = path12.join(currentDir, ".git");
      if (fs19.existsSync(gitDir)) {
        return true;
      }
      const parentDir = path12.dirname(currentDir);
      if (parentDir === currentDir) {
        break;
      }
      currentDir = parentDir;
    }
    return false;
  } catch (_error) {
    return false;
  }
}
var getGitBranch;
var init_gitUtils = __esm({
  "packages/core/dist/src/utils/gitUtils.js"() {
    "use strict";
    init_esbuild_shims();
    __name(isGitRepository, "isGitRepository");
    getGitBranch = /* @__PURE__ */ __name((cwd7) => {
      try {
        const branch = execSync("git rev-parse --abbrev-ref HEAD", {
          cwd: cwd7,
          encoding: "utf8",
          stdio: ["pipe", "pipe", "pipe"]
        }).trim();
        return branch || void 0;
      } catch {
        return void 0;
      }
    }, "getGitBranch");
  }
});

// packages/core/dist/src/services/chatRecordingService.js
import path13 from "node:path";
import fs20 from "node:fs";
import { randomUUID as randomUUID4 } from "node:crypto";
var debugLogger16, ChatRecordingService;
var init_chatRecordingService = __esm({
  "packages/core/dist/src/services/chatRecordingService.js"() {
    "use strict";
    init_esbuild_shims();
    init_config3();
    init_node();
    init_jsonl_utils();
    init_gitUtils();
    init_debugLogger();
    debugLogger16 = createDebugLogger("CHAT_RECORDING");
    ChatRecordingService = class {
      static {
        __name(this, "ChatRecordingService");
      }
      /** UUID of the last written record in the chain */
      lastRecordUuid = null;
      config;
      constructor(config2) {
        this.config = config2;
        this.lastRecordUuid = config2.getResumedSessionData()?.lastCompletedUuid ?? null;
      }
      /**
       * Returns the session ID.
       * @returns The session ID.
       */
      getSessionId() {
        return this.config.getSessionId();
      }
      /**
       * Ensures the chats directory exists, creating it if it doesn't exist.
       * @returns The path to the chats directory.
       * @throws Error if the directory cannot be created.
       */
      ensureChatsDir() {
        const projectDir = this.config.storage.getProjectDir();
        const chatsDir = path13.join(projectDir, "chats");
        try {
          fs20.mkdirSync(chatsDir, { recursive: true });
        } catch {
        }
        return chatsDir;
      }
      /**
       * Ensures the conversation file exists, creating it if it doesn't exist.
       * Uses atomic file creation to avoid race conditions.
       * @returns The path to the conversation file.
       * @throws Error if the file cannot be created or accessed.
       */
      ensureConversationFile() {
        const chatsDir = this.ensureChatsDir();
        const sessionId = this.getSessionId();
        const safeFilename = `${sessionId}.jsonl`;
        const conversationFile = path13.join(chatsDir, safeFilename);
        if (fs20.existsSync(conversationFile)) {
          return conversationFile;
        }
        try {
          fs20.writeFileSync(conversationFile, "", { flag: "wx", encoding: "utf8" });
        } catch (error2) {
          const nodeError = error2;
          if (nodeError.code !== "EEXIST") {
            const message = error2 instanceof Error ? error2.message : String(error2);
            throw new Error(`Failed to create conversation file at ${conversationFile}: ${message}`);
          }
        }
        return conversationFile;
      }
      /**
       * Creates base fields for a ChatRecord.
       */
      createBaseRecord(type) {
        return {
          uuid: randomUUID4(),
          parentUuid: this.lastRecordUuid,
          sessionId: this.getSessionId(),
          timestamp: (/* @__PURE__ */ new Date()).toISOString(),
          type,
          cwd: this.config.getProjectRoot(),
          version: this.config.getCliVersion() || "unknown",
          gitBranch: getGitBranch(this.config.getProjectRoot())
        };
      }
      /**
       * Appends a record to the session file and updates lastRecordUuid.
       */
      appendRecord(record2) {
        try {
          const conversationFile = this.ensureConversationFile();
          writeLineSync(conversationFile, record2);
          this.lastRecordUuid = record2.uuid;
        } catch (error2) {
          debugLogger16.error("Error appending record:", error2);
          throw error2;
        }
      }
      /**
       * Records a user message.
       * Writes immediately to disk.
       *
       * @param message The raw PartListUnion object as used with the API
       */
      recordUserMessage(message) {
        try {
          const record2 = {
            ...this.createBaseRecord("user"),
            message: createUserContent(message)
          };
          this.appendRecord(record2);
        } catch (error2) {
          debugLogger16.error("Error saving user message:", error2);
        }
      }
      /**
       * Records an assistant turn with all available data.
       * Writes immediately to disk.
       *
       * @param data.message The raw PartListUnion object from the model response
       * @param data.model The model name
       * @param data.tokens Token usage statistics
       * @param data.toolCallsMetadata Enriched tool call info for UI recovery
       */
      recordAssistantTurn(data) {
        try {
          const record2 = {
            ...this.createBaseRecord("assistant"),
            model: data.model
          };
          if (data.message !== void 0) {
            record2.message = createModelContent(data.message);
          }
          if (data.tokens) {
            record2.usageMetadata = data.tokens;
          }
          this.appendRecord(record2);
        } catch (error2) {
          debugLogger16.error("Error saving assistant turn:", error2);
        }
      }
      /**
       * Records tool results (function responses) sent back to the model.
       * Writes immediately to disk.
       *
       * @param message The raw PartListUnion object with functionResponse parts
       * @param toolCallResult Optional tool call result info for UI recovery
       */
      recordToolResult(message, toolCallResult) {
        try {
          const record2 = {
            ...this.createBaseRecord("tool_result"),
            message: createUserContent(message)
          };
          if (toolCallResult) {
            if (typeof toolCallResult.resultDisplay === "object" && toolCallResult.resultDisplay !== null && "type" in toolCallResult.resultDisplay && toolCallResult.resultDisplay.type === "task_execution") {
              const taskResult = toolCallResult.resultDisplay;
              record2.toolCallResult = {
                ...toolCallResult,
                resultDisplay: {
                  ...taskResult,
                  toolCalls: []
                }
              };
            } else {
              record2.toolCallResult = toolCallResult;
            }
          }
          this.appendRecord(record2);
        } catch (error2) {
          debugLogger16.error("Error saving tool result:", error2);
        }
      }
      /**
       * Records a slash command invocation as a system record. This keeps the model
       * history clean while allowing resume to replay UI output for commands like
       * /about.
       */
      recordSlashCommand(payload) {
        try {
          const record2 = {
            ...this.createBaseRecord("system"),
            type: "system",
            subtype: "slash_command",
            systemPayload: payload
          };
          this.appendRecord(record2);
        } catch (error2) {
          debugLogger16.error("Error saving slash command record:", error2);
        }
      }
      /**
       * Records a chat compression checkpoint as a system record. This keeps the UI
       * history immutable while allowing resume/continue flows to reconstruct the
       * compressed model-facing history from the stored snapshot.
       */
      recordChatCompression(payload) {
        try {
          const record2 = {
            ...this.createBaseRecord("system"),
            type: "system",
            subtype: "chat_compression",
            systemPayload: payload
          };
          this.appendRecord(record2);
        } catch (error2) {
          debugLogger16.error("Error saving chat compression record:", error2);
        }
      }
      /**
       * Records a UI telemetry event for replaying metrics on resume.
       */
      recordUiTelemetryEvent(uiEvent) {
        try {
          const record2 = {
            ...this.createBaseRecord("system"),
            type: "system",
            subtype: "ui_telemetry",
            systemPayload: { uiEvent }
          };
          this.appendRecord(record2);
        } catch (error2) {
          debugLogger16.error("Error saving ui telemetry record:", error2);
        }
      }
      /**
       * Records @-command metadata as a system record for UI reconstruction.
       */
      recordAtCommand(payload) {
        try {
          const record2 = {
            ...this.createBaseRecord("system"),
            type: "system",
            subtype: "at_command",
            systemPayload: payload
          };
          this.appendRecord(record2);
        } catch (error2) {
          debugLogger16.error("Error saving @-command record:", error2);
        }
      }
    };
  }
});

// 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 && !part.thoughtSignature && // 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 (!isValidContentPart(part)) {
      return false;
    }
  }
  return true;
}
function isValidContentPart(part) {
  const isInvalid = !part.thought && !part.thoughtSignature && part.text !== void 0 && part.text === "" && part.functionCall === void 0;
  return !isInvalid;
}
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 i3 = 0;
  while (i3 < length) {
    if (comprehensiveHistory[i3].role === "user") {
      curatedHistory.push(comprehensiveHistory[i3]);
      i3++;
    } else {
      const modelOutput = [];
      let isValid2 = true;
      while (i3 < length && comprehensiveHistory[i3].role === "model") {
        modelOutput.push(comprehensiveHistory[i3]);
        if (isValid2 && !isValidContent2(comprehensiveHistory[i3])) {
          isValid2 = false;
        }
        i3++;
      }
      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 debugLogger17, StreamEventType, INVALID_CONTENT_RETRY_OPTIONS, RATE_LIMIT_RETRY_OPTIONS, InvalidStreamError, GeminiChat;
var init_geminiChat = __esm({
  "packages/core/dist/src/core/geminiChat.js"() {
    "use strict";
    init_esbuild_shims();
    init_node();
    init_retry();
    init_debugLogger();
    init_errorParsing();
    init_rateLimit();
    init_tools();
    init_loggers();
    init_chatRecordingService();
    init_types();
    init_uiTelemetry();
    debugLogger17 = createDebugLogger("QWEN_CODE_CHAT");
    (function(StreamEventType2) {
      StreamEventType2["CHUNK"] = "chunk";
      StreamEventType2["RETRY"] = "retry";
    })(StreamEventType || (StreamEventType = {}));
    INVALID_CONTENT_RETRY_OPTIONS = {
      maxAttempts: 2,
      // 1 initial call + 1 retry
      initialDelayMs: 500
    };
    RATE_LIMIT_RETRY_OPTIONS = {
      maxRetries: 10,
      delayMs: 6e4
    };
    __name(isValidResponse2, "isValidResponse");
    __name(isValidNonThoughtTextPart, "isValidNonThoughtTextPart");
    __name(isValidContent2, "isValidContent");
    __name(isValidContentPart, "isValidContentPart");
    __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;
      chatRecordingService;
      // A promise to represent the current state of the message being sent to the
      // model.
      sendPromise = Promise.resolve();
      /**
       * Creates a new GeminiChat instance.
       *
       * @param config - The configuration object.
       * @param generationConfig - Optional generation configuration.
       * @param history - Optional initial conversation history.
       * @param chatRecordingService - Optional recording service. If provided, chat
       *   messages will be recorded.
       */
      constructor(config2, generationConfig = {}, history = [], chatRecordingService) {
        this.config = config2;
        this.generationConfig = generationConfig;
        this.history = history;
        this.chatRecordingService = chatRecordingService;
        validateHistory2(history);
      }
      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((resolve30) => {
          streamDoneResolver = resolve30;
        });
        this.sendPromise = streamDonePromise;
        const userContent = createUserContent(params.message);
        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.");
            let rateLimitRetryCount = 0;
            for (let attempt = 0; attempt < INVALID_CONTENT_RETRY_OPTIONS.maxAttempts; attempt++) {
              try {
                if (attempt > 0 || rateLimitRetryCount > 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 (error2) {
                lastError = error2;
                const isRateLimit = isRateLimitError(error2);
                if (isRateLimit && rateLimitRetryCount < RATE_LIMIT_RETRY_OPTIONS.maxRetries) {
                  rateLimitRetryCount++;
                  const delayMs = RATE_LIMIT_RETRY_OPTIONS.delayMs;
                  const message = parseAndFormatApiError(error2 instanceof Error ? error2.message : String(error2));
                  debugLogger17.warn(`Rate limit throttling detected (retry ${rateLimitRetryCount}/${RATE_LIMIT_RETRY_OPTIONS.maxRetries}). Waiting ${delayMs / 1e3}s before retrying...`);
                  yield {
                    type: StreamEventType.RETRY,
                    retryInfo: {
                      message,
                      attempt: rateLimitRetryCount,
                      maxRetries: RATE_LIMIT_RETRY_OPTIONS.maxRetries,
                      delayMs
                    }
                  };
                  attempt--;
                  await new Promise((res) => setTimeout(res, delayMs));
                  continue;
                }
                const isContentError = error2 instanceof InvalidStreamError;
                if (isContentError) {
                  if (attempt < INVALID_CONTENT_RETRY_OPTIONS.maxAttempts - 1) {
                    logContentRetry(self2.config, new ContentRetryEvent(attempt, error2.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(() => this.config.getContentGenerator().generateContentStream({
          model,
          contents: requestContents,
          config: { ...this.generationConfig, ...params.config }
        }, prompt_id), "apiCall");
        const streamResponse2 = await retryWithBackoff(apiCall, {
          shouldRetryOnError: /* @__PURE__ */ __name((error2) => {
            if (error2 instanceof Error) {
              if (isSchemaDepthError(error2.message))
                return false;
              if (isInvalidArgumentError(error2.message))
                return false;
            }
            const status = getErrorStatus(error2);
            if (status === 400)
              return false;
            if (status === 429)
              return true;
            if (status && status >= 500 && status < 600)
              return true;
            return false;
          }, "shouldRetryOnError"),
          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) => {
          if (!content.parts)
            return content;
          const filteredParts = content.parts.filter((part) => !(part && typeof part === "object" && "thought" in part && part.thought)).map((part) => {
            if (part && typeof part === "object" && "thoughtSignature" in part) {
              const newPart = { ...part };
              delete newPart.thoughtSignature;
              return newPart;
            }
            return part;
          });
          return {
            ...content,
            parts: filteredParts
          };
        }).filter((content) => content.parts && content.parts.length > 0);
      }
      setTools(tools) {
        this.generationConfig.tools = tools;
      }
      async maybeIncludeSchemaDepthContext(error2) {
        if (isSchemaDepthError(error2.message) || isInvalidArgumentError(error2.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(`
 - `) + `
`;
            error2.message += extraDetails;
          }
        }
      }
      async *processStreamResponse(model, streamResponse2) {
        const allModelParts = [];
        let usageMetadata;
        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.functionCall)) {
                hasToolCall = true;
              }
              allModelParts.push(...content.parts);
            }
          }
          if (chunk.usageMetadata) {
            usageMetadata = chunk.usageMetadata;
            const lastPromptTokenCount = usageMetadata.totalTokenCount ?? usageMetadata.promptTokenCount;
            if (lastPromptTokenCount) {
              uiTelemetryService.setLastPromptTokenCount(lastPromptTokenCount);
            }
          }
          yield chunk;
        }
        let thoughtContentPart;
        const thoughtText = allModelParts.filter((part) => part.thought).map((part) => part.text).join("").trim();
        if (thoughtText !== "") {
          thoughtContentPart = {
            text: thoughtText,
            thought: true
          };
          const thoughtSignature = allModelParts.filter((part) => part.thoughtSignature && part.thought)?.[0]?.thoughtSignature;
          if (thoughtContentPart && thoughtSignature) {
            thoughtContentPart.thoughtSignature = thoughtSignature;
          }
        }
        const contentParts = allModelParts.filter((part) => !part.thought);
        const consolidatedHistoryParts = [];
        for (const part of contentParts) {
          const lastPart = consolidatedHistoryParts[consolidatedHistoryParts.length - 1];
          if (lastPart?.text && isValidNonThoughtTextPart(lastPart) && isValidNonThoughtTextPart(part)) {
            lastPart.text += part.text;
          } else if (isValidContentPart(part)) {
            consolidatedHistoryParts.push(part);
          }
        }
        const contentText = consolidatedHistoryParts.filter((part) => part.text).map((part) => part.text).join("").trim();
        if (thoughtContentPart || contentText || hasToolCall || usageMetadata) {
          this.chatRecordingService?.recordAssistantTurn({
            model,
            message: [
              ...thoughtContentPart ? [thoughtContentPart] : [],
              ...contentText ? [{ text: contentText }] : [],
              ...hasToolCall ? contentParts.filter((part) => part.functionCall).map((part) => ({ functionCall: part.functionCall })) : []
            ],
            tokens: usageMetadata
          });
        }
        if (!hasToolCall && (!hasFinishReason || !contentText)) {
          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: [
            ...thoughtContentPart ? [thoughtContentPart] : [],
            ...consolidatedHistoryParts
          ]
        });
      }
    };
    __name(isSchemaDepthError, "isSchemaDepthError");
    __name(isInvalidArgumentError, "isInvalidArgumentError");
  }
});

// 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, i3) {
          var oldValue = oldString[oldPos + i3];
          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 i3;
  for (i3 = 0; i3 < str1.length && i3 < str2.length; i3++) {
    if (str1[i3] != str2[i3]) {
      return str1.slice(0, i3);
    }
  }
  return str1.slice(0, i3);
}
function longestCommonSuffix(str1, str2) {
  var i3;
  if (!str1 || !str2 || str1[str1.length - 1] != str2[str2.length - 1]) {
    return "";
  }
  for (i3 = 0; i3 < str1.length && i3 < str2.length; i3++) {
    if (str1[str1.length - (i3 + 1)] != str2[str2.length - (i3 + 1)]) {
      return str1.slice(-i3);
    }
  }
  return str1.slice(-i3);
}
function replacePrefix(string4, oldPrefix, newPrefix) {
  if (string4.slice(0, oldPrefix.length) != oldPrefix) {
    throw Error("string ".concat(JSON.stringify(string4), " doesn't start with prefix ").concat(JSON.stringify(oldPrefix), "; this is a bug"));
  }
  return newPrefix + string4.slice(oldPrefix.length);
}
function replaceSuffix(string4, oldSuffix, newSuffix) {
  if (!oldSuffix) {
    return string4 + newSuffix;
  }
  if (string4.slice(-oldSuffix.length) != oldSuffix) {
    throw Error("string ".concat(JSON.stringify(string4), " doesn't end with suffix ").concat(JSON.stringify(oldSuffix), "; this is a bug"));
  }
  return string4.slice(0, -oldSuffix.length) + newSuffix;
}
function removePrefix(string4, oldPrefix) {
  return replacePrefix(string4, oldPrefix, "");
}
function removeSuffix(string4, oldSuffix) {
  return replaceSuffix(string4, oldSuffix, "");
}
function maximumOverlap(string12, string23) {
  return string23.slice(0, overlapCount(string12, string23));
}
function overlapCount(a2, b2) {
  var startA = 0;
  if (a2.length > b2.length) {
    startA = a2.length - b2.length;
  }
  var endB = b2.length;
  if (a2.length < b2.length) {
    endB = a2.length;
  }
  var map2 = Array(endB);
  var k2 = 0;
  map2[0] = 0;
  for (var j2 = 1; j2 < endB; j2++) {
    if (b2[j2] == b2[k2]) {
      map2[j2] = map2[k2];
    } else {
      map2[j2] = k2;
    }
    while (k2 > 0 && b2[j2] != b2[k2]) {
      k2 = map2[k2];
    }
    if (b2[j2] == b2[k2]) {
      k2++;
    }
  }
  k2 = 0;
  for (var i3 = startA; i3 < a2.length; i3++) {
    while (k2 > 0 && a2[i3] != b2[k2]) {
      k2 = map2[k2];
    }
    if (a2[i3] == b2[k2]) {
      k2++;
    }
  }
  return k2;
}
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(e4, r5) {
  var t5 = Object.keys(e4);
  if (Object.getOwnPropertySymbols) {
    var o3 = Object.getOwnPropertySymbols(e4);
    r5 && (o3 = o3.filter(function(r6) {
      return Object.getOwnPropertyDescriptor(e4, r6).enumerable;
    })), t5.push.apply(t5, o3);
  }
  return t5;
}
function _objectSpread2(e4) {
  for (var r5 = 1; r5 < arguments.length; r5++) {
    var t5 = null != arguments[r5] ? arguments[r5] : {};
    r5 % 2 ? ownKeys(Object(t5), true).forEach(function(r6) {
      _defineProperty(e4, r6, t5[r6]);
    }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e4, Object.getOwnPropertyDescriptors(t5)) : ownKeys(Object(t5)).forEach(function(r6) {
      Object.defineProperty(e4, r6, Object.getOwnPropertyDescriptor(t5, r6));
    });
  }
  return e4;
}
function _toPrimitive(t5, r5) {
  if ("object" != typeof t5 || !t5) return t5;
  var e4 = t5[Symbol.toPrimitive];
  if (void 0 !== e4) {
    var i3 = e4.call(t5, r5 || "default");
    if ("object" != typeof i3) return i3;
    throw new TypeError("@@toPrimitive must return a primitive value.");
  }
  return ("string" === r5 ? String : Number)(t5);
}
function _toPropertyKey(t5) {
  var i3 = _toPrimitive(t5, "string");
  return "symbol" == typeof i3 ? i3 : i3 + "";
}
function _typeof(o3) {
  "@babel/helpers - typeof";
  return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(o4) {
    return typeof o4;
  } : function(o4) {
    return o4 && "function" == typeof Symbol && o4.constructor === Symbol && o4 !== Symbol.prototype ? "symbol" : typeof o4;
  }, _typeof(o3);
}
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(o3, minLen) {
  if (!o3) return;
  if (typeof o3 === "string") return _arrayLikeToArray(o3, minLen);
  var n3 = Object.prototype.toString.call(o3).slice(8, -1);
  if (n3 === "Object" && o3.constructor) n3 = o3.constructor.name;
  if (n3 === "Map" || n3 === "Set") return Array.from(o3);
  if (n3 === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n3)) return _arrayLikeToArray(o3, minLen);
}
function _arrayLikeToArray(arr, len) {
  if (len == null || len > arr.length) len = arr.length;
  for (var i3 = 0, arr2 = new Array(len); i3 < len; i3++) arr2[i3] = arr[i3];
  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 i3;
  for (i3 = 0; i3 < stack.length; i3 += 1) {
    if (stack[i3] === obj) {
      return replacementStack[i3];
    }
  }
  var canonicalizedObj;
  if ("[object Array]" === Object.prototype.toString.call(obj)) {
    stack.push(obj);
    canonicalizedObj = new Array(obj.length);
    replacementStack.push(canonicalizedObj);
    for (i3 = 0; i3 < obj.length; i3 += 1) {
      canonicalizedObj[i3] = canonicalize(obj[i3], 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 (i3 = 0; i3 < sortedKeys.length; i3 += 1) {
      _key = sortedKeys[i3];
      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[i3], lines = current.lines || splitLines(current.value);
      current.lines = lines;
      if (current.added || current.removed) {
        var _curRange;
        if (!oldRangeStart) {
          var prev = diff4[i3 - 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 && i3 < 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 i3 = 0; i3 < diff4.length; i3++) {
      _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 i3 = 0; i3 < diff4.hunks.length; i3++) {
    var hunk = diff4.hunks[i3];
    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 diff(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(path125, added, removed, oldPosInc, options2) {
        var last2 = path125.lastComponent;
        if (last2 && !options2.oneChangePerToken && last2.added === added && last2.removed === removed) {
          return {
            oldPos: path125.oldPos + oldPosInc,
            lastComponent: {
              count: last2.count + 1,
              added,
              removed,
              previousComponent: last2.previousComponent
            }
          };
        } else {
          return {
            oldPos: path125.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(array2) {
        var ret = [];
        for (var i3 = 0; i3 < array2.length; i3++) {
          if (array2[i3]) {
            ret.push(array2[i3]);
          }
        }
        return ret;
      }, "removeEmpty"),
      castInput: /* @__PURE__ */ __name(function castInput(value) {
        return value;
      }, "castInput"),
      tokenize: /* @__PURE__ */ __name(function tokenize2(value) {
        return Array.from(value);
      }, "tokenize"),
      join: /* @__PURE__ */ __name(function join4(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, i3) {
        if (i3 == 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 i3 = 0; i3 < linesAndNewlines.length; i3++) {
        var line = linesAndNewlines[i3];
        if (i3 % 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(k2, v2) {
        return typeof v2 === "undefined" ? undefinedReplacement : v2;
      } : _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/memoryTool.js
import * as fs21 from "node:fs/promises";
import * as path14 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 path14.join(Storage.getGlobalQwenDir(), getCurrentGeminiMdFilename());
}
function getProjectMemoryFilePath() {
  return path14.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 fs21.readFile(getMemoryFilePath(scope), "utf-8");
  } catch (err) {
    const error2 = err;
    if (!(error2 instanceof Error) || error2.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 debugLogger18, 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();
    init_debugLogger();
    debugLogger18 = createDebugLogger("MEMORY_TOOL");
    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 = path14.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 = path14.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 fs21.mkdir(path14.dirname(memoryFilePath), {
              recursive: true
            });
            await fs21.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: fs21.readFile,
              writeFile: fs21.writeFile,
              mkdir: fs21.mkdir
            });
            const successMessage = `Okay, I've remembered that in ${scope} memory: "${fact}"`;
            return {
              llmContent: successMessage,
              returnDisplay: successMessage
            };
          }
        } catch (error2) {
          const errorMessage = error2 instanceof Error ? error2.message : String(error2);
          debugLogger18.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(path14.dirname(memoryFilePath), { recursive: true });
          let currentContent = "";
          try {
            currentContent = await fsAdapter.readFile(memoryFilePath, "utf-8");
          } catch (_e2) {
          }
          const newContent = computeNewContent(currentContent, text);
          await fsAdapter.writeFile(memoryFilePath, newContent, "utf-8");
        } catch (error2) {
          debugLogger18.error(`[MemoryTool] Error adding memory entry to ${memoryFilePath}:`, error2);
          throw new Error(`[MemoryTool] Failed to add memory entry: ${error2 instanceof Error ? error2.message : String(error2)}`);
        }
      }
      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 path15 from "node:path";
import fs22 from "node:fs";
import os8 from "node:os";
import process9 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 = os8.homedir();
      if (customPath === "~") {
        customPath = home;
      } else {
        customPath = path15.join(home, customPath.slice(2));
      }
    } catch (error2) {
      debugLogger19.warn(`Could not resolve home directory for path: ${trimmedEnvVar}`, error2);
      return { isSwitch: false, value: null, isDisabled: false };
    }
  }
  return {
    isSwitch: false,
    value: path15.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 = path15.resolve(path15.join(QWEN_CONFIG_DIR, "system.md"));
  const systemMdResolution = resolvePathFromEnv(process9.env["QWEN_SYSTEM_MD"]);
  if (systemMdResolution.value && !systemMdResolution.isDisabled) {
    systemMdEnabled = true;
    if (!systemMdResolution.isSwitch) {
      systemMdPath = systemMdResolution.value;
    }
    if (!fs22.existsSync(systemMdPath)) {
      throw new Error(`missing system prompt file '${systemMdPath}'`);
    }
  }
  const basePrompt = systemMdEnabled ? fs22.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}', and '${ToolNames.READ_FILE}' 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 = process9.env["SANDBOX"] === "sandbox-exec";
    const isGenericSandbox = !!process9.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(process9.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}' 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(process9.env["QWEN_WRITE_SYSTEM_MD"]);
  if (writeSystemMdResolution.value && !writeSystemMdResolution.isDisabled) {
    const writePath = writeSystemMdResolution.isSwitch ? systemMdPath : writeSystemMdResolution.value;
    fs22.mkdirSync(path15.dirname(writePath), { recursive: true });
    fs22.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 = process9.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:
        debugLogger19.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;
    }
  }
  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(planOnly = false) {
  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 ${planOnly ? "directly" : `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>`;
}
function getInsightPrompt(type) {
  return INSIGHT_PROMPTS[type];
}
var debugLogger19, generalToolCallExamples, qwenCoderToolCallExamples, qwenVlToolCallExamples, INSIGHT_PROMPTS;
var init_prompts = __esm({
  "packages/core/dist/src/core/prompts.js"() {
    "use strict";
    init_esbuild_shims();
    init_tool_names();
    init_gitUtils();
    init_memoryTool();
    init_debugLogger();
    debugLogger19 = createDebugLogger("PROMPTS");
    __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 &' with is_background: true 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_FILE} for path '/path/to/existingTest.test.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>
<parameter=is_background>
true
</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_FILE}>
<parameter=path>
/path/to/existingTest.test.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 &", "is_background": true}}
</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_FILE}", "arguments": {"path": "/path/to/existingTest.test.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");
    INSIGHT_PROMPTS = {
      analysis: `Analyze this Qwen Code session and extract structured facets.

CRITICAL GUIDELINES:

1. **goal_categories**: Count ONLY what the USER explicitly asked for.
   - DO NOT count Qwen's autonomous codebase exploration
   - DO NOT count work Qwen decided to do on its own
   - ONLY count when user says "can you...", "please...", "I need...", "let's...
   - POSSIBLE CATEGORIES (but be open to others that appear in the data):
      - bug_fix
      - feature_request
      - debugging
      - test_creation
      - code_refactoring
      - documentation_update
   "

2. **user_satisfaction_counts**: Base ONLY on explicit user signals.
   - "Yay!", "great!", "perfect!" \u2192 happy
   - "thanks", "looks good", "that works" \u2192 satisfied
   - "ok, now let's..." (continuing without complaint) \u2192 likely_satisfied
   - "that's not right", "try again" \u2192 dissatisfied
   - "this is broken", "I give up" \u2192 frustrated

3. **friction_counts**: Be specific about what went wrong.
   - misunderstood_request: Qwen interpreted incorrectly
   - wrong_approach: Right goal, wrong solution method
   - buggy_code: Code didn't work correctly
   - user_rejected_action: User said no/stop to a tool call
   - excessive_changes: Over-engineered or changed too much

4. If very short or just warmup, use warmup_minimal for goal_category`,
      impressive_workflows: `Analyze this Qwen Code usage data and identify what's working well for this user. Use second person ("you").

Call respond_in_schema function with A VALID JSON OBJECT as argument:
{
  "intro": "1 sentence of context",
  "impressive_workflows": [
    {"title": "Short title (3-6 words)", "description": "2-3 sentences describing the impressive workflow or approach. Use 'you' not 'the user'."}
  ]
}

Include 3 impressive workflows.`,
      project_areas: `Analyze this Qwen Code usage data and identify project areas.

Call respond_in_schema function with A VALID JSON OBJECT as argument:
{
  "areas": [
    {"name": "Area name", "session_count": N, "description": "2-3 sentences about what was worked on and how Qwen Code was used."}
  ]
}

Include 4-5 areas. Skip internal QC operations.`,
      future_opportunities: `Analyze this Qwen Code usage data and identify future opportunities.

Call respond_in_schema function with A VALID JSON OBJECT as argument:
{
  "intro": "1 sentence about evolving AI-assisted development",
  "opportunities": [
    {"title": "Short title (4-8 words)", "whats_possible": "2-3 ambitious sentences about autonomous workflows", "how_to_try": "1-2 sentences mentioning relevant tooling", "copyable_prompt": "Detailed prompt to try"}
  ]
}

Include 3 opportunities. Think BIG - autonomous workflows, parallel agents, iterating against tests.`,
      friction_points: `Analyze this Qwen Code usage data and identify friction points for this user. Use second person ("you").

Call respond_in_schema function with A VALID JSON OBJECT as argument:
{
  "intro": "1 sentence summarizing friction patterns",
  "categories": [
    {"category": "Concrete category name", "description": "1-2 sentences explaining this category and what could be done differently. Use 'you' not 'the user'.", "examples": ["Specific example with consequence", "Another example"]}
  ]
}

Include 3 friction categories with 2 examples each.`,
      memorable_moment: `Analyze this Qwen Code usage data and find a memorable moment.

Call respond_in_schema function with A VALID JSON OBJECT as argument:
{
  "headline": "A memorable QUALITATIVE moment from the transcripts - not a statistic. Something human, funny, or surprising.",
  "detail": "Brief context about when/where this happened"
}

Find something genuinely interesting or amusing from the session summaries.`,
      improvements: `Analyze this Qwen Code usage data and suggest improvements.

## QC FEATURES REFERENCE (pick from these for features_to_try):
1. **MCP Servers**: Connect Qwen to external tools, databases, and APIs via Model Context Protocol.
   - How to use: Run \`qwen mcp add --transport http <server-name> <http-url>\`
   - Good for: database queries, Slack integration, GitHub issue lookup, connecting to internal APIs
   - Example: "To connect to GitHub, run \`qwen mcp add --header "Authorization: Bearer your_github_mcp_pat" --transport http github https://api.githubcopilot.com/mcp/\` and set the AUTHORIZATION header with your PAT. Then you can ask Qwen to query issues, PRs, or repos."

2. **Custom Skills**: Reusable prompts you define as markdown files that run with a single /command.
   - How to use: Create \`.qwen/skills/commit/SKILL.md\` with instructions. Then type \`/commit\` to run it.
   - Good for: repetitive workflows - /commit, /review, /test, /deploy, /pr, or complex multi-step workflows
   - SKILL.md format:
    \`\`\`
    ---
    name: skill-name
    description: A description of what this skill does and when to use it.
    ---

    # Steps
    1. First, do X.
    2. Then do Y.
    3. Finally, verify Z.

    # Examples
    - Input: "fix lint errors in src/" \u2192 Output: runs eslint --fix, commits changes
    - Input: "review this PR" \u2192 Output: reads diff, posts inline comments

    # Edge Cases
    - If no files match, report "nothing to do" instead of failing.
    - If the user didn't specify a branch, default to the current branch.
    \`\`\`

3. **Headless Mode**: Run Qwen non-interactively from scripts and CI/CD.
   - How to use: \`qwen -p "fix lint errors"\`
   - Good for: CI/CD integration, batch code fixes, automated reviews

4. **Task Agents**: Qwen spawns focused sub-agents for complex exploration or parallel work.
   - How to use: Qwen auto-invokes when helpful, or ask "use an agent to explore X"
   - Good for: codebase exploration, understanding complex systems

Call respond_in_schema function with A VALID JSON OBJECT as argument:
{
  "Qwen_md_additions": [
    {"addition": "A specific line or block to add to QWEN.md based on workflow patterns. E.g., 'Always run tests after modifying auth-related files'", "why": "1 sentence explaining why this would help based on actual sessions", "prompt_scaffold": "Instructions for where to add this in QWEN.md. E.g., 'Add under ## Testing section'"}
  ],
  "features_to_try": [
    {"feature": "Feature name from QC FEATURES REFERENCE above", "one_liner": "What it does", "why_for_you": "Why this would help YOU based on your sessions", "example_code": "Actual command or config to copy"}
  ],
  "usage_patterns": [
    {"title": "Short title", "suggestion": "1-2 sentence summary", "detail": "3-4 sentences explaining how this applies to YOUR work", "copyable_prompt": "A specific prompt to copy and try"}
  ]
}

IMPORTANT for Qwen_md_additions: PRIORITIZE instructions that appear MULTIPLE TIMES in the user data. If user told Qwen the same thing in 2+ sessions (e.g., 'always run tests', 'use TypeScript'), that's a PRIME candidate - they shouldn't have to repeat themselves.

IMPORTANT for features_to_try: Pick 2-3 from the QC FEATURES REFERENCE above. Include 2-3 items for each category.`,
      interaction_style: `Analyze this Qwen Code usage data and describe the user's interaction style.

Call respond_in_schema function with A VALID JSON OBJECT as argument:
{
  "narrative": "2-3 paragraphs analyzing HOW the user interacts with Qwen Code. Use second person 'you'. Describe patterns: iterate quickly vs detailed upfront specs? Interrupt often or let Qwen run? Include specific examples. Use **bold** for key insights.",
  "key_pattern": "One sentence summary of most distinctive interaction style"
}
`,
      at_a_glance: `You're writing an "At a Glance" summary for a Qwen Code usage insights report for Qwen Code users. The goal is to help them understand their usage and improve how they can use Qwen better, especially as models improve.

Use this 4-part structure:

1. **What's working** - What is the user's unique style of interacting with Qwen and what are some impactful things they've done? You can include one or two details, but keep it high level since things might not be fresh in the user's memory. Don't be fluffy or overly complimentary. Also, don't focus on the tool calls they use.

2. **What's hindering you** - Split into (a) Qwen's fault (misunderstandings, wrong approaches, bugs) and (b) user-side friction (not providing enough context, environment issues -- ideally more general than just one project). Be honest but constructive.

3. **Quick wins to try** - Specific Qwen Code features they could try from the examples below, or a workflow technique if you think it's really compelling. (Avoid stuff like "Ask Qwen to confirm before taking actions" or "Type out more context up front" which are less compelling.)

4. **Ambitious workflows for better models** - As we move to much more capable models over the next 3-6 months, what should they prepare for? What workflows that seem impossible now will become possible? Draw from the appropriate section below.

Keep each section to 2-3 not-too-long sentences. Don't overwhelm the user. Don't mention specific numerical stats or underlined_categories from the session data below. Use a coaching tone.

Call respond_in_schema function with A VALID JSON OBJECT as argument:
{
  "whats_working": "(refer to instructions above)",
  "whats_hindering": "(refer to instructions above)",
  "quick_wins": "(refer to instructions above)",
  "ambitious_workflows": "(refer to instructions above)"
}`
    };
    __name(getInsightPrompt, "getInsightPrompt");
  }
});

// packages/core/dist/src/utils/thoughtUtils.js
function parseThought(rawText) {
  const startIndex = rawText.indexOf(START_DELIMITER);
  if (startIndex === -1) {
    return { subject: "", description: rawText };
  }
  const endIndex = rawText.indexOf(END_DELIMITER, startIndex + START_DELIMITER.length);
  if (endIndex === -1) {
    return { subject: "", description: rawText };
  }
  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 };
}
function getThoughtText(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.thought).map((part) => part.text ?? "").join("");
    }
  }
  return null;
}
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");
    __name(getThoughtText, "getThoughtText");
  }
});

// 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,
                retryInfo: streamEvent.retryInfo
              };
              continue;
            }
            const resp = streamEvent.value;
            if (!resp)
              continue;
            this.debugResponses.push(resp);
            if (resp.responseId) {
              this.currentResponseId = resp.responseId;
            }
            const thoughtText = getThoughtText(resp);
            if (thoughtText) {
              yield {
                type: GeminiEventType.Thought,
                value: parseThought(thoughtText)
              };
            }
            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 (e4) {
          if (signal.aborted) {
            yield { type: GeminiEventType.UserCancelled };
            return;
          }
          const error2 = toFriendlyError(e4);
          if (error2 instanceof UnauthorizedError) {
            throw error2;
          }
          const contextForReport = [...this.chat.getHistory(
            /*curated*/
            true
          ), req];
          await reportError2(error2, "Error when talking to API", contextForReport, "Turn.run-sendMessageStream");
          const status = typeof error2 === "object" && error2 !== null && "status" in error2 && typeof error2.status === "number" ? error2.status : void 0;
          const structuredError = {
            message: getErrorMessage(error2),
            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/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((a2, b2) => a2 + b2, 0);
  const targetCharCount = totalCharCount * fraction;
  let lastSplitPoint = 0;
  let cumulativeCharCount = 0;
  for (let i3 = 0; i3 < contents.length; i3++) {
    const content = contents[i3];
    if (content.role === "user" && !content.parts?.some((part) => !!part.functionResponse)) {
      if (cumulativeCharCount >= targetCharCount) {
        return i3;
      }
      lastSplitPoint = i3;
    }
    cumulativeCharCount += charCounts[i3];
  }
  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_types();
    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, config2, hasFailedCompressionAttempt) {
        const curatedHistory = chat.getHistory(true);
        const threshold = config2.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) {
          const contextLimit = config2.getContentGeneratorConfig()?.contextWindowSize ?? DEFAULT_TOKEN_LIMIT;
          if (originalTokenCount < threshold * contextLimit) {
            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 config2.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;
        const compressionUsageMetadata = summaryResponse.usageMetadata;
        const compressionInputTokenCount = compressionUsageMetadata?.promptTokenCount;
        let compressionOutputTokenCount = compressionUsageMetadata?.candidatesTokenCount;
        if (compressionOutputTokenCount === void 0 && typeof compressionUsageMetadata?.totalTokenCount === "number" && typeof compressionInputTokenCount === "number") {
          compressionOutputTokenCount = Math.max(0, compressionUsageMetadata.totalTokenCount - compressionInputTokenCount);
        }
        let newTokenCount = originalTokenCount;
        let extraHistory = [];
        let canCalculateNewTokenCount = false;
        if (!isSummaryEmpty) {
          extraHistory = [
            {
              role: "user",
              parts: [{ text: summary }]
            },
            {
              role: "model",
              parts: [{ text: "Got it. Thanks for the additional context!" }]
            },
            ...historyToKeep
          ];
          if (typeof compressionInputTokenCount === "number" && compressionInputTokenCount > 0 && typeof compressionOutputTokenCount === "number" && compressionOutputTokenCount > 0) {
            canCalculateNewTokenCount = true;
            newTokenCount = Math.max(0, originalTokenCount - (compressionInputTokenCount - 1e3) + compressionOutputTokenCount);
          }
        }
        logChatCompression(config2, makeChatCompressionEvent({
          tokens_before: originalTokenCount,
          tokens_after: newTokenCount,
          compression_input_token_count: compressionInputTokenCount,
          compression_output_token_count: compressionOutputTokenCount
        }));
        if (isSummaryEmpty) {
          return {
            newHistory: null,
            info: {
              originalTokenCount,
              newTokenCount: originalTokenCount,
              compressionStatus: CompressionStatus.COMPRESSION_FAILED_EMPTY_SUMMARY
            }
          };
        } else if (!canCalculateNewTokenCount) {
          return {
            newHistory: null,
            info: {
              originalTokenCount,
              newTokenCount: originalTokenCount,
              compressionStatus: CompressionStatus.COMPRESSION_FAILED_TOKEN_COUNT_ERROR
            }
          };
        } 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/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/services/loopDetectionService.js
import { createHash as createHash2 } from "node:crypto";
var debugLogger20, 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_types();
    init_messageInspectors();
    init_models();
    init_debugLogger();
    debugLogger20 = createDebugLogger("LOOP_DETECTION");
    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(config2) {
        this.config = config2;
      }
      /**
       * 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 createHash2("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 = createHash2("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 (e4) {
          this.config.getDebugLogger().error(e4);
          return false;
        }
        if (typeof result["confidence"] === "number") {
          if (result["confidence"] > 0.9) {
            if (typeof result["reasoning"] === "string" && result["reasoning"]) {
              debugLogger20.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_types5 = __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/utils/editor.js
import { execSync as execSync2, 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 {
    execSync2(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) {
    debugLogger21.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((resolve30, reject) => {
      const childProcess3 = spawn(diffCommand.command, diffCommand.args, {
        stdio: "inherit",
        shell: process.platform === "win32"
      });
      childProcess3.on("close", (code2) => {
        if (code2 === 0) {
          resolve30();
        } else {
          reject(new Error(`${editor} exited with code ${code2}`));
        }
      });
      childProcess3.on("error", (error2) => {
        reject(error2);
      });
    });
  } catch (error2) {
    debugLogger21.error(error2);
    throw error2;
  }
}
var debugLogger21, editorCommands;
var init_editor = __esm({
  "packages/core/dist/src/utils/editor.js"() {
    "use strict";
    init_esbuild_shims();
    init_debugLogger();
    debugLogger21 = createDebugLogger("EDITOR");
    __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");
  }
});

// packages/core/dist/src/tools/modifiable-tool.js
import os9 from "node:os";
import path16 from "node:path";
import fs23 from "node:fs";
function isModifiableDeclarativeTool(tool) {
  return "getModifyContext" in tool;
}
function createTempFilesForModify(currentContent, proposedContent, file_path) {
  const tempDir = os9.tmpdir();
  const diffDir = path16.join(tempDir, "qwen-code-tool-modify-diffs");
  if (!fs23.existsSync(diffDir)) {
    fs23.mkdirSync(diffDir, { recursive: true });
  }
  const ext2 = path16.extname(file_path);
  const fileName = path16.basename(file_path, ext2);
  const timestamp = Date.now();
  const tempOldPath = path16.join(diffDir, `qwen-code-modify-${fileName}-old-${timestamp}${ext2}`);
  const tempNewPath = path16.join(diffDir, `qwen-code-modify-${fileName}-new-${timestamp}${ext2}`);
  fs23.writeFileSync(tempOldPath, currentContent, "utf8");
  fs23.writeFileSync(tempNewPath, proposedContent, "utf8");
  return { oldPath: tempOldPath, newPath: tempNewPath };
}
function getUpdatedParams(tmpOldPath, tempNewPath, originalParams, modifyContext) {
  let oldContent = "";
  let newContent = "";
  try {
    oldContent = fs23.readFileSync(tmpOldPath, "utf8");
  } catch (err) {
    if (!isNodeError(err) || err.code !== "ENOENT")
      throw err;
    oldContent = "";
  }
  try {
    newContent = fs23.readFileSync(tempNewPath, "utf8");
  } catch (err) {
    if (!isNodeError(err) || err.code !== "ENOENT")
      throw err;
    newContent = "";
  }
  const updatedParams = modifyContext.createUpdatedParams(oldContent, newContent, originalParams);
  const updatedDiff = createPatch(path16.basename(modifyContext.getFilePath(originalParams)), oldContent, newContent, "Current", "Proposed", DEFAULT_DIFF_OPTIONS);
  return { updatedParams, updatedDiff };
}
function deleteTempFiles(oldPath, newPath) {
  try {
    fs23.unlinkSync(oldPath);
  } catch {
    debugLogger22.warn(`Error deleting temp diff file: ${oldPath}`);
  }
  try {
    fs23.unlinkSync(newPath);
  } catch {
    debugLogger22.warn(`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 debugLogger22;
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();
    init_debugLogger();
    debugLogger22 = createDebugLogger("MODIFIABLE_TOOL");
    __name(isModifiableDeclarativeTool, "isModifiableDeclarativeTool");
    __name(createTempFilesForModify, "createTempFilesForModify");
    __name(getUpdatedParams, "getUpdatedParams");
    __name(deleteTempFiles, "deleteTempFiles");
    __name(modifyWithEditor, "modifyWithEditor");
  }
});

// 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_src2();
    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, i3, j2, tmp;
          for (i3 = 0; i3 < str2Len; ++i3) {
            prevRow[i3] = i3;
            str2Char[i3] = str2.charCodeAt(i3);
          }
          prevRow[str2Len] = str2Len;
          var strCmp;
          if (useCollator) {
            for (i3 = 0; i3 < str1Len; ++i3) {
              nextCol = i3 + 1;
              for (j2 = 0; j2 < str2Len; ++j2) {
                curCol = nextCol;
                strCmp = 0 === collator.compare(str1.charAt(i3), String.fromCharCode(str2Char[j2]));
                nextCol = prevRow[j2] + (strCmp ? 0 : 1);
                tmp = curCol + 1;
                if (nextCol > tmp) {
                  nextCol = tmp;
                }
                tmp = prevRow[j2 + 1] + 1;
                if (nextCol > tmp) {
                  nextCol = tmp;
                }
                prevRow[j2] = curCol;
              }
              prevRow[j2] = nextCol;
            }
          } else {
            for (i3 = 0; i3 < str1Len; ++i3) {
              nextCol = i3 + 1;
              for (j2 = 0; j2 < str2Len; ++j2) {
                curCol = nextCol;
                strCmp = str1.charCodeAt(i3) === str2Char[j2];
                nextCol = prevRow[j2] + (strCmp ? 0 : 1);
                tmp = curCol + 1;
                if (nextCol > tmp) {
                  nextCol = tmp;
                }
                tmp = prevRow[j2 + 1] + 1;
                if (nextCol > tmp) {
                  nextCol = tmp;
                }
                prevRow[j2] = curCol;
              }
              prevRow[j2] = 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/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_QWEN_FLASH_MODEL);
    return getResponseText(parsedResponse) || textToSummarize;
  } catch (error2) {
    debugLogger23.error("Failed to summarize tool output.", error2);
    return textToSummarize;
  }
}
var debugLogger23, SUMMARIZE_TOOL_OUTPUT_PROMPT;
var init_summarizer = __esm({
  "packages/core/dist/src/utils/summarizer.js"() {
    "use strict";
    init_esbuild_shims();
    init_models();
    init_partUtils();
    init_debugLogger();
    debugLogger23 = createDebugLogger("SUMMARIZER");
    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");
  }
});

// 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(string4) {
  if (typeof string4 !== "string") {
    throw new TypeError(`Expected a \`string\`, got \`${typeof string4}\``);
  }
  return string4.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");
  }
});

// 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 (_e2) {
        try {
          const nodePty = "node-pty";
          const module2 = await import(nodePty);
          return { module: module2, name: "node-pty" };
        } catch (_e22) {
          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 i3 = 0; i3 < det.rawLen; i3++) {
          const b2 = input[i3];
          if (b2 < 32 || b2 > 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 i3 = 0; i3 < det.rawLen; i3++) {
          const b2 = input[i3];
          if ((b2 & 128) == 0)
            continue;
          if ((b2 & 224) == 192) {
            trailBytes = 1;
          } else if ((b2 & 240) == 224) {
            trailBytes = 2;
          } else if ((b2 & 248) == 240) {
            trailBytes = 3;
          } else {
            numInvalid++;
            if (numInvalid > 5)
              break;
            trailBytes = 0;
          }
          for (; ; ) {
            i3++;
            if (i3 >= det.rawLen)
              break;
            if ((input[i3] & 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 i3 = 0; i3 < limit2; i3 += 4) {
          const ch = this.getChar(input, i3);
          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(b2) {
        this.ngram = (this.ngram << 8) + (b2 & 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 b2, ignoreSpace = false;
        this.spaceChar = spaceCh;
        while ((b2 = this.nextByte(det)) >= 0) {
          const mb = this.byteMap[b2];
          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 i3 = ngrams.length - 1; i3 >= 0; i3--) {
          const ngl = ngrams[i3];
          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 i3, j2;
        let escN;
        let hits = 0;
        let misses = 0;
        let shifts = 0;
        let confidence;
        const text = det.inputBytes;
        const textLen = det.inputLen;
        scanInput: for (i3 = 0; i3 < textLen; i3++) {
          if (text[i3] == 27) {
            checkEscapes: for (escN = 0; escN < this.escapeSequences.length; escN++) {
              const seq = this.escapeSequences[escN];
              if (textLen - i3 < seq.length)
                continue checkEscapes;
              for (j2 = 1; j2 < seq.length; j2++)
                if (seq[j2] != text[i3 + j2])
                  continue checkEscapes;
              hits++;
              i3 += seq.length - 1;
              continue scanInput;
            }
            misses++;
          }
          if (text[i3] == 14 || text[i3] == 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(o3, m3, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc2 = Object.getOwnPropertyDescriptor(m3, k2);
      if (!desc2 || ("get" in desc2 ? !m3.__esModule : desc2.writable || desc2.configurable)) {
        desc2 = { enumerable: true, get: /* @__PURE__ */ __name(function() {
          return m3[k2];
        }, "get") };
      }
      Object.defineProperty(o3, k22, desc2);
    } : function(o3, m3, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o3[k22] = m3[k2];
    });
    var __setModuleDefault = exports2 && exports2.__setModuleDefault || (Object.create ? function(o3, v2) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v2 });
    } : function(o3, v2) {
      o3["default"] = v2;
    });
    var __importStar = exports2 && exports2.__importStar || /* @__PURE__ */ function() {
      var ownKeys2 = /* @__PURE__ */ __name(function(o3) {
        ownKeys2 = Object.getOwnPropertyNames || function(o4) {
          var ar2 = [];
          for (var k2 in o4) if (Object.prototype.hasOwnProperty.call(o4, k2)) ar2[ar2.length] = k2;
          return ar2;
        };
        return ownKeys2(o3);
      }, "ownKeys");
      return function(mod2) {
        if (mod2 && mod2.__esModule) return mod2;
        var result = {};
        if (mod2 != null) {
          for (var k2 = ownKeys2(mod2), i3 = 0; i3 < k2.length; i3++) if (k2[i3] !== "default") __createBinding(result, mod2, k2[i3]);
        }
        __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 i3 = 0; i3 < 256; i3++)
        byteStats[i3] = 0;
      for (let i3 = buffer.length - 1; i3 >= 0; i3--)
        byteStats[buffer[i3] & 255]++;
      let c1Bytes = false;
      for (let i3 = 128; i3 <= 159; i3 += 1) {
        if (byteStats[i3] !== 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((a2, b2) => {
        return b2.confidence - a2.confidence;
      });
      return matches;
    }, "analyse");
    exports2.analyse = analyse;
    var detectFile = /* @__PURE__ */ __name((filepath, opts = {}) => new Promise((resolve30, reject) => {
      let fd;
      const fs113 = (0, node_1.default)();
      const handler = /* @__PURE__ */ __name((err, buffer) => {
        if (fd) {
          fs113.closeSync(fd);
        }
        if (err) {
          reject(err);
        } else {
          resolve30((0, exports2.detect)(buffer));
        }
      }, "handler");
      if (opts && opts.sampleSize) {
        fd = fs113.openSync(filepath, "r");
        const sample = Buffer.allocUnsafe(opts.sampleSize);
        fs113.read(fd, sample, 0, opts.sampleSize, opts.offset, (err) => {
          handler(err, sample);
        });
        return;
      }
      fs113.readFile(filepath, handler);
    }), "detectFile");
    exports2.detectFile = detectFile;
    var detectFileSync = /* @__PURE__ */ __name((filepath, opts = {}) => {
      const fs113 = (0, node_1.default)();
      if (opts && opts.sampleSize) {
        const fd = fs113.openSync(filepath, "r");
        const sample = Buffer.allocUnsafe(opts.sampleSize);
        fs113.readSync(fd, sample, 0, opts.sampleSize, opts.offset);
        fs113.closeSync(fd);
        return (0, exports2.detect)(sample);
      }
      return (0, exports2.detect)(fs113.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 execSync3 } from "node:child_process";
import os10 from "node:os";
function getCachedEncodingForBuffer(buffer) {
  if (cachedSystemEncoding === void 0) {
    cachedSystemEncoding = getSystemEncoding();
  }
  if (cachedSystemEncoding) {
    if (cachedSystemEncoding !== "utf-8") {
      const detected = detectEncodingFromBuffer(buffer);
      if (detected === "utf-8") {
        return "utf-8";
      }
    }
    return cachedSystemEncoding;
  }
  return detectEncodingFromBuffer(buffer) || "utf-8";
}
function getSystemEncoding() {
  if (os10.platform() === "win32") {
    try {
      const output = execSync3("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 (error2) {
      debugLogger24.warn(`Failed to get Windows code page using 'chcp' command: ${error2 instanceof Error ? error2.message : String(error2)}. 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 = execSync3("locale charmap", { encoding: "utf8" }).toString().trim();
    } catch (_e2) {
      debugLogger24.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(cp3) {
  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[cp3]) {
    return map2[cp3];
  }
  debugLogger24.warn(`Unable to determine encoding for windows code page ${cp3}.`);
  return null;
}
function detectEncodingFromBuffer(buffer) {
  try {
    const detected = (0, import_chardet.detect)(buffer);
    if (detected && typeof detected === "string") {
      return detected.toLowerCase();
    }
  } catch (error2) {
    debugLogger24.warn("Failed to detect encoding with chardet:", error2);
  }
  return null;
}
var import_chardet, debugLogger24, cachedSystemEncoding;
var init_systemEncoding = __esm({
  "packages/core/dist/src/utils/systemEncoding.js"() {
    "use strict";
    init_esbuild_shims();
    import_chardet = __toESM(require_lib3(), 1);
    init_debugLogger();
    debugLogger24 = createDebugLogger("ENCODING");
    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 e4 = { 349: (e5, t6, i4) => {
        Object.defineProperty(t6, "__esModule", { value: true }), t6.CircularList = void 0;
        const s6 = i4(460), r6 = i4(844);
        class n4 extends r6.Disposable {
          static {
            __name(this, "n");
          }
          constructor(e6) {
            super(), this._maxLength = e6, this.onDeleteEmitter = this.register(new s6.EventEmitter()), this.onDelete = this.onDeleteEmitter.event, this.onInsertEmitter = this.register(new s6.EventEmitter()), this.onInsert = this.onInsertEmitter.event, this.onTrimEmitter = this.register(new s6.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(e6) {
            if (this._maxLength === e6) return;
            const t7 = new Array(e6);
            for (let i5 = 0; i5 < Math.min(e6, this.length); i5++) t7[i5] = this._array[this._getCyclicIndex(i5)];
            this._array = t7, this._maxLength = e6, this._startIndex = 0;
          }
          get length() {
            return this._length;
          }
          set length(e6) {
            if (e6 > this._length) for (let t7 = this._length; t7 < e6; t7++) this._array[t7] = void 0;
            this._length = e6;
          }
          get(e6) {
            return this._array[this._getCyclicIndex(e6)];
          }
          set(e6, t7) {
            this._array[this._getCyclicIndex(e6)] = t7;
          }
          push(e6) {
            this._array[this._getCyclicIndex(this._length)] = e6, 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(e6, t7, ...i5) {
            if (t7) {
              for (let i6 = e6; i6 < this._length - t7; i6++) this._array[this._getCyclicIndex(i6)] = this._array[this._getCyclicIndex(i6 + t7)];
              this._length -= t7, this.onDeleteEmitter.fire({ index: e6, amount: t7 });
            }
            for (let t8 = this._length - 1; t8 >= e6; t8--) this._array[this._getCyclicIndex(t8 + i5.length)] = this._array[this._getCyclicIndex(t8)];
            for (let t8 = 0; t8 < i5.length; t8++) this._array[this._getCyclicIndex(e6 + t8)] = i5[t8];
            if (i5.length && this.onInsertEmitter.fire({ index: e6, amount: i5.length }), this._length + i5.length > this._maxLength) {
              const e7 = this._length + i5.length - this._maxLength;
              this._startIndex += e7, this._length = this._maxLength, this.onTrimEmitter.fire(e7);
            } else this._length += i5.length;
          }
          trimStart(e6) {
            e6 > this._length && (e6 = this._length), this._startIndex += e6, this._length -= e6, this.onTrimEmitter.fire(e6);
          }
          shiftElements(e6, t7, i5) {
            if (!(t7 <= 0)) {
              if (e6 < 0 || e6 >= this._length) throw new Error("start argument out of range");
              if (e6 + i5 < 0) throw new Error("Cannot shift elements in list beyond index 0");
              if (i5 > 0) {
                for (let s8 = t7 - 1; s8 >= 0; s8--) this.set(e6 + s8 + i5, this.get(e6 + s8));
                const s7 = e6 + t7 + i5 - this._length;
                if (s7 > 0) for (this._length += s7; this._length > this._maxLength; ) this._length--, this._startIndex++, this.onTrimEmitter.fire(1);
              } else for (let s7 = 0; s7 < t7; s7++) this.set(e6 + s7 + i5, this.get(e6 + s7));
            }
          }
          _getCyclicIndex(e6) {
            return (this._startIndex + e6) % this._maxLength;
          }
        }
        t6.CircularList = n4;
      }, 439: (e5, t6) => {
        Object.defineProperty(t6, "__esModule", { value: true }), t6.clone = void 0, t6.clone = /* @__PURE__ */ __name(function e6(t7, i4 = 5) {
          if ("object" != typeof t7) return t7;
          const s6 = Array.isArray(t7) ? [] : {};
          for (const r6 in t7) s6[r6] = i4 <= 1 ? t7[r6] : t7[r6] && e6(t7[r6], i4 - 1);
          return s6;
        }, "e");
      }, 969: (e5, t6, i4) => {
        Object.defineProperty(t6, "__esModule", { value: true }), t6.CoreTerminal = void 0;
        const s6 = i4(844), r6 = i4(585), n4 = i4(348), a2 = i4(866), o3 = i4(744), h3 = i4(302), c4 = i4(83), l3 = i4(460), _2 = i4(753), d2 = i4(480), f5 = i4(994), u2 = i4(282), p2 = i4(435), g2 = i4(981), v2 = i4(660);
        let b2 = false;
        class S4 extends s6.Disposable {
          static {
            __name(this, "S");
          }
          get onScroll() {
            return this._onScrollApi || (this._onScrollApi = this.register(new l3.EventEmitter()), this._onScroll.event((e6) => {
              this._onScrollApi?.fire(e6.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(e6) {
            for (const t7 in e6) this.optionsService.options[t7] = e6[t7];
          }
          constructor(e6) {
            super(), this._windowsWrappingHeuristics = this.register(new s6.MutableDisposable()), this._onBinary = this.register(new l3.EventEmitter()), this.onBinary = this._onBinary.event, this._onData = this.register(new l3.EventEmitter()), this.onData = this._onData.event, this._onLineFeed = this.register(new l3.EventEmitter()), this.onLineFeed = this._onLineFeed.event, this._onResize = this.register(new l3.EventEmitter()), this.onResize = this._onResize.event, this._onWriteParsed = this.register(new l3.EventEmitter()), this.onWriteParsed = this._onWriteParsed.event, this._onScroll = this.register(new l3.EventEmitter()), this._instantiationService = new n4.InstantiationService(), this.optionsService = this.register(new h3.OptionsService(e6)), this._instantiationService.setService(r6.IOptionsService, this.optionsService), this._bufferService = this.register(this._instantiationService.createInstance(o3.BufferService)), this._instantiationService.setService(r6.IBufferService, this._bufferService), this._logService = this.register(this._instantiationService.createInstance(a2.LogService)), this._instantiationService.setService(r6.ILogService, this._logService), this.coreService = this.register(this._instantiationService.createInstance(c4.CoreService)), this._instantiationService.setService(r6.ICoreService, this.coreService), this.coreMouseService = this.register(this._instantiationService.createInstance(_2.CoreMouseService)), this._instantiationService.setService(r6.ICoreMouseService, this.coreMouseService), this.unicodeService = this.register(this._instantiationService.createInstance(d2.UnicodeService)), this._instantiationService.setService(r6.IUnicodeService, this.unicodeService), this._charsetService = this._instantiationService.createInstance(f5.CharsetService), this._instantiationService.setService(r6.ICharsetService, this._charsetService), this._oscLinkService = this._instantiationService.createInstance(v2.OscLinkService), this._instantiationService.setService(r6.IOscLinkService, this._oscLinkService), this._inputHandler = this.register(new p2.InputHandler(this._bufferService, this._charsetService, this.coreService, this._logService, this.optionsService, this._oscLinkService, this.coreMouseService, this.unicodeService)), this.register((0, l3.forwardEvent)(this._inputHandler.onLineFeed, this._onLineFeed)), this.register(this._inputHandler), this.register((0, l3.forwardEvent)(this._bufferService.onResize, this._onResize)), this.register((0, l3.forwardEvent)(this.coreService.onData, this._onData)), this.register((0, l3.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((e7) => {
              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((e7) => {
              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 g2.WriteBuffer((e7, t7) => this._inputHandler.parse(e7, t7))), this.register((0, l3.forwardEvent)(this._writeBuffer.onWriteParsed, this._onWriteParsed));
          }
          write(e6, t7) {
            this._writeBuffer.write(e6, t7);
          }
          writeSync(e6, t7) {
            this._logService.logLevel <= r6.LogLevelEnum.WARN && !b2 && (this._logService.warn("writeSync is unreliable and will be removed soon."), b2 = true), this._writeBuffer.writeSync(e6, t7);
          }
          input(e6, t7 = true) {
            this.coreService.triggerDataEvent(e6, t7);
          }
          resize(e6, t7) {
            isNaN(e6) || isNaN(t7) || (e6 = Math.max(e6, o3.MINIMUM_COLS), t7 = Math.max(t7, o3.MINIMUM_ROWS), this._bufferService.resize(e6, t7));
          }
          scroll(e6, t7 = false) {
            this._bufferService.scroll(e6, t7);
          }
          scrollLines(e6, t7, i5) {
            this._bufferService.scrollLines(e6, t7, i5);
          }
          scrollPages(e6) {
            this.scrollLines(e6 * (this.rows - 1));
          }
          scrollToTop() {
            this.scrollLines(-this._bufferService.buffer.ydisp);
          }
          scrollToBottom() {
            this.scrollLines(this._bufferService.buffer.ybase - this._bufferService.buffer.ydisp);
          }
          scrollToLine(e6) {
            const t7 = e6 - this._bufferService.buffer.ydisp;
            0 !== t7 && this.scrollLines(t7);
          }
          registerEscHandler(e6, t7) {
            return this._inputHandler.registerEscHandler(e6, t7);
          }
          registerDcsHandler(e6, t7) {
            return this._inputHandler.registerDcsHandler(e6, t7);
          }
          registerCsiHandler(e6, t7) {
            return this._inputHandler.registerCsiHandler(e6, t7);
          }
          registerOscHandler(e6, t7) {
            return this._inputHandler.registerOscHandler(e6, t7);
          }
          _setup() {
            this._handleWindowsPtyOptionChange();
          }
          reset() {
            this._inputHandler.reset(), this._bufferService.reset(), this._charsetService.reset(), this.coreService.reset(), this.coreMouseService.reset();
          }
          _handleWindowsPtyOptionChange() {
            let e6 = false;
            const t7 = this.optionsService.rawOptions.windowsPty;
            t7 && void 0 !== t7.buildNumber && void 0 !== t7.buildNumber ? e6 = !!("conpty" === t7.backend && t7.buildNumber < 21376) : this.optionsService.rawOptions.windowsMode && (e6 = true), e6 ? this._enableWindowsWrappingHeuristics() : this._windowsWrappingHeuristics.clear();
          }
          _enableWindowsWrappingHeuristics() {
            if (!this._windowsWrappingHeuristics.value) {
              const e6 = [];
              e6.push(this.onLineFeed(u2.updateWindowsModeWrappedState.bind(null, this._bufferService))), e6.push(this.registerCsiHandler({ final: "H" }, () => ((0, u2.updateWindowsModeWrappedState)(this._bufferService), false))), this._windowsWrappingHeuristics.value = (0, s6.toDisposable)(() => {
                for (const t7 of e6) t7.dispose();
              });
            }
          }
        }
        t6.CoreTerminal = S4;
      }, 460: (e5, t6) => {
        Object.defineProperty(t6, "__esModule", { value: true }), t6.runAndSubscribe = t6.forwardEvent = t6.EventEmitter = void 0, t6.EventEmitter = class {
          constructor() {
            this._listeners = [], this._disposed = false;
          }
          get event() {
            return this._event || (this._event = (e6) => {
              this._listeners.push(e6);
              const t7 = { dispose: /* @__PURE__ */ __name(() => {
                if (!this._disposed) {
                  for (let t8 = 0; t8 < this._listeners.length; t8++) if (this._listeners[t8] === e6) return void this._listeners.splice(t8, 1);
                }
              }, "dispose") };
              return t7;
            }), this._event;
          }
          fire(e6, t7) {
            const i4 = [];
            for (let e7 = 0; e7 < this._listeners.length; e7++) i4.push(this._listeners[e7]);
            for (let s6 = 0; s6 < i4.length; s6++) i4[s6].call(void 0, e6, t7);
          }
          dispose() {
            this.clearListeners(), this._disposed = true;
          }
          clearListeners() {
            this._listeners && (this._listeners.length = 0);
          }
        }, t6.forwardEvent = function(e6, t7) {
          return e6((e7) => t7.fire(e7));
        }, t6.runAndSubscribe = function(e6, t7) {
          return t7(void 0), e6((e7) => t7(e7));
        };
      }, 435: function(e5, t6, i4) {
        var s6 = this && this.__decorate || function(e6, t7, i5, s7) {
          var r7, n5 = arguments.length, a3 = n5 < 3 ? t7 : null === s7 ? s7 = Object.getOwnPropertyDescriptor(t7, i5) : s7;
          if ("object" == typeof Reflect && "function" == typeof Reflect.decorate) a3 = Reflect.decorate(e6, t7, i5, s7);
          else for (var o4 = e6.length - 1; o4 >= 0; o4--) (r7 = e6[o4]) && (a3 = (n5 < 3 ? r7(a3) : n5 > 3 ? r7(t7, i5, a3) : r7(t7, i5)) || a3);
          return n5 > 3 && a3 && Object.defineProperty(t7, i5, a3), a3;
        }, r6 = this && this.__param || function(e6, t7) {
          return function(i5, s7) {
            t7(i5, s7, e6);
          };
        };
        Object.defineProperty(t6, "__esModule", { value: true }), t6.InputHandler = t6.WindowsOptionsReportType = void 0;
        const n4 = i4(584), a2 = i4(116), o3 = i4(15), h3 = i4(844), c4 = i4(482), l3 = i4(437), _2 = i4(460), d2 = i4(643), f5 = i4(511), u2 = i4(734), p2 = i4(585), g2 = i4(480), v2 = i4(242), b2 = i4(351), S4 = i4(941), m3 = { "(": 0, ")": 1, "*": 2, "+": 3, "-": 1, ".": 2 }, C2 = 131072;
        function y2(e6, t7) {
          if (e6 > 24) return t7.setWinLines || false;
          switch (e6) {
            case 1:
              return !!t7.restoreWin;
            case 2:
              return !!t7.minimizeWin;
            case 3:
              return !!t7.setWinPosition;
            case 4:
              return !!t7.setWinSizePixels;
            case 5:
              return !!t7.raiseWin;
            case 6:
              return !!t7.lowerWin;
            case 7:
              return !!t7.refreshWin;
            case 8:
              return !!t7.setWinSizeChars;
            case 9:
              return !!t7.maximizeWin;
            case 10:
              return !!t7.fullscreenWin;
            case 11:
              return !!t7.getWinState;
            case 13:
              return !!t7.getWinPosition;
            case 14:
              return !!t7.getWinSizePixels;
            case 15:
              return !!t7.getScreenSizePixels;
            case 16:
              return !!t7.getCellSizePixels;
            case 18:
              return !!t7.getWinSizeChars;
            case 19:
              return !!t7.getScreenSizeChars;
            case 20:
              return !!t7.getIconTitle;
            case 21:
              return !!t7.getWinTitle;
            case 22:
              return !!t7.pushTitle;
            case 23:
              return !!t7.popTitle;
            case 24:
              return !!t7.setWinLines;
          }
          return false;
        }
        __name(y2, "y");
        var w2;
        !function(e6) {
          e6[e6.GET_WIN_SIZE_PIXELS = 0] = "GET_WIN_SIZE_PIXELS", e6[e6.GET_CELL_SIZE_PIXELS = 1] = "GET_CELL_SIZE_PIXELS";
        }(w2 || (t6.WindowsOptionsReportType = w2 = {}));
        let B2 = 0;
        class E2 extends h3.Disposable {
          static {
            __name(this, "E");
          }
          getAttrData() {
            return this._curAttrData;
          }
          constructor(e6, t7, i5, s7, r7, h4, d3, u3, p3 = new o3.EscapeSequenceParser()) {
            super(), this._bufferService = e6, this._charsetService = t7, this._coreService = i5, this._logService = s7, this._optionsService = r7, this._oscLinkService = h4, this._coreMouseService = d3, this._unicodeService = u3, this._parser = p3, this._parseBuffer = new Uint32Array(4096), this._stringDecoder = new c4.StringToUtf32(), this._utf8Decoder = new c4.Utf8ToUtf32(), this._workCell = new f5.CellData(), this._windowTitle = "", this._iconName = "", this._windowTitleStack = [], this._iconNameStack = [], this._curAttrData = l3.DEFAULT_ATTR_DATA.clone(), this._eraseAttrDataInternal = l3.DEFAULT_ATTR_DATA.clone(), this._onRequestBell = this.register(new _2.EventEmitter()), this.onRequestBell = this._onRequestBell.event, this._onRequestRefreshRows = this.register(new _2.EventEmitter()), this.onRequestRefreshRows = this._onRequestRefreshRows.event, this._onRequestReset = this.register(new _2.EventEmitter()), this.onRequestReset = this._onRequestReset.event, this._onRequestSendFocus = this.register(new _2.EventEmitter()), this.onRequestSendFocus = this._onRequestSendFocus.event, this._onRequestSyncScrollBar = this.register(new _2.EventEmitter()), this.onRequestSyncScrollBar = this._onRequestSyncScrollBar.event, this._onRequestWindowsOptionsReport = this.register(new _2.EventEmitter()), this.onRequestWindowsOptionsReport = this._onRequestWindowsOptionsReport.event, this._onA11yChar = this.register(new _2.EventEmitter()), this.onA11yChar = this._onA11yChar.event, this._onA11yTab = this.register(new _2.EventEmitter()), this.onA11yTab = this._onA11yTab.event, this._onCursorMove = this.register(new _2.EventEmitter()), this.onCursorMove = this._onCursorMove.event, this._onLineFeed = this.register(new _2.EventEmitter()), this.onLineFeed = this._onLineFeed.event, this._onScroll = this.register(new _2.EventEmitter()), this.onScroll = this._onScroll.event, this._onTitleChange = this.register(new _2.EventEmitter()), this.onTitleChange = this._onTitleChange.event, this._onColor = this.register(new _2.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 A4(this._bufferService), this._activeBuffer = this._bufferService.buffer, this.register(this._bufferService.buffers.onBufferActivate((e7) => this._activeBuffer = e7.activeBuffer)), this._parser.setCsiHandlerFallback((e7, t8) => {
              this._logService.debug("Unknown CSI code: ", { identifier: this._parser.identToString(e7), params: t8.toArray() });
            }), this._parser.setEscHandlerFallback((e7) => {
              this._logService.debug("Unknown ESC code: ", { identifier: this._parser.identToString(e7) });
            }), this._parser.setExecuteHandlerFallback((e7) => {
              this._logService.debug("Unknown EXECUTE code: ", { code: e7 });
            }), this._parser.setOscHandlerFallback((e7, t8, i6) => {
              this._logService.debug("Unknown OSC code: ", { identifier: e7, action: t8, data: i6 });
            }), this._parser.setDcsHandlerFallback((e7, t8, i6) => {
              "HOOK" === t8 && (i6 = i6.toArray()), this._logService.debug("Unknown DCS code: ", { identifier: this._parser.identToString(e7), action: t8, payload: i6 });
            }), this._parser.setPrintHandler((e7, t8, i6) => this.print(e7, t8, i6)), this._parser.registerCsiHandler({ final: "@" }, (e7) => this.insertChars(e7)), this._parser.registerCsiHandler({ intermediates: " ", final: "@" }, (e7) => this.scrollLeft(e7)), this._parser.registerCsiHandler({ final: "A" }, (e7) => this.cursorUp(e7)), this._parser.registerCsiHandler({ intermediates: " ", final: "A" }, (e7) => this.scrollRight(e7)), this._parser.registerCsiHandler({ final: "B" }, (e7) => this.cursorDown(e7)), this._parser.registerCsiHandler({ final: "C" }, (e7) => this.cursorForward(e7)), this._parser.registerCsiHandler({ final: "D" }, (e7) => this.cursorBackward(e7)), this._parser.registerCsiHandler({ final: "E" }, (e7) => this.cursorNextLine(e7)), this._parser.registerCsiHandler({ final: "F" }, (e7) => this.cursorPrecedingLine(e7)), this._parser.registerCsiHandler({ final: "G" }, (e7) => this.cursorCharAbsolute(e7)), this._parser.registerCsiHandler({ final: "H" }, (e7) => this.cursorPosition(e7)), this._parser.registerCsiHandler({ final: "I" }, (e7) => this.cursorForwardTab(e7)), this._parser.registerCsiHandler({ final: "J" }, (e7) => this.eraseInDisplay(e7, false)), this._parser.registerCsiHandler({ prefix: "?", final: "J" }, (e7) => this.eraseInDisplay(e7, true)), this._parser.registerCsiHandler({ final: "K" }, (e7) => this.eraseInLine(e7, false)), this._parser.registerCsiHandler({ prefix: "?", final: "K" }, (e7) => this.eraseInLine(e7, true)), this._parser.registerCsiHandler({ final: "L" }, (e7) => this.insertLines(e7)), this._parser.registerCsiHandler({ final: "M" }, (e7) => this.deleteLines(e7)), this._parser.registerCsiHandler({ final: "P" }, (e7) => this.deleteChars(e7)), this._parser.registerCsiHandler({ final: "S" }, (e7) => this.scrollUp(e7)), this._parser.registerCsiHandler({ final: "T" }, (e7) => this.scrollDown(e7)), this._parser.registerCsiHandler({ final: "X" }, (e7) => this.eraseChars(e7)), this._parser.registerCsiHandler({ final: "Z" }, (e7) => this.cursorBackwardTab(e7)), this._parser.registerCsiHandler({ final: "`" }, (e7) => this.charPosAbsolute(e7)), this._parser.registerCsiHandler({ final: "a" }, (e7) => this.hPositionRelative(e7)), this._parser.registerCsiHandler({ final: "b" }, (e7) => this.repeatPrecedingCharacter(e7)), this._parser.registerCsiHandler({ final: "c" }, (e7) => this.sendDeviceAttributesPrimary(e7)), this._parser.registerCsiHandler({ prefix: ">", final: "c" }, (e7) => this.sendDeviceAttributesSecondary(e7)), this._parser.registerCsiHandler({ final: "d" }, (e7) => this.linePosAbsolute(e7)), this._parser.registerCsiHandler({ final: "e" }, (e7) => this.vPositionRelative(e7)), this._parser.registerCsiHandler({ final: "f" }, (e7) => this.hVPosition(e7)), this._parser.registerCsiHandler({ final: "g" }, (e7) => this.tabClear(e7)), this._parser.registerCsiHandler({ final: "h" }, (e7) => this.setMode(e7)), this._parser.registerCsiHandler({ prefix: "?", final: "h" }, (e7) => this.setModePrivate(e7)), this._parser.registerCsiHandler({ final: "l" }, (e7) => this.resetMode(e7)), this._parser.registerCsiHandler({ prefix: "?", final: "l" }, (e7) => this.resetModePrivate(e7)), this._parser.registerCsiHandler({ final: "m" }, (e7) => this.charAttributes(e7)), this._parser.registerCsiHandler({ final: "n" }, (e7) => this.deviceStatus(e7)), this._parser.registerCsiHandler({ prefix: "?", final: "n" }, (e7) => this.deviceStatusPrivate(e7)), this._parser.registerCsiHandler({ intermediates: "!", final: "p" }, (e7) => this.softReset(e7)), this._parser.registerCsiHandler({ intermediates: " ", final: "q" }, (e7) => this.setCursorStyle(e7)), this._parser.registerCsiHandler({ final: "r" }, (e7) => this.setScrollRegion(e7)), this._parser.registerCsiHandler({ final: "s" }, (e7) => this.saveCursor(e7)), this._parser.registerCsiHandler({ final: "t" }, (e7) => this.windowOptions(e7)), this._parser.registerCsiHandler({ final: "u" }, (e7) => this.restoreCursor(e7)), this._parser.registerCsiHandler({ intermediates: "'", final: "}" }, (e7) => this.insertColumns(e7)), this._parser.registerCsiHandler({ intermediates: "'", final: "~" }, (e7) => this.deleteColumns(e7)), this._parser.registerCsiHandler({ intermediates: '"', final: "q" }, (e7) => this.selectProtected(e7)), this._parser.registerCsiHandler({ intermediates: "$", final: "p" }, (e7) => this.requestMode(e7, true)), this._parser.registerCsiHandler({ prefix: "?", intermediates: "$", final: "p" }, (e7) => this.requestMode(e7, false)), this._parser.setExecuteHandler(n4.C0.BEL, () => this.bell()), this._parser.setExecuteHandler(n4.C0.LF, () => this.lineFeed()), this._parser.setExecuteHandler(n4.C0.VT, () => this.lineFeed()), this._parser.setExecuteHandler(n4.C0.FF, () => this.lineFeed()), this._parser.setExecuteHandler(n4.C0.CR, () => this.carriageReturn()), this._parser.setExecuteHandler(n4.C0.BS, () => this.backspace()), this._parser.setExecuteHandler(n4.C0.HT, () => this.tab()), this._parser.setExecuteHandler(n4.C0.SO, () => this.shiftOut()), this._parser.setExecuteHandler(n4.C0.SI, () => this.shiftIn()), this._parser.setExecuteHandler(n4.C1.IND, () => this.index()), this._parser.setExecuteHandler(n4.C1.NEL, () => this.nextLine()), this._parser.setExecuteHandler(n4.C1.HTS, () => this.tabSet()), this._parser.registerOscHandler(0, new v2.OscHandler((e7) => (this.setTitle(e7), this.setIconName(e7), true))), this._parser.registerOscHandler(1, new v2.OscHandler((e7) => this.setIconName(e7))), this._parser.registerOscHandler(2, new v2.OscHandler((e7) => this.setTitle(e7))), this._parser.registerOscHandler(4, new v2.OscHandler((e7) => this.setOrReportIndexedColor(e7))), this._parser.registerOscHandler(8, new v2.OscHandler((e7) => this.setHyperlink(e7))), this._parser.registerOscHandler(10, new v2.OscHandler((e7) => this.setOrReportFgColor(e7))), this._parser.registerOscHandler(11, new v2.OscHandler((e7) => this.setOrReportBgColor(e7))), this._parser.registerOscHandler(12, new v2.OscHandler((e7) => this.setOrReportCursorColor(e7))), this._parser.registerOscHandler(104, new v2.OscHandler((e7) => this.restoreIndexedColor(e7))), this._parser.registerOscHandler(110, new v2.OscHandler((e7) => this.restoreFgColor(e7))), this._parser.registerOscHandler(111, new v2.OscHandler((e7) => this.restoreBgColor(e7))), this._parser.registerOscHandler(112, new v2.OscHandler((e7) => this.restoreCursorColor(e7))), 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 e7 in a2.CHARSETS) this._parser.registerEscHandler({ intermediates: "(", final: e7 }, () => this.selectCharset("(" + e7)), this._parser.registerEscHandler({ intermediates: ")", final: e7 }, () => this.selectCharset(")" + e7)), this._parser.registerEscHandler({ intermediates: "*", final: e7 }, () => this.selectCharset("*" + e7)), this._parser.registerEscHandler({ intermediates: "+", final: e7 }, () => this.selectCharset("+" + e7)), this._parser.registerEscHandler({ intermediates: "-", final: e7 }, () => this.selectCharset("-" + e7)), this._parser.registerEscHandler({ intermediates: ".", final: e7 }, () => this.selectCharset("." + e7)), this._parser.registerEscHandler({ intermediates: "/", final: e7 }, () => this.selectCharset("/" + e7));
            this._parser.registerEscHandler({ intermediates: "#", final: "8" }, () => this.screenAlignmentPattern()), this._parser.setErrorHandler((e7) => (this._logService.error("Parsing error: ", e7), e7)), this._parser.registerDcsHandler({ intermediates: "$", final: "q" }, new b2.DcsHandler((e7, t8) => this.requestStatusString(e7, t8)));
          }
          _preserveStack(e6, t7, i5, s7) {
            this._parseStack.paused = true, this._parseStack.cursorStartX = e6, this._parseStack.cursorStartY = t7, this._parseStack.decodedLength = i5, this._parseStack.position = s7;
          }
          _logSlowResolvingAsync(e6) {
            this._logService.logLevel <= p2.LogLevelEnum.WARN && Promise.race([e6, new Promise((e7, t7) => setTimeout(() => t7("#SLOW_TIMEOUT"), 5e3))]).catch((e7) => {
              if ("#SLOW_TIMEOUT" !== e7) throw e7;
              console.warn("async parser handler taking longer than 5000 ms");
            });
          }
          _getCurrentLinkId() {
            return this._curAttrData.extended.urlId;
          }
          parse(e6, t7) {
            let i5, s7 = this._activeBuffer.x, r7 = this._activeBuffer.y, n5 = 0;
            const a3 = this._parseStack.paused;
            if (a3) {
              if (i5 = this._parser.parse(this._parseBuffer, this._parseStack.decodedLength, t7)) return this._logSlowResolvingAsync(i5), i5;
              s7 = this._parseStack.cursorStartX, r7 = this._parseStack.cursorStartY, this._parseStack.paused = false, e6.length > C2 && (n5 = this._parseStack.position + C2);
            }
            if (this._logService.logLevel <= p2.LogLevelEnum.DEBUG && this._logService.debug("parsing data" + ("string" == typeof e6 ? ` "${e6}"` : ` "${Array.prototype.map.call(e6, (e7) => String.fromCharCode(e7)).join("")}"`), "string" == typeof e6 ? e6.split("").map((e7) => e7.charCodeAt(0)) : e6), this._parseBuffer.length < e6.length && this._parseBuffer.length < C2 && (this._parseBuffer = new Uint32Array(Math.min(e6.length, C2))), a3 || this._dirtyRowTracker.clearRange(), e6.length > C2) for (let t8 = n5; t8 < e6.length; t8 += C2) {
              const n6 = t8 + C2 < e6.length ? t8 + C2 : e6.length, a4 = "string" == typeof e6 ? this._stringDecoder.decode(e6.substring(t8, n6), this._parseBuffer) : this._utf8Decoder.decode(e6.subarray(t8, n6), this._parseBuffer);
              if (i5 = this._parser.parse(this._parseBuffer, a4)) return this._preserveStack(s7, r7, a4, t8), this._logSlowResolvingAsync(i5), i5;
            }
            else if (!a3) {
              const t8 = "string" == typeof e6 ? this._stringDecoder.decode(e6, this._parseBuffer) : this._utf8Decoder.decode(e6, this._parseBuffer);
              if (i5 = this._parser.parse(this._parseBuffer, t8)) return this._preserveStack(s7, r7, t8, 0), this._logSlowResolvingAsync(i5), i5;
            }
            this._activeBuffer.x === s7 && this._activeBuffer.y === r7 || this._onCursorMove.fire();
            const o4 = this._dirtyRowTracker.end + (this._bufferService.buffer.ybase - this._bufferService.buffer.ydisp), h4 = this._dirtyRowTracker.start + (this._bufferService.buffer.ybase - this._bufferService.buffer.ydisp);
            h4 < this._bufferService.rows && this._onRequestRefreshRows.fire(Math.min(h4, this._bufferService.rows - 1), Math.min(o4, this._bufferService.rows - 1));
          }
          print(e6, t7, i5) {
            let s7, r7;
            const n5 = this._charsetService.charset, a3 = this._optionsService.rawOptions.screenReaderMode, o4 = this._bufferService.cols, h4 = this._coreService.decPrivateModes.wraparound, _3 = this._coreService.modes.insertMode, f6 = this._curAttrData;
            let u3 = this._activeBuffer.lines.get(this._activeBuffer.ybase + this._activeBuffer.y);
            this._dirtyRowTracker.markDirty(this._activeBuffer.y), this._activeBuffer.x && i5 - t7 > 0 && 2 === u3.getWidth(this._activeBuffer.x - 1) && u3.setCellFromCodepoint(this._activeBuffer.x - 1, 0, 1, f6);
            let p3 = this._parser.precedingJoinState;
            for (let v3 = t7; v3 < i5; ++v3) {
              if (s7 = e6[v3], s7 < 127 && n5) {
                const e7 = n5[String.fromCharCode(s7)];
                e7 && (s7 = e7.charCodeAt(0));
              }
              const t8 = this._unicodeService.charProperties(s7, p3);
              r7 = g2.UnicodeService.extractWidth(t8);
              const i6 = g2.UnicodeService.extractShouldJoin(t8), b3 = i6 ? g2.UnicodeService.extractWidth(p3) : 0;
              if (p3 = t8, a3 && this._onA11yChar.fire((0, c4.stringFromCodePoint)(s7)), this._getCurrentLinkId() && this._oscLinkService.addLineToLink(this._getCurrentLinkId(), this._activeBuffer.ybase + this._activeBuffer.y), this._activeBuffer.x + r7 - b3 > o4) {
                if (h4) {
                  const e7 = u3;
                  let t9 = this._activeBuffer.x - b3;
                  for (this._activeBuffer.x = b3, 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), u3 = this._activeBuffer.lines.get(this._activeBuffer.ybase + this._activeBuffer.y), b3 > 0 && u3 instanceof l3.BufferLine && u3.copyCellsFrom(e7, t9, 0, b3, false); t9 < o4; ) e7.setCellFromCodepoint(t9++, 0, 1, f6);
                } else if (this._activeBuffer.x = o4 - 1, 2 === r7) continue;
              }
              if (i6 && this._activeBuffer.x) {
                const e7 = u3.getWidth(this._activeBuffer.x - 1) ? 1 : 2;
                u3.addCodepointToCell(this._activeBuffer.x - e7, s7, r7);
                for (let e8 = r7 - b3; --e8 >= 0; ) u3.setCellFromCodepoint(this._activeBuffer.x++, 0, 0, f6);
              } else if (_3 && (u3.insertCells(this._activeBuffer.x, r7 - b3, this._activeBuffer.getNullCell(f6)), 2 === u3.getWidth(o4 - 1) && u3.setCellFromCodepoint(o4 - 1, d2.NULL_CELL_CODE, d2.NULL_CELL_WIDTH, f6)), u3.setCellFromCodepoint(this._activeBuffer.x++, s7, r7, f6), r7 > 0) for (; --r7; ) u3.setCellFromCodepoint(this._activeBuffer.x++, 0, 0, f6);
            }
            this._parser.precedingJoinState = p3, this._activeBuffer.x < o4 && i5 - t7 > 0 && 0 === u3.getWidth(this._activeBuffer.x) && !u3.hasContent(this._activeBuffer.x) && u3.setCellFromCodepoint(this._activeBuffer.x, 0, 1, f6), this._dirtyRowTracker.markDirty(this._activeBuffer.y);
          }
          registerCsiHandler(e6, t7) {
            return "t" !== e6.final || e6.prefix || e6.intermediates ? this._parser.registerCsiHandler(e6, t7) : this._parser.registerCsiHandler(e6, (e7) => !y2(e7.params[0], this._optionsService.rawOptions.windowOptions) || t7(e7));
          }
          registerDcsHandler(e6, t7) {
            return this._parser.registerDcsHandler(e6, new b2.DcsHandler(t7));
          }
          registerEscHandler(e6, t7) {
            return this._parser.registerEscHandler(e6, t7);
          }
          registerOscHandler(e6, t7) {
            return this._parser.registerOscHandler(e6, new v2.OscHandler(t7));
          }
          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 e6 = this._activeBuffer.lines.get(this._activeBuffer.ybase + this._activeBuffer.y);
              e6.hasWidth(this._activeBuffer.x) && !e6.hasContent(this._activeBuffer.x) && this._activeBuffer.x--;
            }
            return this._restrictCursor(), true;
          }
          tab() {
            if (this._activeBuffer.x >= this._bufferService.cols) return true;
            const e6 = this._activeBuffer.x;
            return this._activeBuffer.x = this._activeBuffer.nextStop(), this._optionsService.rawOptions.screenReaderMode && this._onA11yTab.fire(this._activeBuffer.x - e6), true;
          }
          shiftOut() {
            return this._charsetService.setgLevel(1), true;
          }
          shiftIn() {
            return this._charsetService.setgLevel(0), true;
          }
          _restrictCursor(e6 = this._bufferService.cols - 1) {
            this._activeBuffer.x = Math.min(e6, 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(e6, t7) {
            this._dirtyRowTracker.markDirty(this._activeBuffer.y), this._coreService.decPrivateModes.origin ? (this._activeBuffer.x = e6, this._activeBuffer.y = this._activeBuffer.scrollTop + t7) : (this._activeBuffer.x = e6, this._activeBuffer.y = t7), this._restrictCursor(), this._dirtyRowTracker.markDirty(this._activeBuffer.y);
          }
          _moveCursor(e6, t7) {
            this._restrictCursor(), this._setCursor(this._activeBuffer.x + e6, this._activeBuffer.y + t7);
          }
          cursorUp(e6) {
            const t7 = this._activeBuffer.y - this._activeBuffer.scrollTop;
            return t7 >= 0 ? this._moveCursor(0, -Math.min(t7, e6.params[0] || 1)) : this._moveCursor(0, -(e6.params[0] || 1)), true;
          }
          cursorDown(e6) {
            const t7 = this._activeBuffer.scrollBottom - this._activeBuffer.y;
            return t7 >= 0 ? this._moveCursor(0, Math.min(t7, e6.params[0] || 1)) : this._moveCursor(0, e6.params[0] || 1), true;
          }
          cursorForward(e6) {
            return this._moveCursor(e6.params[0] || 1, 0), true;
          }
          cursorBackward(e6) {
            return this._moveCursor(-(e6.params[0] || 1), 0), true;
          }
          cursorNextLine(e6) {
            return this.cursorDown(e6), this._activeBuffer.x = 0, true;
          }
          cursorPrecedingLine(e6) {
            return this.cursorUp(e6), this._activeBuffer.x = 0, true;
          }
          cursorCharAbsolute(e6) {
            return this._setCursor((e6.params[0] || 1) - 1, this._activeBuffer.y), true;
          }
          cursorPosition(e6) {
            return this._setCursor(e6.length >= 2 ? (e6.params[1] || 1) - 1 : 0, (e6.params[0] || 1) - 1), true;
          }
          charPosAbsolute(e6) {
            return this._setCursor((e6.params[0] || 1) - 1, this._activeBuffer.y), true;
          }
          hPositionRelative(e6) {
            return this._moveCursor(e6.params[0] || 1, 0), true;
          }
          linePosAbsolute(e6) {
            return this._setCursor(this._activeBuffer.x, (e6.params[0] || 1) - 1), true;
          }
          vPositionRelative(e6) {
            return this._moveCursor(0, e6.params[0] || 1), true;
          }
          hVPosition(e6) {
            return this.cursorPosition(e6), true;
          }
          tabClear(e6) {
            const t7 = e6.params[0];
            return 0 === t7 ? delete this._activeBuffer.tabs[this._activeBuffer.x] : 3 === t7 && (this._activeBuffer.tabs = {}), true;
          }
          cursorForwardTab(e6) {
            if (this._activeBuffer.x >= this._bufferService.cols) return true;
            let t7 = e6.params[0] || 1;
            for (; t7--; ) this._activeBuffer.x = this._activeBuffer.nextStop();
            return true;
          }
          cursorBackwardTab(e6) {
            if (this._activeBuffer.x >= this._bufferService.cols) return true;
            let t7 = e6.params[0] || 1;
            for (; t7--; ) this._activeBuffer.x = this._activeBuffer.prevStop();
            return true;
          }
          selectProtected(e6) {
            const t7 = e6.params[0];
            return 1 === t7 && (this._curAttrData.bg |= 536870912), 2 !== t7 && 0 !== t7 || (this._curAttrData.bg &= -536870913), true;
          }
          _eraseInBufferLine(e6, t7, i5, s7 = false, r7 = false) {
            const n5 = this._activeBuffer.lines.get(this._activeBuffer.ybase + e6);
            n5.replaceCells(t7, i5, this._activeBuffer.getNullCell(this._eraseAttrData()), r7), s7 && (n5.isWrapped = false);
          }
          _resetBufferLine(e6, t7 = false) {
            const i5 = this._activeBuffer.lines.get(this._activeBuffer.ybase + e6);
            i5 && (i5.fill(this._activeBuffer.getNullCell(this._eraseAttrData()), t7), this._bufferService.buffer.clearMarkers(this._activeBuffer.ybase + e6), i5.isWrapped = false);
          }
          eraseInDisplay(e6, t7 = false) {
            let i5;
            switch (this._restrictCursor(this._bufferService.cols), e6.params[0]) {
              case 0:
                for (i5 = this._activeBuffer.y, this._dirtyRowTracker.markDirty(i5), this._eraseInBufferLine(i5++, this._activeBuffer.x, this._bufferService.cols, 0 === this._activeBuffer.x, t7); i5 < this._bufferService.rows; i5++) this._resetBufferLine(i5, t7);
                this._dirtyRowTracker.markDirty(i5);
                break;
              case 1:
                for (i5 = this._activeBuffer.y, this._dirtyRowTracker.markDirty(i5), this._eraseInBufferLine(i5, 0, this._activeBuffer.x + 1, true, t7), this._activeBuffer.x + 1 >= this._bufferService.cols && (this._activeBuffer.lines.get(i5 + 1).isWrapped = false); i5--; ) this._resetBufferLine(i5, t7);
                this._dirtyRowTracker.markDirty(0);
                break;
              case 2:
                for (i5 = this._bufferService.rows, this._dirtyRowTracker.markDirty(i5 - 1); i5--; ) this._resetBufferLine(i5, t7);
                this._dirtyRowTracker.markDirty(0);
                break;
              case 3:
                const e7 = this._activeBuffer.lines.length - this._bufferService.rows;
                e7 > 0 && (this._activeBuffer.lines.trimStart(e7), this._activeBuffer.ybase = Math.max(this._activeBuffer.ybase - e7, 0), this._activeBuffer.ydisp = Math.max(this._activeBuffer.ydisp - e7, 0), this._onScroll.fire(0));
            }
            return true;
          }
          eraseInLine(e6, t7 = false) {
            switch (this._restrictCursor(this._bufferService.cols), e6.params[0]) {
              case 0:
                this._eraseInBufferLine(this._activeBuffer.y, this._activeBuffer.x, this._bufferService.cols, 0 === this._activeBuffer.x, t7);
                break;
              case 1:
                this._eraseInBufferLine(this._activeBuffer.y, 0, this._activeBuffer.x + 1, false, t7);
                break;
              case 2:
                this._eraseInBufferLine(this._activeBuffer.y, 0, this._bufferService.cols, true, t7);
            }
            return this._dirtyRowTracker.markDirty(this._activeBuffer.y), true;
          }
          insertLines(e6) {
            this._restrictCursor();
            let t7 = e6.params[0] || 1;
            if (this._activeBuffer.y > this._activeBuffer.scrollBottom || this._activeBuffer.y < this._activeBuffer.scrollTop) return true;
            const i5 = this._activeBuffer.ybase + this._activeBuffer.y, s7 = this._bufferService.rows - 1 - this._activeBuffer.scrollBottom, r7 = this._bufferService.rows - 1 + this._activeBuffer.ybase - s7 + 1;
            for (; t7--; ) this._activeBuffer.lines.splice(r7 - 1, 1), this._activeBuffer.lines.splice(i5, 0, this._activeBuffer.getBlankLine(this._eraseAttrData()));
            return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.y, this._activeBuffer.scrollBottom), this._activeBuffer.x = 0, true;
          }
          deleteLines(e6) {
            this._restrictCursor();
            let t7 = e6.params[0] || 1;
            if (this._activeBuffer.y > this._activeBuffer.scrollBottom || this._activeBuffer.y < this._activeBuffer.scrollTop) return true;
            const i5 = this._activeBuffer.ybase + this._activeBuffer.y;
            let s7;
            for (s7 = this._bufferService.rows - 1 - this._activeBuffer.scrollBottom, s7 = this._bufferService.rows - 1 + this._activeBuffer.ybase - s7; t7--; ) this._activeBuffer.lines.splice(i5, 1), this._activeBuffer.lines.splice(s7, 0, this._activeBuffer.getBlankLine(this._eraseAttrData()));
            return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.y, this._activeBuffer.scrollBottom), this._activeBuffer.x = 0, true;
          }
          insertChars(e6) {
            this._restrictCursor();
            const t7 = this._activeBuffer.lines.get(this._activeBuffer.ybase + this._activeBuffer.y);
            return t7 && (t7.insertCells(this._activeBuffer.x, e6.params[0] || 1, this._activeBuffer.getNullCell(this._eraseAttrData())), this._dirtyRowTracker.markDirty(this._activeBuffer.y)), true;
          }
          deleteChars(e6) {
            this._restrictCursor();
            const t7 = this._activeBuffer.lines.get(this._activeBuffer.ybase + this._activeBuffer.y);
            return t7 && (t7.deleteCells(this._activeBuffer.x, e6.params[0] || 1, this._activeBuffer.getNullCell(this._eraseAttrData())), this._dirtyRowTracker.markDirty(this._activeBuffer.y)), true;
          }
          scrollUp(e6) {
            let t7 = e6.params[0] || 1;
            for (; t7--; ) 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(e6) {
            let t7 = e6.params[0] || 1;
            for (; t7--; ) 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(l3.DEFAULT_ATTR_DATA));
            return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop, this._activeBuffer.scrollBottom), true;
          }
          scrollLeft(e6) {
            if (this._activeBuffer.y > this._activeBuffer.scrollBottom || this._activeBuffer.y < this._activeBuffer.scrollTop) return true;
            const t7 = e6.params[0] || 1;
            for (let e7 = this._activeBuffer.scrollTop; e7 <= this._activeBuffer.scrollBottom; ++e7) {
              const i5 = this._activeBuffer.lines.get(this._activeBuffer.ybase + e7);
              i5.deleteCells(0, t7, this._activeBuffer.getNullCell(this._eraseAttrData())), i5.isWrapped = false;
            }
            return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop, this._activeBuffer.scrollBottom), true;
          }
          scrollRight(e6) {
            if (this._activeBuffer.y > this._activeBuffer.scrollBottom || this._activeBuffer.y < this._activeBuffer.scrollTop) return true;
            const t7 = e6.params[0] || 1;
            for (let e7 = this._activeBuffer.scrollTop; e7 <= this._activeBuffer.scrollBottom; ++e7) {
              const i5 = this._activeBuffer.lines.get(this._activeBuffer.ybase + e7);
              i5.insertCells(0, t7, this._activeBuffer.getNullCell(this._eraseAttrData())), i5.isWrapped = false;
            }
            return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop, this._activeBuffer.scrollBottom), true;
          }
          insertColumns(e6) {
            if (this._activeBuffer.y > this._activeBuffer.scrollBottom || this._activeBuffer.y < this._activeBuffer.scrollTop) return true;
            const t7 = e6.params[0] || 1;
            for (let e7 = this._activeBuffer.scrollTop; e7 <= this._activeBuffer.scrollBottom; ++e7) {
              const i5 = this._activeBuffer.lines.get(this._activeBuffer.ybase + e7);
              i5.insertCells(this._activeBuffer.x, t7, this._activeBuffer.getNullCell(this._eraseAttrData())), i5.isWrapped = false;
            }
            return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop, this._activeBuffer.scrollBottom), true;
          }
          deleteColumns(e6) {
            if (this._activeBuffer.y > this._activeBuffer.scrollBottom || this._activeBuffer.y < this._activeBuffer.scrollTop) return true;
            const t7 = e6.params[0] || 1;
            for (let e7 = this._activeBuffer.scrollTop; e7 <= this._activeBuffer.scrollBottom; ++e7) {
              const i5 = this._activeBuffer.lines.get(this._activeBuffer.ybase + e7);
              i5.deleteCells(this._activeBuffer.x, t7, this._activeBuffer.getNullCell(this._eraseAttrData())), i5.isWrapped = false;
            }
            return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop, this._activeBuffer.scrollBottom), true;
          }
          eraseChars(e6) {
            this._restrictCursor();
            const t7 = this._activeBuffer.lines.get(this._activeBuffer.ybase + this._activeBuffer.y);
            return t7 && (t7.replaceCells(this._activeBuffer.x, this._activeBuffer.x + (e6.params[0] || 1), this._activeBuffer.getNullCell(this._eraseAttrData())), this._dirtyRowTracker.markDirty(this._activeBuffer.y)), true;
          }
          repeatPrecedingCharacter(e6) {
            const t7 = this._parser.precedingJoinState;
            if (!t7) return true;
            const i5 = e6.params[0] || 1, s7 = g2.UnicodeService.extractWidth(t7), r7 = this._activeBuffer.x - s7, n5 = this._activeBuffer.lines.get(this._activeBuffer.ybase + this._activeBuffer.y).getString(r7), a3 = new Uint32Array(n5.length * i5);
            let o4 = 0;
            for (let e7 = 0; e7 < n5.length; ) {
              const t8 = n5.codePointAt(e7) || 0;
              a3[o4++] = t8, e7 += t8 > 65535 ? 2 : 1;
            }
            let h4 = o4;
            for (let e7 = 1; e7 < i5; ++e7) a3.copyWithin(h4, 0, o4), h4 += o4;
            return this.print(a3, 0, h4), true;
          }
          sendDeviceAttributesPrimary(e6) {
            return e6.params[0] > 0 || (this._is("xterm") || this._is("rxvt-unicode") || this._is("screen") ? this._coreService.triggerDataEvent(n4.C0.ESC + "[?1;2c") : this._is("linux") && this._coreService.triggerDataEvent(n4.C0.ESC + "[?6c")), true;
          }
          sendDeviceAttributesSecondary(e6) {
            return e6.params[0] > 0 || (this._is("xterm") ? this._coreService.triggerDataEvent(n4.C0.ESC + "[>0;276;0c") : this._is("rxvt-unicode") ? this._coreService.triggerDataEvent(n4.C0.ESC + "[>85;95;0c") : this._is("linux") ? this._coreService.triggerDataEvent(e6.params[0] + "c") : this._is("screen") && this._coreService.triggerDataEvent(n4.C0.ESC + "[>83;40003;0c")), true;
          }
          _is(e6) {
            return 0 === (this._optionsService.rawOptions.termName + "").indexOf(e6);
          }
          setMode(e6) {
            for (let t7 = 0; t7 < e6.length; t7++) switch (e6.params[t7]) {
              case 4:
                this._coreService.modes.insertMode = true;
                break;
              case 20:
                this._optionsService.options.convertEol = true;
            }
            return true;
          }
          setModePrivate(e6) {
            for (let t7 = 0; t7 < e6.length; t7++) switch (e6.params[t7]) {
              case 1:
                this._coreService.decPrivateModes.applicationCursorKeys = true;
                break;
              case 2:
                this._charsetService.setgCharset(0, a2.DEFAULT_CHARSET), this._charsetService.setgCharset(1, a2.DEFAULT_CHARSET), this._charsetService.setgCharset(2, a2.DEFAULT_CHARSET), this._charsetService.setgCharset(3, a2.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(e6) {
            for (let t7 = 0; t7 < e6.length; t7++) switch (e6.params[t7]) {
              case 4:
                this._coreService.modes.insertMode = false;
                break;
              case 20:
                this._optionsService.options.convertEol = false;
            }
            return true;
          }
          resetModePrivate(e6) {
            for (let t7 = 0; t7 < e6.length; t7++) switch (e6.params[t7]) {
              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 === e6.params[t7] && 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(e6, t7) {
            const i5 = this._coreService.decPrivateModes, { activeProtocol: s7, activeEncoding: r7 } = this._coreMouseService, a3 = this._coreService, { buffers: o4, cols: h4 } = this._bufferService, { active: c5, alt: l4 } = o4, _3 = this._optionsService.rawOptions, d3 = /* @__PURE__ */ __name((e7) => e7 ? 1 : 2, "d"), f6 = e6.params[0];
            return u3 = f6, p3 = t7 ? 2 === f6 ? 4 : 4 === f6 ? d3(a3.modes.insertMode) : 12 === f6 ? 3 : 20 === f6 ? d3(_3.convertEol) : 0 : 1 === f6 ? d3(i5.applicationCursorKeys) : 3 === f6 ? _3.windowOptions.setWinLines ? 80 === h4 ? 2 : 132 === h4 ? 1 : 0 : 0 : 6 === f6 ? d3(i5.origin) : 7 === f6 ? d3(i5.wraparound) : 8 === f6 ? 3 : 9 === f6 ? d3("X10" === s7) : 12 === f6 ? d3(_3.cursorBlink) : 25 === f6 ? d3(!a3.isCursorHidden) : 45 === f6 ? d3(i5.reverseWraparound) : 66 === f6 ? d3(i5.applicationKeypad) : 67 === f6 ? 4 : 1e3 === f6 ? d3("VT200" === s7) : 1002 === f6 ? d3("DRAG" === s7) : 1003 === f6 ? d3("ANY" === s7) : 1004 === f6 ? d3(i5.sendFocus) : 1005 === f6 ? 4 : 1006 === f6 ? d3("SGR" === r7) : 1015 === f6 ? 4 : 1016 === f6 ? d3("SGR_PIXELS" === r7) : 1048 === f6 ? 1 : 47 === f6 || 1047 === f6 || 1049 === f6 ? d3(c5 === l4) : 2004 === f6 ? d3(i5.bracketedPasteMode) : 0, a3.triggerDataEvent(`${n4.C0.ESC}[${t7 ? "" : "?"}${u3};${p3}$y`), true;
            var u3, p3;
          }
          _updateAttrColor(e6, t7, i5, s7, r7) {
            return 2 === t7 ? (e6 |= 50331648, e6 &= -16777216, e6 |= u2.AttributeData.fromColorRGB([i5, s7, r7])) : 5 === t7 && (e6 &= -50331904, e6 |= 33554432 | 255 & i5), e6;
          }
          _extractColor(e6, t7, i5) {
            const s7 = [0, 0, -1, 0, 0, 0];
            let r7 = 0, n5 = 0;
            do {
              if (s7[n5 + r7] = e6.params[t7 + n5], e6.hasSubParams(t7 + n5)) {
                const i6 = e6.getSubParams(t7 + n5);
                let a3 = 0;
                do {
                  5 === s7[1] && (r7 = 1), s7[n5 + a3 + 1 + r7] = i6[a3];
                } while (++a3 < i6.length && a3 + n5 + 1 + r7 < s7.length);
                break;
              }
              if (5 === s7[1] && n5 + r7 >= 2 || 2 === s7[1] && n5 + r7 >= 5) break;
              s7[1] && (r7 = 1);
            } while (++n5 + t7 < e6.length && n5 + r7 < s7.length);
            for (let e7 = 2; e7 < s7.length; ++e7) -1 === s7[e7] && (s7[e7] = 0);
            switch (s7[0]) {
              case 38:
                i5.fg = this._updateAttrColor(i5.fg, s7[1], s7[3], s7[4], s7[5]);
                break;
              case 48:
                i5.bg = this._updateAttrColor(i5.bg, s7[1], s7[3], s7[4], s7[5]);
                break;
              case 58:
                i5.extended = i5.extended.clone(), i5.extended.underlineColor = this._updateAttrColor(i5.extended.underlineColor, s7[1], s7[3], s7[4], s7[5]);
            }
            return n5;
          }
          _processUnderline(e6, t7) {
            t7.extended = t7.extended.clone(), (!~e6 || e6 > 5) && (e6 = 1), t7.extended.underlineStyle = e6, t7.fg |= 268435456, 0 === e6 && (t7.fg &= -268435457), t7.updateExtended();
          }
          _processSGR0(e6) {
            e6.fg = l3.DEFAULT_ATTR_DATA.fg, e6.bg = l3.DEFAULT_ATTR_DATA.bg, e6.extended = e6.extended.clone(), e6.extended.underlineStyle = 0, e6.extended.underlineColor &= -67108864, e6.updateExtended();
          }
          charAttributes(e6) {
            if (1 === e6.length && 0 === e6.params[0]) return this._processSGR0(this._curAttrData), true;
            const t7 = e6.length;
            let i5;
            const s7 = this._curAttrData;
            for (let r7 = 0; r7 < t7; r7++) i5 = e6.params[r7], i5 >= 30 && i5 <= 37 ? (s7.fg &= -50331904, s7.fg |= 16777216 | i5 - 30) : i5 >= 40 && i5 <= 47 ? (s7.bg &= -50331904, s7.bg |= 16777216 | i5 - 40) : i5 >= 90 && i5 <= 97 ? (s7.fg &= -50331904, s7.fg |= 16777224 | i5 - 90) : i5 >= 100 && i5 <= 107 ? (s7.bg &= -50331904, s7.bg |= 16777224 | i5 - 100) : 0 === i5 ? this._processSGR0(s7) : 1 === i5 ? s7.fg |= 134217728 : 3 === i5 ? s7.bg |= 67108864 : 4 === i5 ? (s7.fg |= 268435456, this._processUnderline(e6.hasSubParams(r7) ? e6.getSubParams(r7)[0] : 1, s7)) : 5 === i5 ? s7.fg |= 536870912 : 7 === i5 ? s7.fg |= 67108864 : 8 === i5 ? s7.fg |= 1073741824 : 9 === i5 ? s7.fg |= 2147483648 : 2 === i5 ? s7.bg |= 134217728 : 21 === i5 ? this._processUnderline(2, s7) : 22 === i5 ? (s7.fg &= -134217729, s7.bg &= -134217729) : 23 === i5 ? s7.bg &= -67108865 : 24 === i5 ? (s7.fg &= -268435457, this._processUnderline(0, s7)) : 25 === i5 ? s7.fg &= -536870913 : 27 === i5 ? s7.fg &= -67108865 : 28 === i5 ? s7.fg &= -1073741825 : 29 === i5 ? s7.fg &= 2147483647 : 39 === i5 ? (s7.fg &= -67108864, s7.fg |= 16777215 & l3.DEFAULT_ATTR_DATA.fg) : 49 === i5 ? (s7.bg &= -67108864, s7.bg |= 16777215 & l3.DEFAULT_ATTR_DATA.bg) : 38 === i5 || 48 === i5 || 58 === i5 ? r7 += this._extractColor(e6, r7, s7) : 53 === i5 ? s7.bg |= 1073741824 : 55 === i5 ? s7.bg &= -1073741825 : 59 === i5 ? (s7.extended = s7.extended.clone(), s7.extended.underlineColor = -1, s7.updateExtended()) : 100 === i5 ? (s7.fg &= -67108864, s7.fg |= 16777215 & l3.DEFAULT_ATTR_DATA.fg, s7.bg &= -67108864, s7.bg |= 16777215 & l3.DEFAULT_ATTR_DATA.bg) : this._logService.debug("Unknown SGR attribute: %d.", i5);
            return true;
          }
          deviceStatus(e6) {
            switch (e6.params[0]) {
              case 5:
                this._coreService.triggerDataEvent(`${n4.C0.ESC}[0n`);
                break;
              case 6:
                const e7 = this._activeBuffer.y + 1, t7 = this._activeBuffer.x + 1;
                this._coreService.triggerDataEvent(`${n4.C0.ESC}[${e7};${t7}R`);
            }
            return true;
          }
          deviceStatusPrivate(e6) {
            if (6 === e6.params[0]) {
              const e7 = this._activeBuffer.y + 1, t7 = this._activeBuffer.x + 1;
              this._coreService.triggerDataEvent(`${n4.C0.ESC}[?${e7};${t7}R`);
            }
            return true;
          }
          softReset(e6) {
            return this._coreService.isCursorHidden = false, this._onRequestSyncScrollBar.fire(), this._activeBuffer.scrollTop = 0, this._activeBuffer.scrollBottom = this._bufferService.rows - 1, this._curAttrData = l3.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(e6) {
            const t7 = e6.params[0] || 1;
            switch (t7) {
              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 i5 = t7 % 2 == 1;
            return this._optionsService.options.cursorBlink = i5, true;
          }
          setScrollRegion(e6) {
            const t7 = e6.params[0] || 1;
            let i5;
            return (e6.length < 2 || (i5 = e6.params[1]) > this._bufferService.rows || 0 === i5) && (i5 = this._bufferService.rows), i5 > t7 && (this._activeBuffer.scrollTop = t7 - 1, this._activeBuffer.scrollBottom = i5 - 1, this._setCursor(0, 0)), true;
          }
          windowOptions(e6) {
            if (!y2(e6.params[0], this._optionsService.rawOptions.windowOptions)) return true;
            const t7 = e6.length > 1 ? e6.params[1] : 0;
            switch (e6.params[0]) {
              case 14:
                2 !== t7 && this._onRequestWindowsOptionsReport.fire(w2.GET_WIN_SIZE_PIXELS);
                break;
              case 16:
                this._onRequestWindowsOptionsReport.fire(w2.GET_CELL_SIZE_PIXELS);
                break;
              case 18:
                this._bufferService && this._coreService.triggerDataEvent(`${n4.C0.ESC}[8;${this._bufferService.rows};${this._bufferService.cols}t`);
                break;
              case 22:
                0 !== t7 && 2 !== t7 || (this._windowTitleStack.push(this._windowTitle), this._windowTitleStack.length > 10 && this._windowTitleStack.shift()), 0 !== t7 && 1 !== t7 || (this._iconNameStack.push(this._iconName), this._iconNameStack.length > 10 && this._iconNameStack.shift());
                break;
              case 23:
                0 !== t7 && 2 !== t7 || this._windowTitleStack.length && this.setTitle(this._windowTitleStack.pop()), 0 !== t7 && 1 !== t7 || this._iconNameStack.length && this.setIconName(this._iconNameStack.pop());
            }
            return true;
          }
          saveCursor(e6) {
            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(e6) {
            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(e6) {
            return this._windowTitle = e6, this._onTitleChange.fire(e6), true;
          }
          setIconName(e6) {
            return this._iconName = e6, true;
          }
          setOrReportIndexedColor(e6) {
            const t7 = [], i5 = e6.split(";");
            for (; i5.length > 1; ) {
              const e7 = i5.shift(), s7 = i5.shift();
              if (/^\d+$/.exec(e7)) {
                const i6 = parseInt(e7);
                if (L2(i6)) if ("?" === s7) t7.push({ type: 0, index: i6 });
                else {
                  const e8 = (0, S4.parseColor)(s7);
                  e8 && t7.push({ type: 1, index: i6, color: e8 });
                }
              }
            }
            return t7.length && this._onColor.fire(t7), true;
          }
          setHyperlink(e6) {
            const t7 = e6.split(";");
            return !(t7.length < 2) && (t7[1] ? this._createHyperlink(t7[0], t7[1]) : !t7[0] && this._finishHyperlink());
          }
          _createHyperlink(e6, t7) {
            this._getCurrentLinkId() && this._finishHyperlink();
            const i5 = e6.split(":");
            let s7;
            const r7 = i5.findIndex((e7) => e7.startsWith("id="));
            return -1 !== r7 && (s7 = i5[r7].slice(3) || void 0), this._curAttrData.extended = this._curAttrData.extended.clone(), this._curAttrData.extended.urlId = this._oscLinkService.registerLink({ id: s7, uri: t7 }), this._curAttrData.updateExtended(), true;
          }
          _finishHyperlink() {
            return this._curAttrData.extended = this._curAttrData.extended.clone(), this._curAttrData.extended.urlId = 0, this._curAttrData.updateExtended(), true;
          }
          _setOrReportSpecialColor(e6, t7) {
            const i5 = e6.split(";");
            for (let e7 = 0; e7 < i5.length && !(t7 >= this._specialColors.length); ++e7, ++t7) if ("?" === i5[e7]) this._onColor.fire([{ type: 0, index: this._specialColors[t7] }]);
            else {
              const s7 = (0, S4.parseColor)(i5[e7]);
              s7 && this._onColor.fire([{ type: 1, index: this._specialColors[t7], color: s7 }]);
            }
            return true;
          }
          setOrReportFgColor(e6) {
            return this._setOrReportSpecialColor(e6, 0);
          }
          setOrReportBgColor(e6) {
            return this._setOrReportSpecialColor(e6, 1);
          }
          setOrReportCursorColor(e6) {
            return this._setOrReportSpecialColor(e6, 2);
          }
          restoreIndexedColor(e6) {
            if (!e6) return this._onColor.fire([{ type: 2 }]), true;
            const t7 = [], i5 = e6.split(";");
            for (let e7 = 0; e7 < i5.length; ++e7) if (/^\d+$/.exec(i5[e7])) {
              const s7 = parseInt(i5[e7]);
              L2(s7) && t7.push({ type: 2, index: s7 });
            }
            return t7.length && this._onColor.fire(t7), true;
          }
          restoreFgColor(e6) {
            return this._onColor.fire([{ type: 2, index: 256 }]), true;
          }
          restoreBgColor(e6) {
            return this._onColor.fire([{ type: 2, index: 257 }]), true;
          }
          restoreCursorColor(e6) {
            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, a2.DEFAULT_CHARSET), true;
          }
          selectCharset(e6) {
            return 2 !== e6.length ? (this.selectDefaultCharset(), true) : ("/" === e6[0] || this._charsetService.setgCharset(m3[e6[0]], a2.CHARSETS[e6[1]] || a2.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 e6 = this._activeBuffer.scrollBottom - this._activeBuffer.scrollTop;
              this._activeBuffer.lines.shiftElements(this._activeBuffer.ybase + this._activeBuffer.y, e6, 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 = l3.DEFAULT_ATTR_DATA.clone(), this._eraseAttrDataInternal = l3.DEFAULT_ATTR_DATA.clone();
          }
          _eraseAttrData() {
            return this._eraseAttrDataInternal.bg &= -67108864, this._eraseAttrDataInternal.bg |= 67108863 & this._curAttrData.bg, this._eraseAttrDataInternal;
          }
          setgLevel(e6) {
            return this._charsetService.setgLevel(e6), true;
          }
          screenAlignmentPattern() {
            const e6 = new f5.CellData();
            e6.content = 1 << 22 | "E".charCodeAt(0), e6.fg = this._curAttrData.fg, e6.bg = this._curAttrData.bg, this._setCursor(0, 0);
            for (let t7 = 0; t7 < this._bufferService.rows; ++t7) {
              const i5 = this._activeBuffer.ybase + this._activeBuffer.y + t7, s7 = this._activeBuffer.lines.get(i5);
              s7 && (s7.fill(e6), s7.isWrapped = false);
            }
            return this._dirtyRowTracker.markAllDirty(), this._setCursor(0, 0), true;
          }
          requestStatusString(e6, t7) {
            const i5 = this._bufferService.buffer, s7 = this._optionsService.rawOptions;
            return ((e7) => (this._coreService.triggerDataEvent(`${n4.C0.ESC}${e7}${n4.C0.ESC}\\`), true))('"q' === e6 ? `P1$r${this._curAttrData.isProtected() ? 1 : 0}"q` : '"p' === e6 ? 'P1$r61;1"p' : "r" === e6 ? `P1$r${i5.scrollTop + 1};${i5.scrollBottom + 1}r` : "m" === e6 ? "P1$r0m" : " q" === e6 ? `P1$r${{ block: 2, underline: 4, bar: 6 }[s7.cursorStyle] - (s7.cursorBlink ? 1 : 0)} q` : "P0$r");
          }
          markRangeDirty(e6, t7) {
            this._dirtyRowTracker.markRangeDirty(e6, t7);
          }
        }
        t6.InputHandler = E2;
        let A4 = class {
          static {
            __name(this, "A");
          }
          constructor(e6) {
            this._bufferService = e6, this.clearRange();
          }
          clearRange() {
            this.start = this._bufferService.buffer.y, this.end = this._bufferService.buffer.y;
          }
          markDirty(e6) {
            e6 < this.start ? this.start = e6 : e6 > this.end && (this.end = e6);
          }
          markRangeDirty(e6, t7) {
            e6 > t7 && (B2 = e6, e6 = t7, t7 = B2), e6 < this.start && (this.start = e6), t7 > this.end && (this.end = t7);
          }
          markAllDirty() {
            this.markRangeDirty(0, this._bufferService.rows - 1);
          }
        };
        function L2(e6) {
          return 0 <= e6 && e6 < 256;
        }
        __name(L2, "L");
        A4 = s6([r6(0, p2.IBufferService)], A4);
      }, 844: (e5, t6) => {
        function i4(e6) {
          for (const t7 of e6) t7.dispose();
          e6.length = 0;
        }
        __name(i4, "i");
        Object.defineProperty(t6, "__esModule", { value: true }), t6.getDisposeArrayDisposable = t6.disposeArray = t6.toDisposable = t6.MutableDisposable = t6.Disposable = void 0, t6.Disposable = class {
          constructor() {
            this._disposables = [], this._isDisposed = false;
          }
          dispose() {
            this._isDisposed = true;
            for (const e6 of this._disposables) e6.dispose();
            this._disposables.length = 0;
          }
          register(e6) {
            return this._disposables.push(e6), e6;
          }
          unregister(e6) {
            const t7 = this._disposables.indexOf(e6);
            -1 !== t7 && this._disposables.splice(t7, 1);
          }
        }, t6.MutableDisposable = class {
          constructor() {
            this._isDisposed = false;
          }
          get value() {
            return this._isDisposed ? void 0 : this._value;
          }
          set value(e6) {
            this._isDisposed || e6 === this._value || (this._value?.dispose(), this._value = e6);
          }
          clear() {
            this.value = void 0;
          }
          dispose() {
            this._isDisposed = true, this._value?.dispose(), this._value = void 0;
          }
        }, t6.toDisposable = function(e6) {
          return { dispose: e6 };
        }, t6.disposeArray = i4, t6.getDisposeArrayDisposable = function(e6) {
          return { dispose: /* @__PURE__ */ __name(() => i4(e6), "dispose") };
        };
      }, 114: (e5, t6) => {
        Object.defineProperty(t6, "__esModule", { value: true }), t6.isChromeOS = t6.isLinux = t6.isWindows = t6.isIphone = t6.isIpad = t6.isMac = t6.getSafariVersion = t6.isSafari = t6.isLegacyEdge = t6.isFirefox = t6.isNode = void 0, t6.isNode = "undefined" != typeof process && "title" in process;
        const i4 = t6.isNode ? "node" : navigator.userAgent, s6 = t6.isNode ? "node" : navigator.platform;
        t6.isFirefox = i4.includes("Firefox"), t6.isLegacyEdge = i4.includes("Edge"), t6.isSafari = /^((?!chrome|android).)*safari/i.test(i4), t6.getSafariVersion = function() {
          if (!t6.isSafari) return 0;
          const e6 = i4.match(/Version\/(\d+)/);
          return null === e6 || e6.length < 2 ? 0 : parseInt(e6[1]);
        }, t6.isMac = ["Macintosh", "MacIntel", "MacPPC", "Mac68K"].includes(s6), t6.isIpad = "iPad" === s6, t6.isIphone = "iPhone" === s6, t6.isWindows = ["Windows", "Win16", "Win32", "WinCE"].includes(s6), t6.isLinux = s6.indexOf("Linux") >= 0, t6.isChromeOS = /\bCrOS\b/.test(i4);
      }, 226: (e5, t6, i4) => {
        Object.defineProperty(t6, "__esModule", { value: true }), t6.DebouncedIdleTask = t6.IdleTaskQueue = t6.PriorityTaskQueue = void 0;
        const s6 = i4(114);
        class r6 {
          static {
            __name(this, "r");
          }
          constructor() {
            this._tasks = [], this._i = 0;
          }
          enqueue(e6) {
            this._tasks.push(e6), 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(e6) {
            this._idleCallback = void 0;
            let t7 = 0, i5 = 0, s7 = e6.timeRemaining(), r7 = 0;
            for (; this._i < this._tasks.length; ) {
              if (t7 = Date.now(), this._tasks[this._i]() || this._i++, t7 = Math.max(1, Date.now() - t7), i5 = Math.max(t7, i5), r7 = e6.timeRemaining(), 1.5 * i5 > r7) return s7 - t7 < -20 && console.warn(`task queue exceeded allotted deadline by ${Math.abs(Math.round(s7 - t7))}ms`), void this._start();
              s7 = r7;
            }
            this.clear();
          }
        }
        class n4 extends r6 {
          static {
            __name(this, "n");
          }
          _requestCallback(e6) {
            return setTimeout(() => e6(this._createDeadline(16)));
          }
          _cancelCallback(e6) {
            clearTimeout(e6);
          }
          _createDeadline(e6) {
            const t7 = Date.now() + e6;
            return { timeRemaining: /* @__PURE__ */ __name(() => Math.max(0, t7 - Date.now()), "timeRemaining") };
          }
        }
        t6.PriorityTaskQueue = n4, t6.IdleTaskQueue = !s6.isNode && "requestIdleCallback" in window ? class extends r6 {
          _requestCallback(e6) {
            return requestIdleCallback(e6);
          }
          _cancelCallback(e6) {
            cancelIdleCallback(e6);
          }
        } : n4, t6.DebouncedIdleTask = class {
          constructor() {
            this._queue = new t6.IdleTaskQueue();
          }
          set(e6) {
            this._queue.clear(), this._queue.enqueue(e6);
          }
          flush() {
            this._queue.flush();
          }
        };
      }, 282: (e5, t6, i4) => {
        Object.defineProperty(t6, "__esModule", { value: true }), t6.updateWindowsModeWrappedState = void 0;
        const s6 = i4(643);
        t6.updateWindowsModeWrappedState = function(e6) {
          const t7 = e6.buffer.lines.get(e6.buffer.ybase + e6.buffer.y - 1), i5 = t7?.get(e6.cols - 1), r6 = e6.buffer.lines.get(e6.buffer.ybase + e6.buffer.y);
          r6 && i5 && (r6.isWrapped = i5[s6.CHAR_DATA_CODE_INDEX] !== s6.NULL_CELL_CODE && i5[s6.CHAR_DATA_CODE_INDEX] !== s6.WHITESPACE_CELL_CODE);
        };
      }, 734: (e5, t6) => {
        Object.defineProperty(t6, "__esModule", { value: true }), t6.ExtendedAttrs = t6.AttributeData = void 0;
        class i4 {
          static {
            __name(this, "i");
          }
          constructor() {
            this.fg = 0, this.bg = 0, this.extended = new s6();
          }
          static toColorRGB(e6) {
            return [e6 >>> 16 & 255, e6 >>> 8 & 255, 255 & e6];
          }
          static fromColorRGB(e6) {
            return (255 & e6[0]) << 16 | (255 & e6[1]) << 8 | 255 & e6[2];
          }
          clone() {
            const e6 = new i4();
            return e6.fg = this.fg, e6.bg = this.bg, e6.extended = this.extended.clone(), e6;
          }
          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;
          }
        }
        t6.AttributeData = i4;
        class s6 {
          static {
            __name(this, "s");
          }
          get ext() {
            return this._urlId ? -469762049 & this._ext | this.underlineStyle << 26 : this._ext;
          }
          set ext(e6) {
            this._ext = e6;
          }
          get underlineStyle() {
            return this._urlId ? 5 : (469762048 & this._ext) >> 26;
          }
          set underlineStyle(e6) {
            this._ext &= -469762049, this._ext |= e6 << 26 & 469762048;
          }
          get underlineColor() {
            return 67108863 & this._ext;
          }
          set underlineColor(e6) {
            this._ext &= -67108864, this._ext |= 67108863 & e6;
          }
          get urlId() {
            return this._urlId;
          }
          set urlId(e6) {
            this._urlId = e6;
          }
          get underlineVariantOffset() {
            const e6 = (3758096384 & this._ext) >> 29;
            return e6 < 0 ? 4294967288 ^ e6 : e6;
          }
          set underlineVariantOffset(e6) {
            this._ext &= 536870911, this._ext |= e6 << 29 & 3758096384;
          }
          constructor(e6 = 0, t7 = 0) {
            this._ext = 0, this._urlId = 0, this._ext = e6, this._urlId = t7;
          }
          clone() {
            return new s6(this._ext, this._urlId);
          }
          isEmpty() {
            return 0 === this.underlineStyle && 0 === this._urlId;
          }
        }
        t6.ExtendedAttrs = s6;
      }, 92: (e5, t6, i4) => {
        Object.defineProperty(t6, "__esModule", { value: true }), t6.Buffer = t6.MAX_BUFFER_SIZE = void 0;
        const s6 = i4(349), r6 = i4(226), n4 = i4(734), a2 = i4(437), o3 = i4(634), h3 = i4(511), c4 = i4(643), l3 = i4(863), _2 = i4(116);
        t6.MAX_BUFFER_SIZE = 4294967295, t6.Buffer = class {
          constructor(e6, t7, i5) {
            this._hasScrollback = e6, this._optionsService = t7, this._bufferService = i5, this.ydisp = 0, this.ybase = 0, this.y = 0, this.x = 0, this.tabs = {}, this.savedY = 0, this.savedX = 0, this.savedCurAttrData = a2.DEFAULT_ATTR_DATA.clone(), this.savedCharset = _2.DEFAULT_CHARSET, this.markers = [], this._nullCell = h3.CellData.fromCharData([0, c4.NULL_CELL_CHAR, c4.NULL_CELL_WIDTH, c4.NULL_CELL_CODE]), this._whitespaceCell = h3.CellData.fromCharData([0, c4.WHITESPACE_CELL_CHAR, c4.WHITESPACE_CELL_WIDTH, c4.WHITESPACE_CELL_CODE]), this._isClearing = false, this._memoryCleanupQueue = new r6.IdleTaskQueue(), this._memoryCleanupPosition = 0, this._cols = this._bufferService.cols, this._rows = this._bufferService.rows, this.lines = new s6.CircularList(this._getCorrectBufferLength(this._rows)), this.scrollTop = 0, this.scrollBottom = this._rows - 1, this.setupTabStops();
          }
          getNullCell(e6) {
            return e6 ? (this._nullCell.fg = e6.fg, this._nullCell.bg = e6.bg, this._nullCell.extended = e6.extended) : (this._nullCell.fg = 0, this._nullCell.bg = 0, this._nullCell.extended = new n4.ExtendedAttrs()), this._nullCell;
          }
          getWhitespaceCell(e6) {
            return e6 ? (this._whitespaceCell.fg = e6.fg, this._whitespaceCell.bg = e6.bg, this._whitespaceCell.extended = e6.extended) : (this._whitespaceCell.fg = 0, this._whitespaceCell.bg = 0, this._whitespaceCell.extended = new n4.ExtendedAttrs()), this._whitespaceCell;
          }
          getBlankLine(e6, t7) {
            return new a2.BufferLine(this._bufferService.cols, this.getNullCell(e6), t7);
          }
          get hasScrollback() {
            return this._hasScrollback && this.lines.maxLength > this._rows;
          }
          get isCursorInViewport() {
            const e6 = this.ybase + this.y - this.ydisp;
            return e6 >= 0 && e6 < this._rows;
          }
          _getCorrectBufferLength(e6) {
            if (!this._hasScrollback) return e6;
            const i5 = e6 + this._optionsService.rawOptions.scrollback;
            return i5 > t6.MAX_BUFFER_SIZE ? t6.MAX_BUFFER_SIZE : i5;
          }
          fillViewportRows(e6) {
            if (0 === this.lines.length) {
              void 0 === e6 && (e6 = a2.DEFAULT_ATTR_DATA);
              let t7 = this._rows;
              for (; t7--; ) this.lines.push(this.getBlankLine(e6));
            }
          }
          clear() {
            this.ydisp = 0, this.ybase = 0, this.y = 0, this.x = 0, this.lines = new s6.CircularList(this._getCorrectBufferLength(this._rows)), this.scrollTop = 0, this.scrollBottom = this._rows - 1, this.setupTabStops();
          }
          resize(e6, t7) {
            const i5 = this.getNullCell(a2.DEFAULT_ATTR_DATA);
            let s7 = 0;
            const r7 = this._getCorrectBufferLength(t7);
            if (r7 > this.lines.maxLength && (this.lines.maxLength = r7), this.lines.length > 0) {
              if (this._cols < e6) for (let t8 = 0; t8 < this.lines.length; t8++) s7 += +this.lines.get(t8).resize(e6, i5);
              let n5 = 0;
              if (this._rows < t7) for (let s8 = this._rows; s8 < t7; s8++) this.lines.length < t7 + this.ybase && (this._optionsService.rawOptions.windowsMode || void 0 !== this._optionsService.rawOptions.windowsPty.backend || void 0 !== this._optionsService.rawOptions.windowsPty.buildNumber ? this.lines.push(new a2.BufferLine(e6, i5)) : this.ybase > 0 && this.lines.length <= this.ybase + this.y + n5 + 1 ? (this.ybase--, n5++, this.ydisp > 0 && this.ydisp--) : this.lines.push(new a2.BufferLine(e6, i5)));
              else for (let e7 = this._rows; e7 > t7; e7--) this.lines.length > t7 + this.ybase && (this.lines.length > this.ybase + this.y + 1 ? this.lines.pop() : (this.ybase++, this.ydisp++));
              if (r7 < this.lines.maxLength) {
                const e7 = this.lines.length - r7;
                e7 > 0 && (this.lines.trimStart(e7), this.ybase = Math.max(this.ybase - e7, 0), this.ydisp = Math.max(this.ydisp - e7, 0), this.savedY = Math.max(this.savedY - e7, 0)), this.lines.maxLength = r7;
              }
              this.x = Math.min(this.x, e6 - 1), this.y = Math.min(this.y, t7 - 1), n5 && (this.y += n5), this.savedX = Math.min(this.savedX, e6 - 1), this.scrollTop = 0;
            }
            if (this.scrollBottom = t7 - 1, this._isReflowEnabled && (this._reflow(e6, t7), this._cols > e6)) for (let t8 = 0; t8 < this.lines.length; t8++) s7 += +this.lines.get(t8).resize(e6, i5);
            this._cols = e6, this._rows = t7, this._memoryCleanupQueue.clear(), s7 > 0.1 * this.lines.length && (this._memoryCleanupPosition = 0, this._memoryCleanupQueue.enqueue(() => this._batchedMemoryCleanup()));
          }
          _batchedMemoryCleanup() {
            let e6 = true;
            this._memoryCleanupPosition >= this.lines.length && (this._memoryCleanupPosition = 0, e6 = false);
            let t7 = 0;
            for (; this._memoryCleanupPosition < this.lines.length; ) if (t7 += this.lines.get(this._memoryCleanupPosition++).cleanupMemory(), t7 > 100) return true;
            return e6;
          }
          get _isReflowEnabled() {
            const e6 = this._optionsService.rawOptions.windowsPty;
            return e6 && e6.buildNumber ? this._hasScrollback && "conpty" === e6.backend && e6.buildNumber >= 21376 : this._hasScrollback && !this._optionsService.rawOptions.windowsMode;
          }
          _reflow(e6, t7) {
            this._cols !== e6 && (e6 > this._cols ? this._reflowLarger(e6, t7) : this._reflowSmaller(e6, t7));
          }
          _reflowLarger(e6, t7) {
            const i5 = (0, o3.reflowLargerGetLinesToRemove)(this.lines, this._cols, e6, this.ybase + this.y, this.getNullCell(a2.DEFAULT_ATTR_DATA));
            if (i5.length > 0) {
              const s7 = (0, o3.reflowLargerCreateNewLayout)(this.lines, i5);
              (0, o3.reflowLargerApplyNewLayout)(this.lines, s7.layout), this._reflowLargerAdjustViewport(e6, t7, s7.countRemoved);
            }
          }
          _reflowLargerAdjustViewport(e6, t7, i5) {
            const s7 = this.getNullCell(a2.DEFAULT_ATTR_DATA);
            let r7 = i5;
            for (; r7-- > 0; ) 0 === this.ybase ? (this.y > 0 && this.y--, this.lines.length < t7 && this.lines.push(new a2.BufferLine(e6, s7))) : (this.ydisp === this.ybase && this.ydisp--, this.ybase--);
            this.savedY = Math.max(this.savedY - i5, 0);
          }
          _reflowSmaller(e6, t7) {
            const i5 = this.getNullCell(a2.DEFAULT_ATTR_DATA), s7 = [];
            let r7 = 0;
            for (let n5 = this.lines.length - 1; n5 >= 0; n5--) {
              let h4 = this.lines.get(n5);
              if (!h4 || !h4.isWrapped && h4.getTrimmedLength() <= e6) continue;
              const c5 = [h4];
              for (; h4.isWrapped && n5 > 0; ) h4 = this.lines.get(--n5), c5.unshift(h4);
              const l4 = this.ybase + this.y;
              if (l4 >= n5 && l4 < n5 + c5.length) continue;
              const _3 = c5[c5.length - 1].getTrimmedLength(), d2 = (0, o3.reflowSmallerGetNewLineLengths)(c5, this._cols, e6), f5 = d2.length - c5.length;
              let u2;
              u2 = 0 === this.ybase && this.y !== this.lines.length - 1 ? Math.max(0, this.y - this.lines.maxLength + f5) : Math.max(0, this.lines.length - this.lines.maxLength + f5);
              const p2 = [];
              for (let e7 = 0; e7 < f5; e7++) {
                const e8 = this.getBlankLine(a2.DEFAULT_ATTR_DATA, true);
                p2.push(e8);
              }
              p2.length > 0 && (s7.push({ start: n5 + c5.length + r7, newLines: p2 }), r7 += p2.length), c5.push(...p2);
              let g2 = d2.length - 1, v2 = d2[g2];
              0 === v2 && (g2--, v2 = d2[g2]);
              let b2 = c5.length - f5 - 1, S4 = _3;
              for (; b2 >= 0; ) {
                const e7 = Math.min(S4, v2);
                if (void 0 === c5[g2]) break;
                if (c5[g2].copyCellsFrom(c5[b2], S4 - e7, v2 - e7, e7, true), v2 -= e7, 0 === v2 && (g2--, v2 = d2[g2]), S4 -= e7, 0 === S4) {
                  b2--;
                  const e8 = Math.max(b2, 0);
                  S4 = (0, o3.getWrappedLineTrimmedLength)(c5, e8, this._cols);
                }
              }
              for (let t8 = 0; t8 < c5.length; t8++) d2[t8] < e6 && c5[t8].setCell(d2[t8], i5);
              let m3 = f5 - u2;
              for (; m3-- > 0; ) 0 === this.ybase ? this.y < t7 - 1 ? (this.y++, this.lines.pop()) : (this.ybase++, this.ydisp++) : this.ybase < Math.min(this.lines.maxLength, this.lines.length + r7) - t7 && (this.ybase === this.ydisp && this.ydisp++, this.ybase++);
              this.savedY = Math.min(this.savedY + f5, this.ybase + t7 - 1);
            }
            if (s7.length > 0) {
              const e7 = [], t8 = [];
              for (let e8 = 0; e8 < this.lines.length; e8++) t8.push(this.lines.get(e8));
              const i6 = this.lines.length;
              let n5 = i6 - 1, a3 = 0, o4 = s7[a3];
              this.lines.length = Math.min(this.lines.maxLength, this.lines.length + r7);
              let h4 = 0;
              for (let c6 = Math.min(this.lines.maxLength - 1, i6 + r7 - 1); c6 >= 0; c6--) if (o4 && o4.start > n5 + h4) {
                for (let e8 = o4.newLines.length - 1; e8 >= 0; e8--) this.lines.set(c6--, o4.newLines[e8]);
                c6++, e7.push({ index: n5 + 1, amount: o4.newLines.length }), h4 += o4.newLines.length, o4 = s7[++a3];
              } else this.lines.set(c6, t8[n5--]);
              let c5 = 0;
              for (let t9 = e7.length - 1; t9 >= 0; t9--) e7[t9].index += c5, this.lines.onInsertEmitter.fire(e7[t9]), c5 += e7[t9].amount;
              const l4 = Math.max(0, i6 + r7 - this.lines.maxLength);
              l4 > 0 && this.lines.onTrimEmitter.fire(l4);
            }
          }
          translateBufferLineToString(e6, t7, i5 = 0, s7) {
            const r7 = this.lines.get(e6);
            return r7 ? r7.translateToString(t7, i5, s7) : "";
          }
          getWrappedRangeForLine(e6) {
            let t7 = e6, i5 = e6;
            for (; t7 > 0 && this.lines.get(t7).isWrapped; ) t7--;
            for (; i5 + 1 < this.lines.length && this.lines.get(i5 + 1).isWrapped; ) i5++;
            return { first: t7, last: i5 };
          }
          setupTabStops(e6) {
            for (null != e6 ? this.tabs[e6] || (e6 = this.prevStop(e6)) : (this.tabs = {}, e6 = 0); e6 < this._cols; e6 += this._optionsService.rawOptions.tabStopWidth) this.tabs[e6] = true;
          }
          prevStop(e6) {
            for (null == e6 && (e6 = this.x); !this.tabs[--e6] && e6 > 0; ) ;
            return e6 >= this._cols ? this._cols - 1 : e6 < 0 ? 0 : e6;
          }
          nextStop(e6) {
            for (null == e6 && (e6 = this.x); !this.tabs[++e6] && e6 < this._cols; ) ;
            return e6 >= this._cols ? this._cols - 1 : e6 < 0 ? 0 : e6;
          }
          clearMarkers(e6) {
            this._isClearing = true;
            for (let t7 = 0; t7 < this.markers.length; t7++) this.markers[t7].line === e6 && (this.markers[t7].dispose(), this.markers.splice(t7--, 1));
            this._isClearing = false;
          }
          clearAllMarkers() {
            this._isClearing = true;
            for (let e6 = 0; e6 < this.markers.length; e6++) this.markers[e6].dispose(), this.markers.splice(e6--, 1);
            this._isClearing = false;
          }
          addMarker(e6) {
            const t7 = new l3.Marker(e6);
            return this.markers.push(t7), t7.register(this.lines.onTrim((e7) => {
              t7.line -= e7, t7.line < 0 && t7.dispose();
            })), t7.register(this.lines.onInsert((e7) => {
              t7.line >= e7.index && (t7.line += e7.amount);
            })), t7.register(this.lines.onDelete((e7) => {
              t7.line >= e7.index && t7.line < e7.index + e7.amount && t7.dispose(), t7.line > e7.index && (t7.line -= e7.amount);
            })), t7.register(t7.onDispose(() => this._removeMarker(t7))), t7;
          }
          _removeMarker(e6) {
            this._isClearing || this.markers.splice(this.markers.indexOf(e6), 1);
          }
        };
      }, 437: (e5, t6, i4) => {
        Object.defineProperty(t6, "__esModule", { value: true }), t6.BufferLine = t6.DEFAULT_ATTR_DATA = void 0;
        const s6 = i4(734), r6 = i4(511), n4 = i4(643), a2 = i4(482);
        t6.DEFAULT_ATTR_DATA = Object.freeze(new s6.AttributeData());
        let o3 = 0;
        class h3 {
          static {
            __name(this, "h");
          }
          constructor(e6, t7, i5 = false) {
            this.isWrapped = i5, this._combined = {}, this._extendedAttrs = {}, this._data = new Uint32Array(3 * e6);
            const s7 = t7 || r6.CellData.fromCharData([0, n4.NULL_CELL_CHAR, n4.NULL_CELL_WIDTH, n4.NULL_CELL_CODE]);
            for (let t8 = 0; t8 < e6; ++t8) this.setCell(t8, s7);
            this.length = e6;
          }
          get(e6) {
            const t7 = this._data[3 * e6 + 0], i5 = 2097151 & t7;
            return [this._data[3 * e6 + 1], 2097152 & t7 ? this._combined[e6] : i5 ? (0, a2.stringFromCodePoint)(i5) : "", t7 >> 22, 2097152 & t7 ? this._combined[e6].charCodeAt(this._combined[e6].length - 1) : i5];
          }
          set(e6, t7) {
            this._data[3 * e6 + 1] = t7[n4.CHAR_DATA_ATTR_INDEX], t7[n4.CHAR_DATA_CHAR_INDEX].length > 1 ? (this._combined[e6] = t7[1], this._data[3 * e6 + 0] = 2097152 | e6 | t7[n4.CHAR_DATA_WIDTH_INDEX] << 22) : this._data[3 * e6 + 0] = t7[n4.CHAR_DATA_CHAR_INDEX].charCodeAt(0) | t7[n4.CHAR_DATA_WIDTH_INDEX] << 22;
          }
          getWidth(e6) {
            return this._data[3 * e6 + 0] >> 22;
          }
          hasWidth(e6) {
            return 12582912 & this._data[3 * e6 + 0];
          }
          getFg(e6) {
            return this._data[3 * e6 + 1];
          }
          getBg(e6) {
            return this._data[3 * e6 + 2];
          }
          hasContent(e6) {
            return 4194303 & this._data[3 * e6 + 0];
          }
          getCodePoint(e6) {
            const t7 = this._data[3 * e6 + 0];
            return 2097152 & t7 ? this._combined[e6].charCodeAt(this._combined[e6].length - 1) : 2097151 & t7;
          }
          isCombined(e6) {
            return 2097152 & this._data[3 * e6 + 0];
          }
          getString(e6) {
            const t7 = this._data[3 * e6 + 0];
            return 2097152 & t7 ? this._combined[e6] : 2097151 & t7 ? (0, a2.stringFromCodePoint)(2097151 & t7) : "";
          }
          isProtected(e6) {
            return 536870912 & this._data[3 * e6 + 2];
          }
          loadCell(e6, t7) {
            return o3 = 3 * e6, t7.content = this._data[o3 + 0], t7.fg = this._data[o3 + 1], t7.bg = this._data[o3 + 2], 2097152 & t7.content && (t7.combinedData = this._combined[e6]), 268435456 & t7.bg && (t7.extended = this._extendedAttrs[e6]), t7;
          }
          setCell(e6, t7) {
            2097152 & t7.content && (this._combined[e6] = t7.combinedData), 268435456 & t7.bg && (this._extendedAttrs[e6] = t7.extended), this._data[3 * e6 + 0] = t7.content, this._data[3 * e6 + 1] = t7.fg, this._data[3 * e6 + 2] = t7.bg;
          }
          setCellFromCodepoint(e6, t7, i5, s7) {
            268435456 & s7.bg && (this._extendedAttrs[e6] = s7.extended), this._data[3 * e6 + 0] = t7 | i5 << 22, this._data[3 * e6 + 1] = s7.fg, this._data[3 * e6 + 2] = s7.bg;
          }
          addCodepointToCell(e6, t7, i5) {
            let s7 = this._data[3 * e6 + 0];
            2097152 & s7 ? this._combined[e6] += (0, a2.stringFromCodePoint)(t7) : 2097151 & s7 ? (this._combined[e6] = (0, a2.stringFromCodePoint)(2097151 & s7) + (0, a2.stringFromCodePoint)(t7), s7 &= -2097152, s7 |= 2097152) : s7 = t7 | 1 << 22, i5 && (s7 &= -12582913, s7 |= i5 << 22), this._data[3 * e6 + 0] = s7;
          }
          insertCells(e6, t7, i5) {
            if ((e6 %= this.length) && 2 === this.getWidth(e6 - 1) && this.setCellFromCodepoint(e6 - 1, 0, 1, i5), t7 < this.length - e6) {
              const s7 = new r6.CellData();
              for (let i6 = this.length - e6 - t7 - 1; i6 >= 0; --i6) this.setCell(e6 + t7 + i6, this.loadCell(e6 + i6, s7));
              for (let s8 = 0; s8 < t7; ++s8) this.setCell(e6 + s8, i5);
            } else for (let t8 = e6; t8 < this.length; ++t8) this.setCell(t8, i5);
            2 === this.getWidth(this.length - 1) && this.setCellFromCodepoint(this.length - 1, 0, 1, i5);
          }
          deleteCells(e6, t7, i5) {
            if (e6 %= this.length, t7 < this.length - e6) {
              const s7 = new r6.CellData();
              for (let i6 = 0; i6 < this.length - e6 - t7; ++i6) this.setCell(e6 + i6, this.loadCell(e6 + t7 + i6, s7));
              for (let e7 = this.length - t7; e7 < this.length; ++e7) this.setCell(e7, i5);
            } else for (let t8 = e6; t8 < this.length; ++t8) this.setCell(t8, i5);
            e6 && 2 === this.getWidth(e6 - 1) && this.setCellFromCodepoint(e6 - 1, 0, 1, i5), 0 !== this.getWidth(e6) || this.hasContent(e6) || this.setCellFromCodepoint(e6, 0, 1, i5);
          }
          replaceCells(e6, t7, i5, s7 = false) {
            if (s7) for (e6 && 2 === this.getWidth(e6 - 1) && !this.isProtected(e6 - 1) && this.setCellFromCodepoint(e6 - 1, 0, 1, i5), t7 < this.length && 2 === this.getWidth(t7 - 1) && !this.isProtected(t7) && this.setCellFromCodepoint(t7, 0, 1, i5); e6 < t7 && e6 < this.length; ) this.isProtected(e6) || this.setCell(e6, i5), e6++;
            else for (e6 && 2 === this.getWidth(e6 - 1) && this.setCellFromCodepoint(e6 - 1, 0, 1, i5), t7 < this.length && 2 === this.getWidth(t7 - 1) && this.setCellFromCodepoint(t7, 0, 1, i5); e6 < t7 && e6 < this.length; ) this.setCell(e6++, i5);
          }
          resize(e6, t7) {
            if (e6 === this.length) return 4 * this._data.length * 2 < this._data.buffer.byteLength;
            const i5 = 3 * e6;
            if (e6 > this.length) {
              if (this._data.buffer.byteLength >= 4 * i5) this._data = new Uint32Array(this._data.buffer, 0, i5);
              else {
                const e7 = new Uint32Array(i5);
                e7.set(this._data), this._data = e7;
              }
              for (let i6 = this.length; i6 < e6; ++i6) this.setCell(i6, t7);
            } else {
              this._data = this._data.subarray(0, i5);
              const t8 = Object.keys(this._combined);
              for (let i6 = 0; i6 < t8.length; i6++) {
                const s8 = parseInt(t8[i6], 10);
                s8 >= e6 && delete this._combined[s8];
              }
              const s7 = Object.keys(this._extendedAttrs);
              for (let t9 = 0; t9 < s7.length; t9++) {
                const i6 = parseInt(s7[t9], 10);
                i6 >= e6 && delete this._extendedAttrs[i6];
              }
            }
            return this.length = e6, 4 * i5 * 2 < this._data.buffer.byteLength;
          }
          cleanupMemory() {
            if (4 * this._data.length * 2 < this._data.buffer.byteLength) {
              const e6 = new Uint32Array(this._data.length);
              return e6.set(this._data), this._data = e6, 1;
            }
            return 0;
          }
          fill(e6, t7 = false) {
            if (t7) for (let t8 = 0; t8 < this.length; ++t8) this.isProtected(t8) || this.setCell(t8, e6);
            else {
              this._combined = {}, this._extendedAttrs = {};
              for (let t8 = 0; t8 < this.length; ++t8) this.setCell(t8, e6);
            }
          }
          copyFrom(e6) {
            this.length !== e6.length ? this._data = new Uint32Array(e6._data) : this._data.set(e6._data), this.length = e6.length, this._combined = {};
            for (const t7 in e6._combined) this._combined[t7] = e6._combined[t7];
            this._extendedAttrs = {};
            for (const t7 in e6._extendedAttrs) this._extendedAttrs[t7] = e6._extendedAttrs[t7];
            this.isWrapped = e6.isWrapped;
          }
          clone() {
            const e6 = new h3(0);
            e6._data = new Uint32Array(this._data), e6.length = this.length;
            for (const t7 in this._combined) e6._combined[t7] = this._combined[t7];
            for (const t7 in this._extendedAttrs) e6._extendedAttrs[t7] = this._extendedAttrs[t7];
            return e6.isWrapped = this.isWrapped, e6;
          }
          getTrimmedLength() {
            for (let e6 = this.length - 1; e6 >= 0; --e6) if (4194303 & this._data[3 * e6 + 0]) return e6 + (this._data[3 * e6 + 0] >> 22);
            return 0;
          }
          getNoBgTrimmedLength() {
            for (let e6 = this.length - 1; e6 >= 0; --e6) if (4194303 & this._data[3 * e6 + 0] || 50331648 & this._data[3 * e6 + 2]) return e6 + (this._data[3 * e6 + 0] >> 22);
            return 0;
          }
          copyCellsFrom(e6, t7, i5, s7, r7) {
            const n5 = e6._data;
            if (r7) for (let r8 = s7 - 1; r8 >= 0; r8--) {
              for (let e7 = 0; e7 < 3; e7++) this._data[3 * (i5 + r8) + e7] = n5[3 * (t7 + r8) + e7];
              268435456 & n5[3 * (t7 + r8) + 2] && (this._extendedAttrs[i5 + r8] = e6._extendedAttrs[t7 + r8]);
            }
            else for (let r8 = 0; r8 < s7; r8++) {
              for (let e7 = 0; e7 < 3; e7++) this._data[3 * (i5 + r8) + e7] = n5[3 * (t7 + r8) + e7];
              268435456 & n5[3 * (t7 + r8) + 2] && (this._extendedAttrs[i5 + r8] = e6._extendedAttrs[t7 + r8]);
            }
            const a3 = Object.keys(e6._combined);
            for (let s8 = 0; s8 < a3.length; s8++) {
              const r8 = parseInt(a3[s8], 10);
              r8 >= t7 && (this._combined[r8 - t7 + i5] = e6._combined[r8]);
            }
          }
          translateToString(e6, t7, i5, s7) {
            t7 = t7 ?? 0, i5 = i5 ?? this.length, e6 && (i5 = Math.min(i5, this.getTrimmedLength())), s7 && (s7.length = 0);
            let r7 = "";
            for (; t7 < i5; ) {
              const e7 = this._data[3 * t7 + 0], i6 = 2097151 & e7, o4 = 2097152 & e7 ? this._combined[t7] : i6 ? (0, a2.stringFromCodePoint)(i6) : n4.WHITESPACE_CELL_CHAR;
              if (r7 += o4, s7) for (let e8 = 0; e8 < o4.length; ++e8) s7.push(t7);
              t7 += e7 >> 22 || 1;
            }
            return s7 && s7.push(t7), r7;
          }
        }
        t6.BufferLine = h3;
      }, 634: (e5, t6) => {
        function i4(e6, t7, i5) {
          if (t7 === e6.length - 1) return e6[t7].getTrimmedLength();
          const s6 = !e6[t7].hasContent(i5 - 1) && 1 === e6[t7].getWidth(i5 - 1), r6 = 2 === e6[t7 + 1].getWidth(0);
          return s6 && r6 ? i5 - 1 : i5;
        }
        __name(i4, "i");
        Object.defineProperty(t6, "__esModule", { value: true }), t6.getWrappedLineTrimmedLength = t6.reflowSmallerGetNewLineLengths = t6.reflowLargerApplyNewLayout = t6.reflowLargerCreateNewLayout = t6.reflowLargerGetLinesToRemove = void 0, t6.reflowLargerGetLinesToRemove = function(e6, t7, s6, r6, n4) {
          const a2 = [];
          for (let o3 = 0; o3 < e6.length - 1; o3++) {
            let h3 = o3, c4 = e6.get(++h3);
            if (!c4.isWrapped) continue;
            const l3 = [e6.get(o3)];
            for (; h3 < e6.length && c4.isWrapped; ) l3.push(c4), c4 = e6.get(++h3);
            if (r6 >= o3 && r6 < h3) {
              o3 += l3.length - 1;
              continue;
            }
            let _2 = 0, d2 = i4(l3, _2, t7), f5 = 1, u2 = 0;
            for (; f5 < l3.length; ) {
              const e7 = i4(l3, f5, t7), r7 = e7 - u2, a3 = s6 - d2, o4 = Math.min(r7, a3);
              l3[_2].copyCellsFrom(l3[f5], u2, d2, o4, false), d2 += o4, d2 === s6 && (_2++, d2 = 0), u2 += o4, u2 === e7 && (f5++, u2 = 0), 0 === d2 && 0 !== _2 && 2 === l3[_2 - 1].getWidth(s6 - 1) && (l3[_2].copyCellsFrom(l3[_2 - 1], s6 - 1, d2++, 1, false), l3[_2 - 1].setCell(s6 - 1, n4));
            }
            l3[_2].replaceCells(d2, s6, n4);
            let p2 = 0;
            for (let e7 = l3.length - 1; e7 > 0 && (e7 > _2 || 0 === l3[e7].getTrimmedLength()); e7--) p2++;
            p2 > 0 && (a2.push(o3 + l3.length - p2), a2.push(p2)), o3 += l3.length - 1;
          }
          return a2;
        }, t6.reflowLargerCreateNewLayout = function(e6, t7) {
          const i5 = [];
          let s6 = 0, r6 = t7[s6], n4 = 0;
          for (let a2 = 0; a2 < e6.length; a2++) if (r6 === a2) {
            const i6 = t7[++s6];
            e6.onDeleteEmitter.fire({ index: a2 - n4, amount: i6 }), a2 += i6 - 1, n4 += i6, r6 = t7[++s6];
          } else i5.push(a2);
          return { layout: i5, countRemoved: n4 };
        }, t6.reflowLargerApplyNewLayout = function(e6, t7) {
          const i5 = [];
          for (let s6 = 0; s6 < t7.length; s6++) i5.push(e6.get(t7[s6]));
          for (let t8 = 0; t8 < i5.length; t8++) e6.set(t8, i5[t8]);
          e6.length = t7.length;
        }, t6.reflowSmallerGetNewLineLengths = function(e6, t7, s6) {
          const r6 = [], n4 = e6.map((s7, r7) => i4(e6, r7, t7)).reduce((e7, t8) => e7 + t8);
          let a2 = 0, o3 = 0, h3 = 0;
          for (; h3 < n4; ) {
            if (n4 - h3 < s6) {
              r6.push(n4 - h3);
              break;
            }
            a2 += s6;
            const c4 = i4(e6, o3, t7);
            a2 > c4 && (a2 -= c4, o3++);
            const l3 = 2 === e6[o3].getWidth(a2 - 1);
            l3 && a2--;
            const _2 = l3 ? s6 - 1 : s6;
            r6.push(_2), h3 += _2;
          }
          return r6;
        }, t6.getWrappedLineTrimmedLength = i4;
      }, 295: (e5, t6, i4) => {
        Object.defineProperty(t6, "__esModule", { value: true }), t6.BufferSet = void 0;
        const s6 = i4(460), r6 = i4(844), n4 = i4(92);
        class a2 extends r6.Disposable {
          static {
            __name(this, "a");
          }
          constructor(e6, t7) {
            super(), this._optionsService = e6, this._bufferService = t7, this._onBufferActivate = this.register(new s6.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 n4.Buffer(true, this._optionsService, this._bufferService), this._normal.fillViewportRows(), this._alt = new n4.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(e6) {
            this._activeBuffer !== this._alt && (this._alt.fillViewportRows(e6), 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(e6, t7) {
            this._normal.resize(e6, t7), this._alt.resize(e6, t7), this.setupTabStops(e6);
          }
          setupTabStops(e6) {
            this._normal.setupTabStops(e6), this._alt.setupTabStops(e6);
          }
        }
        t6.BufferSet = a2;
      }, 511: (e5, t6, i4) => {
        Object.defineProperty(t6, "__esModule", { value: true }), t6.CellData = void 0;
        const s6 = i4(482), r6 = i4(643), n4 = i4(734);
        class a2 extends n4.AttributeData {
          static {
            __name(this, "a");
          }
          constructor() {
            super(...arguments), this.content = 0, this.fg = 0, this.bg = 0, this.extended = new n4.ExtendedAttrs(), this.combinedData = "";
          }
          static fromCharData(e6) {
            const t7 = new a2();
            return t7.setFromCharData(e6), t7;
          }
          isCombined() {
            return 2097152 & this.content;
          }
          getWidth() {
            return this.content >> 22;
          }
          getChars() {
            return 2097152 & this.content ? this.combinedData : 2097151 & this.content ? (0, s6.stringFromCodePoint)(2097151 & this.content) : "";
          }
          getCode() {
            return this.isCombined() ? this.combinedData.charCodeAt(this.combinedData.length - 1) : 2097151 & this.content;
          }
          setFromCharData(e6) {
            this.fg = e6[r6.CHAR_DATA_ATTR_INDEX], this.bg = 0;
            let t7 = false;
            if (e6[r6.CHAR_DATA_CHAR_INDEX].length > 2) t7 = true;
            else if (2 === e6[r6.CHAR_DATA_CHAR_INDEX].length) {
              const i5 = e6[r6.CHAR_DATA_CHAR_INDEX].charCodeAt(0);
              if (55296 <= i5 && i5 <= 56319) {
                const s7 = e6[r6.CHAR_DATA_CHAR_INDEX].charCodeAt(1);
                56320 <= s7 && s7 <= 57343 ? this.content = 1024 * (i5 - 55296) + s7 - 56320 + 65536 | e6[r6.CHAR_DATA_WIDTH_INDEX] << 22 : t7 = true;
              } else t7 = true;
            } else this.content = e6[r6.CHAR_DATA_CHAR_INDEX].charCodeAt(0) | e6[r6.CHAR_DATA_WIDTH_INDEX] << 22;
            t7 && (this.combinedData = e6[r6.CHAR_DATA_CHAR_INDEX], this.content = 2097152 | e6[r6.CHAR_DATA_WIDTH_INDEX] << 22);
          }
          getAsCharData() {
            return [this.fg, this.getChars(), this.getWidth(), this.getCode()];
          }
        }
        t6.CellData = a2;
      }, 643: (e5, t6) => {
        Object.defineProperty(t6, "__esModule", { value: true }), t6.WHITESPACE_CELL_CODE = t6.WHITESPACE_CELL_WIDTH = t6.WHITESPACE_CELL_CHAR = t6.NULL_CELL_CODE = t6.NULL_CELL_WIDTH = t6.NULL_CELL_CHAR = t6.CHAR_DATA_CODE_INDEX = t6.CHAR_DATA_WIDTH_INDEX = t6.CHAR_DATA_CHAR_INDEX = t6.CHAR_DATA_ATTR_INDEX = t6.DEFAULT_EXT = t6.DEFAULT_ATTR = t6.DEFAULT_COLOR = void 0, t6.DEFAULT_COLOR = 0, t6.DEFAULT_ATTR = 256 | t6.DEFAULT_COLOR << 9, t6.DEFAULT_EXT = 0, t6.CHAR_DATA_ATTR_INDEX = 0, t6.CHAR_DATA_CHAR_INDEX = 1, t6.CHAR_DATA_WIDTH_INDEX = 2, t6.CHAR_DATA_CODE_INDEX = 3, t6.NULL_CELL_CHAR = "", t6.NULL_CELL_WIDTH = 1, t6.NULL_CELL_CODE = 0, t6.WHITESPACE_CELL_CHAR = " ", t6.WHITESPACE_CELL_WIDTH = 1, t6.WHITESPACE_CELL_CODE = 32;
      }, 863: (e5, t6, i4) => {
        Object.defineProperty(t6, "__esModule", { value: true }), t6.Marker = void 0;
        const s6 = i4(460), r6 = i4(844);
        class n4 {
          static {
            __name(this, "n");
          }
          get id() {
            return this._id;
          }
          constructor(e6) {
            this.line = e6, this.isDisposed = false, this._disposables = [], this._id = n4._nextId++, this._onDispose = this.register(new s6.EventEmitter()), this.onDispose = this._onDispose.event;
          }
          dispose() {
            this.isDisposed || (this.isDisposed = true, this.line = -1, this._onDispose.fire(), (0, r6.disposeArray)(this._disposables), this._disposables.length = 0);
          }
          register(e6) {
            return this._disposables.push(e6), e6;
          }
        }
        t6.Marker = n4, n4._nextId = 1;
      }, 116: (e5, t6) => {
        Object.defineProperty(t6, "__esModule", { value: true }), t6.DEFAULT_CHARSET = t6.CHARSETS = void 0, t6.CHARSETS = {}, t6.DEFAULT_CHARSET = t6.CHARSETS.B, t6.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" }, t6.CHARSETS.A = { "#": "\xA3" }, t6.CHARSETS.B = void 0, t6.CHARSETS[4] = { "#": "\xA3", "@": "\xBE", "[": "ij", "\\": "\xBD", "]": "|", "{": "\xA8", "|": "f", "}": "\xBC", "~": "\xB4" }, t6.CHARSETS.C = t6.CHARSETS[5] = { "[": "\xC4", "\\": "\xD6", "]": "\xC5", "^": "\xDC", "`": "\xE9", "{": "\xE4", "|": "\xF6", "}": "\xE5", "~": "\xFC" }, t6.CHARSETS.R = { "#": "\xA3", "@": "\xE0", "[": "\xB0", "\\": "\xE7", "]": "\xA7", "{": "\xE9", "|": "\xF9", "}": "\xE8", "~": "\xA8" }, t6.CHARSETS.Q = { "@": "\xE0", "[": "\xE2", "\\": "\xE7", "]": "\xEA", "^": "\xEE", "`": "\xF4", "{": "\xE9", "|": "\xF9", "}": "\xE8", "~": "\xFB" }, t6.CHARSETS.K = { "@": "\xA7", "[": "\xC4", "\\": "\xD6", "]": "\xDC", "{": "\xE4", "|": "\xF6", "}": "\xFC", "~": "\xDF" }, t6.CHARSETS.Y = { "#": "\xA3", "@": "\xA7", "[": "\xB0", "\\": "\xE7", "]": "\xE9", "`": "\xF9", "{": "\xE0", "|": "\xF2", "}": "\xE8", "~": "\xEC" }, t6.CHARSETS.E = t6.CHARSETS[6] = { "@": "\xC4", "[": "\xC6", "\\": "\xD8", "]": "\xC5", "^": "\xDC", "`": "\xE4", "{": "\xE6", "|": "\xF8", "}": "\xE5", "~": "\xFC" }, t6.CHARSETS.Z = { "#": "\xA3", "@": "\xA7", "[": "\xA1", "\\": "\xD1", "]": "\xBF", "{": "\xB0", "|": "\xF1", "}": "\xE7" }, t6.CHARSETS.H = t6.CHARSETS[7] = { "@": "\xC9", "[": "\xC4", "\\": "\xD6", "]": "\xC5", "^": "\xDC", "`": "\xE9", "{": "\xE4", "|": "\xF6", "}": "\xE5", "~": "\xFC" }, t6.CHARSETS["="] = { "#": "\xF9", "@": "\xE0", "[": "\xE9", "\\": "\xE7", "]": "\xEA", "^": "\xEE", _: "\xE8", "`": "\xF4", "{": "\xE4", "|": "\xF6", "}": "\xFC", "~": "\xFB" };
      }, 584: (e5, t6) => {
        var i4, s6, r6;
        Object.defineProperty(t6, "__esModule", { value: true }), t6.C1_ESCAPED = t6.C1 = t6.C0 = void 0, function(e6) {
          e6.NUL = "\0", e6.SOH = "", e6.STX = "", e6.ETX = "", e6.EOT = "", e6.ENQ = "", e6.ACK = "", e6.BEL = "\x07", e6.BS = "\b", e6.HT = "	", e6.LF = "\n", e6.VT = "\v", e6.FF = "\f", e6.CR = "\r", e6.SO = "", e6.SI = "", e6.DLE = "", e6.DC1 = "", e6.DC2 = "", e6.DC3 = "", e6.DC4 = "", e6.NAK = "", e6.SYN = "", e6.ETB = "", e6.CAN = "", e6.EM = "", e6.SUB = "", e6.ESC = "\x1B", e6.FS = "", e6.GS = "", e6.RS = "", e6.US = "", e6.SP = " ", e6.DEL = "\x7F";
        }(i4 || (t6.C0 = i4 = {})), function(e6) {
          e6.PAD = "\x80", e6.HOP = "\x81", e6.BPH = "\x82", e6.NBH = "\x83", e6.IND = "\x84", e6.NEL = "\x85", e6.SSA = "\x86", e6.ESA = "\x87", e6.HTS = "\x88", e6.HTJ = "\x89", e6.VTS = "\x8A", e6.PLD = "\x8B", e6.PLU = "\x8C", e6.RI = "\x8D", e6.SS2 = "\x8E", e6.SS3 = "\x8F", e6.DCS = "\x90", e6.PU1 = "\x91", e6.PU2 = "\x92", e6.STS = "\x93", e6.CCH = "\x94", e6.MW = "\x95", e6.SPA = "\x96", e6.EPA = "\x97", e6.SOS = "\x98", e6.SGCI = "\x99", e6.SCI = "\x9A", e6.CSI = "\x9B", e6.ST = "\x9C", e6.OSC = "\x9D", e6.PM = "\x9E", e6.APC = "\x9F";
        }(s6 || (t6.C1 = s6 = {})), function(e6) {
          e6.ST = `${i4.ESC}\\`;
        }(r6 || (t6.C1_ESCAPED = r6 = {}));
      }, 482: (e5, t6) => {
        Object.defineProperty(t6, "__esModule", { value: true }), t6.Utf8ToUtf32 = t6.StringToUtf32 = t6.utf32ToString = t6.stringFromCodePoint = void 0, t6.stringFromCodePoint = function(e6) {
          return e6 > 65535 ? (e6 -= 65536, String.fromCharCode(55296 + (e6 >> 10)) + String.fromCharCode(e6 % 1024 + 56320)) : String.fromCharCode(e6);
        }, t6.utf32ToString = function(e6, t7 = 0, i4 = e6.length) {
          let s6 = "";
          for (let r6 = t7; r6 < i4; ++r6) {
            let t8 = e6[r6];
            t8 > 65535 ? (t8 -= 65536, s6 += String.fromCharCode(55296 + (t8 >> 10)) + String.fromCharCode(t8 % 1024 + 56320)) : s6 += String.fromCharCode(t8);
          }
          return s6;
        }, t6.StringToUtf32 = class {
          constructor() {
            this._interim = 0;
          }
          clear() {
            this._interim = 0;
          }
          decode(e6, t7) {
            const i4 = e6.length;
            if (!i4) return 0;
            let s6 = 0, r6 = 0;
            if (this._interim) {
              const i5 = e6.charCodeAt(r6++);
              56320 <= i5 && i5 <= 57343 ? t7[s6++] = 1024 * (this._interim - 55296) + i5 - 56320 + 65536 : (t7[s6++] = this._interim, t7[s6++] = i5), this._interim = 0;
            }
            for (let n4 = r6; n4 < i4; ++n4) {
              const r7 = e6.charCodeAt(n4);
              if (55296 <= r7 && r7 <= 56319) {
                if (++n4 >= i4) return this._interim = r7, s6;
                const a2 = e6.charCodeAt(n4);
                56320 <= a2 && a2 <= 57343 ? t7[s6++] = 1024 * (r7 - 55296) + a2 - 56320 + 65536 : (t7[s6++] = r7, t7[s6++] = a2);
              } else 65279 !== r7 && (t7[s6++] = r7);
            }
            return s6;
          }
        }, t6.Utf8ToUtf32 = class {
          constructor() {
            this.interim = new Uint8Array(3);
          }
          clear() {
            this.interim.fill(0);
          }
          decode(e6, t7) {
            const i4 = e6.length;
            if (!i4) return 0;
            let s6, r6, n4, a2, o3 = 0, h3 = 0, c4 = 0;
            if (this.interim[0]) {
              let s7 = false, r7 = this.interim[0];
              r7 &= 192 == (224 & r7) ? 31 : 224 == (240 & r7) ? 15 : 7;
              let n5, a3 = 0;
              for (; (n5 = 63 & this.interim[++a3]) && a3 < 4; ) r7 <<= 6, r7 |= n5;
              const h4 = 192 == (224 & this.interim[0]) ? 2 : 224 == (240 & this.interim[0]) ? 3 : 4, l4 = h4 - a3;
              for (; c4 < l4; ) {
                if (c4 >= i4) return 0;
                if (n5 = e6[c4++], 128 != (192 & n5)) {
                  c4--, s7 = true;
                  break;
                }
                this.interim[a3++] = n5, r7 <<= 6, r7 |= 63 & n5;
              }
              s7 || (2 === h4 ? r7 < 128 ? c4-- : t7[o3++] = r7 : 3 === h4 ? r7 < 2048 || r7 >= 55296 && r7 <= 57343 || 65279 === r7 || (t7[o3++] = r7) : r7 < 65536 || r7 > 1114111 || (t7[o3++] = r7)), this.interim.fill(0);
            }
            const l3 = i4 - 4;
            let _2 = c4;
            for (; _2 < i4; ) {
              for (; !(!(_2 < l3) || 128 & (s6 = e6[_2]) || 128 & (r6 = e6[_2 + 1]) || 128 & (n4 = e6[_2 + 2]) || 128 & (a2 = e6[_2 + 3])); ) t7[o3++] = s6, t7[o3++] = r6, t7[o3++] = n4, t7[o3++] = a2, _2 += 4;
              if (s6 = e6[_2++], s6 < 128) t7[o3++] = s6;
              else if (192 == (224 & s6)) {
                if (_2 >= i4) return this.interim[0] = s6, o3;
                if (r6 = e6[_2++], 128 != (192 & r6)) {
                  _2--;
                  continue;
                }
                if (h3 = (31 & s6) << 6 | 63 & r6, h3 < 128) {
                  _2--;
                  continue;
                }
                t7[o3++] = h3;
              } else if (224 == (240 & s6)) {
                if (_2 >= i4) return this.interim[0] = s6, o3;
                if (r6 = e6[_2++], 128 != (192 & r6)) {
                  _2--;
                  continue;
                }
                if (_2 >= i4) return this.interim[0] = s6, this.interim[1] = r6, o3;
                if (n4 = e6[_2++], 128 != (192 & n4)) {
                  _2--;
                  continue;
                }
                if (h3 = (15 & s6) << 12 | (63 & r6) << 6 | 63 & n4, h3 < 2048 || h3 >= 55296 && h3 <= 57343 || 65279 === h3) continue;
                t7[o3++] = h3;
              } else if (240 == (248 & s6)) {
                if (_2 >= i4) return this.interim[0] = s6, o3;
                if (r6 = e6[_2++], 128 != (192 & r6)) {
                  _2--;
                  continue;
                }
                if (_2 >= i4) return this.interim[0] = s6, this.interim[1] = r6, o3;
                if (n4 = e6[_2++], 128 != (192 & n4)) {
                  _2--;
                  continue;
                }
                if (_2 >= i4) return this.interim[0] = s6, this.interim[1] = r6, this.interim[2] = n4, o3;
                if (a2 = e6[_2++], 128 != (192 & a2)) {
                  _2--;
                  continue;
                }
                if (h3 = (7 & s6) << 18 | (63 & r6) << 12 | (63 & n4) << 6 | 63 & a2, h3 < 65536 || h3 > 1114111) continue;
                t7[o3++] = h3;
              }
            }
            return o3;
          }
        };
      }, 225: (e5, t6, i4) => {
        Object.defineProperty(t6, "__esModule", { value: true }), t6.UnicodeV6 = void 0;
        const s6 = i4(480), r6 = [[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]], n4 = [[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 a2;
        t6.UnicodeV6 = class {
          constructor() {
            if (this.version = "6", !a2) {
              a2 = new Uint8Array(65536), a2.fill(1), a2[0] = 0, a2.fill(0, 1, 32), a2.fill(0, 127, 160), a2.fill(2, 4352, 4448), a2[9001] = 2, a2[9002] = 2, a2.fill(2, 11904, 42192), a2[12351] = 1, a2.fill(2, 44032, 55204), a2.fill(2, 63744, 64256), a2.fill(2, 65040, 65050), a2.fill(2, 65072, 65136), a2.fill(2, 65280, 65377), a2.fill(2, 65504, 65511);
              for (let e6 = 0; e6 < r6.length; ++e6) a2.fill(0, r6[e6][0], r6[e6][1] + 1);
            }
          }
          wcwidth(e6) {
            return e6 < 32 ? 0 : e6 < 127 ? 1 : e6 < 65536 ? a2[e6] : function(e7, t7) {
              let i5, s7 = 0, r7 = t7.length - 1;
              if (e7 < t7[0][0] || e7 > t7[r7][1]) return false;
              for (; r7 >= s7; ) if (i5 = s7 + r7 >> 1, e7 > t7[i5][1]) s7 = i5 + 1;
              else {
                if (!(e7 < t7[i5][0])) return true;
                r7 = i5 - 1;
              }
              return false;
            }(e6, n4) ? 0 : e6 >= 131072 && e6 <= 196605 || e6 >= 196608 && e6 <= 262141 ? 2 : 1;
          }
          charProperties(e6, t7) {
            let i5 = this.wcwidth(e6), r7 = 0 === i5 && 0 !== t7;
            if (r7) {
              const e7 = s6.UnicodeService.extractWidth(t7);
              0 === e7 ? r7 = false : e7 > i5 && (i5 = e7);
            }
            return s6.UnicodeService.createPropertyValue(0, i5, r7);
          }
        };
      }, 981: (e5, t6, i4) => {
        Object.defineProperty(t6, "__esModule", { value: true }), t6.WriteBuffer = void 0;
        const s6 = i4(460), r6 = i4(844);
        class n4 extends r6.Disposable {
          static {
            __name(this, "n");
          }
          constructor(e6) {
            super(), this._action = e6, this._writeBuffer = [], this._callbacks = [], this._pendingData = 0, this._bufferOffset = 0, this._isSyncWriting = false, this._syncCalls = 0, this._didUserInput = false, this._onWriteParsed = this.register(new s6.EventEmitter()), this.onWriteParsed = this._onWriteParsed.event;
          }
          handleUserInput() {
            this._didUserInput = true;
          }
          writeSync(e6, t7) {
            if (void 0 !== t7 && this._syncCalls > t7) return void (this._syncCalls = 0);
            if (this._pendingData += e6.length, this._writeBuffer.push(e6), this._callbacks.push(void 0), this._syncCalls++, this._isSyncWriting) return;
            let i5;
            for (this._isSyncWriting = true; i5 = this._writeBuffer.shift(); ) {
              this._action(i5);
              const e7 = this._callbacks.shift();
              e7 && e7();
            }
            this._pendingData = 0, this._bufferOffset = 2147483647, this._isSyncWriting = false, this._syncCalls = 0;
          }
          write(e6, t7) {
            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 += e6.length, this._writeBuffer.push(e6), this._callbacks.push(t7), void this._innerWrite();
              setTimeout(() => this._innerWrite());
            }
            this._pendingData += e6.length, this._writeBuffer.push(e6), this._callbacks.push(t7);
          }
          _innerWrite(e6 = 0, t7 = true) {
            const i5 = e6 || Date.now();
            for (; this._writeBuffer.length > this._bufferOffset; ) {
              const e7 = this._writeBuffer[this._bufferOffset], s7 = this._action(e7, t7);
              if (s7) {
                const e8 = /* @__PURE__ */ __name((e9) => Date.now() - i5 >= 12 ? setTimeout(() => this._innerWrite(0, e9)) : this._innerWrite(i5, e9), "e");
                return void s7.catch((e9) => (queueMicrotask(() => {
                  throw e9;
                }), Promise.resolve(false))).then(e8);
              }
              const r7 = this._callbacks[this._bufferOffset];
              if (r7 && r7(), this._bufferOffset++, this._pendingData -= e7.length, Date.now() - i5 >= 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();
          }
        }
        t6.WriteBuffer = n4;
      }, 941: (e5, t6) => {
        Object.defineProperty(t6, "__esModule", { value: true }), t6.toRgbString = t6.parseColor = void 0;
        const i4 = /^([\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})$/, s6 = /^[\da-f]+$/;
        function r6(e6, t7) {
          const i5 = e6.toString(16), s7 = i5.length < 2 ? "0" + i5 : i5;
          switch (t7) {
            case 4:
              return i5[0];
            case 8:
              return s7;
            case 12:
              return (s7 + s7).slice(0, 3);
            default:
              return s7 + s7;
          }
        }
        __name(r6, "r");
        t6.parseColor = function(e6) {
          if (!e6) return;
          let t7 = e6.toLowerCase();
          if (0 === t7.indexOf("rgb:")) {
            t7 = t7.slice(4);
            const e7 = i4.exec(t7);
            if (e7) {
              const t8 = e7[1] ? 15 : e7[4] ? 255 : e7[7] ? 4095 : 65535;
              return [Math.round(parseInt(e7[1] || e7[4] || e7[7] || e7[10], 16) / t8 * 255), Math.round(parseInt(e7[2] || e7[5] || e7[8] || e7[11], 16) / t8 * 255), Math.round(parseInt(e7[3] || e7[6] || e7[9] || e7[12], 16) / t8 * 255)];
            }
          } else if (0 === t7.indexOf("#") && (t7 = t7.slice(1), s6.exec(t7) && [3, 6, 9, 12].includes(t7.length))) {
            const e7 = t7.length / 3, i5 = [0, 0, 0];
            for (let s7 = 0; s7 < 3; ++s7) {
              const r7 = parseInt(t7.slice(e7 * s7, e7 * s7 + e7), 16);
              i5[s7] = 1 === e7 ? r7 << 4 : 2 === e7 ? r7 : 3 === e7 ? r7 >> 4 : r7 >> 8;
            }
            return i5;
          }
        }, t6.toRgbString = function(e6, t7 = 16) {
          const [i5, s7, n4] = e6;
          return `rgb:${r6(i5, t7)}/${r6(s7, t7)}/${r6(n4, t7)}`;
        };
      }, 770: (e5, t6) => {
        Object.defineProperty(t6, "__esModule", { value: true }), t6.PAYLOAD_LIMIT = void 0, t6.PAYLOAD_LIMIT = 1e7;
      }, 351: (e5, t6, i4) => {
        Object.defineProperty(t6, "__esModule", { value: true }), t6.DcsHandler = t6.DcsParser = void 0;
        const s6 = i4(482), r6 = i4(742), n4 = i4(770), a2 = [];
        t6.DcsParser = class {
          constructor() {
            this._handlers = /* @__PURE__ */ Object.create(null), this._active = a2, this._ident = 0, this._handlerFb = () => {
            }, this._stack = { paused: false, loopPosition: 0, fallThrough: false };
          }
          dispose() {
            this._handlers = /* @__PURE__ */ Object.create(null), this._handlerFb = () => {
            }, this._active = a2;
          }
          registerHandler(e6, t7) {
            void 0 === this._handlers[e6] && (this._handlers[e6] = []);
            const i5 = this._handlers[e6];
            return i5.push(t7), { dispose: /* @__PURE__ */ __name(() => {
              const e7 = i5.indexOf(t7);
              -1 !== e7 && i5.splice(e7, 1);
            }, "dispose") };
          }
          clearHandler(e6) {
            this._handlers[e6] && delete this._handlers[e6];
          }
          setHandlerFallback(e6) {
            this._handlerFb = e6;
          }
          reset() {
            if (this._active.length) for (let e6 = this._stack.paused ? this._stack.loopPosition - 1 : this._active.length - 1; e6 >= 0; --e6) this._active[e6].unhook(false);
            this._stack.paused = false, this._active = a2, this._ident = 0;
          }
          hook(e6, t7) {
            if (this.reset(), this._ident = e6, this._active = this._handlers[e6] || a2, this._active.length) for (let e7 = this._active.length - 1; e7 >= 0; e7--) this._active[e7].hook(t7);
            else this._handlerFb(this._ident, "HOOK", t7);
          }
          put(e6, t7, i5) {
            if (this._active.length) for (let s7 = this._active.length - 1; s7 >= 0; s7--) this._active[s7].put(e6, t7, i5);
            else this._handlerFb(this._ident, "PUT", (0, s6.utf32ToString)(e6, t7, i5));
          }
          unhook(e6, t7 = true) {
            if (this._active.length) {
              let i5 = false, s7 = this._active.length - 1, r7 = false;
              if (this._stack.paused && (s7 = this._stack.loopPosition - 1, i5 = t7, r7 = this._stack.fallThrough, this._stack.paused = false), !r7 && false === i5) {
                for (; s7 >= 0 && (i5 = this._active[s7].unhook(e6), true !== i5); s7--) if (i5 instanceof Promise) return this._stack.paused = true, this._stack.loopPosition = s7, this._stack.fallThrough = false, i5;
                s7--;
              }
              for (; s7 >= 0; s7--) if (i5 = this._active[s7].unhook(false), i5 instanceof Promise) return this._stack.paused = true, this._stack.loopPosition = s7, this._stack.fallThrough = true, i5;
            } else this._handlerFb(this._ident, "UNHOOK", e6);
            this._active = a2, this._ident = 0;
          }
        };
        const o3 = new r6.Params();
        o3.addParam(0), t6.DcsHandler = class {
          constructor(e6) {
            this._handler = e6, this._data = "", this._params = o3, this._hitLimit = false;
          }
          hook(e6) {
            this._params = e6.length > 1 || e6.params[0] ? e6.clone() : o3, this._data = "", this._hitLimit = false;
          }
          put(e6, t7, i5) {
            this._hitLimit || (this._data += (0, s6.utf32ToString)(e6, t7, i5), this._data.length > n4.PAYLOAD_LIMIT && (this._data = "", this._hitLimit = true));
          }
          unhook(e6) {
            let t7 = false;
            if (this._hitLimit) t7 = false;
            else if (e6 && (t7 = this._handler(this._data, this._params), t7 instanceof Promise)) return t7.then((e7) => (this._params = o3, this._data = "", this._hitLimit = false, e7));
            return this._params = o3, this._data = "", this._hitLimit = false, t7;
          }
        };
      }, 15: (e5, t6, i4) => {
        Object.defineProperty(t6, "__esModule", { value: true }), t6.EscapeSequenceParser = t6.VT500_TRANSITION_TABLE = t6.TransitionTable = void 0;
        const s6 = i4(844), r6 = i4(742), n4 = i4(242), a2 = i4(351);
        class o3 {
          static {
            __name(this, "o");
          }
          constructor(e6) {
            this.table = new Uint8Array(e6);
          }
          setDefault(e6, t7) {
            this.table.fill(e6 << 4 | t7);
          }
          add(e6, t7, i5, s7) {
            this.table[t7 << 8 | e6] = i5 << 4 | s7;
          }
          addMany(e6, t7, i5, s7) {
            for (let r7 = 0; r7 < e6.length; r7++) this.table[t7 << 8 | e6[r7]] = i5 << 4 | s7;
          }
        }
        t6.TransitionTable = o3;
        const h3 = 160;
        t6.VT500_TRANSITION_TABLE = function() {
          const e6 = new o3(4095), t7 = Array.apply(null, Array(256)).map((e7, t8) => t8), i5 = /* @__PURE__ */ __name((e7, i6) => t7.slice(e7, i6), "i"), s7 = i5(32, 127), r7 = i5(0, 24);
          r7.push(25), r7.push.apply(r7, i5(28, 32));
          const n5 = i5(0, 14);
          let a3;
          for (a3 in e6.setDefault(1, 0), e6.addMany(s7, 0, 2, 0), n5) e6.addMany([24, 26, 153, 154], a3, 3, 0), e6.addMany(i5(128, 144), a3, 3, 0), e6.addMany(i5(144, 152), a3, 3, 0), e6.add(156, a3, 0, 0), e6.add(27, a3, 11, 1), e6.add(157, a3, 4, 8), e6.addMany([152, 158, 159], a3, 0, 7), e6.add(155, a3, 11, 3), e6.add(144, a3, 11, 9);
          return e6.addMany(r7, 0, 3, 0), e6.addMany(r7, 1, 3, 1), e6.add(127, 1, 0, 1), e6.addMany(r7, 8, 0, 8), e6.addMany(r7, 3, 3, 3), e6.add(127, 3, 0, 3), e6.addMany(r7, 4, 3, 4), e6.add(127, 4, 0, 4), e6.addMany(r7, 6, 3, 6), e6.addMany(r7, 5, 3, 5), e6.add(127, 5, 0, 5), e6.addMany(r7, 2, 3, 2), e6.add(127, 2, 0, 2), e6.add(93, 1, 4, 8), e6.addMany(s7, 8, 5, 8), e6.add(127, 8, 5, 8), e6.addMany([156, 27, 24, 26, 7], 8, 6, 0), e6.addMany(i5(28, 32), 8, 0, 8), e6.addMany([88, 94, 95], 1, 0, 7), e6.addMany(s7, 7, 0, 7), e6.addMany(r7, 7, 0, 7), e6.add(156, 7, 0, 0), e6.add(127, 7, 0, 7), e6.add(91, 1, 11, 3), e6.addMany(i5(64, 127), 3, 7, 0), e6.addMany(i5(48, 60), 3, 8, 4), e6.addMany([60, 61, 62, 63], 3, 9, 4), e6.addMany(i5(48, 60), 4, 8, 4), e6.addMany(i5(64, 127), 4, 7, 0), e6.addMany([60, 61, 62, 63], 4, 0, 6), e6.addMany(i5(32, 64), 6, 0, 6), e6.add(127, 6, 0, 6), e6.addMany(i5(64, 127), 6, 0, 0), e6.addMany(i5(32, 48), 3, 9, 5), e6.addMany(i5(32, 48), 5, 9, 5), e6.addMany(i5(48, 64), 5, 0, 6), e6.addMany(i5(64, 127), 5, 7, 0), e6.addMany(i5(32, 48), 4, 9, 5), e6.addMany(i5(32, 48), 1, 9, 2), e6.addMany(i5(32, 48), 2, 9, 2), e6.addMany(i5(48, 127), 2, 10, 0), e6.addMany(i5(48, 80), 1, 10, 0), e6.addMany(i5(81, 88), 1, 10, 0), e6.addMany([89, 90, 92], 1, 10, 0), e6.addMany(i5(96, 127), 1, 10, 0), e6.add(80, 1, 11, 9), e6.addMany(r7, 9, 0, 9), e6.add(127, 9, 0, 9), e6.addMany(i5(28, 32), 9, 0, 9), e6.addMany(i5(32, 48), 9, 9, 12), e6.addMany(i5(48, 60), 9, 8, 10), e6.addMany([60, 61, 62, 63], 9, 9, 10), e6.addMany(r7, 11, 0, 11), e6.addMany(i5(32, 128), 11, 0, 11), e6.addMany(i5(28, 32), 11, 0, 11), e6.addMany(r7, 10, 0, 10), e6.add(127, 10, 0, 10), e6.addMany(i5(28, 32), 10, 0, 10), e6.addMany(i5(48, 60), 10, 8, 10), e6.addMany([60, 61, 62, 63], 10, 0, 11), e6.addMany(i5(32, 48), 10, 9, 12), e6.addMany(r7, 12, 0, 12), e6.add(127, 12, 0, 12), e6.addMany(i5(28, 32), 12, 0, 12), e6.addMany(i5(32, 48), 12, 9, 12), e6.addMany(i5(48, 64), 12, 0, 11), e6.addMany(i5(64, 127), 12, 12, 13), e6.addMany(i5(64, 127), 10, 12, 13), e6.addMany(i5(64, 127), 9, 12, 13), e6.addMany(r7, 13, 13, 13), e6.addMany(s7, 13, 13, 13), e6.add(127, 13, 0, 13), e6.addMany([27, 156, 24, 26], 13, 14, 0), e6.add(h3, 0, 2, 0), e6.add(h3, 8, 5, 8), e6.add(h3, 6, 0, 6), e6.add(h3, 11, 0, 11), e6.add(h3, 13, 13, 13), e6;
        }();
        class c4 extends s6.Disposable {
          static {
            __name(this, "c");
          }
          constructor(e6 = t6.VT500_TRANSITION_TABLE) {
            super(), this._transitions = e6, this._parseStack = { state: 0, handlers: [], handlerPos: 0, transition: 0, chunkPos: 0 }, this.initialState = 0, this.currentState = this.initialState, this._params = new r6.Params(), this._params.addParam(0), this._collect = 0, this.precedingJoinState = 0, this._printHandlerFb = (e7, t7, i5) => {
            }, this._executeHandlerFb = (e7) => {
            }, this._csiHandlerFb = (e7, t7) => {
            }, this._escHandlerFb = (e7) => {
            }, this._errorHandlerFb = (e7) => e7, 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, s6.toDisposable)(() => {
              this._csiHandlers = /* @__PURE__ */ Object.create(null), this._executeHandlers = /* @__PURE__ */ Object.create(null), this._escHandlers = /* @__PURE__ */ Object.create(null);
            })), this._oscParser = this.register(new n4.OscParser()), this._dcsParser = this.register(new a2.DcsParser()), this._errorHandler = this._errorHandlerFb, this.registerEscHandler({ final: "\\" }, () => true);
          }
          _identifier(e6, t7 = [64, 126]) {
            let i5 = 0;
            if (e6.prefix) {
              if (e6.prefix.length > 1) throw new Error("only one byte as prefix supported");
              if (i5 = e6.prefix.charCodeAt(0), i5 && 60 > i5 || i5 > 63) throw new Error("prefix must be in range 0x3c .. 0x3f");
            }
            if (e6.intermediates) {
              if (e6.intermediates.length > 2) throw new Error("only two bytes as intermediates are supported");
              for (let t8 = 0; t8 < e6.intermediates.length; ++t8) {
                const s8 = e6.intermediates.charCodeAt(t8);
                if (32 > s8 || s8 > 47) throw new Error("intermediate must be in range 0x20 .. 0x2f");
                i5 <<= 8, i5 |= s8;
              }
            }
            if (1 !== e6.final.length) throw new Error("final must be a single byte");
            const s7 = e6.final.charCodeAt(0);
            if (t7[0] > s7 || s7 > t7[1]) throw new Error(`final must be in range ${t7[0]} .. ${t7[1]}`);
            return i5 <<= 8, i5 |= s7, i5;
          }
          identToString(e6) {
            const t7 = [];
            for (; e6; ) t7.push(String.fromCharCode(255 & e6)), e6 >>= 8;
            return t7.reverse().join("");
          }
          setPrintHandler(e6) {
            this._printHandler = e6;
          }
          clearPrintHandler() {
            this._printHandler = this._printHandlerFb;
          }
          registerEscHandler(e6, t7) {
            const i5 = this._identifier(e6, [48, 126]);
            void 0 === this._escHandlers[i5] && (this._escHandlers[i5] = []);
            const s7 = this._escHandlers[i5];
            return s7.push(t7), { dispose: /* @__PURE__ */ __name(() => {
              const e7 = s7.indexOf(t7);
              -1 !== e7 && s7.splice(e7, 1);
            }, "dispose") };
          }
          clearEscHandler(e6) {
            this._escHandlers[this._identifier(e6, [48, 126])] && delete this._escHandlers[this._identifier(e6, [48, 126])];
          }
          setEscHandlerFallback(e6) {
            this._escHandlerFb = e6;
          }
          setExecuteHandler(e6, t7) {
            this._executeHandlers[e6.charCodeAt(0)] = t7;
          }
          clearExecuteHandler(e6) {
            this._executeHandlers[e6.charCodeAt(0)] && delete this._executeHandlers[e6.charCodeAt(0)];
          }
          setExecuteHandlerFallback(e6) {
            this._executeHandlerFb = e6;
          }
          registerCsiHandler(e6, t7) {
            const i5 = this._identifier(e6);
            void 0 === this._csiHandlers[i5] && (this._csiHandlers[i5] = []);
            const s7 = this._csiHandlers[i5];
            return s7.push(t7), { dispose: /* @__PURE__ */ __name(() => {
              const e7 = s7.indexOf(t7);
              -1 !== e7 && s7.splice(e7, 1);
            }, "dispose") };
          }
          clearCsiHandler(e6) {
            this._csiHandlers[this._identifier(e6)] && delete this._csiHandlers[this._identifier(e6)];
          }
          setCsiHandlerFallback(e6) {
            this._csiHandlerFb = e6;
          }
          registerDcsHandler(e6, t7) {
            return this._dcsParser.registerHandler(this._identifier(e6), t7);
          }
          clearDcsHandler(e6) {
            this._dcsParser.clearHandler(this._identifier(e6));
          }
          setDcsHandlerFallback(e6) {
            this._dcsParser.setHandlerFallback(e6);
          }
          registerOscHandler(e6, t7) {
            return this._oscParser.registerHandler(e6, t7);
          }
          clearOscHandler(e6) {
            this._oscParser.clearHandler(e6);
          }
          setOscHandlerFallback(e6) {
            this._oscParser.setHandlerFallback(e6);
          }
          setErrorHandler(e6) {
            this._errorHandler = e6;
          }
          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(e6, t7, i5, s7, r7) {
            this._parseStack.state = e6, this._parseStack.handlers = t7, this._parseStack.handlerPos = i5, this._parseStack.transition = s7, this._parseStack.chunkPos = r7;
          }
          parse(e6, t7, i5) {
            let s7, r7 = 0, n5 = 0, a3 = 0;
            if (this._parseStack.state) if (2 === this._parseStack.state) this._parseStack.state = 0, a3 = this._parseStack.chunkPos + 1;
            else {
              if (void 0 === i5 || 1 === this._parseStack.state) throw this._parseStack.state = 1, new Error("improper continuation due to previous async handler, giving up parsing");
              const t8 = this._parseStack.handlers;
              let n6 = this._parseStack.handlerPos - 1;
              switch (this._parseStack.state) {
                case 3:
                  if (false === i5 && n6 > -1) {
                    for (; n6 >= 0 && (s7 = t8[n6](this._params), true !== s7); n6--) if (s7 instanceof Promise) return this._parseStack.handlerPos = n6, s7;
                  }
                  this._parseStack.handlers = [];
                  break;
                case 4:
                  if (false === i5 && n6 > -1) {
                    for (; n6 >= 0 && (s7 = t8[n6](), true !== s7); n6--) if (s7 instanceof Promise) return this._parseStack.handlerPos = n6, s7;
                  }
                  this._parseStack.handlers = [];
                  break;
                case 6:
                  if (r7 = e6[this._parseStack.chunkPos], s7 = this._dcsParser.unhook(24 !== r7 && 26 !== r7, i5), s7) return s7;
                  27 === r7 && (this._parseStack.transition |= 1), this._params.reset(), this._params.addParam(0), this._collect = 0;
                  break;
                case 5:
                  if (r7 = e6[this._parseStack.chunkPos], s7 = this._oscParser.end(24 !== r7 && 26 !== r7, i5), s7) return s7;
                  27 === r7 && (this._parseStack.transition |= 1), this._params.reset(), this._params.addParam(0), this._collect = 0;
              }
              this._parseStack.state = 0, a3 = this._parseStack.chunkPos + 1, this.precedingJoinState = 0, this.currentState = 15 & this._parseStack.transition;
            }
            for (let i6 = a3; i6 < t7; ++i6) {
              switch (r7 = e6[i6], n5 = this._transitions.table[this.currentState << 8 | (r7 < 160 ? r7 : h3)], n5 >> 4) {
                case 2:
                  for (let s8 = i6 + 1; ; ++s8) {
                    if (s8 >= t7 || (r7 = e6[s8]) < 32 || r7 > 126 && r7 < h3) {
                      this._printHandler(e6, i6, s8), i6 = s8 - 1;
                      break;
                    }
                    if (++s8 >= t7 || (r7 = e6[s8]) < 32 || r7 > 126 && r7 < h3) {
                      this._printHandler(e6, i6, s8), i6 = s8 - 1;
                      break;
                    }
                    if (++s8 >= t7 || (r7 = e6[s8]) < 32 || r7 > 126 && r7 < h3) {
                      this._printHandler(e6, i6, s8), i6 = s8 - 1;
                      break;
                    }
                    if (++s8 >= t7 || (r7 = e6[s8]) < 32 || r7 > 126 && r7 < h3) {
                      this._printHandler(e6, i6, s8), i6 = s8 - 1;
                      break;
                    }
                  }
                  break;
                case 3:
                  this._executeHandlers[r7] ? this._executeHandlers[r7]() : this._executeHandlerFb(r7), this.precedingJoinState = 0;
                  break;
                case 0:
                  break;
                case 1:
                  if (this._errorHandler({ position: i6, code: r7, currentState: this.currentState, collect: this._collect, params: this._params, abort: false }).abort) return;
                  break;
                case 7:
                  const a4 = this._csiHandlers[this._collect << 8 | r7];
                  let o4 = a4 ? a4.length - 1 : -1;
                  for (; o4 >= 0 && (s7 = a4[o4](this._params), true !== s7); o4--) if (s7 instanceof Promise) return this._preserveStack(3, a4, o4, n5, i6), s7;
                  o4 < 0 && this._csiHandlerFb(this._collect << 8 | r7, this._params), this.precedingJoinState = 0;
                  break;
                case 8:
                  do {
                    switch (r7) {
                      case 59:
                        this._params.addParam(0);
                        break;
                      case 58:
                        this._params.addSubParam(-1);
                        break;
                      default:
                        this._params.addDigit(r7 - 48);
                    }
                  } while (++i6 < t7 && (r7 = e6[i6]) > 47 && r7 < 60);
                  i6--;
                  break;
                case 9:
                  this._collect <<= 8, this._collect |= r7;
                  break;
                case 10:
                  const c5 = this._escHandlers[this._collect << 8 | r7];
                  let l3 = c5 ? c5.length - 1 : -1;
                  for (; l3 >= 0 && (s7 = c5[l3](), true !== s7); l3--) if (s7 instanceof Promise) return this._preserveStack(4, c5, l3, n5, i6), s7;
                  l3 < 0 && this._escHandlerFb(this._collect << 8 | r7), 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 | r7, this._params);
                  break;
                case 13:
                  for (let s8 = i6 + 1; ; ++s8) if (s8 >= t7 || 24 === (r7 = e6[s8]) || 26 === r7 || 27 === r7 || r7 > 127 && r7 < h3) {
                    this._dcsParser.put(e6, i6, s8), i6 = s8 - 1;
                    break;
                  }
                  break;
                case 14:
                  if (s7 = this._dcsParser.unhook(24 !== r7 && 26 !== r7), s7) return this._preserveStack(6, [], 0, n5, i6), s7;
                  27 === r7 && (n5 |= 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 s8 = i6 + 1; ; s8++) if (s8 >= t7 || (r7 = e6[s8]) < 32 || r7 > 127 && r7 < h3) {
                    this._oscParser.put(e6, i6, s8), i6 = s8 - 1;
                    break;
                  }
                  break;
                case 6:
                  if (s7 = this._oscParser.end(24 !== r7 && 26 !== r7), s7) return this._preserveStack(5, [], 0, n5, i6), s7;
                  27 === r7 && (n5 |= 1), this._params.reset(), this._params.addParam(0), this._collect = 0, this.precedingJoinState = 0;
              }
              this.currentState = 15 & n5;
            }
          }
        }
        t6.EscapeSequenceParser = c4;
      }, 242: (e5, t6, i4) => {
        Object.defineProperty(t6, "__esModule", { value: true }), t6.OscHandler = t6.OscParser = void 0;
        const s6 = i4(770), r6 = i4(482), n4 = [];
        t6.OscParser = class {
          constructor() {
            this._state = 0, this._active = n4, this._id = -1, this._handlers = /* @__PURE__ */ Object.create(null), this._handlerFb = () => {
            }, this._stack = { paused: false, loopPosition: 0, fallThrough: false };
          }
          registerHandler(e6, t7) {
            void 0 === this._handlers[e6] && (this._handlers[e6] = []);
            const i5 = this._handlers[e6];
            return i5.push(t7), { dispose: /* @__PURE__ */ __name(() => {
              const e7 = i5.indexOf(t7);
              -1 !== e7 && i5.splice(e7, 1);
            }, "dispose") };
          }
          clearHandler(e6) {
            this._handlers[e6] && delete this._handlers[e6];
          }
          setHandlerFallback(e6) {
            this._handlerFb = e6;
          }
          dispose() {
            this._handlers = /* @__PURE__ */ Object.create(null), this._handlerFb = () => {
            }, this._active = n4;
          }
          reset() {
            if (2 === this._state) for (let e6 = this._stack.paused ? this._stack.loopPosition - 1 : this._active.length - 1; e6 >= 0; --e6) this._active[e6].end(false);
            this._stack.paused = false, this._active = n4, this._id = -1, this._state = 0;
          }
          _start() {
            if (this._active = this._handlers[this._id] || n4, this._active.length) for (let e6 = this._active.length - 1; e6 >= 0; e6--) this._active[e6].start();
            else this._handlerFb(this._id, "START");
          }
          _put(e6, t7, i5) {
            if (this._active.length) for (let s7 = this._active.length - 1; s7 >= 0; s7--) this._active[s7].put(e6, t7, i5);
            else this._handlerFb(this._id, "PUT", (0, r6.utf32ToString)(e6, t7, i5));
          }
          start() {
            this.reset(), this._state = 1;
          }
          put(e6, t7, i5) {
            if (3 !== this._state) {
              if (1 === this._state) for (; t7 < i5; ) {
                const i6 = e6[t7++];
                if (59 === i6) {
                  this._state = 2, this._start();
                  break;
                }
                if (i6 < 48 || 57 < i6) return void (this._state = 3);
                -1 === this._id && (this._id = 0), this._id = 10 * this._id + i6 - 48;
              }
              2 === this._state && i5 - t7 > 0 && this._put(e6, t7, i5);
            }
          }
          end(e6, t7 = true) {
            if (0 !== this._state) {
              if (3 !== this._state) if (1 === this._state && this._start(), this._active.length) {
                let i5 = false, s7 = this._active.length - 1, r7 = false;
                if (this._stack.paused && (s7 = this._stack.loopPosition - 1, i5 = t7, r7 = this._stack.fallThrough, this._stack.paused = false), !r7 && false === i5) {
                  for (; s7 >= 0 && (i5 = this._active[s7].end(e6), true !== i5); s7--) if (i5 instanceof Promise) return this._stack.paused = true, this._stack.loopPosition = s7, this._stack.fallThrough = false, i5;
                  s7--;
                }
                for (; s7 >= 0; s7--) if (i5 = this._active[s7].end(false), i5 instanceof Promise) return this._stack.paused = true, this._stack.loopPosition = s7, this._stack.fallThrough = true, i5;
              } else this._handlerFb(this._id, "END", e6);
              this._active = n4, this._id = -1, this._state = 0;
            }
          }
        }, t6.OscHandler = class {
          constructor(e6) {
            this._handler = e6, this._data = "", this._hitLimit = false;
          }
          start() {
            this._data = "", this._hitLimit = false;
          }
          put(e6, t7, i5) {
            this._hitLimit || (this._data += (0, r6.utf32ToString)(e6, t7, i5), this._data.length > s6.PAYLOAD_LIMIT && (this._data = "", this._hitLimit = true));
          }
          end(e6) {
            let t7 = false;
            if (this._hitLimit) t7 = false;
            else if (e6 && (t7 = this._handler(this._data), t7 instanceof Promise)) return t7.then((e7) => (this._data = "", this._hitLimit = false, e7));
            return this._data = "", this._hitLimit = false, t7;
          }
        };
      }, 742: (e5, t6) => {
        Object.defineProperty(t6, "__esModule", { value: true }), t6.Params = void 0;
        const i4 = 2147483647;
        class s6 {
          static {
            __name(this, "s");
          }
          static fromArray(e6) {
            const t7 = new s6();
            if (!e6.length) return t7;
            for (let i5 = Array.isArray(e6[0]) ? 1 : 0; i5 < e6.length; ++i5) {
              const s7 = e6[i5];
              if (Array.isArray(s7)) for (let e7 = 0; e7 < s7.length; ++e7) t7.addSubParam(s7[e7]);
              else t7.addParam(s7);
            }
            return t7;
          }
          constructor(e6 = 32, t7 = 32) {
            if (this.maxLength = e6, this.maxSubParamsLength = t7, t7 > 256) throw new Error("maxSubParamsLength must not be greater than 256");
            this.params = new Int32Array(e6), this.length = 0, this._subParams = new Int32Array(t7), this._subParamsLength = 0, this._subParamsIdx = new Uint16Array(e6), this._rejectDigits = false, this._rejectSubDigits = false, this._digitIsSub = false;
          }
          clone() {
            const e6 = new s6(this.maxLength, this.maxSubParamsLength);
            return e6.params.set(this.params), e6.length = this.length, e6._subParams.set(this._subParams), e6._subParamsLength = this._subParamsLength, e6._subParamsIdx.set(this._subParamsIdx), e6._rejectDigits = this._rejectDigits, e6._rejectSubDigits = this._rejectSubDigits, e6._digitIsSub = this._digitIsSub, e6;
          }
          toArray() {
            const e6 = [];
            for (let t7 = 0; t7 < this.length; ++t7) {
              e6.push(this.params[t7]);
              const i5 = this._subParamsIdx[t7] >> 8, s7 = 255 & this._subParamsIdx[t7];
              s7 - i5 > 0 && e6.push(Array.prototype.slice.call(this._subParams, i5, s7));
            }
            return e6;
          }
          reset() {
            this.length = 0, this._subParamsLength = 0, this._rejectDigits = false, this._rejectSubDigits = false, this._digitIsSub = false;
          }
          addParam(e6) {
            if (this._digitIsSub = false, this.length >= this.maxLength) this._rejectDigits = true;
            else {
              if (e6 < -1) throw new Error("values lesser than -1 are not allowed");
              this._subParamsIdx[this.length] = this._subParamsLength << 8 | this._subParamsLength, this.params[this.length++] = e6 > i4 ? i4 : e6;
            }
          }
          addSubParam(e6) {
            if (this._digitIsSub = true, this.length) if (this._rejectDigits || this._subParamsLength >= this.maxSubParamsLength) this._rejectSubDigits = true;
            else {
              if (e6 < -1) throw new Error("values lesser than -1 are not allowed");
              this._subParams[this._subParamsLength++] = e6 > i4 ? i4 : e6, this._subParamsIdx[this.length - 1]++;
            }
          }
          hasSubParams(e6) {
            return (255 & this._subParamsIdx[e6]) - (this._subParamsIdx[e6] >> 8) > 0;
          }
          getSubParams(e6) {
            const t7 = this._subParamsIdx[e6] >> 8, i5 = 255 & this._subParamsIdx[e6];
            return i5 - t7 > 0 ? this._subParams.subarray(t7, i5) : null;
          }
          getSubParamsAll() {
            const e6 = {};
            for (let t7 = 0; t7 < this.length; ++t7) {
              const i5 = this._subParamsIdx[t7] >> 8, s7 = 255 & this._subParamsIdx[t7];
              s7 - i5 > 0 && (e6[t7] = this._subParams.slice(i5, s7));
            }
            return e6;
          }
          addDigit(e6) {
            let t7;
            if (this._rejectDigits || !(t7 = this._digitIsSub ? this._subParamsLength : this.length) || this._digitIsSub && this._rejectSubDigits) return;
            const s7 = this._digitIsSub ? this._subParams : this.params, r6 = s7[t7 - 1];
            s7[t7 - 1] = ~r6 ? Math.min(10 * r6 + e6, i4) : e6;
          }
        }
        t6.Params = s6;
      }, 741: (e5, t6) => {
        Object.defineProperty(t6, "__esModule", { value: true }), t6.AddonManager = void 0, t6.AddonManager = class {
          constructor() {
            this._addons = [];
          }
          dispose() {
            for (let e6 = this._addons.length - 1; e6 >= 0; e6--) this._addons[e6].instance.dispose();
          }
          loadAddon(e6, t7) {
            const i4 = { instance: t7, dispose: t7.dispose, isDisposed: false };
            this._addons.push(i4), t7.dispose = () => this._wrappedAddonDispose(i4), t7.activate(e6);
          }
          _wrappedAddonDispose(e6) {
            if (e6.isDisposed) return;
            let t7 = -1;
            for (let i4 = 0; i4 < this._addons.length; i4++) if (this._addons[i4] === e6) {
              t7 = i4;
              break;
            }
            if (-1 === t7) throw new Error("Could not dispose an addon that has not been loaded");
            e6.isDisposed = true, e6.dispose.apply(e6.instance), this._addons.splice(t7, 1);
          }
        };
      }, 771: (e5, t6, i4) => {
        Object.defineProperty(t6, "__esModule", { value: true }), t6.BufferApiView = void 0;
        const s6 = i4(785), r6 = i4(511);
        t6.BufferApiView = class {
          constructor(e6, t7) {
            this._buffer = e6, this.type = t7;
          }
          init(e6) {
            return this._buffer = e6, 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(e6) {
            const t7 = this._buffer.lines.get(e6);
            if (t7) return new s6.BufferLineApiView(t7);
          }
          getNullCell() {
            return new r6.CellData();
          }
        };
      }, 785: (e5, t6, i4) => {
        Object.defineProperty(t6, "__esModule", { value: true }), t6.BufferLineApiView = void 0;
        const s6 = i4(511);
        t6.BufferLineApiView = class {
          constructor(e6) {
            this._line = e6;
          }
          get isWrapped() {
            return this._line.isWrapped;
          }
          get length() {
            return this._line.length;
          }
          getCell(e6, t7) {
            if (!(e6 < 0 || e6 >= this._line.length)) return t7 ? (this._line.loadCell(e6, t7), t7) : this._line.loadCell(e6, new s6.CellData());
          }
          translateToString(e6, t7, i5) {
            return this._line.translateToString(e6, t7, i5);
          }
        };
      }, 285: (e5, t6, i4) => {
        Object.defineProperty(t6, "__esModule", { value: true }), t6.BufferNamespaceApi = void 0;
        const s6 = i4(771), r6 = i4(460), n4 = i4(844);
        class a2 extends n4.Disposable {
          static {
            __name(this, "a");
          }
          constructor(e6) {
            super(), this._core = e6, this._onBufferChange = this.register(new r6.EventEmitter()), this.onBufferChange = this._onBufferChange.event, this._normal = new s6.BufferApiView(this._core.buffers.normal, "normal"), this._alternate = new s6.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);
          }
        }
        t6.BufferNamespaceApi = a2;
      }, 975: (e5, t6) => {
        Object.defineProperty(t6, "__esModule", { value: true }), t6.ParserApi = void 0, t6.ParserApi = class {
          constructor(e6) {
            this._core = e6;
          }
          registerCsiHandler(e6, t7) {
            return this._core.registerCsiHandler(e6, (e7) => t7(e7.toArray()));
          }
          addCsiHandler(e6, t7) {
            return this.registerCsiHandler(e6, t7);
          }
          registerDcsHandler(e6, t7) {
            return this._core.registerDcsHandler(e6, (e7, i4) => t7(e7, i4.toArray()));
          }
          addDcsHandler(e6, t7) {
            return this.registerDcsHandler(e6, t7);
          }
          registerEscHandler(e6, t7) {
            return this._core.registerEscHandler(e6, t7);
          }
          addEscHandler(e6, t7) {
            return this.registerEscHandler(e6, t7);
          }
          registerOscHandler(e6, t7) {
            return this._core.registerOscHandler(e6, t7);
          }
          addOscHandler(e6, t7) {
            return this.registerOscHandler(e6, t7);
          }
        };
      }, 90: (e5, t6) => {
        Object.defineProperty(t6, "__esModule", { value: true }), t6.UnicodeApi = void 0, t6.UnicodeApi = class {
          constructor(e6) {
            this._core = e6;
          }
          register(e6) {
            this._core.unicodeService.register(e6);
          }
          get versions() {
            return this._core.unicodeService.versions;
          }
          get activeVersion() {
            return this._core.unicodeService.activeVersion;
          }
          set activeVersion(e6) {
            this._core.unicodeService.activeVersion = e6;
          }
        };
      }, 744: function(e5, t6, i4) {
        var s6 = this && this.__decorate || function(e6, t7, i5, s7) {
          var r7, n5 = arguments.length, a3 = n5 < 3 ? t7 : null === s7 ? s7 = Object.getOwnPropertyDescriptor(t7, i5) : s7;
          if ("object" == typeof Reflect && "function" == typeof Reflect.decorate) a3 = Reflect.decorate(e6, t7, i5, s7);
          else for (var o4 = e6.length - 1; o4 >= 0; o4--) (r7 = e6[o4]) && (a3 = (n5 < 3 ? r7(a3) : n5 > 3 ? r7(t7, i5, a3) : r7(t7, i5)) || a3);
          return n5 > 3 && a3 && Object.defineProperty(t7, i5, a3), a3;
        }, r6 = this && this.__param || function(e6, t7) {
          return function(i5, s7) {
            t7(i5, s7, e6);
          };
        };
        Object.defineProperty(t6, "__esModule", { value: true }), t6.BufferService = t6.MINIMUM_ROWS = t6.MINIMUM_COLS = void 0;
        const n4 = i4(460), a2 = i4(844), o3 = i4(295), h3 = i4(585);
        t6.MINIMUM_COLS = 2, t6.MINIMUM_ROWS = 1;
        let c4 = t6.BufferService = class extends a2.Disposable {
          get buffer() {
            return this.buffers.active;
          }
          constructor(e6) {
            super(), this.isUserScrolling = false, this._onResize = this.register(new n4.EventEmitter()), this.onResize = this._onResize.event, this._onScroll = this.register(new n4.EventEmitter()), this.onScroll = this._onScroll.event, this.cols = Math.max(e6.rawOptions.cols || 0, t6.MINIMUM_COLS), this.rows = Math.max(e6.rawOptions.rows || 0, t6.MINIMUM_ROWS), this.buffers = this.register(new o3.BufferSet(e6, this));
          }
          resize(e6, t7) {
            this.cols = e6, this.rows = t7, this.buffers.resize(e6, t7), this._onResize.fire({ cols: e6, rows: t7 });
          }
          reset() {
            this.buffers.reset(), this.isUserScrolling = false;
          }
          scroll(e6, t7 = false) {
            const i5 = this.buffer;
            let s7;
            s7 = this._cachedBlankLine, s7 && s7.length === this.cols && s7.getFg(0) === e6.fg && s7.getBg(0) === e6.bg || (s7 = i5.getBlankLine(e6, t7), this._cachedBlankLine = s7), s7.isWrapped = t7;
            const r7 = i5.ybase + i5.scrollTop, n5 = i5.ybase + i5.scrollBottom;
            if (0 === i5.scrollTop) {
              const e7 = i5.lines.isFull;
              n5 === i5.lines.length - 1 ? e7 ? i5.lines.recycle().copyFrom(s7) : i5.lines.push(s7.clone()) : i5.lines.splice(n5 + 1, 0, s7.clone()), e7 ? this.isUserScrolling && (i5.ydisp = Math.max(i5.ydisp - 1, 0)) : (i5.ybase++, this.isUserScrolling || i5.ydisp++);
            } else {
              const e7 = n5 - r7 + 1;
              i5.lines.shiftElements(r7 + 1, e7 - 1, -1), i5.lines.set(n5, s7.clone());
            }
            this.isUserScrolling || (i5.ydisp = i5.ybase), this._onScroll.fire(i5.ydisp);
          }
          scrollLines(e6, t7, i5) {
            const s7 = this.buffer;
            if (e6 < 0) {
              if (0 === s7.ydisp) return;
              this.isUserScrolling = true;
            } else e6 + s7.ydisp >= s7.ybase && (this.isUserScrolling = false);
            const r7 = s7.ydisp;
            s7.ydisp = Math.max(Math.min(s7.ydisp + e6, s7.ybase), 0), r7 !== s7.ydisp && (t7 || this._onScroll.fire(s7.ydisp));
          }
        };
        t6.BufferService = c4 = s6([r6(0, h3.IOptionsService)], c4);
      }, 994: (e5, t6) => {
        Object.defineProperty(t6, "__esModule", { value: true }), t6.CharsetService = void 0, t6.CharsetService = class {
          constructor() {
            this.glevel = 0, this._charsets = [];
          }
          reset() {
            this.charset = void 0, this._charsets = [], this.glevel = 0;
          }
          setgLevel(e6) {
            this.glevel = e6, this.charset = this._charsets[e6];
          }
          setgCharset(e6, t7) {
            this._charsets[e6] = t7, this.glevel === e6 && (this.charset = t7);
          }
        };
      }, 753: function(e5, t6, i4) {
        var s6 = this && this.__decorate || function(e6, t7, i5, s7) {
          var r7, n5 = arguments.length, a3 = n5 < 3 ? t7 : null === s7 ? s7 = Object.getOwnPropertyDescriptor(t7, i5) : s7;
          if ("object" == typeof Reflect && "function" == typeof Reflect.decorate) a3 = Reflect.decorate(e6, t7, i5, s7);
          else for (var o4 = e6.length - 1; o4 >= 0; o4--) (r7 = e6[o4]) && (a3 = (n5 < 3 ? r7(a3) : n5 > 3 ? r7(t7, i5, a3) : r7(t7, i5)) || a3);
          return n5 > 3 && a3 && Object.defineProperty(t7, i5, a3), a3;
        }, r6 = this && this.__param || function(e6, t7) {
          return function(i5, s7) {
            t7(i5, s7, e6);
          };
        };
        Object.defineProperty(t6, "__esModule", { value: true }), t6.CoreMouseService = void 0;
        const n4 = i4(585), a2 = i4(460), o3 = i4(844), h3 = { NONE: { events: 0, restrict: /* @__PURE__ */ __name(() => false, "restrict") }, X10: { events: 1, restrict: /* @__PURE__ */ __name((e6) => 4 !== e6.button && 1 === e6.action && (e6.ctrl = false, e6.alt = false, e6.shift = false, true), "restrict") }, VT200: { events: 19, restrict: /* @__PURE__ */ __name((e6) => 32 !== e6.action, "restrict") }, DRAG: { events: 23, restrict: /* @__PURE__ */ __name((e6) => 32 !== e6.action || 3 !== e6.button, "restrict") }, ANY: { events: 31, restrict: /* @__PURE__ */ __name((e6) => true, "restrict") } };
        function c4(e6, t7) {
          let i5 = (e6.ctrl ? 16 : 0) | (e6.shift ? 4 : 0) | (e6.alt ? 8 : 0);
          return 4 === e6.button ? (i5 |= 64, i5 |= e6.action) : (i5 |= 3 & e6.button, 4 & e6.button && (i5 |= 64), 8 & e6.button && (i5 |= 128), 32 === e6.action ? i5 |= 32 : 0 !== e6.action || t7 || (i5 |= 3)), i5;
        }
        __name(c4, "c");
        const l3 = String.fromCharCode, _2 = { DEFAULT: /* @__PURE__ */ __name((e6) => {
          const t7 = [c4(e6, false) + 32, e6.col + 32, e6.row + 32];
          return t7[0] > 255 || t7[1] > 255 || t7[2] > 255 ? "" : `\x1B[M${l3(t7[0])}${l3(t7[1])}${l3(t7[2])}`;
        }, "DEFAULT"), SGR: /* @__PURE__ */ __name((e6) => {
          const t7 = 0 === e6.action && 4 !== e6.button ? "m" : "M";
          return `\x1B[<${c4(e6, true)};${e6.col};${e6.row}${t7}`;
        }, "SGR"), SGR_PIXELS: /* @__PURE__ */ __name((e6) => {
          const t7 = 0 === e6.action && 4 !== e6.button ? "m" : "M";
          return `\x1B[<${c4(e6, true)};${e6.x};${e6.y}${t7}`;
        }, "SGR_PIXELS") };
        let d2 = t6.CoreMouseService = class extends o3.Disposable {
          constructor(e6, t7) {
            super(), this._bufferService = e6, this._coreService = t7, this._protocols = {}, this._encodings = {}, this._activeProtocol = "", this._activeEncoding = "", this._lastEvent = null, this._onProtocolChange = this.register(new a2.EventEmitter()), this.onProtocolChange = this._onProtocolChange.event;
            for (const e7 of Object.keys(h3)) this.addProtocol(e7, h3[e7]);
            for (const e7 of Object.keys(_2)) this.addEncoding(e7, _2[e7]);
            this.reset();
          }
          addProtocol(e6, t7) {
            this._protocols[e6] = t7;
          }
          addEncoding(e6, t7) {
            this._encodings[e6] = t7;
          }
          get activeProtocol() {
            return this._activeProtocol;
          }
          get areMouseEventsActive() {
            return 0 !== this._protocols[this._activeProtocol].events;
          }
          set activeProtocol(e6) {
            if (!this._protocols[e6]) throw new Error(`unknown protocol "${e6}"`);
            this._activeProtocol = e6, this._onProtocolChange.fire(this._protocols[e6].events);
          }
          get activeEncoding() {
            return this._activeEncoding;
          }
          set activeEncoding(e6) {
            if (!this._encodings[e6]) throw new Error(`unknown encoding "${e6}"`);
            this._activeEncoding = e6;
          }
          reset() {
            this.activeProtocol = "NONE", this.activeEncoding = "DEFAULT", this._lastEvent = null;
          }
          triggerMouseEvent(e6) {
            if (e6.col < 0 || e6.col >= this._bufferService.cols || e6.row < 0 || e6.row >= this._bufferService.rows) return false;
            if (4 === e6.button && 32 === e6.action) return false;
            if (3 === e6.button && 32 !== e6.action) return false;
            if (4 !== e6.button && (2 === e6.action || 3 === e6.action)) return false;
            if (e6.col++, e6.row++, 32 === e6.action && this._lastEvent && this._equalEvents(this._lastEvent, e6, "SGR_PIXELS" === this._activeEncoding)) return false;
            if (!this._protocols[this._activeProtocol].restrict(e6)) return false;
            const t7 = this._encodings[this._activeEncoding](e6);
            return t7 && ("DEFAULT" === this._activeEncoding ? this._coreService.triggerBinaryEvent(t7) : this._coreService.triggerDataEvent(t7, true)), this._lastEvent = e6, true;
          }
          explainEvents(e6) {
            return { down: !!(1 & e6), up: !!(2 & e6), drag: !!(4 & e6), move: !!(8 & e6), wheel: !!(16 & e6) };
          }
          _equalEvents(e6, t7, i5) {
            if (i5) {
              if (e6.x !== t7.x) return false;
              if (e6.y !== t7.y) return false;
            } else {
              if (e6.col !== t7.col) return false;
              if (e6.row !== t7.row) return false;
            }
            return e6.button === t7.button && e6.action === t7.action && e6.ctrl === t7.ctrl && e6.alt === t7.alt && e6.shift === t7.shift;
          }
        };
        t6.CoreMouseService = d2 = s6([r6(0, n4.IBufferService), r6(1, n4.ICoreService)], d2);
      }, 83: function(e5, t6, i4) {
        var s6 = this && this.__decorate || function(e6, t7, i5, s7) {
          var r7, n5 = arguments.length, a3 = n5 < 3 ? t7 : null === s7 ? s7 = Object.getOwnPropertyDescriptor(t7, i5) : s7;
          if ("object" == typeof Reflect && "function" == typeof Reflect.decorate) a3 = Reflect.decorate(e6, t7, i5, s7);
          else for (var o4 = e6.length - 1; o4 >= 0; o4--) (r7 = e6[o4]) && (a3 = (n5 < 3 ? r7(a3) : n5 > 3 ? r7(t7, i5, a3) : r7(t7, i5)) || a3);
          return n5 > 3 && a3 && Object.defineProperty(t7, i5, a3), a3;
        }, r6 = this && this.__param || function(e6, t7) {
          return function(i5, s7) {
            t7(i5, s7, e6);
          };
        };
        Object.defineProperty(t6, "__esModule", { value: true }), t6.CoreService = void 0;
        const n4 = i4(439), a2 = i4(460), o3 = i4(844), h3 = i4(585), c4 = Object.freeze({ insertMode: false }), l3 = Object.freeze({ applicationCursorKeys: false, applicationKeypad: false, bracketedPasteMode: false, origin: false, reverseWraparound: false, sendFocus: false, wraparound: true });
        let _2 = t6.CoreService = class extends o3.Disposable {
          constructor(e6, t7, i5) {
            super(), this._bufferService = e6, this._logService = t7, this._optionsService = i5, this.isCursorInitialized = false, this.isCursorHidden = false, this._onData = this.register(new a2.EventEmitter()), this.onData = this._onData.event, this._onUserInput = this.register(new a2.EventEmitter()), this.onUserInput = this._onUserInput.event, this._onBinary = this.register(new a2.EventEmitter()), this.onBinary = this._onBinary.event, this._onRequestScrollToBottom = this.register(new a2.EventEmitter()), this.onRequestScrollToBottom = this._onRequestScrollToBottom.event, this.modes = (0, n4.clone)(c4), this.decPrivateModes = (0, n4.clone)(l3);
          }
          reset() {
            this.modes = (0, n4.clone)(c4), this.decPrivateModes = (0, n4.clone)(l3);
          }
          triggerDataEvent(e6, t7 = false) {
            if (this._optionsService.rawOptions.disableStdin) return;
            const i5 = this._bufferService.buffer;
            t7 && this._optionsService.rawOptions.scrollOnUserInput && i5.ybase !== i5.ydisp && this._onRequestScrollToBottom.fire(), t7 && this._onUserInput.fire(), this._logService.debug(`sending data "${e6}"`, () => e6.split("").map((e7) => e7.charCodeAt(0))), this._onData.fire(e6);
          }
          triggerBinaryEvent(e6) {
            this._optionsService.rawOptions.disableStdin || (this._logService.debug(`sending binary "${e6}"`, () => e6.split("").map((e7) => e7.charCodeAt(0))), this._onBinary.fire(e6));
          }
        };
        t6.CoreService = _2 = s6([r6(0, h3.IBufferService), r6(1, h3.ILogService), r6(2, h3.IOptionsService)], _2);
      }, 348: (e5, t6, i4) => {
        Object.defineProperty(t6, "__esModule", { value: true }), t6.InstantiationService = t6.ServiceCollection = void 0;
        const s6 = i4(585), r6 = i4(343);
        class n4 {
          static {
            __name(this, "n");
          }
          constructor(...e6) {
            this._entries = /* @__PURE__ */ new Map();
            for (const [t7, i5] of e6) this.set(t7, i5);
          }
          set(e6, t7) {
            const i5 = this._entries.get(e6);
            return this._entries.set(e6, t7), i5;
          }
          forEach(e6) {
            for (const [t7, i5] of this._entries.entries()) e6(t7, i5);
          }
          has(e6) {
            return this._entries.has(e6);
          }
          get(e6) {
            return this._entries.get(e6);
          }
        }
        t6.ServiceCollection = n4, t6.InstantiationService = class {
          constructor() {
            this._services = new n4(), this._services.set(s6.IInstantiationService, this);
          }
          setService(e6, t7) {
            this._services.set(e6, t7);
          }
          getService(e6) {
            return this._services.get(e6);
          }
          createInstance(e6, ...t7) {
            const i5 = (0, r6.getServiceDependencies)(e6).sort((e7, t8) => e7.index - t8.index), s7 = [];
            for (const t8 of i5) {
              const i6 = this._services.get(t8.id);
              if (!i6) throw new Error(`[createInstance] ${e6.name} depends on UNKNOWN service ${t8.id}.`);
              s7.push(i6);
            }
            const n5 = i5.length > 0 ? i5[0].index : t7.length;
            if (t7.length !== n5) throw new Error(`[createInstance] First service dependency of ${e6.name} at position ${n5 + 1} conflicts with ${t7.length} static arguments`);
            return new e6(...[...t7, ...s7]);
          }
        };
      }, 866: function(e5, t6, i4) {
        var s6 = this && this.__decorate || function(e6, t7, i5, s7) {
          var r7, n5 = arguments.length, a3 = n5 < 3 ? t7 : null === s7 ? s7 = Object.getOwnPropertyDescriptor(t7, i5) : s7;
          if ("object" == typeof Reflect && "function" == typeof Reflect.decorate) a3 = Reflect.decorate(e6, t7, i5, s7);
          else for (var o4 = e6.length - 1; o4 >= 0; o4--) (r7 = e6[o4]) && (a3 = (n5 < 3 ? r7(a3) : n5 > 3 ? r7(t7, i5, a3) : r7(t7, i5)) || a3);
          return n5 > 3 && a3 && Object.defineProperty(t7, i5, a3), a3;
        }, r6 = this && this.__param || function(e6, t7) {
          return function(i5, s7) {
            t7(i5, s7, e6);
          };
        };
        Object.defineProperty(t6, "__esModule", { value: true }), t6.traceCall = t6.setTraceLogger = t6.LogService = void 0;
        const n4 = i4(844), a2 = i4(585), o3 = { trace: a2.LogLevelEnum.TRACE, debug: a2.LogLevelEnum.DEBUG, info: a2.LogLevelEnum.INFO, warn: a2.LogLevelEnum.WARN, error: a2.LogLevelEnum.ERROR, off: a2.LogLevelEnum.OFF };
        let h3, c4 = t6.LogService = class extends n4.Disposable {
          get logLevel() {
            return this._logLevel;
          }
          constructor(e6) {
            super(), this._optionsService = e6, this._logLevel = a2.LogLevelEnum.OFF, this._updateLogLevel(), this.register(this._optionsService.onSpecificOptionChange("logLevel", () => this._updateLogLevel())), h3 = this;
          }
          _updateLogLevel() {
            this._logLevel = o3[this._optionsService.rawOptions.logLevel];
          }
          _evalLazyOptionalParams(e6) {
            for (let t7 = 0; t7 < e6.length; t7++) "function" == typeof e6[t7] && (e6[t7] = e6[t7]());
          }
          _log(e6, t7, i5) {
            this._evalLazyOptionalParams(i5), e6.call(console, (this._optionsService.options.logger ? "" : "xterm.js: ") + t7, ...i5);
          }
          trace(e6, ...t7) {
            this._logLevel <= a2.LogLevelEnum.TRACE && this._log(this._optionsService.options.logger?.trace.bind(this._optionsService.options.logger) ?? console.log, e6, t7);
          }
          debug(e6, ...t7) {
            this._logLevel <= a2.LogLevelEnum.DEBUG && this._log(this._optionsService.options.logger?.debug.bind(this._optionsService.options.logger) ?? console.log, e6, t7);
          }
          info(e6, ...t7) {
            this._logLevel <= a2.LogLevelEnum.INFO && this._log(this._optionsService.options.logger?.info.bind(this._optionsService.options.logger) ?? console.info, e6, t7);
          }
          warn(e6, ...t7) {
            this._logLevel <= a2.LogLevelEnum.WARN && this._log(this._optionsService.options.logger?.warn.bind(this._optionsService.options.logger) ?? console.warn, e6, t7);
          }
          error(e6, ...t7) {
            this._logLevel <= a2.LogLevelEnum.ERROR && this._log(this._optionsService.options.logger?.error.bind(this._optionsService.options.logger) ?? console.error, e6, t7);
          }
        };
        t6.LogService = c4 = s6([r6(0, a2.IOptionsService)], c4), t6.setTraceLogger = function(e6) {
          h3 = e6;
        }, t6.traceCall = function(e6, t7, i5) {
          if ("function" != typeof i5.value) throw new Error("not supported");
          const s7 = i5.value;
          i5.value = function(...e7) {
            if (h3.logLevel !== a2.LogLevelEnum.TRACE) return s7.apply(this, e7);
            h3.trace(`GlyphRenderer#${s7.name}(${e7.map((e8) => JSON.stringify(e8)).join(", ")})`);
            const t8 = s7.apply(this, e7);
            return h3.trace(`GlyphRenderer#${s7.name} return`, t8), t8;
          };
        };
      }, 302: (e5, t6, i4) => {
        Object.defineProperty(t6, "__esModule", { value: true }), t6.OptionsService = t6.DEFAULT_OPTIONS = void 0;
        const s6 = i4(460), r6 = i4(844), n4 = i4(114);
        t6.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: n4.isMac, windowOptions: {}, windowsMode: false, windowsPty: {}, wordSeparator: " ()[]{}',\"`", altClickMovesCursor: true, convertEol: false, termName: "xterm", cancelEvents: false, overviewRulerWidth: 0 };
        const a2 = ["normal", "bold", "100", "200", "300", "400", "500", "600", "700", "800", "900"];
        class o3 extends r6.Disposable {
          static {
            __name(this, "o");
          }
          constructor(e6) {
            super(), this._onOptionChange = this.register(new s6.EventEmitter()), this.onOptionChange = this._onOptionChange.event;
            const i5 = { ...t6.DEFAULT_OPTIONS };
            for (const t7 in e6) if (t7 in i5) try {
              const s7 = e6[t7];
              i5[t7] = this._sanitizeAndValidateOption(t7, s7);
            } catch (e7) {
              console.error(e7);
            }
            this.rawOptions = i5, this.options = { ...i5 }, this._setupOptions(), this.register((0, r6.toDisposable)(() => {
              this.rawOptions.linkHandler = null, this.rawOptions.documentOverride = null;
            }));
          }
          onSpecificOptionChange(e6, t7) {
            return this.onOptionChange((i5) => {
              i5 === e6 && t7(this.rawOptions[e6]);
            });
          }
          onMultipleOptionChange(e6, t7) {
            return this.onOptionChange((i5) => {
              -1 !== e6.indexOf(i5) && t7();
            });
          }
          _setupOptions() {
            const e6 = /* @__PURE__ */ __name((e7) => {
              if (!(e7 in t6.DEFAULT_OPTIONS)) throw new Error(`No option with key "${e7}"`);
              return this.rawOptions[e7];
            }, "e"), i5 = /* @__PURE__ */ __name((e7, i6) => {
              if (!(e7 in t6.DEFAULT_OPTIONS)) throw new Error(`No option with key "${e7}"`);
              i6 = this._sanitizeAndValidateOption(e7, i6), this.rawOptions[e7] !== i6 && (this.rawOptions[e7] = i6, this._onOptionChange.fire(e7));
            }, "i");
            for (const t7 in this.rawOptions) {
              const s7 = { get: e6.bind(this, t7), set: i5.bind(this, t7) };
              Object.defineProperty(this.options, t7, s7);
            }
          }
          _sanitizeAndValidateOption(e6, i5) {
            switch (e6) {
              case "cursorStyle":
                if (i5 || (i5 = t6.DEFAULT_OPTIONS[e6]), !/* @__PURE__ */ function(e7) {
                  return "block" === e7 || "underline" === e7 || "bar" === e7;
                }(i5)) throw new Error(`"${i5}" is not a valid value for ${e6}`);
                break;
              case "wordSeparator":
                i5 || (i5 = t6.DEFAULT_OPTIONS[e6]);
                break;
              case "fontWeight":
              case "fontWeightBold":
                if ("number" == typeof i5 && 1 <= i5 && i5 <= 1e3) break;
                i5 = a2.includes(i5) ? i5 : t6.DEFAULT_OPTIONS[e6];
                break;
              case "cursorWidth":
                i5 = Math.floor(i5);
              case "lineHeight":
              case "tabStopWidth":
                if (i5 < 1) throw new Error(`${e6} cannot be less than 1, value: ${i5}`);
                break;
              case "minimumContrastRatio":
                i5 = Math.max(1, Math.min(21, Math.round(10 * i5) / 10));
                break;
              case "scrollback":
                if ((i5 = Math.min(i5, 4294967295)) < 0) throw new Error(`${e6} cannot be less than 0, value: ${i5}`);
                break;
              case "fastScrollSensitivity":
              case "scrollSensitivity":
                if (i5 <= 0) throw new Error(`${e6} cannot be less than or equal to 0, value: ${i5}`);
                break;
              case "rows":
              case "cols":
                if (!i5 && 0 !== i5) throw new Error(`${e6} must be numeric, value: ${i5}`);
                break;
              case "windowsPty":
                i5 = i5 ?? {};
            }
            return i5;
          }
        }
        t6.OptionsService = o3;
      }, 660: function(e5, t6, i4) {
        var s6 = this && this.__decorate || function(e6, t7, i5, s7) {
          var r7, n5 = arguments.length, a3 = n5 < 3 ? t7 : null === s7 ? s7 = Object.getOwnPropertyDescriptor(t7, i5) : s7;
          if ("object" == typeof Reflect && "function" == typeof Reflect.decorate) a3 = Reflect.decorate(e6, t7, i5, s7);
          else for (var o3 = e6.length - 1; o3 >= 0; o3--) (r7 = e6[o3]) && (a3 = (n5 < 3 ? r7(a3) : n5 > 3 ? r7(t7, i5, a3) : r7(t7, i5)) || a3);
          return n5 > 3 && a3 && Object.defineProperty(t7, i5, a3), a3;
        }, r6 = this && this.__param || function(e6, t7) {
          return function(i5, s7) {
            t7(i5, s7, e6);
          };
        };
        Object.defineProperty(t6, "__esModule", { value: true }), t6.OscLinkService = void 0;
        const n4 = i4(585);
        let a2 = t6.OscLinkService = class {
          constructor(e6) {
            this._bufferService = e6, this._nextId = 1, this._entriesWithId = /* @__PURE__ */ new Map(), this._dataByLinkId = /* @__PURE__ */ new Map();
          }
          registerLink(e6) {
            const t7 = this._bufferService.buffer;
            if (void 0 === e6.id) {
              const i6 = t7.addMarker(t7.ybase + t7.y), s8 = { data: e6, id: this._nextId++, lines: [i6] };
              return i6.onDispose(() => this._removeMarkerFromLink(s8, i6)), this._dataByLinkId.set(s8.id, s8), s8.id;
            }
            const i5 = e6, s7 = this._getEntryIdKey(i5), r7 = this._entriesWithId.get(s7);
            if (r7) return this.addLineToLink(r7.id, t7.ybase + t7.y), r7.id;
            const n5 = t7.addMarker(t7.ybase + t7.y), a3 = { id: this._nextId++, key: this._getEntryIdKey(i5), data: i5, lines: [n5] };
            return n5.onDispose(() => this._removeMarkerFromLink(a3, n5)), this._entriesWithId.set(a3.key, a3), this._dataByLinkId.set(a3.id, a3), a3.id;
          }
          addLineToLink(e6, t7) {
            const i5 = this._dataByLinkId.get(e6);
            if (i5 && i5.lines.every((e7) => e7.line !== t7)) {
              const e7 = this._bufferService.buffer.addMarker(t7);
              i5.lines.push(e7), e7.onDispose(() => this._removeMarkerFromLink(i5, e7));
            }
          }
          getLinkData(e6) {
            return this._dataByLinkId.get(e6)?.data;
          }
          _getEntryIdKey(e6) {
            return `${e6.id};;${e6.uri}`;
          }
          _removeMarkerFromLink(e6, t7) {
            const i5 = e6.lines.indexOf(t7);
            -1 !== i5 && (e6.lines.splice(i5, 1), 0 === e6.lines.length && (void 0 !== e6.data.id && this._entriesWithId.delete(e6.key), this._dataByLinkId.delete(e6.id)));
          }
        };
        t6.OscLinkService = a2 = s6([r6(0, n4.IBufferService)], a2);
      }, 343: (e5, t6) => {
        Object.defineProperty(t6, "__esModule", { value: true }), t6.createDecorator = t6.getServiceDependencies = t6.serviceRegistry = void 0;
        const i4 = "di$target", s6 = "di$dependencies";
        t6.serviceRegistry = /* @__PURE__ */ new Map(), t6.getServiceDependencies = function(e6) {
          return e6[s6] || [];
        }, t6.createDecorator = function(e6) {
          if (t6.serviceRegistry.has(e6)) return t6.serviceRegistry.get(e6);
          const r6 = /* @__PURE__ */ __name(function(e7, t7, n4) {
            if (3 !== arguments.length) throw new Error("@IServiceName-decorator can only be used to decorate a parameter");
            !function(e8, t8, r7) {
              t8[i4] === t8 ? t8[s6].push({ id: e8, index: r7 }) : (t8[s6] = [{ id: e8, index: r7 }], t8[i4] = t8);
            }(r6, e7, n4);
          }, "r");
          return r6.toString = () => e6, t6.serviceRegistry.set(e6, r6), r6;
        };
      }, 585: (e5, t6, i4) => {
        Object.defineProperty(t6, "__esModule", { value: true }), t6.IDecorationService = t6.IUnicodeService = t6.IOscLinkService = t6.IOptionsService = t6.ILogService = t6.LogLevelEnum = t6.IInstantiationService = t6.ICharsetService = t6.ICoreService = t6.ICoreMouseService = t6.IBufferService = void 0;
        const s6 = i4(343);
        var r6;
        t6.IBufferService = (0, s6.createDecorator)("BufferService"), t6.ICoreMouseService = (0, s6.createDecorator)("CoreMouseService"), t6.ICoreService = (0, s6.createDecorator)("CoreService"), t6.ICharsetService = (0, s6.createDecorator)("CharsetService"), t6.IInstantiationService = (0, s6.createDecorator)("InstantiationService"), function(e6) {
          e6[e6.TRACE = 0] = "TRACE", e6[e6.DEBUG = 1] = "DEBUG", e6[e6.INFO = 2] = "INFO", e6[e6.WARN = 3] = "WARN", e6[e6.ERROR = 4] = "ERROR", e6[e6.OFF = 5] = "OFF";
        }(r6 || (t6.LogLevelEnum = r6 = {})), t6.ILogService = (0, s6.createDecorator)("LogService"), t6.IOptionsService = (0, s6.createDecorator)("OptionsService"), t6.IOscLinkService = (0, s6.createDecorator)("OscLinkService"), t6.IUnicodeService = (0, s6.createDecorator)("UnicodeService"), t6.IDecorationService = (0, s6.createDecorator)("DecorationService");
      }, 480: (e5, t6, i4) => {
        Object.defineProperty(t6, "__esModule", { value: true }), t6.UnicodeService = void 0;
        const s6 = i4(460), r6 = i4(225);
        class n4 {
          static {
            __name(this, "n");
          }
          static extractShouldJoin(e6) {
            return 0 != (1 & e6);
          }
          static extractWidth(e6) {
            return e6 >> 1 & 3;
          }
          static extractCharKind(e6) {
            return e6 >> 3;
          }
          static createPropertyValue(e6, t7, i5 = false) {
            return (16777215 & e6) << 3 | (3 & t7) << 1 | (i5 ? 1 : 0);
          }
          constructor() {
            this._providers = /* @__PURE__ */ Object.create(null), this._active = "", this._onChange = new s6.EventEmitter(), this.onChange = this._onChange.event;
            const e6 = new r6.UnicodeV6();
            this.register(e6), this._active = e6.version, this._activeProvider = e6;
          }
          dispose() {
            this._onChange.dispose();
          }
          get versions() {
            return Object.keys(this._providers);
          }
          get activeVersion() {
            return this._active;
          }
          set activeVersion(e6) {
            if (!this._providers[e6]) throw new Error(`unknown Unicode version "${e6}"`);
            this._active = e6, this._activeProvider = this._providers[e6], this._onChange.fire(e6);
          }
          register(e6) {
            this._providers[e6.version] = e6;
          }
          wcwidth(e6) {
            return this._activeProvider.wcwidth(e6);
          }
          getStringCellWidth(e6) {
            let t7 = 0, i5 = 0;
            const s7 = e6.length;
            for (let r7 = 0; r7 < s7; ++r7) {
              let a2 = e6.charCodeAt(r7);
              if (55296 <= a2 && a2 <= 56319) {
                if (++r7 >= s7) return t7 + this.wcwidth(a2);
                const i6 = e6.charCodeAt(r7);
                56320 <= i6 && i6 <= 57343 ? a2 = 1024 * (a2 - 55296) + i6 - 56320 + 65536 : t7 += this.wcwidth(i6);
              }
              const o3 = this.charProperties(a2, i5);
              let h3 = n4.extractWidth(o3);
              n4.extractShouldJoin(o3) && (h3 -= n4.extractWidth(i5)), t7 += h3, i5 = o3;
            }
            return t7;
          }
          charProperties(e6, t7) {
            return this._activeProvider.charProperties(e6, t7);
          }
        }
        t6.UnicodeService = n4;
      }, 781: (e5, t6, i4) => {
        Object.defineProperty(t6, "__esModule", { value: true }), t6.Terminal = void 0;
        const s6 = i4(437), r6 = i4(969), n4 = i4(460);
        class a2 extends r6.CoreTerminal {
          static {
            __name(this, "a");
          }
          constructor(e6 = {}) {
            super(e6), this._onBell = this.register(new n4.EventEmitter()), this.onBell = this._onBell.event, this._onCursorMove = this.register(new n4.EventEmitter()), this.onCursorMove = this._onCursorMove.event, this._onTitleChange = this.register(new n4.EventEmitter()), this.onTitleChange = this._onTitleChange.event, this._onA11yCharEmitter = this.register(new n4.EventEmitter()), this.onA11yChar = this._onA11yCharEmitter.event, this._onA11yTabEmitter = this.register(new n4.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, n4.forwardEvent)(this._inputHandler.onCursorMove, this._onCursorMove)), this.register((0, n4.forwardEvent)(this._inputHandler.onTitleChange, this._onTitleChange)), this.register((0, n4.forwardEvent)(this._inputHandler.onA11yChar, this._onA11yCharEmitter)), this.register((0, n4.forwardEvent)(this._inputHandler.onA11yTab, this._onA11yTabEmitter));
          }
          get buffer() {
            return this.buffers.active;
          }
          get markers() {
            return this.buffer.markers;
          }
          addMarker(e6) {
            if (this.buffer === this.buffers.normal) return this.buffer.addMarker(this.buffer.ybase + this.buffer.y + e6);
          }
          bell() {
            this._onBell.fire();
          }
          input(e6, t7 = true) {
            this.coreService.triggerDataEvent(e6, t7);
          }
          resize(e6, t7) {
            e6 === this.cols && t7 === this.rows || super.resize(e6, t7);
          }
          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 e6 = 1; e6 < this.rows; e6++) this.buffer.lines.push(this.buffer.getBlankLine(s6.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();
          }
        }
        t6.Terminal = a2;
      } }, t5 = {};
      function i3(s6) {
        var r6 = t5[s6];
        if (void 0 !== r6) return r6.exports;
        var n4 = t5[s6] = { exports: {} };
        return e4[s6].call(n4.exports, n4, n4.exports, i3), n4.exports;
      }
      __name(i3, "i");
      var s5 = {};
      (() => {
        var e5 = s5;
        Object.defineProperty(e5, "__esModule", { value: true }), e5.Terminal = void 0;
        const t6 = i3(285), r6 = i3(975), n4 = i3(90), a2 = i3(781), o3 = i3(741), h3 = i3(844), c4 = ["cols", "rows"];
        class l3 extends h3.Disposable {
          static {
            __name(this, "l");
          }
          constructor(e6) {
            super(), this._core = this.register(new a2.Terminal(e6)), this._addonManager = this.register(new o3.AddonManager()), this._publicOptions = { ...this._core.options };
            const t7 = /* @__PURE__ */ __name((e7) => this._core.options[e7], "t"), i4 = /* @__PURE__ */ __name((e7, t8) => {
              this._checkReadonlyOptions(e7), this._core.options[e7] = t8;
            }, "i");
            for (const e7 in this._core.options) {
              Object.defineProperty(this._publicOptions, e7, { get: /* @__PURE__ */ __name(() => this._core.options[e7], "get"), set: /* @__PURE__ */ __name((t8) => {
                this._checkReadonlyOptions(e7), this._core.options[e7] = t8;
              }, "set") });
              const s6 = { get: t7.bind(this, e7), set: i4.bind(this, e7) };
              Object.defineProperty(this._publicOptions, e7, s6);
            }
          }
          _checkReadonlyOptions(e6) {
            if (c4.includes(e6)) throw new Error(`Option "${e6}" 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 r6.ParserApi(this._core)), this._parser;
          }
          get unicode() {
            return this._checkProposedApi(), new n4.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 t6.BufferNamespaceApi(this._core))), this._buffer;
          }
          get markers() {
            return this._checkProposedApi(), this._core.markers;
          }
          get modes() {
            const e6 = this._core.coreService.decPrivateModes;
            let t7 = "none";
            switch (this._core.coreMouseService.activeProtocol) {
              case "X10":
                t7 = "x10";
                break;
              case "VT200":
                t7 = "vt200";
                break;
              case "DRAG":
                t7 = "drag";
                break;
              case "ANY":
                t7 = "any";
            }
            return { applicationCursorKeysMode: e6.applicationCursorKeys, applicationKeypadMode: e6.applicationKeypad, bracketedPasteMode: e6.bracketedPasteMode, insertMode: this._core.coreService.modes.insertMode, mouseTrackingMode: t7, originMode: e6.origin, reverseWraparoundMode: e6.reverseWraparound, sendFocusMode: e6.sendFocus, wraparoundMode: e6.wraparound };
          }
          get options() {
            return this._publicOptions;
          }
          set options(e6) {
            for (const t7 in e6) this._publicOptions[t7] = e6[t7];
          }
          input(e6, t7 = true) {
            this._core.input(e6, t7);
          }
          resize(e6, t7) {
            this._verifyIntegers(e6, t7), this._core.resize(e6, t7);
          }
          registerMarker(e6 = 0) {
            return this._checkProposedApi(), this._verifyIntegers(e6), this._core.addMarker(e6);
          }
          addMarker(e6) {
            return this.registerMarker(e6);
          }
          dispose() {
            super.dispose();
          }
          scrollLines(e6) {
            this._verifyIntegers(e6), this._core.scrollLines(e6);
          }
          scrollPages(e6) {
            this._verifyIntegers(e6), this._core.scrollPages(e6);
          }
          scrollToTop() {
            this._core.scrollToTop();
          }
          scrollToBottom() {
            this._core.scrollToBottom();
          }
          scrollToLine(e6) {
            this._verifyIntegers(e6), this._core.scrollToLine(e6);
          }
          clear() {
            this._core.clear();
          }
          write(e6, t7) {
            this._core.write(e6, t7);
          }
          writeln(e6, t7) {
            this._core.write(e6), this._core.write("\r\n", t7);
          }
          reset() {
            this._core.reset();
          }
          loadAddon(e6) {
            this._addonManager.loadAddon(this, e6);
          }
          _verifyIntegers(...e6) {
            for (const t7 of e6) if (t7 === 1 / 0 || isNaN(t7) || t7 % 1 != 0) throw new Error("This API only accepts integers");
          }
        }
        e5.Terminal = l3;
      })();
      var r5 = exports2;
      for (var n3 in s5) r5[n3] = s5[n3];
      s5.__esModule && Object.defineProperty(r5, "__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 y2 = 0; y2 < terminal.rows; y2++) {
    const line = buffer.getLine(buffer.viewportY + y2);
    const currentLine = [];
    if (!line) {
      result.push(currentLine);
      continue;
    }
    let lastCell = new Cell(null, -1, -1, cursorX, cursorY);
    let currentText = "";
    for (let x3 = 0; x3 < terminal.cols; x3++) {
      const cellData = line.getCell(x3);
      const cell = new Cell(cellData || null, x3, y2, cursorX, cursorY);
      if (x3 > 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 r5 = color >> 16 & 255;
    const g2 = color >> 8 & 255;
    const b2 = color & 255;
    return `#${r5.toString(16).padStart(2, "0")}${g2.toString(16).padStart(2, "0")}${b2.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, x3, y2, cursorX, cursorY) {
        this.cell = cell;
        this.x = x3;
        this.y = y2;
        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, spawnSync as spawnSync2 } from "node:child_process";
import { TextDecoder as TextDecoder2 } from "node:util";
import os11 from "node:os";
var import_headless, Terminal, SIGKILL_TIMEOUT_MS, getFullBufferText, windowsStrategy, posixStrategy, getCleanupStrategy, 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 i3 = 0; i3 < buffer.length; i3++) {
        const line = buffer.getLine(i3);
        const lineContent = line ? line.translateToString() : "";
        lines.push(lineContent);
      }
      return lines.join("\n").trimEnd();
    }, "getFullBufferText");
    windowsStrategy = {
      killPty: /* @__PURE__ */ __name((_pid, pty) => {
        pty.ptyProcess.kill();
      }, "killPty"),
      killChildProcesses: /* @__PURE__ */ __name((pids) => {
        if (pids.size > 0) {
          try {
            const args = ["/f", "/t"];
            for (const pid of pids) {
              args.push("/pid", pid.toString());
            }
            spawnSync2("taskkill", args);
          } catch {
          }
        }
      }, "killChildProcesses")
    };
    posixStrategy = {
      killPty: /* @__PURE__ */ __name((pid, _pty) => {
        process.kill(-pid, "SIGKILL");
      }, "killPty"),
      killChildProcesses: /* @__PURE__ */ __name((pids) => {
        for (const pid of pids) {
          try {
            process.kill(-pid, "SIGKILL");
          } catch {
          }
        }
      }, "killChildProcesses")
    };
    getCleanupStrategy = /* @__PURE__ */ __name(() => os11.platform() === "win32" ? windowsStrategy : posixStrategy, "getCleanupStrategy");
    ShellExecutionService = class _ShellExecutionService {
      static {
        __name(this, "ShellExecutionService");
      }
      static activePtys = /* @__PURE__ */ new Map();
      static activeChildProcesses = /* @__PURE__ */ new Set();
      static cleanup() {
        const strategy = getCleanupStrategy();
        for (const [pid, pty] of this.activePtys) {
          try {
            strategy.killPty(pid, pty);
          } catch {
          }
        }
        strategy.killChildProcesses(this.activeChildProcesses);
      }
      static {
        process.on("exit", () => {
          _ShellExecutionService.cleanup();
        });
      }
      /**
       * 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 (_e2) {
            }
          }
        }
        return this.childProcessFallback(commandToExecute, cwd7, onOutputEvent, abortSignal);
      }
      static childProcessFallback(commandToExecute, cwd7, onOutputEvent, abortSignal) {
        try {
          const isWindows9 = os11.platform() === "win32";
          const shell2 = isWindows9 ? "cmd.exe" : "bash";
          const shellArgs = isWindows9 ? ["/c", commandToExecute] : ["-c", commandToExecute];
          const child = cpSpawn(shell2, shellArgs, {
            cwd: cwd7,
            stdio: ["ignore", "pipe", "pipe"],
            windowsVerbatimArguments: isWindows9,
            detached: !isWindows9,
            windowsHide: isWindows9,
            env: {
              ...process.env,
              QWEN_CODE: "1",
              TERM: "xterm-256color",
              PAGER: "cat"
            }
          });
          const result = new Promise((resolve30) => {
            let stdoutDecoder = null;
            let stderrDecoder = null;
            let stdout = "";
            let stderr = "";
            const outputChunks = [];
            let error2 = 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" });
              }
              resolve30({
                rawOutput: finalBuffer,
                output: finalStrippedOutput,
                exitCode: code2,
                signal: signal ? os11.constants.signals[signal] : null,
                error: error2,
                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) => {
              error2 = err;
              handleExit(1, null);
            });
            const abortHandler = /* @__PURE__ */ __name(async () => {
              if (child.pid && !exited) {
                if (isWindows9) {
                  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 (_e2) {
                    if (!exited)
                      child.kill("SIGKILL");
                  }
                }
              }
            }, "abortHandler");
            abortSignal.addEventListener("abort", abortHandler, { once: true });
            if (child.pid) {
              this.activeChildProcesses.add(child.pid);
            }
            child.on("exit", (code2, signal) => {
              if (child.pid) {
                this.activeChildProcesses.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: child.pid, result };
        } catch (e4) {
          const error2 = e4;
          return {
            pid: void 0,
            result: Promise.resolve({
              error: error2,
              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 isWindows9 = os11.platform() === "win32";
          const shell2 = isWindows9 ? "cmd.exe" : "bash";
          const args = isWindows9 ? `/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((resolve30) => {
            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 error2 = 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 y2 = 0; y2 < headlessTerminal.rows; y2++) {
                    const line = buffer.getLine(buffer.viewportY + y2);
                    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 i3 = newOutput.length - 1; i3 >= 0; i3--) {
                  const line = newOutput[i3];
                  if (line.map((segment) => segment.text).join("").trim().length > 0) {
                    lastNonEmptyLine = i3;
                    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((resolve31) => {
                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;
                    resolve31();
                  });
                } else {
                  const totalBytes = outputChunks.reduce((sum, chunk) => sum + chunk.length, 0);
                  onOutputEvent({
                    type: "binary_progress",
                    bytesReceived: totalBytes
                  });
                  resolve31();
                }
              }));
            }, "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);
                resolve30({
                  rawOutput: finalBuffer,
                  output: getFullBufferText(headlessTerminal),
                  exitCode,
                  signal: signal ?? null,
                  error: error2,
                  aborted: abortSignal.aborted,
                  pid: ptyProcess.pid,
                  executionMethod: ptyInfo?.name ?? "node-pty"
                });
              });
            });
            const abortHandler = /* @__PURE__ */ __name(async () => {
              if (ptyProcess.pid && !exited) {
                if (os11.platform() === "win32") {
                  ptyProcess.kill();
                } else {
                  try {
                    process.kill(-ptyProcess.pid, "SIGINT");
                  } catch (_e2) {
                    ptyProcess.kill("SIGINT");
                  }
                }
              }
            }, "abortHandler");
            abortSignal.addEventListener("abort", abortHandler, { once: true });
          });
          return { pid: ptyProcess.pid, result };
        } catch (e4) {
          const error2 = e4;
          return {
            pid: void 0,
            result: Promise.resolve({
              error: error2,
              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 (_2) {
          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 (e4) {
            if (e4 instanceof Error && "code" in e4 && e4.code === "ESRCH") {
            } else {
              throw e4;
            }
          }
        }
      }
      /**
       * 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 (e4) {
            if (e4 instanceof Error && "code" in e4 && e4.code === "ESRCH") {
            } else {
              throw e4;
            }
          }
        }
      }
    };
  }
});

// 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(s5) {
        if (s5 === "") {
          return "''";
        }
        if (s5 && typeof s5 === "object") {
          return s5.op.replace(/(.)/g, "\\$1");
        }
        if (/["\s\\]/.test(s5) && !/'/.test(s5)) {
          return "'" + s5.replace(/(['])/g, "\\$1") + "'";
        }
        if (/["'\s]/.test(s5)) {
          return '"' + s5.replace(/(["\\$`!])/g, "\\$1") + '"';
        }
        return String(s5).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 (i3 = 0; i3 < 4; i3++) {
      TOKEN += (mult * Math.random()).toString(16);
    }
    var i3;
    var startsWithToken = new RegExp("^" + TOKEN);
    function matchAll(s5, r5) {
      var origIndex = r5.lastIndex;
      var matches = [];
      var matchObj;
      while (matchObj = r5.exec(s5)) {
        matches.push(matchObj);
        if (r5.lastIndex === matchObj.index) {
          r5.lastIndex += 1;
        }
      }
      r5.lastIndex = origIndex;
      return matches;
    }
    __name(matchAll, "matchAll");
    function getVar(env7, pre, key) {
      var r5 = typeof env7 === "function" ? env7(key) : env7[key];
      if (typeof r5 === "undefined" && key != "") {
        r5 = "";
      } else if (typeof r5 === "undefined") {
        r5 = "$";
      }
      if (typeof r5 === "object") {
        return pre + TOKEN + JSON.stringify(r5) + TOKEN;
      }
      return pre + r5;
    }
    __name(getVar, "getVar");
    function parseInternal(string4, 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(string4, chunker);
      if (matches.length === 0) {
        return [];
      }
      if (!env7) {
        env7 = {};
      }
      var commented = false;
      return matches.map(function(match2) {
        var s5 = match2[0];
        if (!s5 || commented) {
          return void 0;
        }
        if (controlRE.test(s5)) {
          return { op: s5 };
        }
        var quote3 = false;
        var esc2 = false;
        var out = "";
        var isGlob = false;
        var i4;
        function parseEnvVar() {
          i4 += 1;
          var varend;
          var varname;
          var char = s5.charAt(i4);
          if (char === "{") {
            i4 += 1;
            if (s5.charAt(i4) === "}") {
              throw new Error("Bad substitution: " + s5.slice(i4 - 2, i4 + 1));
            }
            varend = s5.indexOf("}", i4);
            if (varend < 0) {
              throw new Error("Bad substitution: " + s5.slice(i4));
            }
            varname = s5.slice(i4, varend);
            i4 = varend;
          } else if (/[*@#?$!_-]/.test(char)) {
            varname = char;
            i4 += 1;
          } else {
            var slicedFromI = s5.slice(i4);
            varend = slicedFromI.match(/[^\w\d_]/);
            if (!varend) {
              varname = slicedFromI;
              i4 = s5.length;
            } else {
              varname = slicedFromI.slice(0, varend.index);
              i4 += varend.index - 1;
            }
          }
          return getVar(env7, "", varname);
        }
        __name(parseEnvVar, "parseEnvVar");
        for (i4 = 0; i4 < s5.length; i4++) {
          var c4 = s5.charAt(i4);
          isGlob = isGlob || !quote3 && (c4 === "*" || c4 === "?");
          if (esc2) {
            out += c4;
            esc2 = false;
          } else if (quote3) {
            if (c4 === quote3) {
              quote3 = false;
            } else if (quote3 == SQ) {
              out += c4;
            } else {
              if (c4 === BS) {
                i4 += 1;
                c4 = s5.charAt(i4);
                if (c4 === DQ || c4 === BS || c4 === DS) {
                  out += c4;
                } else {
                  out += BS + c4;
                }
              } else if (c4 === DS) {
                out += parseEnvVar();
              } else {
                out += c4;
              }
            }
          } else if (c4 === DQ || c4 === SQ) {
            quote3 = c4;
          } else if (controlRE.test(c4)) {
            return { op: s5 };
          } else if (hash.test(c4)) {
            commented = true;
            var commentObj = { comment: string4.slice(match2.index + i4 + 1) };
            if (out.length) {
              return [out, commentObj];
            }
            return [commentObj];
          } else if (c4 === BS) {
            esc2 = true;
          } else if (c4 === DS) {
            out += parseEnvVar();
          } else {
            out += c4;
          }
        }
        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 parse14(s5, env7, opts) {
      var mapped = parseInternal(s5, env7, opts);
      if (typeof env7 !== "function") {
        return mapped;
      }
      return mapped.reduce(function(acc, s6) {
        if (typeof s6 === "object") {
          return acc.concat(s6);
        }
        var xs = s6.split(RegExp("(" + TOKEN + ".*?" + TOKEN + ")", "g"));
        if (xs.length === 1) {
          return acc.concat(xs[0]);
        }
        return acc.concat(xs.filter(Boolean).map(function(x3) {
          if (startsWithToken.test(x3)) {
            return JSON.parse(x3.split(TOKEN)[1]);
          }
          return x3;
        }));
      }, []);
    }, "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 lower3 = token2.toLowerCase();
    if (BLOCKED_FIND_FLAGS.has(lower3)) {
      return false;
    }
    if (BLOCKED_FIND_PREFIXES.some((prefix) => lower3.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;
    }
  }
  const scriptContent = rest.join(" ");
  for (const pattern of SED_SIDE_EFFECT_PATTERNS) {
    if (pattern.test(scriptContent)) {
      return false;
    }
  }
  return true;
}
function evaluateAwkCommand(tokens) {
  const [, ...rest] = tokens;
  const scriptContent = rest.join(" ");
  for (const pattern of AWK_SIDE_EFFECT_PATTERNS) {
    if (pattern.test(scriptContent)) {
      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 === "awk") {
    return evaluateAwkCommand([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) {
    if (!evaluateShellSegment(segment)) {
      return false;
    }
  }
  return segments.length > 0;
}
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, AWK_SIDE_EFFECT_PATTERNS, SED_SIDE_EFFECT_PATTERNS, 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"];
    AWK_SIDE_EFFECT_PATTERNS = [
      /system\s*\(/,
      // system() function calls
      /print\s+[^>|]*>\s*"[^"]*"/,
      // print > "file"
      /printf\s+[^>|]*>\s*"[^"]*"/,
      // printf > "file"
      /print\s+[^>|]*>>\s*"[^"]*"/,
      // print >> "file"
      /printf\s+[^>|]*>>\s*"[^"]*"/,
      // printf >> "file"
      /print\s+[^|]*\|\s*"[^"]*"/,
      // print | "command"
      /printf\s+[^|]*\|\s*"[^"]*"/,
      // printf | "command"
      /getline\s*<\s*"[^"]*"/,
      // getline < "command"
      /"[^"]*"\s*\|\s*getline/,
      // "command" | getline
      /close\s*\(/
      // close() can trigger command execution
    ];
    SED_SIDE_EFFECT_PATTERNS = [
      /[^\\]e\s/,
      // e command (execute)
      /^e\s/,
      // e command at start
      /[^\\]w\s/,
      // w command (write)
      /^w\s/,
      // w command at start
      /[^\\]r\s/,
      // r command (read file)
      /^r\s/
      // r command at start
    ];
    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(evaluateAwkCommand, "evaluateAwkCommand");
    __name(evaluateGitRemoteArgs, "evaluateGitRemoteArgs");
    __name(evaluateGitBranchArgs, "evaluateGitBranchArgs");
    __name(evaluateGitCommand, "evaluateGitCommand");
    __name(evaluateShellSegment, "evaluateShellSegment");
    __name(isShellCommandReadOnly, "isShellCommandReadOnly");
  }
});

// packages/core/dist/src/utils/shell-utils.js
import os12 from "node:os";
import { execFile as execFile6, execFileSync as execFileSync2 } from "node:child_process";
import { accessSync, constants as fsConstants3 } from "node:fs";
function getShellConfiguration() {
  if (isWindows()) {
    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 i3 = 0;
  while (i3 < command2.length) {
    const char = command2[i3];
    const nextChar = command2[i3 + 1];
    if (char === "\\" && i3 < command2.length - 1) {
      currentCommand += char + command2[i3 + 1];
      i3 += 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 = "";
        i3++;
      } else if (char === ";" || char === "&" || char === "|") {
        commands.push(currentCommand.trim());
        currentCommand = "";
      } else if (char === "\r" && nextChar === "\n") {
        commands.push(currentCommand.trim());
        currentCommand = "";
        i3++;
      } else if (char === "\n") {
        commands.push(currentCommand.trim());
        currentCommand = "";
      } else {
        currentCommand += char;
      }
    } else {
      currentCommand += char;
    }
    i3++;
  }
  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((c4) => getCommandRoot(c4)).filter((c4) => !!c4);
}
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) {
  const isCommentStart = /* @__PURE__ */ __name((index) => {
    if (command2[index] !== "#")
      return false;
    if (index === 0)
      return true;
    const prev = command2[index - 1];
    if (prev === " " || prev === "	" || prev === "\n" || prev === "\r") {
      return true;
    }
    return [";", "&", "|", "(", ")", "<", ">"].includes(prev);
  }, "isCommentStart");
  const isWordBoundary = /* @__PURE__ */ __name((char) => {
    if (char === " " || char === "	" || char === "\n" || char === "\r") {
      return true;
    }
    return [";", "&", "|", "<", ">", "(", ")"].includes(char);
  }, "isWordBoundary");
  const parseHeredocOperator = /* @__PURE__ */ __name((startIndex) => {
    if (command2[startIndex] !== "<" || command2[startIndex + 1] !== "<") {
      return null;
    }
    let i4 = startIndex + 2;
    const stripLeadingTabs = command2[i4] === "-";
    if (stripLeadingTabs)
      i4++;
    while (i4 < command2.length && (command2[i4] === " " || command2[i4] === "	")) {
      i4++;
    }
    let delimiter2 = "";
    let isQuotedDelimiter = false;
    let inSingleQuotes2 = false;
    let inDoubleQuotes2 = false;
    while (i4 < command2.length) {
      const char = command2[i4];
      if (!inSingleQuotes2 && !inDoubleQuotes2 && isWordBoundary(char)) {
        break;
      }
      if (!inSingleQuotes2 && !inDoubleQuotes2) {
        if (char === "'") {
          isQuotedDelimiter = true;
          inSingleQuotes2 = true;
          i4++;
          continue;
        }
        if (char === '"') {
          isQuotedDelimiter = true;
          inDoubleQuotes2 = true;
          i4++;
          continue;
        }
        if (char === "\\") {
          isQuotedDelimiter = true;
          i4++;
          if (i4 >= command2.length)
            break;
          delimiter2 += command2[i4];
          i4++;
          continue;
        }
        delimiter2 += char;
        i4++;
        continue;
      }
      if (inSingleQuotes2) {
        if (char === "'") {
          inSingleQuotes2 = false;
          i4++;
          continue;
        }
        delimiter2 += char;
        i4++;
        continue;
      }
      if (char === '"') {
        inDoubleQuotes2 = false;
        i4++;
        continue;
      }
      if (char === "\\") {
        isQuotedDelimiter = true;
        i4++;
        if (i4 >= command2.length)
          break;
        delimiter2 += command2[i4];
        i4++;
        continue;
      }
      delimiter2 += char;
      i4++;
    }
    if (delimiter2.length === 0) {
      return null;
    }
    return {
      nextIndex: i4,
      heredoc: {
        delimiter: delimiter2,
        isQuotedDelimiter,
        stripLeadingTabs
      }
    };
  }, "parseHeredocOperator");
  const lineHasCommandSubstitution = /* @__PURE__ */ __name((line) => {
    for (let i4 = 0; i4 < line.length; i4++) {
      const char = line[i4];
      const nextChar = line[i4 + 1];
      if (char === "\\") {
        i4++;
        continue;
      }
      if (char === "$" && nextChar === "(") {
        return true;
      }
      if (char === "`") {
        return true;
      }
    }
    return false;
  }, "lineHasCommandSubstitution");
  const consumeHeredocBodies = /* @__PURE__ */ __name((startIndex, pending) => {
    let i4 = startIndex;
    for (const heredoc of pending) {
      let pendingDollarLineContinuation = false;
      while (i4 <= command2.length) {
        const lineStart = i4;
        while (i4 < command2.length && command2[i4] !== "\n" && command2[i4] !== "\r") {
          i4++;
        }
        const lineEnd = i4;
        let newlineLength = 0;
        if (i4 < command2.length && command2[i4] === "\r" && command2[i4 + 1] === "\n") {
          newlineLength = 2;
        } else if (i4 < command2.length && (command2[i4] === "\n" || command2[i4] === "\r")) {
          newlineLength = 1;
        }
        const rawLine = command2.slice(lineStart, lineEnd);
        const effectiveLine = heredoc.stripLeadingTabs ? rawLine.replace(/^\t+/, "") : rawLine;
        if (effectiveLine === heredoc.delimiter) {
          i4 = lineEnd + newlineLength;
          break;
        }
        if (!heredoc.isQuotedDelimiter) {
          if (pendingDollarLineContinuation && effectiveLine.startsWith("(")) {
            return { nextIndex: i4, hasSubstitution: true };
          }
          if (lineHasCommandSubstitution(effectiveLine)) {
            return { nextIndex: i4, hasSubstitution: true };
          }
          pendingDollarLineContinuation = false;
          if (newlineLength > 0 && rawLine.length >= 2 && rawLine.endsWith("\\") && rawLine[rawLine.length - 2] === "$") {
            let backslashCount = 0;
            for (let j2 = rawLine.length - 3; j2 >= 0 && rawLine[j2] === "\\"; j2--) {
              backslashCount++;
            }
            const isEscapedDollar = backslashCount % 2 === 1;
            pendingDollarLineContinuation = !isEscapedDollar;
          }
        }
        i4 = lineEnd + newlineLength;
        if (newlineLength === 0) {
          break;
        }
      }
    }
    return { nextIndex: i4, hasSubstitution: false };
  }, "consumeHeredocBodies");
  let inSingleQuotes = false;
  let inDoubleQuotes = false;
  let inBackticks = false;
  let inComment = false;
  const pendingHeredocs = [];
  let i3 = 0;
  while (i3 < command2.length) {
    const char = command2[i3];
    const nextChar = command2[i3 + 1];
    if (!inSingleQuotes && !inDoubleQuotes && !inBackticks) {
      if (char === "\r" && nextChar === "\n") {
        inComment = false;
        if (pendingHeredocs.length > 0) {
          const result = consumeHeredocBodies(i3 + 2, pendingHeredocs);
          if (result.hasSubstitution)
            return true;
          pendingHeredocs.length = 0;
          i3 = result.nextIndex;
          continue;
        }
      } else if (char === "\n" || char === "\r") {
        inComment = false;
        if (pendingHeredocs.length > 0) {
          const result = consumeHeredocBodies(i3 + 1, pendingHeredocs);
          if (result.hasSubstitution)
            return true;
          pendingHeredocs.length = 0;
          i3 = result.nextIndex;
          continue;
        }
      }
    }
    if (!inSingleQuotes && !inDoubleQuotes && !inBackticks) {
      if (!inComment && isCommentStart(i3)) {
        inComment = true;
        i3++;
        continue;
      }
      if (inComment) {
        i3++;
        continue;
      }
    }
    if (char === "\\" && !inSingleQuotes) {
      i3 += 2;
      continue;
    }
    if (char === "'" && !inDoubleQuotes && !inBackticks) {
      inSingleQuotes = !inSingleQuotes;
    } else if (char === '"' && !inSingleQuotes && !inBackticks) {
      inDoubleQuotes = !inDoubleQuotes;
    } else if (char === "`" && !inSingleQuotes) {
      inBackticks = !inBackticks;
    }
    if (!inSingleQuotes && !inDoubleQuotes && !inBackticks && char === "<" && nextChar === "<") {
      const parsed = parseHeredocOperator(i3);
      if (parsed) {
        pendingHeredocs.push(parsed.heredoc);
        i3 = parsed.nextIndex;
        continue;
      }
    }
    if (!inSingleQuotes) {
      if (char === "$" && nextChar === "(") {
        return true;
      }
      if (char === "<" && nextChar === "(" && !inDoubleQuotes && !inBackticks) {
        return true;
      }
      if (char === ">" && nextChar === "(" && !inDoubleQuotes && !inBackticks) {
        return true;
      }
      if (char === "`") {
        return true;
      }
    }
    i3++;
  }
  return false;
}
function checkCommandPermissions(command2, config2, sessionAllowlist) {
  if (detectCommandSubstitution(command2)) {
    return {
      allAllowed: false,
      disallowedCommands: [command2],
      blockReason: "Command substitution using $(), `` ` ``, <(), or >() is not allowed for security reasons",
      isHardDenial: true
    };
  }
  const normalize12 = /* @__PURE__ */ __name((cmd) => cmd.trim().replace(/\s+/g, " "), "normalize");
  const commandsToValidate = splitCommands(command2).map(normalize12);
  const invocation = {
    params: { command: "" }
  };
  const excludeTools = config2.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 = config2.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((c4) => JSON.stringify(c4)).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((c4) => JSON.stringify(c4)).join(", ")}`,
          isHardDenial: false
          // This is a soft denial.
        };
      }
    }
  }
  return { allAllowed: true, disallowedCommands: [] };
}
function execCommand(command2, args, options2 = {}) {
  return new Promise((resolve30, reject) => {
    const child = execFile6(command2, args, { encoding: "utf8", ...options2 }, (error2, stdout, stderr) => {
      if (error2) {
        if (!options2.preserveOutputOnError) {
          reject(error2);
        } else {
          resolve30({
            stdout: stdout ?? "",
            stderr: stderr ?? "",
            code: typeof error2.code === "number" ? error2.code : 1
          });
        }
        return;
      }
      resolve30({ stdout: stdout ?? "", stderr: stderr ?? "", code: 0 });
    });
    child.on("error", reject);
  });
}
function resolveCommandPath(command2) {
  try {
    const isWin = process.platform === "win32";
    if (isWin) {
      const checkCommand = "where.exe";
      const checkArgs = [command2];
      let result = null;
      try {
        result = execFileSync2(checkCommand, checkArgs, {
          encoding: "utf8",
          shell: false
        }).trim();
      } catch {
        return { path: null, error: void 0 };
      }
      return result ? { path: result } : { path: null };
    } else {
      const shell2 = "/bin/sh";
      const checkArgs = ["-c", `command -v ${escapeShellArg(command2, "bash")}`];
      let result = null;
      try {
        result = execFileSync2(shell2, checkArgs, {
          encoding: "utf8",
          shell: false
        }).trim();
      } catch {
        return { path: null, error: void 0 };
      }
      if (!result)
        return { path: null, error: void 0 };
      accessSync(result, fsConstants3.X_OK);
      return { path: result, error: void 0 };
    }
  } catch (error2) {
    return {
      path: null,
      error: error2 instanceof Error ? error2 : new Error(String(error2))
    };
  }
}
function isCommandAvailable(command2) {
  const { path: path125, error: error2 } = resolveCommandPath(command2);
  return { available: path125 !== null, error: error2 };
}
function isCommandAllowed(command2, config2) {
  const { allAllowed, blockReason } = checkCommandPermissions(command2, config2);
  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, isWindows;
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");
    isWindows = /* @__PURE__ */ __name(() => os12.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 fs24 from "node:fs";
import path17 from "node:path";
import os13, { EOL } from "node:os";
import crypto6 from "node:crypto";
function getShellToolDescription() {
  const isWindows9 = os13.platform() === "win32";
  const executionWrapper = isWindows9 ? "cmd.exe /c <command>" : "bash -c <command>";
  const processGroupNote = isWindows9 ? "" : "\n  - 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`.";
  return `Executes a given shell command (as \`${executionWrapper}\`) in a persistent shell session with optional timeout, ensuring proper handling and security measures.

IMPORTANT: This tool is for terminal operations like git, npm, docker, etc. DO NOT use it for file operations (reading, writing, editing, searching, finding files) - use the specialized tools for this instead.

**Usage notes**:
- The command argument is required.
- You can specify an optional timeout in milliseconds (up to 600000ms / 10 minutes). If not specified, commands will timeout after 120000ms (2 minutes).
- It is very helpful if you write a clear, concise description of what this command does in 5-10 words.

- Avoid using run_shell_command with the \`find\`, \`grep\`, \`cat\`, \`head\`, \`tail\`, \`sed\`, \`awk\`, or \`echo\` commands, unless explicitly instructed or when these commands are truly necessary for the task. Instead, always prefer using the dedicated tools for these commands:
  - File search: Use ${ToolNames.GLOB} (NOT find or ls)
  - Content search: Use ${ToolNames.GREP} (NOT grep or rg)
  - Read files: Use ${ToolNames.READ_FILE} (NOT cat/head/tail)
  - Edit files: Use ${ToolNames.EDIT} (NOT sed/awk)
  - Write files: Use ${ToolNames.WRITE_FILE} (NOT echo >/cat <<EOF)
  - Communication: Output text directly (NOT echo/printf)
- When issuing multiple commands:
  - If the commands are independent and can run in parallel, make multiple run_shell_command tool calls in a single message. For example, if you need to run "git status" and "git diff", send a single message with two run_shell_command tool calls in parallel.
  - If the commands depend on each other and must run sequentially, use a single run_shell_command call with '&&' to chain them together (e.g., \`git add . && git commit -m "message" && git push\`). For instance, if one operation must complete before another starts (like mkdir before cp, Write before run_shell_command for git operations, or git add before git commit), run these operations sequentially instead.
  - Use ';' only when you need to run commands sequentially but don't care if earlier commands fail
  - DO NOT use newlines to separate commands (newlines are ok in quoted strings)
- Try to maintain your current working directory throughout the session by using absolute paths and avoiding usage of \`cd\`. You may use \`cd\` if the User explicitly requests it.
  <good-example>
  pytest /foo/bar/tests
  </good-example>
  <bad-example>
  cd /foo/bar && pytest tests
  </bad-example>

**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
${processGroupNote}
- 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\`
`;
}
function getCommandDescription() {
  const cmd_substitution_warning = "\n*** WARNING: Command substitution using $(), `` ` ``, <(), or >() is not allowed for security reasons.";
  if (os13.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 debugLogger25, OUTPUT_UPDATE_INTERVAL_MS, DEFAULT_FOREGROUND_TIMEOUT_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_paths();
    init_shell_utils();
    init_debugLogger();
    debugLogger25 = createDebugLogger("SHELL");
    OUTPUT_UPDATE_INTERVAL_MS = 1e3;
    DEFAULT_FOREGROUND_TIMEOUT_MS = 12e4;
    ShellToolInvocation = class extends BaseToolInvocation {
      static {
        __name(this, "ShellToolInvocation");
      }
      config;
      allowlist;
      constructor(config2, params, allowlist) {
        super(params);
        this.config = config2;
        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]`;
        } else if (this.params.timeout) {
          description += ` [timeout: ${this.params.timeout}ms]`;
        }
        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, _payload) => {
            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 effectiveTimeout = this.params.is_background ? void 0 : this.params.timeout ?? DEFAULT_FOREGROUND_TIMEOUT_MS;
        let combinedSignal = signal;
        if (effectiveTimeout) {
          const timeoutSignal = AbortSignal.timeout(effectiveTimeout);
          combinedSignal = AbortSignal.any([signal, timeoutSignal]);
        }
        const isWindows9 = os13.platform() === "win32";
        const tempFileName = `shell_pgrep_${crypto6.randomBytes(6).toString("hex")}.tmp`;
        const tempFilePath = path17.join(os13.tmpdir(), tempFileName);
        try {
          const processedCommand = this.addCoAuthorToGitCommit(strippedCommand);
          const shouldRunInBackground = this.params.is_background;
          let finalCommand = processedCommand;
          if (!isWindows9 && shouldRunInBackground && !finalCommand.trim().endsWith("&")) {
            finalCommand = finalCommand.trim() + " &";
          }
          if (isWindows9 && shouldRunInBackground) {
            finalCommand = finalCommand.trim().replace(/&+$/, "").trim();
          }
          const commandToExecute = isWindows9 ? 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) => {
            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) {
              updateOutput2(typeof cumulativeOutput === "string" ? cumulativeOutput : { ansiOutput: cumulativeOutput });
              lastUpdateTime = Date.now();
            }
          }, combinedSignal, this.config.getShouldUseNodePtyShell(), shellExecutionConfig ?? {});
          if (pid && setPidCallback) {
            setPidCallback(pid);
          }
          if (shouldRunInBackground) {
            const pidMsg = pid ? ` PID: ${pid}` : "";
            const killHint = isWindows9 ? " (Use taskkill /F /T /PID <pid> to stop)" : " (Use kill <pid> to stop)";
            return {
              llmContent: `Background command started.${pidMsg}${killHint}`,
              returnDisplay: `Background command started.${pidMsg}${killHint}`
            };
          }
          const result = await resultPromise;
          const backgroundPIDs = [];
          if (os13.platform() !== "win32") {
            if (fs24.existsSync(tempFilePath)) {
              const pgrepLines = fs24.readFileSync(tempFilePath, "utf8").split(EOL).filter(Boolean);
              for (const line of pgrepLines) {
                if (!/^\d+$/.test(line)) {
                  debugLogger25.warn(`pgrep: ${line}`);
                }
                const pid2 = Number(line);
                if (pid2 !== result.pid) {
                  backgroundPIDs.push(pid2);
                }
              }
            } else {
              if (!signal.aborted) {
                debugLogger25.warn("missing pgrep output");
              }
            }
          }
          let llmContent = "";
          if (result.aborted) {
            const wasTimeout = !this.params.is_background && effectiveTimeout && combinedSignal.aborted && !signal.aborted;
            if (wasTimeout) {
              llmContent = `Command timed out after ${effectiveTimeout}ms before it could complete.`;
              if (result.output.trim()) {
                llmContent += ` Below is the output before it timed out:
${result.output}`;
              } else {
                llmContent += " There was no output before it timed out.";
              }
            } else {
              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) {
                const wasTimeout = !this.params.is_background && effectiveTimeout && combinedSignal.aborted && !signal.aborted;
                returnDisplayMessage = wasTimeout ? `Command timed out after ${effectiveTimeout}ms.` : "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 (fs24.existsSync(tempFilePath)) {
            fs24.unlinkSync(tempFilePath);
          }
        }
      }
      addCoAuthorToGitCommit(command2) {
        const gitCoAuthorSettings = this.config.getGitCoAuthor();
        if (!gitCoAuthorSettings.enabled) {
          return command2;
        }
        const gitCommitPattern = /\bgit\s+commit\b/;
        if (!gitCommitPattern.test(command2)) {
          return command2;
        }
        const coAuthor = `

Co-authored-by: ${gitCoAuthorSettings.name} <${gitCoAuthorSettings.email}>`;
        const doubleQuotePattern = /(-[a-zA-Z]*m\s+)"((?:[^"\\]|\\.)*)"/;
        const singleQuotePattern = /(-[a-zA-Z]*m\s+)'((?:[^'\\]|\\.)*)'/;
        const doubleMatch = command2.match(doubleQuotePattern);
        const singleMatch = command2.match(singleQuotePattern);
        const match2 = doubleMatch ?? singleMatch;
        const quote3 = doubleMatch ? '"' : "'";
        if (match2) {
          const [fullMatch, prefix, existingMessage] = match2;
          const newMessage = existingMessage + coAuthor;
          const replacement = prefix + quote3 + newMessage + quote3;
          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(config2) {
        super(
          _ShellTool.Name,
          ToolDisplayNames.SHELL,
          getShellToolDescription(),
          Kind.Execute,
          {
            type: "object",
            properties: {
              command: {
                type: "string",
                description: getCommandDescription()
              },
              is_background: {
                type: "boolean",
                description: "Optional: Whether to run the command in background. If not specified, defaults to false (foreground execution). Explicitly set to true for long-running processes like development servers, watchers, or daemons that should continue running without blocking further commands."
              },
              timeout: {
                type: "number",
                description: "Optional timeout in milliseconds (max 600000)"
              },
              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"]
          },
          false,
          // output is not markdown
          true
        );
        this.config = config2;
      }
      validateToolParamValues(params) {
        const commandCheck = isCommandAllowed(params.command, this.config);
        if (!commandCheck.allowed) {
          if (!commandCheck.reason) {
            debugLogger25.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.timeout !== void 0) {
          if (typeof params.timeout !== "number" || !Number.isInteger(params.timeout)) {
            return "Timeout must be an integer number of milliseconds.";
          }
          if (params.timeout <= 0) {
            return "Timeout must be a positive number.";
          }
          if (params.timeout > 6e5) {
            return "Timeout cannot exceed 600000ms (10 minutes).";
          }
        }
        if (params.directory) {
          if (!path17.isAbsolute(params.directory)) {
            return "Directory must be an absolute path.";
          }
          const userSkillsDir = this.config.storage.getUserSkillsDir();
          const resolvedDirectoryPath = path17.resolve(params.directory);
          const isWithinUserSkills = isSubpath(userSkillsDir, resolvedDirectoryPath);
          if (isWithinUserSkills) {
            return `Explicitly running shell commands from within the user skills directory is not allowed. Please use absolute paths for command parameter instead.`;
          }
          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 fs25 from "node:fs/promises";
import * as path18 from "node:path";
function createFunctionResponsePart(callId, toolName, output, mediaParts) {
  const functionResponse = {
    id: callId,
    name: toolName,
    response: { output },
    ...mediaParts && mediaParts.length > 0 ? { parts: mediaParts } : {}
  };
  return {
    functionResponse
  };
}
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 textParts = [];
    const mediaParts = [];
    for (const part of toParts(contentToProcess)) {
      if (part.text !== void 0) {
        textParts.push(part.text);
      } else if (part.inlineData) {
        mediaParts.push({ inlineData: part.inlineData });
      } else if (part.fileData) {
        mediaParts.push({ fileData: part.fileData });
      }
    }
    const output = textParts.length > 0 ? textParts.join("\n") : "Tool execution succeeded.";
    return [createFunctionResponsePart(callId, toolName, output, mediaParts)];
  }
  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 mediaParts = [];
    if (contentToProcess.inlineData) {
      mediaParts.push({ inlineData: contentToProcess.inlineData });
    }
    if (contentToProcess.fileData) {
      mediaParts.push({ fileData: contentToProcess.fileData });
    }
    const functionResponse = createFunctionResponsePart(callId, toolName, "", mediaParts);
    return [functionResponse];
  }
  if (contentToProcess.text !== void 0) {
    return [
      createFunctionResponsePart(callId, toolName, contentToProcess.text)
    ];
  }
  return [
    createFunctionResponsePart(callId, toolName, "Tool execution succeeded.")
  ];
}
function toParts(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 i3 = 0; i3 < line.length; i3 += wrapWidth) {
          wrappedLines.push(line.substring(i3, i3 + 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 = `${path18.basename(callId)}.output`;
  const outputFile = path18.join(projectTempDir, safeFileName);
  try {
    await fs25.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, debugLogger26, createErrorResponse, CoreToolScheduler;
var init_coreToolScheduler = __esm({
  "packages/core/dist/src/core/coreToolScheduler.js"() {
    "use strict";
    init_esbuild_shims();
    init_debugLogger();
    init_src2();
    init_tool_names();
    init_generateContentResponseUtilities();
    init_modifiable_tool();
    init_lib();
    init_tool_utils();
    import_fast_levenshtein = __toESM(require_levenshtein(), 1);
    init_prompts();
    init_shell();
    debugLogger26 = createDebugLogger("TOOL_SCHEDULER");
    __name(createFunctionResponsePart, "createFunctionResponsePart");
    __name(convertToFunctionResponse, "convertToFunctionResponse");
    __name(toParts, "toParts");
    createErrorResponse = /* @__PURE__ */ __name((request4, error2, errorType) => ({
      callId: request4.callId,
      error: error2,
      responseParts: [
        {
          functionResponse: {
            id: request4.callId,
            name: request4.name,
            response: { error: error2.message }
          }
        }
      ],
      resultDisplay: error2.message,
      errorType,
      contentLength: error2.message.length
    }), "createErrorResponse");
    __name(truncateAndSaveToFile, "truncateAndSaveToFile");
    CoreToolScheduler = class {
      static {
        __name(this, "CoreToolScheduler");
      }
      toolRegistry;
      toolCalls = [];
      outputUpdateHandler;
      onAllToolCallsComplete;
      onToolCallsUpdate;
      getPreferredEditor;
      config;
      onEditorClose;
      chatRecordingService;
      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;
        this.chatRecordingService = options2.chatRecordingService;
      }
      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 (e4) {
          if (e4 instanceof Error) {
            return e4;
          }
          return new Error(String(e4));
        }
      }
      /**
       * Generates error message for unknown tool. Returns early with skill-specific
       * message if the name matches a skill, otherwise uses Levenshtein suggestions.
       */
      getToolNotFoundMessage(unknownToolName, topN = 3) {
        const skillTool = this.toolRegistry.getTool(ToolNames.SKILL);
        if (skillTool instanceof SkillTool) {
          const availableSkillNames = skillTool.getAvailableSkillNames();
          if (availableSkillNames.includes(unknownToolName)) {
            return `"${unknownToolName}" is a skill name, not a tool name. To use this skill, invoke the "${ToolNames.SKILL}" tool with parameter: skill: "${unknownToolName}"`;
          }
        }
        const suggestion = this.getToolSuggestion(unknownToolName, topN);
        return `Tool "${unknownToolName}" not found in registry. Tools must use the exact names that are registered.${suggestion}`;
      }
      /** Suggests similar tool names using Levenshtein distance. */
      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((a2, b2) => a2.distance - b2.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((resolve30, 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);
                resolve30();
              }, "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 excludeTools = this.config.getExcludeTools?.() ?? void 0;
            if (excludeTools && excludeTools.length > 0) {
              const normalizedToolName = reqInfo.name.toLowerCase().trim();
              const excludedMatch = excludeTools.find((excludedTool) => excludedTool.toLowerCase().trim() === normalizedToolName);
              if (excludedMatch) {
                const permissionErrorMessage = `Qwen Code requires permission to use ${excludedMatch}, but that permission was declined.`;
                return {
                  status: "error",
                  request: reqInfo,
                  response: createErrorResponse(reqInfo, new Error(permissionErrorMessage), ToolErrorType.EXECUTION_DENIED),
                  durationMs: 0
                };
              }
            }
            const toolInstance = this.toolRegistry.getTool(reqInfo.name);
            if (!toolInstance) {
              const errorMessage = this.getToolNotFoundMessage(reqInfo.name);
              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 {
                const shouldAutoDeny = !this.config.isInteractive() && !this.config.getExperimentalZedIntegration() && this.config.getInputFormat() !== InputFormat.STREAM_JSON;
                if (shouldAutoDeny) {
                  const errorMessage = `Qwen Code requires permission to use "${reqInfo.name}", but that permission was declined.`;
                  this.setStatusInternal(reqInfo.callId, "error", createErrorResponse(reqInfo, new Error(errorMessage), ToolErrorType.EXECUTION_DENIED));
                  continue;
                }
                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 (error2) {
              if (signal.aborted) {
                this.setStatusInternal(reqInfo.callId, "cancelled", "Tool call cancelled by user.");
                continue;
              }
              this.setStatusInternal(reqInfo.callId, "error", createErrorResponse(reqInfo, error2 instanceof Error ? error2 : new Error(String(error2)), 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((c4) => c4.request.callId === callId && c4.status === "awaiting_approval");
        await originalOnConfirm(outcome, payload);
        if (outcome === ToolConfirmationOutcome.ProceedAlways) {
          await this.autoApproveCompatiblePendingTools(signal, callId);
        }
        this.setToolCallOutcome(callId, outcome);
        if (outcome === ToolConfirmationOutcome.Cancel || signal.aborted) {
          const cancelMessage = payload?.cancelMessage || "User did not allow tool call";
          this.setStatusInternal(callId, "cancelled", cancelMessage);
        } 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) || !payload.newContent) {
          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 error2 = new Error(toolResult.error.message);
                const errorResponse = createErrorResponse(scheduledCall.request, error2, 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));
          }
          this.recordToolResults(completedCalls);
          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);
          }
        }
      }
      /**
       * Records tool results to the chat recording service.
       * This captures both the raw Content (for API reconstruction) and
       * enriched metadata (for UI recovery).
       */
      recordToolResults(completedCalls) {
        if (!this.chatRecordingService)
          return;
        const responseParts = completedCalls.flatMap((call) => call.response.responseParts);
        if (responseParts.length === 0)
          return;
        for (const call of completedCalls) {
          this.chatRecordingService.recordToolResult(call.response.responseParts, {
            callId: call.request.callId,
            status: call.status,
            resultDisplay: call.response.resultDisplay,
            error: call.response.error,
            errorType: call.response.errorType
          });
        }
      }
      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 (error2) {
            debugLogger26.error(`Error checking confirmation for tool ${pendingTool.request.callId}:`, error2);
          }
        }
      }
    };
  }
});

// packages/core/dist/src/config/constants.js
var DEFAULT_FILE_FILTERING_OPTIONS;
var init_constants4 = __esm({
  "packages/core/dist/src/config/constants.js"() {
    "use strict";
    init_esbuild_shims();
    DEFAULT_FILE_FILTERING_OPTIONS = {
      respectGitIgnore: true,
      respectQwenIgnore: true
    };
  }
});

// packages/core/dist/src/utils/getFolderStructure.js
import * as fs26 from "node:fs/promises";
import * as path19 from "node:path";
async function readFullStructure(rootPath, options2) {
  const rootName = path19.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 fs26.readdir(currentPath, { withFileTypes: true });
      entries = rawEntries.sort((a2, b2) => a2.name.localeCompare(b2.name));
    } catch (error2) {
      if (isNodeError(error2) && (error2.code === "EACCES" || error2.code === "ENOENT")) {
        debugLogger27.warn(`Warning: Could not read directory ${currentPath}: ${error2.message}`);
        if (currentPath === rootPath && error2.code === "ENOENT") {
          return null;
        }
        continue;
      }
      throw error2;
    }
    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 = path19.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 = path19.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}${path19.sep}${node.isIgnored ? TRUNCATION_INDICATOR : ""}`);
  }
  const indentForChildren = isProcessingRootNode ? "" : currentIndent + (isLastChildOfParent ? "    " : "\u2502   ");
  const fileCount = node.files.length;
  for (let i3 = 0; i3 < fileCount; i3++) {
    const isLastFileAmongSiblings = i3 === 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[i3]}`);
  }
  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 i3 = 0; i3 < subFolderCount; i3++) {
    const isLastSubfolderAmongSiblings = i3 === subFolderCount - 1 && !node.hasMoreSubfolders;
    formatStructure(node.subFolders[i3], indentForChildren, isLastSubfolderAmongSiblings, false, builder);
  }
  if (node.hasMoreSubfolders) {
    builder.push(`${indentForChildren}\u2514\u2500\u2500\u2500${TRUNCATION_INDICATOR}`);
  }
}
async function getFolderStructure(directory, options2) {
  const resolvedPath = path19.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 {
    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);
    return `Showing up to ${mergedOptions.maxItems} items:

${resolvedPath}${path19.sep}
${structureLines.join("\n")}`;
  } catch (error2) {
    debugLogger27.error(`Error getting folder structure for ${resolvedPath}:`, error2);
    return `Error processing directory "${resolvedPath}": ${getErrorMessage(error2)}`;
  }
}
var debugLogger27, 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_constants4();
    init_debugLogger();
    debugLogger27 = createDebugLogger("FOLDER_STRUCTURE");
    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(config2) {
  const workspaceContext = config2.getWorkspaceContext();
  const workspaceDirectories = workspaceContext.getDirectories();
  const folderStructures = await Promise.all(workspaceDirectories.map((dir) => getFolderStructure(dir, {
    fileService: config2.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(config2) {
  const today = (/* @__PURE__ */ new Date()).toLocaleDateString(void 0, {
    weekday: "long",
    year: "numeric",
    month: "long",
    day: "numeric"
  });
  const platform16 = process.platform;
  const directoryContext = await getDirectoryContextString(config2);
  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: ${platform16}
${directoryContext}
        `.trim();
  return [{ text: context2 }];
}
async function getInitialChatHistory(config2, extraHistory) {
  if (config2.getSkipStartupContext()) {
    return extraHistory ? [...extraHistory] : [];
  }
  const envParts = await getEnvironmentContext(config2);
  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/subagents/subagent-events.js
import { EventEmitter as EventEmitter3 } 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["USAGE_METADATA"] = "usage_metadata";
      SubAgentEventType2["FINISH"] = "finish";
      SubAgentEventType2["ERROR"] = "error";
    })(SubAgentEventType || (SubAgentEventType = {}));
    SubAgentEventEmitter = class {
      static {
        __name(this, "SubAgentEventEmitter");
      }
      ee = new EventEmitter3();
      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 debugLogger28, ContextState, SubAgentScope;
var init_subagent = __esm({
  "packages/core/dist/src/subagents/subagent.js"() {
    "use strict";
    init_esbuild_shims();
    init_errorReporting();
    init_debugLogger();
    init_turn();
    init_coreToolScheduler();
    init_environmentContext();
    init_geminiChat();
    init_types5();
    init_subagent_events();
    init_subagent_statistics();
    init_loggers();
    init_types();
    init_task();
    init_models();
    debugLogger28 = createDebugLogger("SUBAGENT");
    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;
        }
        let currentRoundAbortController = null;
        const onExternalAbort = /* @__PURE__ */ __name(() => {
          currentRoundAbortController?.abort();
        }, "onExternalAbort");
        if (externalSignal) {
          externalSignal.addEventListener("abort", onExternalAbort);
        }
        const toolRegistry = this.runtimeContext.getToolRegistry();
        const toolsList = [];
        if (this.toolConfig) {
          const asStrings = this.toolConfig.tools.filter((t5) => typeof t5 === "string");
          const hasWildcard = asStrings.includes("*");
          const onlyInlineDecls = this.toolConfig.tools.filter((t5) => typeof t5 !== "string");
          if (hasWildcard || asStrings.length === 0) {
            toolsList.push(...toolRegistry.getFunctionDeclarations().filter((t5) => t5.name !== TaskTool.Name));
          } else {
            toolsList.push(...toolRegistry.getFunctionDeclarationsFiltered(asStrings));
          }
          toolsList.push(...onlyInlineDecls);
        } else {
          toolsList.push(...toolRegistry.getFunctionDeclarations().filter((t5) => t5.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((t5) => typeof t5 === "string" ? t5 : t5.name),
            timestamp: Date.now()
          });
          const startEvent = new SubagentExecutionEvent(this.name, "started");
          logSubagentExecution(this.runtimeContext, startEvent);
          while (true) {
            const roundAbortController = new AbortController();
            currentRoundAbortController = roundAbortController;
            if (externalSignal?.aborted) {
              roundAbortController.abort();
            }
            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: roundAbortController.signal,
                tools: [{ functionDeclarations: toolsList }]
              }
            };
            const roundStreamStart = Date.now();
            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 (roundAbortController.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 p2 of parts) {
                  const txt = p2.text;
                  const isThought = p2.thought ?? false;
                  if (txt && !isThought)
                    roundText += txt;
                  if (txt)
                    this.eventEmitter?.emit(SubAgentEventType.STREAM_TEXT, {
                      subagentId: this.subagentId,
                      round: turnCounter,
                      text: txt,
                      thought: isThought,
                      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);
              const thoughtTok = Number(lastUsage.thoughtsTokenCount || 0);
              const cachedTok = Number(lastUsage.cachedContentTokenCount || 0);
              if (isFinite(inTok) || isFinite(outTok) || isFinite(thoughtTok) || isFinite(cachedTok)) {
                this.stats.recordTokens(isFinite(inTok) ? inTok : 0, isFinite(outTok) ? outTok : 0, isFinite(thoughtTok) ? thoughtTok : 0, isFinite(cachedTok) ? cachedTok : 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) + (isFinite(thoughtTok) ? thoughtTok : 0) + (isFinite(cachedTok) ? cachedTok : 0);
                this.executionStats.estimatedCost = (this.executionStats.inputTokens || 0) * 3e-5 + (this.executionStats.outputTokens || 0) * 6e-5;
              }
              this.eventEmitter?.emit(SubAgentEventType.USAGE_METADATA, {
                subagentId: this.subagentId,
                round: turnCounter,
                usage: lastUsage,
                durationMs: Date.now() - roundStreamStart,
                timestamp: Date.now()
              });
            }
            if (functionCalls.length > 0) {
              currentMessages = await this.processFunctionCalls(functionCalls, roundAbortController, promptId, turnCounter, toolsList, 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 (error2) {
          debugLogger28.error("Error during subagent execution:", error2);
          this.terminateMode = SubagentTerminateMode.ERROR;
          this.eventEmitter?.emit(SubAgentEventType.ERROR, {
            subagentId: this.subagentId,
            error: error2 instanceof Error ? error2.message : String(error2),
            timestamp: Date.now()
          });
          throw error2;
        } finally {
          if (externalSignal) {
            externalSignal.removeEventListener("abort", onExternalAbort);
          }
          currentRoundAbortController = null;
          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, toolsList, responseId) {
        const toolResponseParts = [];
        const allowedToolNames = new Set(toolsList.map((t5) => t5.name));
        const authorizedCalls = [];
        for (const fc of functionCalls) {
          const callId = fc.id ?? `${fc.name}-${Date.now()}`;
          if (!allowedToolNames.has(fc.name)) {
            const toolName = String(fc.name);
            const errorMessage = `Tool "${toolName}" not found. Tools must use the exact names provided.`;
            this.eventEmitter?.emit(SubAgentEventType.TOOL_CALL, {
              subagentId: this.subagentId,
              round: currentRound,
              callId,
              name: toolName,
              args: fc.args ?? {},
              description: `Tool "${toolName}" not found`,
              timestamp: Date.now()
            });
            const functionResponsePart = {
              functionResponse: {
                id: callId,
                name: toolName,
                response: { error: errorMessage }
              }
            };
            this.eventEmitter?.emit(SubAgentEventType.TOOL_RESULT, {
              subagentId: this.subagentId,
              round: currentRound,
              callId,
              name: toolName,
              success: false,
              error: errorMessage,
              responseParts: [functionResponsePart],
              resultDisplay: errorMessage,
              durationMs: 0,
              timestamp: Date.now()
            });
            this.recordToolCallStats(toolName, false, 0, errorMessage);
            toolResponseParts.push(functionResponsePart);
            continue;
          }
          authorizedCalls.push(fc);
        }
        const responded = /* @__PURE__ */ new Set();
        let resolveBatch = null;
        const scheduler = new CoreToolScheduler({
          config: this.runtimeContext,
          outputUpdateHandler: void 0,
          onAllToolCallsComplete: /* @__PURE__ */ __name(async (completedCalls) => {
            for (const call of completedCalls) {
              const toolName = call.request.name;
              const duration3 = call.durationMs ?? 0;
              const success = call.status === "success";
              const errorMessage = call.status === "error" || call.status === "cancelled" ? call.response.error?.message : void 0;
              this.recordToolCallStats(toolName, success, duration3, errorMessage);
              this.eventEmitter?.emit(SubAgentEventType.TOOL_RESULT, {
                subagentId: this.subagentId,
                round: currentRound,
                callId: call.request.callId,
                name: toolName,
                success,
                error: errorMessage,
                responseParts: call.response.responseParts,
                resultDisplay: call.response.resultDisplay ? typeof call.response.resultDisplay === "string" ? call.response.resultDisplay : JSON.stringify(call.response.resultDisplay) : void 0,
                durationMs: duration3,
                timestamp: Date.now()
              });
              await this.hooks?.postToolUse?.({
                subagentId: this.subagentId,
                name: this.name,
                toolName,
                args: call.request.args,
                success,
                durationMs: duration3,
                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"),
          onEditorClose: /* @__PURE__ */ __name(() => {
          }, "onEditorClose")
        });
        const requests = authorizedCalls.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((resolve30) => {
            resolveBatch = /* @__PURE__ */ __name(() => {
              resolve30();
              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, v2]) => ({
            name: name3,
            ...v2
          }))
        };
      }
      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 (error2) {
          await reportError2(error2, "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 "";
        }
      }
      /**
       * Records tool call statistics for both successful and failed tool calls.
       * This includes updating aggregate stats, per-tool usage, and the statistics service.
       */
      recordToolCallStats(toolName, success, durationMs, errorMessage) {
        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) + durationMs;
        tu.averageDurationMs = tu.count > 0 ? tu.totalDurationMs / tu.count : 0;
        this.toolUsage.set(toolName, tu);
        this.stats.recordToolCall(toolName, success, durationMs, this.toolUsage.get(toolName)?.lastError);
      }
      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 debugLogger29, 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_types5();
    init_subagent();
    init_subagent_events();
    init_debugLogger();
    debugLogger29 = createDebugLogger("TASK");
    TaskTool = class _TaskTool extends BaseDeclarativeTool {
      static {
        __name(this, "TaskTool");
      }
      config;
      static Name = ToolNames.TASK;
      subagentManager;
      availableSubagents = [];
      constructor(config2) {
        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 = config2;
        this.subagentManager = config2.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 (error2) {
          debugLogger29.warn("Failed to load subagents for Task tool:", error2);
          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((s5) => s5.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((s5) => s5.name);
          return `Subagent "${params.subagent_type}" not found. Available subagents: ${availableNames.join(", ")}`;
        }
        return null;
      }
      createInvocation(params) {
        return new TaskToolInvocation(this.config, this.subagentManager, params);
      }
      getAvailableSubagentNames() {
        return this.availableSubagents.map((subagent) => subagent.name);
      }
    };
    TaskToolInvocation = class extends BaseToolInvocation {
      static {
        __name(this, "TaskToolInvocation");
      }
      config;
      subagentManager;
      _eventEmitter;
      currentDisplay = null;
      currentToolCalls = [];
      constructor(config2, subagentManager, params) {
        super(params);
        this.config = config2;
        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,
              responseParts: event.responseParts
            };
            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((c4) => c4.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((c4) => c4.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 (error2) {
          const errorMessage = error2 instanceof Error ? error2.message : String(error2);
          debugLogger29.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/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((p2) => p2 === 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_types();
    init_types();
    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/services/sessionService.js
import path20 from "node:path";
import fs27 from "node:fs";
import readline2 from "node:readline";
function stripThoughtsFromContent(content) {
  if (!content.parts)
    return content;
  const filteredParts = content.parts.filter((part) => !part.thought);
  if (filteredParts.length === 0) {
    return null;
  }
  return {
    ...content,
    parts: filteredParts
  };
}
function buildApiHistoryFromConversation(conversation, options2 = {}) {
  const { stripThoughtsFromHistory = true } = options2;
  const { messages } = conversation;
  let lastCompressionIndex = -1;
  let compressedHistory;
  messages.forEach((record2, index) => {
    if (record2.type === "system" && record2.subtype === "chat_compression") {
      const payload = record2.systemPayload;
      if (payload?.compressedHistory) {
        lastCompressionIndex = index;
        compressedHistory = payload.compressedHistory;
      }
    }
  });
  if (compressedHistory && lastCompressionIndex >= 0) {
    const baseHistory = structuredClone(compressedHistory);
    for (let i3 = lastCompressionIndex + 1; i3 < messages.length; i3++) {
      const record2 = messages[i3];
      if (record2.type === "system")
        continue;
      if (record2.message) {
        baseHistory.push(structuredClone(record2.message));
      }
    }
    if (stripThoughtsFromHistory) {
      return baseHistory.map(stripThoughtsFromContent).filter((content) => content !== null);
    }
    return baseHistory;
  }
  const result = messages.map((record2) => record2.message).filter((message) => message !== void 0).map((message) => structuredClone(message));
  if (stripThoughtsFromHistory) {
    return result.map(stripThoughtsFromContent).filter((content) => content !== null);
  }
  return result;
}
function replayUiTelemetryFromConversation(conversation) {
  uiTelemetryService.reset();
  for (const record2 of conversation.messages) {
    if (record2.type !== "system" || record2.subtype !== "ui_telemetry") {
      continue;
    }
    const payload = record2.systemPayload;
    const uiEvent = payload?.uiEvent;
    if (uiEvent) {
      uiTelemetryService.addEvent(uiEvent);
    }
  }
  const resumePromptTokens = getResumePromptTokenCount(conversation);
  if (resumePromptTokens !== void 0) {
    uiTelemetryService.setLastPromptTokenCount(resumePromptTokens);
  }
}
function getResumePromptTokenCount(conversation) {
  let fallback;
  for (let i3 = conversation.messages.length - 1; i3 >= 0; i3--) {
    const record2 = conversation.messages[i3];
    if (record2.type === "system" && record2.subtype === "chat_compression") {
      const payload = record2.systemPayload;
      if (payload?.info) {
        return payload.info.newTokenCount;
      }
    }
    if (fallback === void 0 && record2.type === "assistant") {
      const usage2 = record2.usageMetadata;
      if (usage2) {
        fallback = usage2.totalTokenCount ?? usage2.promptTokenCount;
      }
    }
  }
  return fallback;
}
var debugLogger30, MAX_FILES_TO_PROCESS, SESSION_FILE_PATTERN, MAX_PROMPT_SCAN_LINES, SessionService;
var init_sessionService = __esm({
  "packages/core/dist/src/services/sessionService.js"() {
    "use strict";
    init_esbuild_shims();
    init_storage();
    init_paths();
    init_jsonl_utils();
    init_uiTelemetry();
    init_debugLogger();
    debugLogger30 = createDebugLogger("SESSION");
    MAX_FILES_TO_PROCESS = 1e4;
    SESSION_FILE_PATTERN = /^[0-9a-fA-F-]{32,36}\.jsonl$/;
    MAX_PROMPT_SCAN_LINES = 10;
    SessionService = class {
      static {
        __name(this, "SessionService");
      }
      storage;
      projectHash;
      constructor(cwd7) {
        this.storage = new Storage(cwd7);
        this.projectHash = getProjectHash(cwd7);
      }
      getChatsDir() {
        return path20.join(this.storage.getProjectDir(), "chats");
      }
      /**
       * Extracts the first user prompt text from a Content object.
       */
      extractPromptText(message) {
        if (!message?.parts)
          return "";
        for (const part of message.parts) {
          if ("text" in part) {
            const textPart = part;
            const text = textPart.text;
            return text.length > 200 ? `${text.slice(0, 200)}...` : text;
          }
        }
        return "";
      }
      /**
       * Finds the first available prompt text by scanning the first N records,
       * preferring user messages. Returns an empty string if none found.
       */
      extractFirstPromptFromRecords(records) {
        for (const record2 of records) {
          if (record2.type !== "user")
            continue;
          const prompt = this.extractPromptText(record2.message);
          if (prompt)
            return prompt;
        }
        return "";
      }
      /**
       * Counts unique message UUIDs in a session file.
       * This gives the number of logical messages in the session.
       */
      async countSessionMessages(filePath) {
        const uniqueUuids = /* @__PURE__ */ new Set();
        try {
          const fileStream = fs27.createReadStream(filePath);
          const rl = readline2.createInterface({
            input: fileStream,
            crlfDelay: Infinity
          });
          for await (const line of rl) {
            const trimmed2 = line.trim();
            if (!trimmed2)
              continue;
            try {
              const record2 = JSON.parse(trimmed2);
              if (record2.type === "user" || record2.type === "assistant") {
                uniqueUuids.add(record2.uuid);
              }
            } catch {
              continue;
            }
          }
          return uniqueUuids.size;
        } catch {
          return 0;
        }
      }
      /**
       * Lists sessions for the current project with pagination.
       *
       * Sessions are ordered by file modification time (most recent first).
       * Uses cursor-based pagination with mtime as the cursor.
       *
       * Only reads the first line of each JSONL file for efficiency.
       * Files are filtered by UUID pattern first, then by project hash.
       *
       * @param options Pagination options
       * @returns Paginated list of sessions
       */
      async listSessions(options2 = {}) {
        const { cursor, size = 20 } = options2;
        const chatsDir = this.getChatsDir();
        let files = [];
        try {
          const fileNames = fs27.readdirSync(chatsDir);
          for (const name3 of fileNames) {
            if (!SESSION_FILE_PATTERN.test(name3))
              continue;
            const filePath = path20.join(chatsDir, name3);
            try {
              const stats = fs27.statSync(filePath);
              files.push({ name: name3, mtime: stats.mtimeMs });
            } catch {
              continue;
            }
          }
        } catch (error2) {
          if (error2.code === "ENOENT") {
            return { items: [], hasMore: false };
          }
          throw error2;
        }
        files.sort((a2, b2) => b2.mtime - a2.mtime);
        if (cursor !== void 0) {
          files = files.filter((f5) => f5.mtime < cursor);
        }
        const items = [];
        let filesProcessed = 0;
        let lastProcessedMtime;
        let hasMoreFiles = false;
        for (const file of files) {
          if (filesProcessed >= MAX_FILES_TO_PROCESS) {
            hasMoreFiles = true;
            break;
          }
          if (items.length >= size) {
            hasMoreFiles = true;
            break;
          }
          filesProcessed++;
          lastProcessedMtime = file.mtime;
          const filePath = path20.join(chatsDir, file.name);
          const records = await readLines(filePath, MAX_PROMPT_SCAN_LINES);
          if (records.length === 0)
            continue;
          const firstRecord = records[0];
          const recordProjectHash = getProjectHash(firstRecord.cwd);
          if (recordProjectHash !== this.projectHash)
            continue;
          const messageCount = await this.countSessionMessages(filePath);
          const prompt = this.extractFirstPromptFromRecords(records);
          items.push({
            sessionId: firstRecord.sessionId,
            cwd: firstRecord.cwd,
            startTime: firstRecord.timestamp,
            mtime: file.mtime,
            prompt,
            gitBranch: firstRecord.gitBranch,
            filePath,
            messageCount
          });
        }
        const nextCursor = hasMoreFiles && lastProcessedMtime !== void 0 ? lastProcessedMtime : void 0;
        return {
          items,
          nextCursor,
          hasMore: hasMoreFiles
        };
      }
      /**
       * Reads all records from a session file.
       */
      async readAllRecords(filePath) {
        try {
          return await read(filePath);
        } catch (error2) {
          if (error2.code !== "ENOENT") {
            debugLogger30.error("Error reading session file:", error2);
          }
          return [];
        }
      }
      /**
       * Aggregates multiple records with the same uuid into a single ChatRecord.
       * Merges content fields (message, tokens, model, toolCallResult).
       */
      aggregateRecords(records) {
        if (records.length === 0) {
          throw new Error("Cannot aggregate empty records array");
        }
        const base = { ...records[0] };
        for (let i3 = 1; i3 < records.length; i3++) {
          const record2 = records[i3];
          if (record2.message !== void 0) {
            if (base.message === void 0) {
              base.message = record2.message;
            } else {
              base.message = {
                role: base.message.role,
                parts: [
                  ...base.message.parts || [],
                  ...record2.message.parts || []
                ]
              };
            }
          }
          if (record2.usageMetadata) {
            base.usageMetadata = record2.usageMetadata;
          }
          if (record2.toolCallResult && !base.toolCallResult) {
            base.toolCallResult = record2.toolCallResult;
          }
          if (record2.model && !base.model) {
            base.model = record2.model;
          }
          if (record2.timestamp > base.timestamp) {
            base.timestamp = record2.timestamp;
          }
        }
        return base;
      }
      /**
       * Reconstructs a linear conversation from tree-structured records.
       */
      reconstructHistory(records, leafUuid) {
        if (records.length === 0)
          return [];
        const recordsByUuid = /* @__PURE__ */ new Map();
        for (const record2 of records) {
          const existing = recordsByUuid.get(record2.uuid) || [];
          existing.push(record2);
          recordsByUuid.set(record2.uuid, existing);
        }
        let currentUuid = leafUuid ?? records[records.length - 1].uuid;
        const uuidChain = [];
        const visited = /* @__PURE__ */ new Set();
        while (currentUuid && !visited.has(currentUuid)) {
          visited.add(currentUuid);
          uuidChain.push(currentUuid);
          const recordsForUuid = recordsByUuid.get(currentUuid);
          if (!recordsForUuid || recordsForUuid.length === 0)
            break;
          currentUuid = recordsForUuid[0].parentUuid;
        }
        uuidChain.reverse();
        const messages = [];
        for (const uuid2 of uuidChain) {
          const recordsForUuid = recordsByUuid.get(uuid2);
          if (recordsForUuid && recordsForUuid.length > 0) {
            messages.push(this.aggregateRecords(recordsForUuid));
          }
        }
        return messages;
      }
      /**
       * Loads a session by its session ID.
       * Reconstructs the full conversation from tree-structured records.
       *
       * @param sessionId The session ID to load
       * @returns Session data for resumption, or null if not found
       */
      async loadSession(sessionId) {
        const chatsDir = this.getChatsDir();
        const filePath = path20.join(chatsDir, `${sessionId}.jsonl`);
        const records = await this.readAllRecords(filePath);
        if (records.length === 0) {
          return;
        }
        const firstRecord = records[0];
        const recordProjectHash = getProjectHash(firstRecord.cwd);
        if (recordProjectHash !== this.projectHash) {
          return;
        }
        const messages = this.reconstructHistory(records);
        if (messages.length === 0) {
          return;
        }
        const lastMessage = messages[messages.length - 1];
        const stats = fs27.statSync(filePath);
        const conversation = {
          sessionId: firstRecord.sessionId,
          projectHash: this.projectHash,
          startTime: firstRecord.timestamp,
          lastUpdated: new Date(stats.mtimeMs).toISOString(),
          messages
        };
        return {
          conversation,
          filePath,
          lastCompletedUuid: lastMessage.uuid
        };
      }
      /**
       * Removes a session by its session ID.
       *
       * @param sessionId The session ID to remove
       * @returns true if removed, false if not found
       */
      async removeSession(sessionId) {
        const chatsDir = this.getChatsDir();
        const filePath = path20.join(chatsDir, `${sessionId}.jsonl`);
        try {
          const records = await readLines(filePath, 1);
          if (records.length === 0) {
            return false;
          }
          const recordProjectHash = getProjectHash(records[0].cwd);
          if (recordProjectHash !== this.projectHash) {
            return false;
          }
          fs27.unlinkSync(filePath);
          return true;
        } catch (error2) {
          if (error2.code === "ENOENT") {
            return false;
          }
          throw error2;
        }
      }
      /**
       * Loads the most recent session for the current project.
       * Combines listSessions and loadSession for convenience.
       *
       * @returns Session data for resumption, or undefined if no sessions exist
       */
      async loadLastSession() {
        const result = await this.listSessions({ size: 1 });
        if (result.items.length === 0) {
          return;
        }
        return this.loadSession(result.items[0].sessionId);
      }
      /**
       * Checks if a session exists by its session ID.
       *
       * @param sessionId The session ID to check
       * @returns true if session exists and belongs to current project
       */
      async sessionExists(sessionId) {
        const chatsDir = this.getChatsDir();
        const filePath = path20.join(chatsDir, `${sessionId}.jsonl`);
        try {
          const records = await readLines(filePath, 1);
          if (records.length === 0) {
            return false;
          }
          const recordProjectHash = getProjectHash(records[0].cwd);
          return recordProjectHash === this.projectHash;
        } catch {
          return false;
        }
      }
    };
    __name(stripThoughtsFromContent, "stripThoughtsFromContent");
    __name(buildApiHistoryFromConversation, "buildApiHistoryFromConversation");
    __name(replayUiTelemetryFromConversation, "replayUiTelemetryFromConversation");
    __name(getResumePromptTokenCount, "getResumePromptTokenCount");
  }
});

// packages/core/dist/src/utils/nextSpeakerChecker.js
async function checkNextSpeaker(chat, config2, 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 config2.getBaseLlmClient().generateJson({
      contents,
      schema: RESPONSE_SCHEMA,
      model: config2.getModel() || DEFAULT_QWEN_MODEL,
      abortSignal,
      promptId
    });
    if (parsedResponse && parsedResponse.next_speaker && ["user", "model"].includes(parsedResponse.next_speaker)) {
      return parsedResponse;
    }
    return null;
  } catch (error2) {
    debugLogger31.warn("Failed to talk to Gemini endpoint when seeing if conversation should continue.", error2);
    return null;
  }
}
var debugLogger31, CHECK_PROMPT, RESPONSE_SCHEMA;
var init_nextSpeakerChecker = __esm({
  "packages/core/dist/src/utils/nextSpeakerChecker.js"() {
    "use strict";
    init_esbuild_shims();
    init_models();
    init_messageInspectors();
    init_debugLogger();
    debugLogger31 = createDebugLogger("NEXT_SPEAKER");
    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_constants5 = __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_constants5();
    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((a2, b2) => b2.timestamp - a2.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(util3) {
      util3.assertEqual = (_2) => {
      };
      function assertIs2(_arg) {
      }
      __name(assertIs2, "assertIs");
      util3.assertIs = assertIs2;
      function assertNever4(_x) {
        throw new Error();
      }
      __name(assertNever4, "assertNever");
      util3.assertNever = assertNever4;
      util3.arrayToEnum = (items) => {
        const obj = {};
        for (const item of items) {
          obj[item] = item;
        }
        return obj;
      };
      util3.getValidEnumValues = (obj) => {
        const validKeys = util3.objectKeys(obj).filter((k2) => typeof obj[obj[k2]] !== "number");
        const filtered = {};
        for (const k2 of validKeys) {
          filtered[k2] = obj[k2];
        }
        return util3.objectValues(filtered);
      };
      util3.objectValues = (obj) => {
        return util3.objectKeys(obj).map(function(e4) {
          return obj[e4];
        });
      };
      util3.objectKeys = typeof Object.keys === "function" ? (obj) => Object.keys(obj) : (object3) => {
        const keys = [];
        for (const key in object3) {
          if (Object.prototype.hasOwnProperty.call(object3, key)) {
            keys.push(key);
          }
        }
        return keys;
      };
      util3.find = (arr, checker) => {
        for (const item of arr) {
          if (checker(item))
            return item;
        }
        return void 0;
      };
      util3.isInteger = typeof Number.isInteger === "function" ? (val) => Number.isInteger(val) : (val) => typeof val === "number" && Number.isFinite(val) && Math.floor(val) === val;
      function joinValues2(array2, separator = " | ") {
        return array2.map((val) => typeof val === "string" ? `'${val}'` : val).join(separator);
      }
      __name(joinValues2, "joinValues");
      util3.joinValues = joinValues2;
      util3.jsonStringifyReplacer = (_2, 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 t5 = typeof data;
      switch (t5) {
        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(issue2) {
          return issue2.message;
        };
        const fieldErrors = { _errors: [] };
        const processError = /* @__PURE__ */ __name((error2) => {
          for (const issue2 of error2.issues) {
            if (issue2.code === "invalid_union") {
              issue2.unionErrors.map(processError);
            } else if (issue2.code === "invalid_return_type") {
              processError(issue2.returnTypeError);
            } else if (issue2.code === "invalid_arguments") {
              processError(issue2.argumentsError);
            } else if (issue2.path.length === 0) {
              fieldErrors._errors.push(mapper(issue2));
            } else {
              let curr = fieldErrors;
              let i3 = 0;
              while (i3 < issue2.path.length) {
                const el = issue2.path[i3];
                const terminal = i3 === issue2.path.length - 1;
                if (!terminal) {
                  curr[el] = curr[el] || { _errors: [] };
                } else {
                  curr[el] = curr[el] || { _errors: [] };
                  curr[el]._errors.push(mapper(issue2));
                }
                curr = curr[el];
                i3++;
              }
            }
          }
        }, "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 = (issue2) => issue2.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 error2 = new ZodError(issues);
      return error2;
    };
  }
});

// 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((issue2, _ctx) => {
      let message;
      switch (issue2.code) {
        case ZodIssueCode.invalid_type:
          if (issue2.received === ZodParsedType.undefined) {
            message = "Required";
          } else {
            message = `Expected ${issue2.expected}, received ${issue2.received}`;
          }
          break;
        case ZodIssueCode.invalid_literal:
          message = `Invalid literal value, expected ${JSON.stringify(issue2.expected, util2.jsonStringifyReplacer)}`;
          break;
        case ZodIssueCode.unrecognized_keys:
          message = `Unrecognized key(s) in object: ${util2.joinValues(issue2.keys, ", ")}`;
          break;
        case ZodIssueCode.invalid_union:
          message = `Invalid input`;
          break;
        case ZodIssueCode.invalid_union_discriminator:
          message = `Invalid discriminator value. Expected ${util2.joinValues(issue2.options)}`;
          break;
        case ZodIssueCode.invalid_enum_value:
          message = `Invalid enum value. Expected ${util2.joinValues(issue2.options)}, received '${issue2.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 issue2.validation === "object") {
            if ("includes" in issue2.validation) {
              message = `Invalid input: must include "${issue2.validation.includes}"`;
              if (typeof issue2.validation.position === "number") {
                message = `${message} at one or more positions greater than or equal to ${issue2.validation.position}`;
              }
            } else if ("startsWith" in issue2.validation) {
              message = `Invalid input: must start with "${issue2.validation.startsWith}"`;
            } else if ("endsWith" in issue2.validation) {
              message = `Invalid input: must end with "${issue2.validation.endsWith}"`;
            } else {
              util2.assertNever(issue2.validation);
            }
          } else if (issue2.validation !== "regex") {
            message = `Invalid ${issue2.validation}`;
          } else {
            message = "Invalid";
          }
          break;
        case ZodIssueCode.too_small:
          if (issue2.type === "array")
            message = `Array must contain ${issue2.exact ? "exactly" : issue2.inclusive ? `at least` : `more than`} ${issue2.minimum} element(s)`;
          else if (issue2.type === "string")
            message = `String must contain ${issue2.exact ? "exactly" : issue2.inclusive ? `at least` : `over`} ${issue2.minimum} character(s)`;
          else if (issue2.type === "number")
            message = `Number must be ${issue2.exact ? `exactly equal to ` : issue2.inclusive ? `greater than or equal to ` : `greater than `}${issue2.minimum}`;
          else if (issue2.type === "bigint")
            message = `Number must be ${issue2.exact ? `exactly equal to ` : issue2.inclusive ? `greater than or equal to ` : `greater than `}${issue2.minimum}`;
          else if (issue2.type === "date")
            message = `Date must be ${issue2.exact ? `exactly equal to ` : issue2.inclusive ? `greater than or equal to ` : `greater than `}${new Date(Number(issue2.minimum))}`;
          else
            message = "Invalid input";
          break;
        case ZodIssueCode.too_big:
          if (issue2.type === "array")
            message = `Array must contain ${issue2.exact ? `exactly` : issue2.inclusive ? `at most` : `less than`} ${issue2.maximum} element(s)`;
          else if (issue2.type === "string")
            message = `String must contain ${issue2.exact ? `exactly` : issue2.inclusive ? `at most` : `under`} ${issue2.maximum} character(s)`;
          else if (issue2.type === "number")
            message = `Number must be ${issue2.exact ? `exactly` : issue2.inclusive ? `less than or equal to` : `less than`} ${issue2.maximum}`;
          else if (issue2.type === "bigint")
            message = `BigInt must be ${issue2.exact ? `exactly` : issue2.inclusive ? `less than or equal to` : `less than`} ${issue2.maximum}`;
          else if (issue2.type === "date")
            message = `Date must be ${issue2.exact ? `exactly` : issue2.inclusive ? `smaller than or equal to` : `smaller than`} ${new Date(Number(issue2.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 ${issue2.multipleOf}`;
          break;
        case ZodIssueCode.not_finite:
          message = "Number must be finite";
          break;
        default:
          message = _ctx.defaultError;
          util2.assertNever(issue2);
      }
      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 issue2 = 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((x3) => !!x3)
  });
  ctx.common.issues.push(issue2);
}
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: path125, errorMaps, issueData } = params;
      const fullPath = [...path125, ...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((m3) => !!m3).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 s5 of results) {
          if (s5.status === "aborted")
            return INVALID;
          if (s5.status === "dirty")
            status.dirty();
          arrayValue.push(s5.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((x3) => x3.status === "aborted", "isAborted");
    isDirty = /* @__PURE__ */ __name((x3) => x3.status === "dirty", "isDirty");
    isValid = /* @__PURE__ */ __name((x3) => x3.status === "valid", "isValid");
    isAsync = /* @__PURE__ */ __name((x3) => typeof Promise !== "undefined" && x3 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 base642 = header.replace(/-/g, "+").replace(/_/g, "/").padEnd(header.length + (4 - header.length % 4) % 4, "=");
    const decoded = JSON.parse(atob(base642));
    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(a2, b2) {
  const aType = getParsedType(a2);
  const bType = getParsedType(b2);
  if (a2 === b2) {
    return { valid: true, data: a2 };
  } else if (aType === ZodParsedType.object && bType === ZodParsedType.object) {
    const bKeys = util2.objectKeys(b2);
    const sharedKeys = util2.objectKeys(a2).filter((key) => bKeys.indexOf(key) !== -1);
    const newObj = { ...a2, ...b2 };
    for (const key of sharedKeys) {
      const sharedValue = mergeValues(a2[key], b2[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 (a2.length !== b2.length) {
      return { valid: false };
    }
    const newArray = [];
    for (let index = 0; index < a2.length; index++) {
      const itemA = a2[index];
      const itemB = b2[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 && +a2 === +b2) {
    return { valid: true, data: a2 };
  } else {
    return { valid: false };
  }
}
function createZodEnum(values, params) {
  return new ZodEnum({
    values,
    typeName: ZodFirstPartyTypeKind.ZodEnum,
    ...processCreateParams(params)
  });
}
function cleanParams(params, data) {
  const p2 = typeof params === "function" ? params(data) : typeof params === "string" ? { message: params } : params;
  const p22 = typeof p2 === "string" ? { message: p2 } : p2;
  return p22;
}
function custom(check2, _params = {}, fatal) {
  if (check2)
    return ZodAny.create().superRefine((data, ctx) => {
      const r5 = check2(data);
      if (r5 instanceof Promise) {
        return r5.then((r6) => {
          if (!r6) {
            const params = cleanParams(_params, data);
            const _fatal = params.fatal ?? fatal ?? true;
            ctx.addIssue({ code: "custom", ...params, fatal: _fatal });
          }
        });
      }
      if (!r5) {
        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, emojiRegex, 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_types6 = __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, path125, key) {
        this._cachedPath = [];
        this.parent = parent;
        this.data = value;
        this._path = path125;
        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 error2 = new ZodError(ctx.common.issues);
            this._error = error2;
            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(check2, 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 = check2(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(check2, refinementData) {
        return this._refinement((val, ctx) => {
          if (!check2(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(transform2) {
        return new ZodEffects({
          ...processCreateParams(this._def),
          schema: this,
          typeName: ZodFirstPartyTypeKind.ZodEffects,
          effect: { type: "transform", transform: transform2 }
        });
      }
      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 _ZodString2 extends ZodType {
      static {
        __name(this, "ZodString");
      }
      _parse(input) {
        if (this._def.coerce) {
          input.data = String(input.data);
        }
        const parsedType2 = this._getType(input);
        if (parsedType2 !== 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 check2 of this._def.checks) {
          if (check2.kind === "min") {
            if (input.data.length < check2.value) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                code: ZodIssueCode.too_small,
                minimum: check2.value,
                type: "string",
                inclusive: true,
                exact: false,
                message: check2.message
              });
              status.dirty();
            }
          } else if (check2.kind === "max") {
            if (input.data.length > check2.value) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                code: ZodIssueCode.too_big,
                maximum: check2.value,
                type: "string",
                inclusive: true,
                exact: false,
                message: check2.message
              });
              status.dirty();
            }
          } else if (check2.kind === "length") {
            const tooBig = input.data.length > check2.value;
            const tooSmall = input.data.length < check2.value;
            if (tooBig || tooSmall) {
              ctx = this._getOrReturnCtx(input, ctx);
              if (tooBig) {
                addIssueToContext(ctx, {
                  code: ZodIssueCode.too_big,
                  maximum: check2.value,
                  type: "string",
                  inclusive: true,
                  exact: true,
                  message: check2.message
                });
              } else if (tooSmall) {
                addIssueToContext(ctx, {
                  code: ZodIssueCode.too_small,
                  minimum: check2.value,
                  type: "string",
                  inclusive: true,
                  exact: true,
                  message: check2.message
                });
              }
              status.dirty();
            }
          } else if (check2.kind === "email") {
            if (!emailRegex.test(input.data)) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                validation: "email",
                code: ZodIssueCode.invalid_string,
                message: check2.message
              });
              status.dirty();
            }
          } else if (check2.kind === "emoji") {
            if (!emojiRegex) {
              emojiRegex = new RegExp(_emojiRegex, "u");
            }
            if (!emojiRegex.test(input.data)) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                validation: "emoji",
                code: ZodIssueCode.invalid_string,
                message: check2.message
              });
              status.dirty();
            }
          } else if (check2.kind === "uuid") {
            if (!uuidRegex.test(input.data)) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                validation: "uuid",
                code: ZodIssueCode.invalid_string,
                message: check2.message
              });
              status.dirty();
            }
          } else if (check2.kind === "nanoid") {
            if (!nanoidRegex.test(input.data)) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                validation: "nanoid",
                code: ZodIssueCode.invalid_string,
                message: check2.message
              });
              status.dirty();
            }
          } else if (check2.kind === "cuid") {
            if (!cuidRegex.test(input.data)) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                validation: "cuid",
                code: ZodIssueCode.invalid_string,
                message: check2.message
              });
              status.dirty();
            }
          } else if (check2.kind === "cuid2") {
            if (!cuid2Regex.test(input.data)) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                validation: "cuid2",
                code: ZodIssueCode.invalid_string,
                message: check2.message
              });
              status.dirty();
            }
          } else if (check2.kind === "ulid") {
            if (!ulidRegex.test(input.data)) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                validation: "ulid",
                code: ZodIssueCode.invalid_string,
                message: check2.message
              });
              status.dirty();
            }
          } else if (check2.kind === "url") {
            try {
              new URL(input.data);
            } catch {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                validation: "url",
                code: ZodIssueCode.invalid_string,
                message: check2.message
              });
              status.dirty();
            }
          } else if (check2.kind === "regex") {
            check2.regex.lastIndex = 0;
            const testResult = check2.regex.test(input.data);
            if (!testResult) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                validation: "regex",
                code: ZodIssueCode.invalid_string,
                message: check2.message
              });
              status.dirty();
            }
          } else if (check2.kind === "trim") {
            input.data = input.data.trim();
          } else if (check2.kind === "includes") {
            if (!input.data.includes(check2.value, check2.position)) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                code: ZodIssueCode.invalid_string,
                validation: { includes: check2.value, position: check2.position },
                message: check2.message
              });
              status.dirty();
            }
          } else if (check2.kind === "toLowerCase") {
            input.data = input.data.toLowerCase();
          } else if (check2.kind === "toUpperCase") {
            input.data = input.data.toUpperCase();
          } else if (check2.kind === "startsWith") {
            if (!input.data.startsWith(check2.value)) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                code: ZodIssueCode.invalid_string,
                validation: { startsWith: check2.value },
                message: check2.message
              });
              status.dirty();
            }
          } else if (check2.kind === "endsWith") {
            if (!input.data.endsWith(check2.value)) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                code: ZodIssueCode.invalid_string,
                validation: { endsWith: check2.value },
                message: check2.message
              });
              status.dirty();
            }
          } else if (check2.kind === "datetime") {
            const regex3 = datetimeRegex(check2);
            if (!regex3.test(input.data)) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                code: ZodIssueCode.invalid_string,
                validation: "datetime",
                message: check2.message
              });
              status.dirty();
            }
          } else if (check2.kind === "date") {
            const regex3 = dateRegex;
            if (!regex3.test(input.data)) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                code: ZodIssueCode.invalid_string,
                validation: "date",
                message: check2.message
              });
              status.dirty();
            }
          } else if (check2.kind === "time") {
            const regex3 = timeRegex(check2);
            if (!regex3.test(input.data)) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                code: ZodIssueCode.invalid_string,
                validation: "time",
                message: check2.message
              });
              status.dirty();
            }
          } else if (check2.kind === "duration") {
            if (!durationRegex.test(input.data)) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                validation: "duration",
                code: ZodIssueCode.invalid_string,
                message: check2.message
              });
              status.dirty();
            }
          } else if (check2.kind === "ip") {
            if (!isValidIP(input.data, check2.version)) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                validation: "ip",
                code: ZodIssueCode.invalid_string,
                message: check2.message
              });
              status.dirty();
            }
          } else if (check2.kind === "jwt") {
            if (!isValidJWT(input.data, check2.alg)) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                validation: "jwt",
                code: ZodIssueCode.invalid_string,
                message: check2.message
              });
              status.dirty();
            }
          } else if (check2.kind === "cidr") {
            if (!isValidCidr(input.data, check2.version)) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                validation: "cidr",
                code: ZodIssueCode.invalid_string,
                message: check2.message
              });
              status.dirty();
            }
          } else if (check2.kind === "base64") {
            if (!base64Regex.test(input.data)) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                validation: "base64",
                code: ZodIssueCode.invalid_string,
                message: check2.message
              });
              status.dirty();
            }
          } else if (check2.kind === "base64url") {
            if (!base64urlRegex.test(input.data)) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                validation: "base64url",
                code: ZodIssueCode.invalid_string,
                message: check2.message
              });
              status.dirty();
            }
          } else {
            util2.assertNever(check2);
          }
        }
        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(check2) {
        return new _ZodString2({
          ...this._def,
          checks: [...this._def.checks, check2]
        });
      }
      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 _ZodString2({
          ...this._def,
          checks: [...this._def.checks, { kind: "trim" }]
        });
      }
      toLowerCase() {
        return new _ZodString2({
          ...this._def,
          checks: [...this._def.checks, { kind: "toLowerCase" }]
        });
      }
      toUpperCase() {
        return new _ZodString2({
          ...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 parsedType2 = this._getType(input);
        if (parsedType2 !== 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 check2 of this._def.checks) {
          if (check2.kind === "int") {
            if (!util2.isInteger(input.data)) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                code: ZodIssueCode.invalid_type,
                expected: "integer",
                received: "float",
                message: check2.message
              });
              status.dirty();
            }
          } else if (check2.kind === "min") {
            const tooSmall = check2.inclusive ? input.data < check2.value : input.data <= check2.value;
            if (tooSmall) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                code: ZodIssueCode.too_small,
                minimum: check2.value,
                type: "number",
                inclusive: check2.inclusive,
                exact: false,
                message: check2.message
              });
              status.dirty();
            }
          } else if (check2.kind === "max") {
            const tooBig = check2.inclusive ? input.data > check2.value : input.data >= check2.value;
            if (tooBig) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                code: ZodIssueCode.too_big,
                maximum: check2.value,
                type: "number",
                inclusive: check2.inclusive,
                exact: false,
                message: check2.message
              });
              status.dirty();
            }
          } else if (check2.kind === "multipleOf") {
            if (floatSafeRemainder(input.data, check2.value) !== 0) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                code: ZodIssueCode.not_multiple_of,
                multipleOf: check2.value,
                message: check2.message
              });
              status.dirty();
            }
          } else if (check2.kind === "finite") {
            if (!Number.isFinite(input.data)) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                code: ZodIssueCode.not_finite,
                message: check2.message
              });
              status.dirty();
            }
          } else {
            util2.assertNever(check2);
          }
        }
        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(kind2, value, inclusive, message) {
        return new _ZodNumber({
          ...this._def,
          checks: [
            ...this._def.checks,
            {
              kind: kind2,
              value,
              inclusive,
              message: errorUtil.toString(message)
            }
          ]
        });
      }
      _addCheck(check2) {
        return new _ZodNumber({
          ...this._def,
          checks: [...this._def.checks, check2]
        });
      }
      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 parsedType2 = this._getType(input);
        if (parsedType2 !== ZodParsedType.bigint) {
          return this._getInvalidInput(input);
        }
        let ctx = void 0;
        const status = new ParseStatus();
        for (const check2 of this._def.checks) {
          if (check2.kind === "min") {
            const tooSmall = check2.inclusive ? input.data < check2.value : input.data <= check2.value;
            if (tooSmall) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                code: ZodIssueCode.too_small,
                type: "bigint",
                minimum: check2.value,
                inclusive: check2.inclusive,
                message: check2.message
              });
              status.dirty();
            }
          } else if (check2.kind === "max") {
            const tooBig = check2.inclusive ? input.data > check2.value : input.data >= check2.value;
            if (tooBig) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                code: ZodIssueCode.too_big,
                type: "bigint",
                maximum: check2.value,
                inclusive: check2.inclusive,
                message: check2.message
              });
              status.dirty();
            }
          } else if (check2.kind === "multipleOf") {
            if (input.data % check2.value !== BigInt(0)) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                code: ZodIssueCode.not_multiple_of,
                multipleOf: check2.value,
                message: check2.message
              });
              status.dirty();
            }
          } else {
            util2.assertNever(check2);
          }
        }
        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(kind2, value, inclusive, message) {
        return new _ZodBigInt({
          ...this._def,
          checks: [
            ...this._def.checks,
            {
              kind: kind2,
              value,
              inclusive,
              message: errorUtil.toString(message)
            }
          ]
        });
      }
      _addCheck(check2) {
        return new _ZodBigInt({
          ...this._def,
          checks: [...this._def.checks, check2]
        });
      }
      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 parsedType2 = this._getType(input);
        if (parsedType2 !== 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 parsedType2 = this._getType(input);
        if (parsedType2 !== 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 check2 of this._def.checks) {
          if (check2.kind === "min") {
            if (input.data.getTime() < check2.value) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                code: ZodIssueCode.too_small,
                message: check2.message,
                inclusive: true,
                exact: false,
                minimum: check2.value,
                type: "date"
              });
              status.dirty();
            }
          } else if (check2.kind === "max") {
            if (input.data.getTime() > check2.value) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                code: ZodIssueCode.too_big,
                message: check2.message,
                inclusive: true,
                exact: false,
                maximum: check2.value,
                type: "date"
              });
              status.dirty();
            }
          } else {
            util2.assertNever(check2);
          }
        }
        return {
          status: status.value,
          value: new Date(input.data.getTime())
        };
      }
      _addCheck(check2) {
        return new _ZodDate({
          ...this._def,
          checks: [...this._def.checks, check2]
        });
      }
      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 parsedType2 = this._getType(input);
        if (parsedType2 !== 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 parsedType2 = this._getType(input);
        if (parsedType2 !== 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 parsedType2 = this._getType(input);
        if (parsedType2 !== 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 parsedType2 = this._getType(input);
        if (parsedType2 !== 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, i3) => {
            return def2.type._parseAsync(new ParseInputLazyPath(ctx, item, ctx.path, i3));
          })).then((result2) => {
            return ParseStatus.mergeArray(status, result2);
          });
        }
        const result = [...ctx.data].map((item, i3) => {
          return def2.type._parseSync(new ParseInputLazyPath(ctx, item, ctx.path, i3));
        });
        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 parsedType2 = this._getType(input);
        if (parsedType2 !== 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((issue2, ctx) => {
              const defaultError = this._def.errorMap?.(issue2, ctx).message ?? ctx.defaultError;
              if (issue2.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 = (types7, params) => {
      return new ZodUnion({
        options: types7,
        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((x3) => !!x3);
        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, i3) => valueType._parse(new ParseInputLazyPath(ctx, item, ctx.path, i3)));
        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, error2) {
          return makeIssue({
            data: args,
            path: ctx.path,
            errorMaps: [ctx.common.contextualErrorMap, ctx.schemaErrorMap, getErrorMap(), en_default].filter((x3) => !!x3),
            issueData: {
              code: ZodIssueCode.invalid_arguments,
              argumentsError: error2
            }
          });
        }
        __name(makeArgsIssue, "makeArgsIssue");
        function makeReturnsIssue(returns, error2) {
          return makeIssue({
            data: returns,
            path: ctx.path,
            errorMaps: [ctx.common.contextualErrorMap, ctx.schemaErrorMap, getErrorMap(), en_default].filter((x3) => !!x3),
            issueData: {
              code: ZodIssueCode.invalid_return_type,
              returnTypeError: error2
            }
          });
        }
        __name(makeReturnsIssue, "makeReturnsIssue");
        const params = { errorMap: ctx.common.contextualErrorMap };
        const fn = ctx.data;
        if (this._def.returns instanceof ZodPromise) {
          const me2 = this;
          return OK(async function(...args) {
            const error2 = new ZodError([]);
            const parsedArgs = await me2._def.args.parseAsync(args, params).catch((e4) => {
              error2.addIssue(makeArgsIssue(args, e4));
              throw error2;
            });
            const result = await Reflect.apply(fn, this, parsedArgs);
            const parsedReturns = await me2._def.returns._def.type.parseAsync(result, params).catch((e4) => {
              error2.addIssue(makeReturnsIssue(result, e4));
              throw error2;
            });
            return parsedReturns;
          });
        } else {
          const me2 = this;
          return OK(function(...args) {
            const parsedArgs = me2._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 = me2._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 = (preprocess3, schema, params) => {
      return new ZodEffects({
        schema,
        effect: { type: "preprocess", transform: preprocess3 },
        typeName: ZodFirstPartyTypeKind.ZodEffects,
        ...processCreateParams(params)
      });
    };
    ZodOptional = class extends ZodType {
      static {
        __name(this, "ZodOptional");
      }
      _parse(input) {
        const parsedType2 = this._getType(input);
        if (parsedType2 === 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 parsedType2 = this._getType(input);
        if (parsedType2 === 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 parsedType2 = this._getType(input);
        if (parsedType2 !== 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(a2, b2) {
        return new _ZodPipeline({
          in: a2,
          out: b2,
          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_types6();
    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_types7 = __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
var debugLogger32, MAX_TURNS, GeminiClient;
var init_client2 = __esm({
  "packages/core/dist/src/core/client.js"() {
    "use strict";
    init_esbuild_shims();
    init_config3();
    init_debugLogger();
    init_geminiChat();
    init_prompts();
    init_turn();
    init_chatCompressionService();
    init_loopDetectionService();
    init_task();
    init_telemetry();
    init_uiTelemetry();
    init_environmentContext();
    init_sessionService();
    init_errorReporting();
    init_errors();
    init_nextSpeakerChecker();
    init_partUtils();
    init_retry();
    init_ideContext();
    init_types7();
    debugLogger32 = createDebugLogger("CLIENT");
    MAX_TURNS = 100;
    GeminiClient = class {
      static {
        __name(this, "GeminiClient");
      }
      config;
      chat;
      sessionTurnCount = 0;
      loopDetector;
      lastPromptId = void 0;
      lastSentIdeContext;
      forceFullIdeContext = true;
      /**
       * At any point in this conversation, was compression triggered without
       * being forced and did it fail?
       */
      hasFailedCompressionAttempt = false;
      constructor(config2) {
        this.config = config2;
        this.loopDetector = new LoopDetectionService(config2);
      }
      async initialize() {
        this.lastPromptId = this.config.getSessionId();
        const resumedSessionData = this.config.getResumedSessionData();
        if (resumedSessionData) {
          replayUiTelemetryFromConversation(resumedSessionData.conversation);
          const resumedHistory = buildApiHistoryFromConversation(resumedSessionData.conversation);
          this.chat = await this.startChat(resumedHistory);
        } else {
          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();
      }
      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);
          return new GeminiChat(this.config, {
            systemInstruction,
            tools
          }, history, this.config.getChatRecordingService());
        } catch (error2) {
          await reportError2(error2, "Error initializing chat session.", history, "startChat");
          throw new Error(`Failed to initialize chat: ${getErrorMessage(error2)}`);
        }
      }
      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((f5) => f5.isActive);
          const otherOpenFiles = openFiles.filter((f5) => !f5.isActive).map((f5) => f5.path);
          const contextLines = [];
          if (activeFile) {
            contextLines.push("Active file:");
            contextLines.push(`  Path: ${activeFile.path}`);
            if (activeFile.cursor) {
              contextLines.push(`  Cursor: line ${activeFile.cursor.line}, character ${activeFile.cursor.character}`);
            }
            if (activeFile.selectedText) {
              contextLines.push("  Selected text:");
              contextLines.push("```");
              contextLines.push(activeFile.selectedText);
              contextLines.push("```");
            }
          }
          if (otherOpenFiles.length > 0) {
            if (contextLines.length > 0) {
              contextLines.push("");
            }
            contextLines.push("Other open files:");
            for (const filePath of otherOpenFiles) {
              contextLines.push(`  - ${filePath}`);
            }
          }
          if (contextLines.length === 0) {
            return { contextParts: [], newIdeContext: currentIdeContext };
          }
          const contextParts = [
            "Here is the user's editor context. This is for your information only.",
            contextLines.join("\n")
          ];
          debugLogger32.debug(contextParts.join("\n"));
          return {
            contextParts,
            newIdeContext: currentIdeContext
          };
        } else {
          const changeLines = [];
          const lastFiles = new Map((this.lastSentIdeContext.workspaceState?.openFiles || []).map((f5) => [f5.path, f5]));
          const currentFiles = new Map((currentIdeContext.workspaceState?.openFiles || []).map((f5) => [
            f5.path,
            f5
          ]));
          const openedFiles = [];
          for (const [path125] of currentFiles.entries()) {
            if (!lastFiles.has(path125)) {
              openedFiles.push(path125);
            }
          }
          if (openedFiles.length > 0) {
            changeLines.push("Files opened:");
            for (const filePath of openedFiles) {
              changeLines.push(`  - ${filePath}`);
            }
          }
          const closedFiles = [];
          for (const [path125] of lastFiles.entries()) {
            if (!currentFiles.has(path125)) {
              closedFiles.push(path125);
            }
          }
          if (closedFiles.length > 0) {
            if (changeLines.length > 0) {
              changeLines.push("");
            }
            changeLines.push("Files closed:");
            for (const filePath of closedFiles) {
              changeLines.push(`  - ${filePath}`);
            }
          }
          const lastActiveFile = (this.lastSentIdeContext.workspaceState?.openFiles || []).find((f5) => f5.isActive);
          const currentActiveFile = (currentIdeContext.workspaceState?.openFiles || []).find((f5) => f5.isActive);
          if (currentActiveFile) {
            if (!lastActiveFile || lastActiveFile.path !== currentActiveFile.path) {
              if (changeLines.length > 0) {
                changeLines.push("");
              }
              changeLines.push("Active file changed:");
              changeLines.push(`  Path: ${currentActiveFile.path}`);
              if (currentActiveFile.cursor) {
                changeLines.push(`  Cursor: line ${currentActiveFile.cursor.line}, character ${currentActiveFile.cursor.character}`);
              }
              if (currentActiveFile.selectedText) {
                changeLines.push("  Selected text:");
                changeLines.push("```");
                changeLines.push(currentActiveFile.selectedText);
                changeLines.push("```");
              }
            } else {
              const lastCursor = lastActiveFile.cursor;
              const currentCursor = currentActiveFile.cursor;
              if (currentCursor && (!lastCursor || lastCursor.line !== currentCursor.line || lastCursor.character !== currentCursor.character)) {
                if (changeLines.length > 0) {
                  changeLines.push("");
                }
                changeLines.push("Cursor moved:");
                changeLines.push(`  Path: ${currentActiveFile.path}`);
                changeLines.push(`  New position: line ${currentCursor.line}, character ${currentCursor.character}`);
              }
              const lastSelectedText = lastActiveFile.selectedText || "";
              const currentSelectedText = currentActiveFile.selectedText || "";
              if (lastSelectedText !== currentSelectedText) {
                if (changeLines.length > 0) {
                  changeLines.push("");
                }
                changeLines.push("Selection changed:");
                changeLines.push(`  Path: ${currentActiveFile.path}`);
                if (currentSelectedText) {
                  changeLines.push("  Selected text:");
                  changeLines.push("```");
                  changeLines.push(currentSelectedText);
                  changeLines.push("```");
                } else {
                  changeLines.push("  Selected text: (none)");
                }
              }
            }
          } else if (lastActiveFile) {
            if (changeLines.length > 0) {
              changeLines.push("");
            }
            changeLines.push("Active file changed:");
            changeLines.push("  No active file");
            changeLines.push(`  Previous path: ${lastActiveFile.path}`);
          }
          if (changeLines.length === 0) {
            return { contextParts: [], newIdeContext: currentIdeContext };
          }
          const contextParts = [
            "Here is a summary of changes in the user's editor context. This is for your information only.",
            changeLines.join("\n")
          ];
          debugLogger32.debug(contextParts.join("\n"));
          return {
            contextParts,
            newIdeContext: currentIdeContext
          };
        }
      }
      async *sendMessageStream(request4, signal, prompt_id, options2, turns = MAX_TURNS) {
        if (!options2?.isContinuation) {
          this.loopDetector.reset(prompt_id);
          this.lastPromptId = prompt_id;
          this.config.getChatRecordingService()?.recordUserMessage(request4);
          this.stripThoughtsFromHistory();
        }
        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 lastPromptTokenCount = uiTelemetryService.getLastPromptTokenCount();
          if (lastPromptTokenCount > sessionTokenLimit) {
            yield {
              type: GeminiEventType.SessionTokenLimitExceeded,
              value: {
                currentTokens: lastPromptTokenCount,
                limit: sessionTokenLimit,
                message: `Session token limit exceeded: ${lastPromptTokenCount} 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((p2) => "functionCall" in p2) || 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 (!options2?.isContinuation) {
          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(this.config.getSdkMode()));
          }
          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.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, options2, boundedTurns - 1);
          }
        }
        return turn;
      }
      async generateContent(contents, generationConfig, abortSignal, model) {
        let currentAttemptModel = model;
        try {
          const userMemory = this.config.getUserMemory();
          const finalSystemInstruction = generationConfig.systemInstruction ? getCustomSystemPrompt(generationConfig.systemInstruction, userMemory) : getCoreSystemPrompt(userMemory, this.config.getModel());
          const requestConfig = {
            abortSignal,
            ...generationConfig,
            systemInstruction: finalSystemInstruction
          };
          const apiCall = /* @__PURE__ */ __name(() => {
            currentAttemptModel = model;
            return this.getContentGeneratorOrFail().generateContent({
              model,
              config: requestConfig,
              contents
            }, this.lastPromptId);
          }, "apiCall");
          const result = await retryWithBackoff(apiCall, {
            authType: this.config.getContentGeneratorConfig()?.authType
          });
          return result;
        } catch (error2) {
          if (abortSignal.aborted) {
            throw error2;
          }
          await reportError2(error2, `Error generating content via API with model ${currentAttemptModel}.`, {
            requestContents: contents,
            requestConfig: generationConfig
          }, "generateContent-api");
          throw new Error(`Failed to generate content with model ${currentAttemptModel}: ${getErrorMessage(error2)}`);
        }
      }
      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) {
            const chatRecordingService = this.config.getChatRecordingService();
            chatRecordingService?.recordChatCompression({
              info,
              compressedHistory: newHistory
            });
            this.chat = await this.startChat(newHistory);
            uiTelemetryService.setLastPromptTokenCount(info.newTokenCount);
            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 SPACE3 = " ";
    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 SLASH2 = "/";
    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((object3, key, value) => {
      Object.defineProperty(object3, 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+)$/,
        (_2, m1, m22) => m1 + (m22.indexOf("\\") === 0 ? SPACE3 : EMPTY2)
      ],
      // Replace (\ ) with ' '
      // (\ ) -> ' '
      // (\\ ) -> '\\ '
      // (\\\ ) -> '\\ '
      [
        /(\\+?)\s/g,
        (_2, m1) => {
          const { length } = m1;
          return m1.slice(0, length - length % 2) + SPACE3;
        }
      ],
      // 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 `'/**'`
        (_2, 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'
        (_2, 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](_2, p1) {
        const prefix = p1 ? `${p1}[^/]+` : "[^/]*";
        return `${prefix}(?=$|\\/$)`;
      },
      [MODE_CHECK_IGNORE](_2, 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(path125, 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(path125);
          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((path125, originalPath, doThrow) => {
      if (!isString2(path125)) {
        return doThrow(
          `path must be a string, but got \`${originalPath}\``,
          TypeError
        );
      }
      if (!path125) {
        return doThrow(`path must not be empty`, TypeError);
      }
      if (checkPath.isNotRelative(path125)) {
        const r5 = "`path.relative()`d";
        return doThrow(
          `path should be a ${r5} string, but got "${originalPath}"`,
          RangeError
        );
      }
      return true;
    }, "checkPath");
    var isNotRelative = /* @__PURE__ */ __name((path125) => REGEX_TEST_INVALID_PATH.test(path125), "isNotRelative");
    checkPath.isNotRelative = isNotRelative;
    checkPath.convert = (p2) => p2;
    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 path125 = originalPath && checkPath.convert(originalPath);
        checkPath(
          path125,
          originalPath,
          this._strictPathCheck ? throwError : RETURN_FALSE
        );
        return this._t(path125, cache5, checkUnignored, slices);
      }
      checkIgnore(path125) {
        if (!REGEX_TEST_TRAILING_SLASH.test(path125)) {
          return this.test(path125);
        }
        const slices = path125.split(SLASH2).filter(Boolean);
        slices.pop();
        if (slices.length) {
          const parent = this._t(
            slices.join(SLASH2) + SLASH2,
            this._testCache,
            true,
            slices
          );
          if (parent.ignored) {
            return parent;
          }
        }
        return this._rules.test(path125, false, MODE_CHECK_IGNORE);
      }
      _t(path125, cache5, checkUnignored, slices) {
        if (path125 in cache5) {
          return cache5[path125];
        }
        if (!slices) {
          slices = path125.split(SLASH2).filter(Boolean);
        }
        slices.pop();
        if (!slices.length) {
          return cache5[path125] = this._rules.test(path125, checkUnignored, MODE_IGNORE);
        }
        const parent = this._t(
          slices.join(SLASH2) + SLASH2,
          cache5,
          checkUnignored,
          slices
        );
        return cache5[path125] = parent.ignored ? parent : this._rules.test(path125, checkUnignored, MODE_IGNORE);
      }
      ignores(path125) {
        return this._test(path125, this._ignoreCache, false).ignored;
      }
      createFilter() {
        return (path125) => !this.ignores(path125);
      }
      filter(paths) {
        return makeArray(paths).filter(this.createFilter());
      }
      // @returns {TestResult}
      test(path125) {
        return this._test(path125, this._testCache, true);
      }
    };
    var factory = /* @__PURE__ */ __name((options2) => new Ignore3(options2), "factory");
    var isPathValid = /* @__PURE__ */ __name((path125) => checkPath(path125 && checkPath.convert(path125), path125, 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 = (path125) => REGEX_TEST_WINDOWS_PATH_ABSOLUTE.test(path125) || isNotRelative(path125);
    }, "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 fs28 from "node:fs";
import * as path21 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 = path21.resolve(projectRoot);
      }
      loadPatternsForFile(patternsFilePath) {
        let content;
        try {
          content = fs28.readFileSync(patternsFilePath, "utf-8");
        } catch (_error) {
          return [];
        }
        const isExcludeFile = patternsFilePath.endsWith(path21.join(".git", "info", "exclude"));
        const relativeBaseDir = isExcludeFile ? "." : path21.dirname(path21.relative(this.projectRoot, patternsFilePath));
        return content.split("\n").map((p2) => p2.trim()).filter((p2) => p2 !== "" && !p2.startsWith("#")).map((p2) => {
          const isNegative = p2.startsWith("!");
          if (isNegative) {
            p2 = p2.substring(1);
          }
          const isAnchoredInFile = p2.startsWith("/");
          if (isAnchoredInFile) {
            p2 = p2.substring(1);
          }
          if (p2 === "") {
            return "";
          }
          let newPattern = p2;
          if (relativeBaseDir && relativeBaseDir !== ".") {
            if (!isAnchoredInFile && !p2.includes("/")) {
              newPattern = path21.join("**", p2);
            }
            newPattern = path21.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((p2) => p2 !== "");
      }
      isIgnored(filePath) {
        if (!filePath || typeof filePath !== "string") {
          return false;
        }
        const absoluteFilePath = path21.resolve(this.projectRoot, filePath);
        if (!absoluteFilePath.startsWith(this.projectRoot)) {
          return false;
        }
        try {
          const resolved = path21.resolve(this.projectRoot, filePath);
          const relativePath = path21.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 = path21.join(this.projectRoot, ".git", "info", "exclude");
            this.globalPatterns = fs28.existsSync(excludeFile) ? this.loadPatternsForFile(excludeFile) : [];
          }
          ig.add(this.globalPatterns);
          const pathParts = relativePath.split(path21.sep);
          const dirsToVisit = [this.projectRoot];
          let currentAbsDir = this.projectRoot;
          for (let i3 = 0; i3 < pathParts.length - 1; i3++) {
            currentAbsDir = path21.join(currentAbsDir, pathParts[i3]);
            dirsToVisit.push(currentAbsDir);
          }
          for (const dir of dirsToVisit) {
            const relativeDir = path21.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 = path21.join(dir, ".gitignore");
              if (fs28.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 fs29 from "node:fs";
import * as path22 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 = path22.resolve(projectRoot);
        this.loadPatterns();
      }
      loadPatterns() {
        const patternsFilePath = path22.join(this.projectRoot, ".qwenignore");
        let content;
        try {
          content = fs29.readFileSync(patternsFilePath, "utf-8");
        } catch (_error) {
          return;
        }
        this.patterns = (content ?? "").split("\n").map((p2) => p2.trim()).filter((p2) => p2 !== "" && !p2.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 = 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;
        }
        return this.ig.ignores(normalizedPath);
      }
      getPatterns() {
        return this.patterns;
      }
    };
  }
});

// packages/core/dist/src/services/fileDiscoveryService.js
import * as path23 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 = path23.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(a2, b2, str2) {
      if (a2 instanceof RegExp) a2 = maybeMatch(a2, str2);
      if (b2 instanceof RegExp) b2 = maybeMatch(b2, str2);
      var r5 = range(a2, b2, str2);
      return r5 && {
        start: r5[0],
        end: r5[1],
        pre: str2.slice(0, r5[0]),
        body: str2.slice(r5[0] + a2.length, r5[1]),
        post: str2.slice(r5[1] + b2.length)
      };
    }
    __name(balanced, "balanced");
    function maybeMatch(reg, str2) {
      var m3 = str2.match(reg);
      return m3 ? m3[0] : null;
    }
    __name(maybeMatch, "maybeMatch");
    balanced.range = range;
    function range(a2, b2, str2) {
      var begs, beg, left3, right3, result;
      var ai = str2.indexOf(a2);
      var bi = str2.indexOf(b2, ai + 1);
      var i3 = ai;
      if (ai >= 0 && bi > 0) {
        if (a2 === b2) {
          return [ai, bi];
        }
        begs = [];
        left3 = str2.length;
        while (i3 >= 0 && !result) {
          if (i3 == ai) {
            begs.push(i3);
            ai = str2.indexOf(a2, i3 + 1);
          } else if (begs.length == 1) {
            result = [begs.pop(), bi];
          } else {
            beg = begs.pop();
            if (beg < left3) {
              left3 = beg;
              right3 = bi;
            }
            bi = str2.indexOf(b2, i3 + 1);
          }
          i3 = 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 m3 = balanced("{", "}", str2);
      if (!m3)
        return str2.split(",");
      var pre = m3.pre;
      var body = m3.body;
      var post = m3.post;
      var p2 = pre.split(",");
      p2[p2.length - 1] += "{" + body + "}";
      var postParts = parseCommaParts(post);
      if (post.length) {
        p2[p2.length - 1] += postParts.shift();
        p2.push.apply(p2, postParts);
      }
      parts.push.apply(parts, p2);
      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(i3, y2) {
      return i3 <= y2;
    }
    __name(lte, "lte");
    function gte(i3, y2) {
      return i3 >= y2;
    }
    __name(gte, "gte");
    function expand2(str2, isTop) {
      var expansions = [];
      var m3 = balanced("{", "}", str2);
      if (!m3) return [str2];
      var pre = m3.pre;
      var post = m3.post.length ? expand2(m3.post, false) : [""];
      if (/\$$/.test(m3.pre)) {
        for (var k2 = 0; k2 < post.length; k2++) {
          var expansion = pre + "{" + m3.body + "}" + post[k2];
          expansions.push(expansion);
        }
      } else {
        var isNumericSequence = /^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(m3.body);
        var isAlphaSequence = /^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(m3.body);
        var isSequence = isNumericSequence || isAlphaSequence;
        var isOptions = m3.body.indexOf(",") >= 0;
        if (!isSequence && !isOptions) {
          if (m3.post.match(/,(?!,).*\}/)) {
            str2 = m3.pre + "{" + m3.body + escClose + m3.post;
            return expand2(str2);
          }
          return [str2];
        }
        var n3;
        if (isSequence) {
          n3 = m3.body.split(/\.\./);
        } else {
          n3 = parseCommaParts(m3.body);
          if (n3.length === 1) {
            n3 = expand2(n3[0], false).map(embrace);
            if (n3.length === 1) {
              return post.map(function(p2) {
                return m3.pre + n3[0] + p2;
              });
            }
          }
        }
        var N2;
        if (isSequence) {
          var x3 = numeric(n3[0]);
          var y2 = numeric(n3[1]);
          var width = Math.max(n3[0].length, n3[1].length);
          var incr = n3.length == 3 ? Math.abs(numeric(n3[2])) : 1;
          var test = lte;
          var reverse = y2 < x3;
          if (reverse) {
            incr *= -1;
            test = gte;
          }
          var pad = n3.some(isPadded);
          N2 = [];
          for (var i3 = x3; test(i3, y2); i3 += incr) {
            var c4;
            if (isAlphaSequence) {
              c4 = String.fromCharCode(i3);
              if (c4 === "\\")
                c4 = "";
            } else {
              c4 = String(i3);
              if (pad) {
                var need = width - c4.length;
                if (need > 0) {
                  var z2 = new Array(need + 1).join("0");
                  if (i3 < 0)
                    c4 = "-" + z2 + c4.slice(1);
                  else
                    c4 = z2 + c4;
                }
              }
            }
            N2.push(c4);
          }
        } else {
          N2 = [];
          for (var j2 = 0; j2 < n3.length; j2++) {
            N2.push.apply(N2, expand2(n3[j2], false));
          }
        }
        for (var j2 = 0; j2 < N2.length; j2++) {
          for (var k2 = 0; k2 < post.length; k2++) {
            var expansion = pre + N2[j2] + post[k2];
            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((s5) => s5.replace(/[[\]\\-]/g, "\\$&"), "braceEscape");
    regexpEscape = /* @__PURE__ */ __name((s5) => s5.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 i3 = pos2 + 1;
      let sawStart = false;
      let uflag = false;
      let escaping = false;
      let negate = false;
      let endPos = pos2;
      let rangeStart = "";
      WHILE: while (i3 < glob2.length) {
        const c4 = glob2.charAt(i3);
        if ((c4 === "!" || c4 === "^") && i3 === pos2 + 1) {
          negate = true;
          i3++;
          continue;
        }
        if (c4 === "]" && sawStart && !escaping) {
          endPos = i3 + 1;
          break;
        }
        sawStart = true;
        if (c4 === "\\") {
          if (!escaping) {
            escaping = true;
            i3++;
            continue;
          }
        }
        if (c4 === "[" && !escaping) {
          for (const [cls, [unip, u2, neg]] of Object.entries(posixClasses)) {
            if (glob2.startsWith(cls, i3)) {
              if (rangeStart) {
                return ["$.", false, glob2.length - pos2, true];
              }
              i3 += cls.length;
              if (neg)
                negs.push(unip);
              else
                ranges2.push(unip);
              uflag = uflag || u2;
              continue WHILE;
            }
          }
        }
        escaping = false;
        if (rangeStart) {
          if (c4 > rangeStart) {
            ranges2.push(braceEscape(rangeStart) + "-" + braceEscape(c4));
          } else if (c4 === rangeStart) {
            ranges2.push(braceEscape(c4));
          }
          rangeStart = "";
          i3++;
          continue;
        }
        if (glob2.startsWith("-]", i3 + 1)) {
          ranges2.push(braceEscape(c4 + "-"));
          i3 += 2;
          continue;
        }
        if (glob2.startsWith("-", i3 + 1)) {
          rangeStart = c4;
          i3 += 2;
          continue;
        }
        ranges2.push(braceEscape(c4));
        i3++;
      }
      if (endPos < i3) {
        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 r5 = ranges2[0].length === 2 ? ranges2[0].slice(-1) : ranges2[0];
        return [regexpEscape(r5), 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((s5, { windowsPathsNoEscape = false } = {}) => {
      return windowsPathsNoEscape ? s5.replace(/\[([^\/\\])\]/g, "$1") : s5.replace(/((?!\\).|^)\[([^\/\\])\]/g, "$1$2").replace(/\\([^\/])/g, "$1");
    }, "unescape");
  }
});

// node_modules/glob/node_modules/minimatch/dist/esm/ast.js
var types3, 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();
    types3 = /* @__PURE__ */ new Set(["!", "?", "+", "*", "@"]);
    isExtglobType = /* @__PURE__ */ __name((c4) => types3.has(c4), "isExtglobType");
    startNoTraversal = "(?!(?:^|/)\\.\\.?(?:$|/))";
    startNoDot = "(?!\\.)";
    addPatternStart = /* @__PURE__ */ new Set(["[", "."]);
    justDots = /* @__PURE__ */ new Set(["..", "."]);
    reSpecials = new Set("().*{}+?[]^$\\!");
    regExpEscape = /* @__PURE__ */ __name((s5) => s5.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 p2 of this.#parts) {
          if (typeof p2 === "string")
            continue;
          if (p2.type || p2.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((p2) => String(p2)).join("");
        } else {
          return this.#toString = this.type + "(" + this.#parts.map((p2) => String(p2)).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 n3;
        while (n3 = this.#negs.pop()) {
          if (n3.type !== "!")
            continue;
          let p2 = n3;
          let pp = p2.#parent;
          while (pp) {
            for (let i3 = p2.#parentIndex + 1; !pp.type && i3 < pp.#parts.length; i3++) {
              for (const part of n3.#parts) {
                if (typeof part === "string") {
                  throw new Error("string part in extglob AST??");
                }
                part.copyIn(pp.#parts[i3]);
              }
            }
            p2 = pp;
            pp = p2.#parent;
          }
        }
        return this;
      }
      push(...parts) {
        for (const p2 of parts) {
          if (p2 === "")
            continue;
          if (typeof p2 !== "string" && !(p2 instanceof _AST && p2.#parent === this)) {
            throw new Error("invalid part: " + p2);
          }
          this.#parts.push(p2);
        }
      }
      toJSON() {
        const ret = this.type === null ? this.#parts.slice().map((p2) => typeof p2 === "string" ? p2 : p2.toJSON()) : [this.type, ...this.#parts.map((p2) => p2.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 p2 = this.#parent;
        for (let i3 = 0; i3 < this.#parentIndex; i3++) {
          const pp = p2.#parts[i3];
          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 pl2 = this.#parent ? this.#parent.#parts.length : 0;
        return this.#parentIndex === pl2 - 1;
      }
      copyIn(part) {
        if (typeof part === "string")
          this.push(part);
        else
          this.push(part.clone(this));
      }
      clone(parent) {
        const c4 = new _AST(this.type, parent);
        for (const p2 of this.#parts) {
          c4.copyIn(p2);
        }
        return c4;
      }
      static #parseAST(str2, ast, pos2, opt) {
        let escaping = false;
        let inBrace = false;
        let braceStart = -1;
        let braceNeg = false;
        if (ast.type === null) {
          let i4 = pos2;
          let acc2 = "";
          while (i4 < str2.length) {
            const c4 = str2.charAt(i4++);
            if (escaping || c4 === "\\") {
              escaping = !escaping;
              acc2 += c4;
              continue;
            }
            if (inBrace) {
              if (i4 === braceStart + 1) {
                if (c4 === "^" || c4 === "!") {
                  braceNeg = true;
                }
              } else if (c4 === "]" && !(i4 === braceStart + 2 && braceNeg)) {
                inBrace = false;
              }
              acc2 += c4;
              continue;
            } else if (c4 === "[") {
              inBrace = true;
              braceStart = i4;
              braceNeg = false;
              acc2 += c4;
              continue;
            }
            if (!opt.noext && isExtglobType(c4) && str2.charAt(i4) === "(") {
              ast.push(acc2);
              acc2 = "";
              const ext2 = new _AST(c4, ast);
              i4 = _AST.#parseAST(str2, ext2, i4, opt);
              ast.push(ext2);
              continue;
            }
            acc2 += c4;
          }
          ast.push(acc2);
          return i4;
        }
        let i3 = pos2 + 1;
        let part = new _AST(null, ast);
        const parts = [];
        let acc = "";
        while (i3 < str2.length) {
          const c4 = str2.charAt(i3++);
          if (escaping || c4 === "\\") {
            escaping = !escaping;
            acc += c4;
            continue;
          }
          if (inBrace) {
            if (i3 === braceStart + 1) {
              if (c4 === "^" || c4 === "!") {
                braceNeg = true;
              }
            } else if (c4 === "]" && !(i3 === braceStart + 2 && braceNeg)) {
              inBrace = false;
            }
            acc += c4;
            continue;
          } else if (c4 === "[") {
            inBrace = true;
            braceStart = i3;
            braceNeg = false;
            acc += c4;
            continue;
          }
          if (isExtglobType(c4) && str2.charAt(i3) === "(") {
            part.push(acc);
            acc = "";
            const ext2 = new _AST(c4, part);
            part.push(ext2);
            i3 = _AST.#parseAST(str2, ext2, i3, opt);
            continue;
          }
          if (c4 === "|") {
            part.push(acc);
            acc = "";
            parts.push(part);
            part = new _AST(null, ast);
            continue;
          }
          if (c4 === ")") {
            if (acc === "" && ast.#parts.length === 0) {
              ast.#emptyExt = true;
            }
            part.push(acc);
            acc = "";
            ast.push(...parts, part);
            return i3;
          }
          acc += c4;
        }
        ast.type = null;
        ast.#hasMagic = void 0;
        ast.#parts = [str2.substring(pos2 - 1)];
        return i3;
      }
      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 [re3, 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(`^${re3}$`, flags), {
          _src: re3,
          _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((p2) => {
            const [re3, _2, hasMagic2, uflag] = typeof p2 === "string" ? _AST.#parseGlob(p2, this.#hasMagic, noEmpty) : p2.toRegExpSource(allowDot);
            this.#hasMagic = this.#hasMagic || hasMagic2;
            this.#uflag = this.#uflag || uflag;
            return re3;
          }).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 s5 = this.toString();
          this.#parts = [s5];
          this.type = null;
          this.#hasMagic = void 0;
          return [s5, 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((p2) => {
          if (typeof p2 === "string") {
            throw new Error("string type in extglob ast??");
          }
          const [re3, _2, _hasMagic, uflag] = p2.toRegExpSource(dot);
          this.#uflag = this.#uflag || uflag;
          return re3;
        }).filter((p2) => !(this.isStart() && this.isEnd()) || !!p2).join("|");
      }
      static #parseGlob(glob2, hasMagic2, noEmpty = false) {
        let escaping = false;
        let re3 = "";
        let uflag = false;
        for (let i3 = 0; i3 < glob2.length; i3++) {
          const c4 = glob2.charAt(i3);
          if (escaping) {
            escaping = false;
            re3 += (reSpecials.has(c4) ? "\\" : "") + c4;
            continue;
          }
          if (c4 === "\\") {
            if (i3 === glob2.length - 1) {
              re3 += "\\\\";
            } else {
              escaping = true;
            }
            continue;
          }
          if (c4 === "[") {
            const [src, needUflag, consumed, magic] = parseClass(glob2, i3);
            if (consumed) {
              re3 += src;
              uflag = uflag || needUflag;
              i3 += consumed - 1;
              hasMagic2 = hasMagic2 || magic;
              continue;
            }
          }
          if (c4 === "*") {
            if (noEmpty && glob2 === "*")
              re3 += starNoEmpty;
            else
              re3 += star;
            hasMagic2 = true;
            continue;
          }
          if (c4 === "?") {
            re3 += qmark;
            hasMagic2 = true;
            continue;
          }
          re3 += regExpEscape(c4);
        }
        return [re3, unescape2(glob2), !!hasMagic2, uflag];
      }
    };
  }
});

// node_modules/glob/node_modules/minimatch/dist/esm/escape.js
var escape2;
var init_escape = __esm({
  "node_modules/glob/node_modules/minimatch/dist/esm/escape.js"() {
    init_esbuild_shims();
    escape2 = /* @__PURE__ */ __name((s5, { windowsPathsNoEscape = false } = {}) => {
      return windowsPathsNoEscape ? s5.replace(/[?*()[\]]/g, "[$&]") : s5.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, path24, sep3, GLOBSTAR, qmark2, star2, twoStarDot, twoStarNoDot, filter, ext, defaults2, braceExpand, makeRe, match, globMagic, regExpEscape2, Minimatch;
var init_esm7 = __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((p2, pattern, options2 = {}) => {
      assertValidPattern(pattern);
      if (!options2.nocomment && pattern.charAt(0) === "#") {
        return false;
      }
      return new Minimatch(pattern, options2).match(p2);
    }, "minimatch");
    starDotExtRE = /^\*+([^+@!?\*\[\(]*)$/;
    starDotExtTest = /* @__PURE__ */ __name((ext2) => (f5) => !f5.startsWith(".") && f5.endsWith(ext2), "starDotExtTest");
    starDotExtTestDot = /* @__PURE__ */ __name((ext2) => (f5) => f5.endsWith(ext2), "starDotExtTestDot");
    starDotExtTestNocase = /* @__PURE__ */ __name((ext2) => {
      ext2 = ext2.toLowerCase();
      return (f5) => !f5.startsWith(".") && f5.toLowerCase().endsWith(ext2);
    }, "starDotExtTestNocase");
    starDotExtTestNocaseDot = /* @__PURE__ */ __name((ext2) => {
      ext2 = ext2.toLowerCase();
      return (f5) => f5.toLowerCase().endsWith(ext2);
    }, "starDotExtTestNocaseDot");
    starDotStarRE = /^\*+\.\*+$/;
    starDotStarTest = /* @__PURE__ */ __name((f5) => !f5.startsWith(".") && f5.includes("."), "starDotStarTest");
    starDotStarTestDot = /* @__PURE__ */ __name((f5) => f5 !== "." && f5 !== ".." && f5.includes("."), "starDotStarTestDot");
    dotStarRE = /^\.\*+$/;
    dotStarTest = /* @__PURE__ */ __name((f5) => f5 !== "." && f5 !== ".." && f5.startsWith("."), "dotStarTest");
    starRE = /^\*+$/;
    starTest = /* @__PURE__ */ __name((f5) => f5.length !== 0 && !f5.startsWith("."), "starTest");
    starTestDot = /* @__PURE__ */ __name((f5) => f5.length !== 0 && f5 !== "." && f5 !== "..", "starTestDot");
    qmarksRE = /^\?+([^+@!?\*\[\(]*)?$/;
    qmarksTestNocase = /* @__PURE__ */ __name(([$0, ext2 = ""]) => {
      const noext = qmarksTestNoExt([$0]);
      if (!ext2)
        return noext;
      ext2 = ext2.toLowerCase();
      return (f5) => noext(f5) && f5.toLowerCase().endsWith(ext2);
    }, "qmarksTestNocase");
    qmarksTestNocaseDot = /* @__PURE__ */ __name(([$0, ext2 = ""]) => {
      const noext = qmarksTestNoExtDot([$0]);
      if (!ext2)
        return noext;
      ext2 = ext2.toLowerCase();
      return (f5) => noext(f5) && f5.toLowerCase().endsWith(ext2);
    }, "qmarksTestNocaseDot");
    qmarksTestDot = /* @__PURE__ */ __name(([$0, ext2 = ""]) => {
      const noext = qmarksTestNoExtDot([$0]);
      return !ext2 ? noext : (f5) => noext(f5) && f5.endsWith(ext2);
    }, "qmarksTestDot");
    qmarksTest = /* @__PURE__ */ __name(([$0, ext2 = ""]) => {
      const noext = qmarksTestNoExt([$0]);
      return !ext2 ? noext : (f5) => noext(f5) && f5.endsWith(ext2);
    }, "qmarksTest");
    qmarksTestNoExt = /* @__PURE__ */ __name(([$0]) => {
      const len = $0.length;
      return (f5) => f5.length === len && !f5.startsWith(".");
    }, "qmarksTestNoExt");
    qmarksTestNoExtDot = /* @__PURE__ */ __name(([$0]) => {
      const len = $0.length;
      return (f5) => f5.length === len && f5 !== "." && f5 !== "..";
    }, "qmarksTestNoExtDot");
    defaultPlatform = typeof process === "object" && process ? typeof process.env === "object" && process.env && process.env.__MINIMATCH_TESTING_PLATFORM__ || process.platform : "posix";
    path24 = {
      win32: { sep: "\\" },
      posix: { sep: "/" }
    };
    sep3 = defaultPlatform === "win32" ? path24.win32.sep : path24.posix.sep;
    minimatch.sep = sep3;
    GLOBSTAR = Symbol("globstar **");
    minimatch.GLOBSTAR = GLOBSTAR;
    qmark2 = "[^/]";
    star2 = qmark2 + "*?";
    twoStarDot = "(?:(?!(?:\\/|^)(?:\\.{1,2})($|\\/)).)*?";
    twoStarNoDot = "(?:(?!(?:\\/|^)\\.).)*?";
    filter = /* @__PURE__ */ __name((pattern, options2 = {}) => (p2) => minimatch(p2, pattern, options2), "filter");
    minimatch.filter = filter;
    ext = /* @__PURE__ */ __name((a2, b2 = {}) => Object.assign({}, a2, b2), "ext");
    defaults2 = /* @__PURE__ */ __name((def2) => {
      if (!def2 || typeof def2 !== "object" || !Object.keys(def2).length) {
        return minimatch;
      }
      const orig = minimatch;
      const m3 = /* @__PURE__ */ __name((p2, pattern, options2 = {}) => orig(p2, pattern, ext(def2, options2)), "m");
      return Object.assign(m3, {
        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((s5, options2 = {}) => orig.unescape(s5, ext(def2, options2)), "unescape"),
        escape: /* @__PURE__ */ __name((s5, options2 = {}) => orig.escape(s5, 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((f5) => mm.match(f5));
      if (mm.options.nonull && !list3.length) {
        list3.push(pattern);
      }
      return list3;
    }, "match");
    minimatch.match = match;
    globMagic = /[?*]|[+@!]\(.*?\)|\[|\]/;
    regExpEscape2 = /* @__PURE__ */ __name((s5) => s5.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(..._2) {
      }
      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((s5) => this.slashSplit(s5));
        this.globParts = this.preprocess(rawGlobParts);
        this.debug(this.pattern, this.globParts);
        let set = this.globParts.map((s5, _2, __) => {
          if (this.isWindows && this.windowsNoMagicRoot) {
            const isUNC = s5[0] === "" && s5[1] === "" && (s5[2] === "?" || !globMagic.test(s5[2])) && !globMagic.test(s5[3]);
            const isDrive = /^[a-z]:/i.test(s5[0]);
            if (isUNC) {
              return [...s5.slice(0, 4), ...s5.slice(4).map((ss) => this.parse(ss))];
            } else if (isDrive) {
              return [s5[0], ...s5.slice(1).map((ss) => this.parse(ss))];
            }
          }
          return s5.map((ss) => this.parse(ss));
        });
        this.debug(this.pattern, set);
        this.set = set.filter((s5) => s5.indexOf(false) === -1);
        if (this.isWindows) {
          for (let i3 = 0; i3 < this.set.length; i3++) {
            const p2 = this.set[i3];
            if (p2[0] === "" && p2[1] === "" && this.globParts[i3][2] === "?" && typeof p2[3] === "string" && /^[a-z]:$/i.test(p2[3])) {
              p2[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 i3 = 0; i3 < globParts.length; i3++) {
            for (let j2 = 0; j2 < globParts[i3].length; j2++) {
              if (globParts[i3][j2] === "**") {
                globParts[i3][j2] = "*";
              }
            }
          }
        }
        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 i3 = gs;
            while (parts[i3 + 1] === "**") {
              i3++;
            }
            if (i3 !== gs) {
              parts.splice(gs, i3 - 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 i3 = 1; i3 < parts.length - 1; i3++) {
              const p2 = parts[i3];
              if (i3 === 1 && p2 === "" && parts[0] === "")
                continue;
              if (p2 === "." || p2 === "") {
                didSomething = true;
                parts.splice(i3, 1);
                i3--;
              }
            }
            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 p2 = parts[dd - 1];
            if (p2 && p2 !== "." && p2 !== ".." && p2 !== "**") {
              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 p2 = parts[gs + 2];
              const p22 = parts[gs + 3];
              if (next !== "..")
                continue;
              if (!p2 || p2 === "." || p2 === ".." || !p22 || p22 === "." || p22 === "..") {
                continue;
              }
              didSomething = true;
              parts.splice(gs, 1);
              const other2 = parts.slice(0);
              other2[gs] = "**";
              globParts.push(other2);
              gs--;
            }
            if (!this.preserveMultipleSlashes) {
              for (let i3 = 1; i3 < parts.length - 1; i3++) {
                const p2 = parts[i3];
                if (i3 === 1 && p2 === "" && parts[0] === "")
                  continue;
                if (p2 === "." || p2 === "") {
                  didSomething = true;
                  parts.splice(i3, 1);
                  i3--;
                }
              }
              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 p2 = parts[dd - 1];
              if (p2 && p2 !== "." && p2 !== ".." && p2 !== "**") {
                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 i3 = 0; i3 < globParts.length - 1; i3++) {
          for (let j2 = i3 + 1; j2 < globParts.length; j2++) {
            const matched = this.partsMatch(globParts[i3], globParts[j2], !this.preserveMultipleSlashes);
            if (matched) {
              globParts[i3] = [];
              globParts[j2] = matched;
              break;
            }
          }
        }
        return globParts.filter((gs) => gs.length);
      }
      partsMatch(a2, b2, emptyGSMatch = false) {
        let ai = 0;
        let bi = 0;
        let result = [];
        let which = "";
        while (ai < a2.length && bi < b2.length) {
          if (a2[ai] === b2[bi]) {
            result.push(which === "b" ? b2[bi] : a2[ai]);
            ai++;
            bi++;
          } else if (emptyGSMatch && a2[ai] === "**" && b2[bi] === a2[ai + 1]) {
            result.push(a2[ai]);
            ai++;
          } else if (emptyGSMatch && b2[bi] === "**" && a2[ai] === b2[bi + 1]) {
            result.push(b2[bi]);
            bi++;
          } else if (a2[ai] === "*" && b2[bi] && (this.options.dot || !b2[bi].startsWith(".")) && b2[bi] !== "**") {
            if (which === "b")
              return false;
            which = "a";
            result.push(a2[ai]);
            ai++;
            bi++;
          } else if (b2[bi] === "*" && a2[ai] && (this.options.dot || !a2[ai].startsWith(".")) && a2[ai] !== "**") {
            if (which === "a")
              return false;
            which = "b";
            result.push(b2[bi]);
            ai++;
            bi++;
          } else {
            return false;
          }
        }
        return a2.length === b2.length && result;
      }
      parseNegate() {
        if (this.nonegate)
          return;
        const pattern = this.pattern;
        let negate = false;
        let negateOffset = 0;
        for (let i3 = 0; i3 < pattern.length && pattern.charAt(i3) === "!"; i3++) {
          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, partial2 = 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, pl2 = pattern.length; fi < fl && pi < pl2; fi++, pi++) {
          this.debug("matchOne loop");
          var p2 = pattern[pi];
          var f5 = file[fi];
          this.debug(pattern, p2, f5);
          if (p2 === false) {
            return false;
          }
          if (p2 === GLOBSTAR) {
            this.debug("GLOBSTAR", [pattern, p2, f5]);
            var fr2 = fi;
            var pr2 = pi + 1;
            if (pr2 === pl2) {
              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 (fr2 < fl) {
              var swallowee = file[fr2];
              this.debug("\nglobstar while", file, fr2, pattern, pr2, swallowee);
              if (this.matchOne(file.slice(fr2), pattern.slice(pr2), partial2)) {
                this.debug("globstar found match!", fr2, fl, swallowee);
                return true;
              } else {
                if (swallowee === "." || swallowee === ".." || !options2.dot && swallowee.charAt(0) === ".") {
                  this.debug("dot detected!", file, fr2, pattern, pr2);
                  break;
                }
                this.debug("globstar swallow a segment, and continue");
                fr2++;
              }
            }
            if (partial2) {
              this.debug("\n>>> no match, partial?", file, fr2, pattern, pr2);
              if (fr2 === fl) {
                return true;
              }
            }
            return false;
          }
          let hit;
          if (typeof p2 === "string") {
            hit = f5 === p2;
            this.debug("string match", p2, f5, hit);
          } else {
            hit = p2.test(f5);
            this.debug("pattern match", p2, f5, hit);
          }
          if (!hit)
            return false;
        }
        if (fi === fl && pi === pl2) {
          return true;
        } else if (fi === fl) {
          return partial2;
        } else if (pi === pl2) {
          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 m3;
        let fastTest = null;
        if (m3 = pattern.match(starRE)) {
          fastTest = options2.dot ? starTestDot : starTest;
        } else if (m3 = pattern.match(starDotExtRE)) {
          fastTest = (options2.nocase ? options2.dot ? starDotExtTestNocaseDot : starDotExtTestNocase : options2.dot ? starDotExtTestDot : starDotExtTest)(m3[1]);
        } else if (m3 = pattern.match(qmarksRE)) {
          fastTest = (options2.nocase ? options2.dot ? qmarksTestNocaseDot : qmarksTestNocase : options2.dot ? qmarksTestDot : qmarksTest)(m3);
        } else if (m3 = pattern.match(starDotStarRE)) {
          fastTest = options2.dot ? starDotStarTestDot : starDotStarTest;
        } else if (m3 = pattern.match(dotStarRE)) {
          fastTest = dotStarTest;
        }
        const re3 = AST.fromGlob(pattern, this.options).toMMPattern();
        if (fastTest && typeof re3 === "object") {
          Reflect.defineProperty(re3, "test", { value: fastTest });
        }
        return re3;
      }
      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 re3 = set.map((pattern) => {
          const pp = pattern.map((p2) => {
            if (p2 instanceof RegExp) {
              for (const f5 of p2.flags.split(""))
                flags.add(f5);
            }
            return typeof p2 === "string" ? regExpEscape2(p2) : p2 === GLOBSTAR ? GLOBSTAR : p2._src;
          });
          pp.forEach((p2, i3) => {
            const next = pp[i3 + 1];
            const prev = pp[i3 - 1];
            if (p2 !== GLOBSTAR || prev === GLOBSTAR) {
              return;
            }
            if (prev === void 0) {
              if (next !== void 0 && next !== GLOBSTAR) {
                pp[i3 + 1] = "(?:\\/|" + twoStar + "\\/)?" + next;
              } else {
                pp[i3] = twoStar;
              }
            } else if (next === void 0) {
              pp[i3 - 1] = prev + "(?:\\/|" + twoStar + ")?";
            } else if (next !== GLOBSTAR) {
              pp[i3 - 1] = prev + "(?:\\/|\\/" + twoStar + "\\/)" + next;
              pp[i3 + 1] = GLOBSTAR;
            }
          });
          return pp.filter((p2) => p2 !== GLOBSTAR).join("/");
        }).join("|");
        const [open4, close] = set.length > 1 ? ["(?:", ")"] : ["", ""];
        re3 = "^" + open4 + re3 + close + "$";
        if (this.negate)
          re3 = "^(?!" + re3 + ").+$";
        try {
          this.regexp = new RegExp(re3, [...flags].join(""));
        } catch (ex) {
          this.regexp = false;
        }
        return this.regexp;
      }
      slashSplit(p2) {
        if (this.preserveMultipleSlashes) {
          return p2.split("/");
        } else if (this.isWindows && /^\/\/[^\/]+/.test(p2)) {
          return ["", ...p2.split(/\/+/)];
        } else {
          return p2.split(/\/+/);
        }
      }
      match(f5, partial2 = this.partial) {
        this.debug("match", f5, this.pattern);
        if (this.comment) {
          return false;
        }
        if (this.empty) {
          return f5 === "";
        }
        if (f5 === "/" && partial2) {
          return true;
        }
        const options2 = this.options;
        if (this.isWindows) {
          f5 = f5.split("\\").join("/");
        }
        const ff = this.slashSplit(f5);
        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 i3 = ff.length - 2; !filename && i3 >= 0; i3--) {
            filename = ff[i3];
          }
        }
        for (let i3 = 0; i3 < set.length; i3++) {
          const pattern = set[i3];
          let file = ff;
          if (options2.matchBase && pattern.length === 1) {
            file = [filename];
          }
          const hit = this.matchOne(file, pattern, partial2);
          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 = escape2;
    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_esm8 = __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(_2, 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((n3) => n3 && n3 === Math.floor(n3) && n3 > 0 && isFinite(n3), "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 s5 = new _Stack(max, HeapCls);
        _Stack.#constructing = false;
        return s5;
      }
      constructor(max, HeapCls) {
        if (!_Stack.#constructing) {
          throw new TypeError("instantiate Stack using Stack.create(n)");
        }
        this.heap = new HeapCls(max);
        this.length = 0;
      }
      push(n3) {
        this.heap[this.length++] = n3;
      }
      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(c4) {
        return {
          // properties
          starts: c4.#starts,
          ttls: c4.#ttls,
          sizes: c4.#sizes,
          keyMap: c4.#keyMap,
          keyList: c4.#keyList,
          valList: c4.#valList,
          next: c4.#next,
          prev: c4.#prev,
          get head() {
            return c4.#head;
          },
          get tail() {
            return c4.#tail;
          },
          free: c4.#free,
          // methods
          isBackgroundFetch: /* @__PURE__ */ __name((p2) => c4.#isBackgroundFetch(p2), "isBackgroundFetch"),
          backgroundFetch: /* @__PURE__ */ __name((k2, index, options2, context2) => c4.#backgroundFetch(k2, index, options2, context2), "backgroundFetch"),
          moveToTail: /* @__PURE__ */ __name((index) => c4.#moveToTail(index), "moveToTail"),
          indexes: /* @__PURE__ */ __name((options2) => c4.#indexes(options2), "indexes"),
          rindexes: /* @__PURE__ */ __name((options2) => c4.#rindexes(options2), "rindexes"),
          isStale: /* @__PURE__ */ __name((index) => c4.#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 t5 = setTimeout(() => {
              if (this.#isStale(index)) {
                this.#delete(this.#keyList[index], "expire");
              }
            }, ttl + 1);
            if (t5.unref) {
              t5.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 n3 = perf.now();
          if (this.ttlResolution > 0) {
            cachedNow = n3;
            const t5 = setTimeout(() => cachedNow = 0, this.ttlResolution);
            if (t5.unref) {
              t5.unref();
            }
          }
          return n3;
        }, "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 s5 = starts[index];
          const t5 = ttls[index];
          return !!t5 && !!s5 && (cachedNow || getNow()) - s5 > t5;
        };
      }
      // 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 = (k2, v2, size, sizeCalculation) => {
          if (this.#isBackgroundFetch(v2)) {
            return 0;
          }
          if (!isPosInt(size)) {
            if (sizeCalculation) {
              if (typeof sizeCalculation !== "function") {
                throw new TypeError("sizeCalculation must be a function");
              }
              size = sizeCalculation(v2, k2);
              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 i3 = this.#tail; true; ) {
            if (!this.#isValidIndex(i3)) {
              break;
            }
            if (allowStale || !this.#isStale(i3)) {
              yield i3;
            }
            if (i3 === this.#head) {
              break;
            } else {
              i3 = this.#prev[i3];
            }
          }
        }
      }
      *#rindexes({ allowStale = this.allowStale } = {}) {
        if (this.#size) {
          for (let i3 = this.#head; true; ) {
            if (!this.#isValidIndex(i3)) {
              break;
            }
            if (allowStale || !this.#isStale(i3)) {
              yield i3;
            }
            if (i3 === this.#tail) {
              break;
            } else {
              i3 = this.#next[i3];
            }
          }
        }
      }
      #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 i3 of this.#indexes()) {
          if (this.#valList[i3] !== void 0 && this.#keyList[i3] !== void 0 && !this.#isBackgroundFetch(this.#valList[i3])) {
            yield [this.#keyList[i3], this.#valList[i3]];
          }
        }
      }
      /**
       * 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 i3 of this.#rindexes()) {
          if (this.#valList[i3] !== void 0 && this.#keyList[i3] !== void 0 && !this.#isBackgroundFetch(this.#valList[i3])) {
            yield [this.#keyList[i3], this.#valList[i3]];
          }
        }
      }
      /**
       * Return a generator yielding the keys in the cache,
       * in order from most recently used to least recently used.
       */
      *keys() {
        for (const i3 of this.#indexes()) {
          const k2 = this.#keyList[i3];
          if (k2 !== void 0 && !this.#isBackgroundFetch(this.#valList[i3])) {
            yield k2;
          }
        }
      }
      /**
       * 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 i3 of this.#rindexes()) {
          const k2 = this.#keyList[i3];
          if (k2 !== void 0 && !this.#isBackgroundFetch(this.#valList[i3])) {
            yield k2;
          }
        }
      }
      /**
       * Return a generator yielding the values in the cache,
       * in order from most recently used to least recently used.
       */
      *values() {
        for (const i3 of this.#indexes()) {
          const v2 = this.#valList[i3];
          if (v2 !== void 0 && !this.#isBackgroundFetch(this.#valList[i3])) {
            yield this.#valList[i3];
          }
        }
      }
      /**
       * 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 i3 of this.#rindexes()) {
          const v2 = this.#valList[i3];
          if (v2 !== void 0 && !this.#isBackgroundFetch(this.#valList[i3])) {
            yield this.#valList[i3];
          }
        }
      }
      /**
       * 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 i3 of this.#indexes()) {
          const v2 = this.#valList[i3];
          const value = this.#isBackgroundFetch(v2) ? v2.__staleWhileFetching : v2;
          if (value === void 0)
            continue;
          if (fn(value, this.#keyList[i3], this)) {
            return this.get(this.#keyList[i3], 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 i3 of this.#indexes()) {
          const v2 = this.#valList[i3];
          const value = this.#isBackgroundFetch(v2) ? v2.__staleWhileFetching : v2;
          if (value === void 0)
            continue;
          fn.call(thisp, value, this.#keyList[i3], 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 i3 of this.#rindexes()) {
          const v2 = this.#valList[i3];
          const value = this.#isBackgroundFetch(v2) ? v2.__staleWhileFetching : v2;
          if (value === void 0)
            continue;
          fn.call(thisp, value, this.#keyList[i3], this);
        }
      }
      /**
       * Delete any stale entries. Returns true if anything was removed,
       * false otherwise.
       */
      purgeStale() {
        let deleted = false;
        for (const i3 of this.#rindexes({ allowStale: true })) {
          if (this.#isStale(i3)) {
            this.#delete(this.#keyList[i3], "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 i3 = this.#keyMap.get(key);
        if (i3 === void 0)
          return void 0;
        const v2 = this.#valList[i3];
        const value = this.#isBackgroundFetch(v2) ? v2.__staleWhileFetching : v2;
        if (value === void 0)
          return void 0;
        const entry = { value };
        if (this.#ttls && this.#starts) {
          const ttl = this.#ttls[i3];
          const start = this.#starts[i3];
          if (ttl && start) {
            const remain = ttl - (perf.now() - start);
            entry.ttl = remain;
            entry.start = Date.now();
          }
        }
        if (this.#sizes) {
          entry.size = this.#sizes[i3];
        }
        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 i3 of this.#indexes({ allowStale: true })) {
          const key = this.#keyList[i3];
          const v2 = this.#valList[i3];
          const value = this.#isBackgroundFetch(v2) ? v2.__staleWhileFetching : v2;
          if (value === void 0 || key === void 0)
            continue;
          const entry = { value };
          if (this.#ttls && this.#starts) {
            entry.ttl = this.#ttls[i3];
            const age = perf.now() - this.#starts[i3];
            entry.start = Math.floor(Date.now() - age);
          }
          if (this.#sizes) {
            entry.size = this.#sizes[i3];
          }
          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(k2, v2, setOptions2 = {}) {
        if (v2 === void 0) {
          this.delete(k2);
          return this;
        }
        const { ttl = this.ttl, start, noDisposeOnSet = this.noDisposeOnSet, sizeCalculation = this.sizeCalculation, status } = setOptions2;
        let { noUpdateTTL = this.noUpdateTTL } = setOptions2;
        const size = this.#requireSize(k2, v2, setOptions2.size || 0, sizeCalculation);
        if (this.maxEntrySize && size > this.maxEntrySize) {
          if (status) {
            status.set = "miss";
            status.maxEntrySizeExceeded = true;
          }
          this.#delete(k2, "set");
          return this;
        }
        let index = this.#size === 0 ? void 0 : this.#keyMap.get(k2);
        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] = k2;
          this.#valList[index] = v2;
          this.#keyMap.set(k2, 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 (v2 !== oldVal) {
            if (this.#hasFetchMethod && this.#isBackgroundFetch(oldVal)) {
              oldVal.__abortController.abort(new Error("replaced"));
              const { __staleWhileFetching: s5 } = oldVal;
              if (s5 !== void 0 && !noDisposeOnSet) {
                if (this.#hasDispose) {
                  this.#dispose?.(s5, k2, "set");
                }
                if (this.#hasDisposeAfter) {
                  this.#disposed?.push([s5, k2, "set"]);
                }
              }
            } else if (!noDisposeOnSet) {
              if (this.#hasDispose) {
                this.#dispose?.(oldVal, k2, "set");
              }
              if (this.#hasDisposeAfter) {
                this.#disposed?.push([oldVal, k2, "set"]);
              }
            }
            this.#removeItemSize(index);
            this.#addItemSize(index, size, status);
            this.#valList[index] = v2;
            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 dt2 = this.#disposed;
          let task;
          while (task = dt2?.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 dt2 = this.#disposed;
            let task;
            while (task = dt2?.shift()) {
              this.#disposeAfter?.(...task);
            }
          }
        }
      }
      #evict(free) {
        const head = this.#head;
        const k2 = this.#keyList[head];
        const v2 = this.#valList[head];
        if (this.#hasFetchMethod && this.#isBackgroundFetch(v2)) {
          v2.__abortController.abort(new Error("evicted"));
        } else if (this.#hasDispose || this.#hasDisposeAfter) {
          if (this.#hasDispose) {
            this.#dispose?.(v2, k2, "evict");
          }
          if (this.#hasDisposeAfter) {
            this.#disposed?.push([v2, k2, "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(k2);
        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(k2, hasOptions = {}) {
        const { updateAgeOnHas = this.updateAgeOnHas, status } = hasOptions;
        const index = this.#keyMap.get(k2);
        if (index !== void 0) {
          const v2 = this.#valList[index];
          if (this.#isBackgroundFetch(v2) && v2.__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(k2, peekOptions = {}) {
        const { allowStale = this.allowStale } = peekOptions;
        const index = this.#keyMap.get(k2);
        if (index === void 0 || !allowStale && this.#isStale(index)) {
          return;
        }
        const v2 = this.#valList[index];
        return this.#isBackgroundFetch(v2) ? v2.__staleWhileFetching : v2;
      }
      #backgroundFetch(k2, index, options2, context2) {
        const v2 = index === void 0 ? void 0 : this.#valList[index];
        if (this.#isBackgroundFetch(v2)) {
          return v2;
        }
        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((v3, updateCache = false) => {
          const { aborted: aborted2 } = ac.signal;
          const ignoreAbort = options2.ignoreFetchAbort && v3 !== void 0;
          if (options2.status) {
            if (aborted2 && !updateCache) {
              options2.status.fetchAborted = true;
              options2.status.fetchError = ac.signal.reason;
              if (ignoreAbort)
                options2.status.fetchAbortIgnored = true;
            } else {
              options2.status.fetchResolved = true;
            }
          }
          if (aborted2 && !ignoreAbort && !updateCache) {
            return fetchFail(ac.signal.reason);
          }
          const bf2 = p2;
          if (this.#valList[index] === p2) {
            if (v3 === void 0) {
              if (bf2.__staleWhileFetching) {
                this.#valList[index] = bf2.__staleWhileFetching;
              } else {
                this.#delete(k2, "fetch");
              }
            } else {
              if (options2.status)
                options2.status.fetchUpdated = true;
              this.set(k2, v3, fetchOpts.options);
            }
          }
          return v3;
        }, "cb");
        const eb = /* @__PURE__ */ __name((er2) => {
          if (options2.status) {
            options2.status.fetchRejected = true;
            options2.status.fetchError = er2;
          }
          return fetchFail(er2);
        }, "eb");
        const fetchFail = /* @__PURE__ */ __name((er2) => {
          const { aborted: aborted2 } = ac.signal;
          const allowStaleAborted = aborted2 && options2.allowStaleOnFetchAbort;
          const allowStale = allowStaleAborted || options2.allowStaleOnFetchRejection;
          const noDelete = allowStale || options2.noDeleteOnFetchRejection;
          const bf2 = p2;
          if (this.#valList[index] === p2) {
            const del = !noDelete || bf2.__staleWhileFetching === void 0;
            if (del) {
              this.#delete(k2, "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 er2;
          }
        }, "fetchFail");
        const pcall = /* @__PURE__ */ __name((res, rej) => {
          const fmp = this.#fetchMethod?.(k2, v2, fetchOpts);
          if (fmp && fmp instanceof Promise) {
            fmp.then((v3) => res(v3 === void 0 ? void 0 : v3), rej);
          }
          ac.signal.addEventListener("abort", () => {
            if (!options2.ignoreFetchAbort || options2.allowStaleOnFetchAbort) {
              res(void 0);
              if (options2.allowStaleOnFetchAbort) {
                res = /* @__PURE__ */ __name((v3) => cb(v3, true), "res");
              }
            }
          });
        }, "pcall");
        if (options2.status)
          options2.status.fetchDispatched = true;
        const p2 = new Promise(pcall).then(cb, eb);
        const bf = Object.assign(p2, {
          __abortController: ac,
          __staleWhileFetching: v2,
          __returned: void 0
        });
        if (index === void 0) {
          this.set(k2, bf, { ...fetchOpts.options, status: void 0 });
          index = this.#keyMap.get(k2);
        } else {
          this.#valList[index] = bf;
        }
        return bf;
      }
      #isBackgroundFetch(p2) {
        if (!this.#hasFetchMethod)
          return false;
        const b2 = p2;
        return !!b2 && b2 instanceof Promise && b2.hasOwnProperty("__staleWhileFetching") && b2.__abortController instanceof AC;
      }
      async fetch(k2, 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(k2, {
            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(k2);
        if (index === void 0) {
          if (status)
            status.fetch = "miss";
          const p2 = this.#backgroundFetch(k2, index, options2, context2);
          return p2.__returned = p2;
        } else {
          const v2 = this.#valList[index];
          if (this.#isBackgroundFetch(v2)) {
            const stale = allowStale && v2.__staleWhileFetching !== void 0;
            if (status) {
              status.fetch = "inflight";
              if (stale)
                status.returnedStale = true;
            }
            return stale ? v2.__staleWhileFetching : v2.__returned = v2;
          }
          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 v2;
          }
          const p2 = this.#backgroundFetch(k2, index, options2, context2);
          const hasStale = p2.__staleWhileFetching !== void 0;
          const staleVal = hasStale && allowStale;
          if (status) {
            status.fetch = isStale ? "stale" : "refresh";
            if (staleVal && isStale)
              status.returnedStale = true;
          }
          return staleVal ? p2.__staleWhileFetching : p2.__returned = p2;
        }
      }
      async forceFetch(k2, fetchOptions = {}) {
        const v2 = await this.fetch(k2, fetchOptions);
        if (v2 === void 0)
          throw new Error("fetch() returned undefined");
        return v2;
      }
      memo(k2, memoOptions = {}) {
        const memoMethod = this.#memoMethod;
        if (!memoMethod) {
          throw new Error("no memoMethod provided to constructor");
        }
        const { context: context2, forceRefresh, ...options2 } = memoOptions;
        const v2 = this.get(k2, options2);
        if (!forceRefresh && v2 !== void 0)
          return v2;
        const vv = memoMethod(k2, v2, {
          options: options2,
          context: context2
        });
        this.set(k2, 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(k2, getOptions2 = {}) {
        const { allowStale = this.allowStale, updateAgeOnGet = this.updateAgeOnGet, noDeleteOnStaleGet = this.noDeleteOnStaleGet, status } = getOptions2;
        const index = this.#keyMap.get(k2);
        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(k2, "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(p2, n3) {
        this.#prev[n3] = p2;
        this.#next[p2] = n3;
      }
      #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(k2) {
        return this.#delete(k2, "delete");
      }
      #delete(k2, reason) {
        let deleted = false;
        if (this.#size !== 0) {
          const index = this.#keyMap.get(k2);
          if (index !== void 0) {
            deleted = true;
            if (this.#size === 1) {
              this.#clear(reason);
            } else {
              this.#removeItemSize(index);
              const v2 = this.#valList[index];
              if (this.#isBackgroundFetch(v2)) {
                v2.__abortController.abort(new Error("deleted"));
              } else if (this.#hasDispose || this.#hasDisposeAfter) {
                if (this.#hasDispose) {
                  this.#dispose?.(v2, k2, reason);
                }
                if (this.#hasDisposeAfter) {
                  this.#disposed?.push([v2, k2, reason]);
                }
              }
              this.#keyMap.delete(k2);
              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 dt2 = this.#disposed;
          let task;
          while (task = dt2?.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 v2 = this.#valList[index];
          if (this.#isBackgroundFetch(v2)) {
            v2.__abortController.abort(new Error("deleted"));
          } else {
            const k2 = this.#keyList[index];
            if (this.#hasDispose) {
              this.#dispose?.(v2, k2, reason);
            }
            if (this.#hasDisposeAfter) {
              this.#disposed?.push([v2, k2, 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 dt2 = this.#disposed;
          let task;
          while (task = dt2?.shift()) {
            this.#disposeAfter?.(...task);
          }
        }
      }
    };
  }
});

// node_modules/minipass/dist/esm/index.js
import { EventEmitter as EventEmitter4 } from "node:events";
import Stream5 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_esm9 = __esm({
  "node_modules/minipass/dist/esm/index.js"() {
    init_esbuild_shims();
    proc = typeof process === "object" && process ? process : {
      stdout: null,
      stderr: null
    };
    isStream = /* @__PURE__ */ __name((s5) => !!s5 && typeof s5 === "object" && (s5 instanceof Minipass || s5 instanceof Stream5 || isReadable(s5) || isWritable(s5)), "isStream");
    isReadable = /* @__PURE__ */ __name((s5) => !!s5 && typeof s5 === "object" && s5 instanceof EventEmitter4 && typeof s5.pipe === "function" && // node core Writable streams have a pipe() method, but it throws
    s5.pipe !== Stream5.Writable.prototype.pipe, "isReadable");
    isWritable = /* @__PURE__ */ __name((s5) => !!s5 && typeof s5 === "object" && s5 instanceof EventEmitter4 && typeof s5.write === "function" && typeof s5.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((b2) => b2 instanceof ArrayBuffer || !!b2 && typeof b2 === "object" && b2.constructor && b2.constructor.name === "ArrayBuffer" && b2.byteLength >= 0, "isArrayBufferLike");
    isArrayBufferView = /* @__PURE__ */ __name((b2) => !Buffer.isBuffer(b2) && ArrayBuffer.isView(b2), "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 = (er2) => dest.emit("error", er2);
        src.on("error", this.proxyErrors);
      }
    };
    isObjectModeOptions = /* @__PURE__ */ __name((o3) => !!o3.objectMode, "isObjectModeOptions");
    isEncodingOptions = /* @__PURE__ */ __name((o3) => !o3.objectMode && !!o3.encoding && o3.encoding !== "buffer", "isEncodingOptions");
    Minipass = class extends EventEmitter4 {
      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"](a2) {
        this[ASYNC] = this[ASYNC] || !!a2;
      }
      // 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(_2) {
      }
      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(n3) {
        if (this[DESTROYED])
          return null;
        this[DISCARDED] = false;
        if (this[BUFFERLENGTH] === 0 || n3 === 0 || n3 && n3 > this[BUFFERLENGTH]) {
          this[MAYBE_EMIT_END]();
          return null;
        }
        if (this[OBJECTMODE])
          n3 = 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](n3 || null, this[BUFFER][0]);
        this[MAYBE_EMIT_END]();
        return ret;
      }
      [READ](n3, chunk) {
        if (this[OBJECTMODE])
          this[BUFFERSHIFT]();
        else {
          const c4 = chunk;
          if (n3 === c4.length || n3 === null)
            this[BUFFERSHIFT]();
          else if (typeof c4 === "string") {
            this[BUFFER][0] = c4.slice(n3);
            chunk = c4.slice(0, n3);
            this[BUFFERLENGTH] -= n3;
          } else {
            this[BUFFER][0] = c4.subarray(n3);
            chunk = c4.subarray(0, n3);
            this[BUFFERLENGTH] -= n3;
          }
        }
        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 p2 = this[PIPES].find((p3) => p3.dest === dest);
        if (p2) {
          if (this[PIPES].length === 1) {
            if (this[FLOWING] && this[DATALISTENERS] === 0) {
              this[FLOWING] = false;
            }
            this[PIPES] = [];
          } else
            this[PIPES].splice(this[PIPES].indexOf(p2), 1);
          p2.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 h3 = handler;
          if (this[ASYNC])
            defer(() => h3.call(this, this[EMITTED_ERROR]));
          else
            h3.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 p2 of this[PIPES]) {
          if (p2.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 p2 of this[PIPES]) {
              p2.dest.write(data);
            }
            if (!this[DISCARDED])
              super.emit("data", data);
          }
        }
        for (const p2 of this[PIPES]) {
          p2.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 p2 = this.promise();
        this.on("data", (c4) => {
          buf.push(c4);
          if (!this[OBJECTMODE])
            buf.dataLength += c4.length;
        });
        await p2;
        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((resolve30, reject) => {
          this.on(DESTROYED, () => reject(new Error("stream destroyed")));
          this.on("error", (er2) => reject(er2));
          this.on("end", () => resolve30());
        });
      }
      /**
       * 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 resolve30;
          let reject;
          const onerr = /* @__PURE__ */ __name((er2) => {
            this.off("data", ondata);
            this.off("end", onend);
            this.off(DESTROYED, ondestroy);
            stop2();
            reject(er2);
          }, "onerr");
          const ondata = /* @__PURE__ */ __name((value) => {
            this.off("error", onerr);
            this.off("end", onend);
            this.off(DESTROYED, ondestroy);
            this.pause();
            resolve30({ value, done: !!this[EOF] });
          }, "ondata");
          const onend = /* @__PURE__ */ __name(() => {
            this.off("error", onerr);
            this.off("data", ondata);
            this.off(DESTROYED, ondestroy);
            stop2();
            resolve30({ done: true, value: void 0 });
          }, "onend");
          const ondestroy = /* @__PURE__ */ __name(() => onerr(new Error("stream destroyed")), "ondestroy");
          return new Promise((res2, rej) => {
            reject = rej;
            resolve30 = 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(er2) {
        if (this[DESTROYED]) {
          if (er2)
            this.emit("error", er2);
          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 (er2)
          this.emit("error", er2);
        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_esm10 = __esm({
  "node_modules/path-scurry/dist/esm/index.js"() {
    init_esbuild_shims();
    init_esm8();
    init_esm9();
    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((s5) => s5.isFile() ? IFREG : s5.isDirectory() ? IFDIR : s5.isSymbolicLink() ? IFLNK : s5.isCharacterDevice() ? IFCHR : s5.isBlockDevice() ? IFBLK : s5.isSocket() ? IFSOCK : s5.isFIFO() ? IFIFO : UNKNOWN, "entToType");
    normalizeCache = /* @__PURE__ */ new Map();
    normalize3 = /* @__PURE__ */ __name((s5) => {
      const c4 = normalizeCache.get(s5);
      if (c4)
        return c4;
      const n3 = s5.normalize("NFKD");
      normalizeCache.set(s5, n3);
      return n3;
    }, "normalize");
    normalizeNocaseCache = /* @__PURE__ */ new Map();
    normalizeNocase = /* @__PURE__ */ __name((s5) => {
      const c4 = normalizeNocaseCache.get(s5);
      if (c4)
        return c4;
      const n3 = normalize3(s5.toLowerCase());
      normalizeNocaseCache.set(s5, n3);
      return n3;
    }, "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((a2) => a2.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(path125) {
        if (!path125) {
          return this;
        }
        const rootPath = this.getRootString(path125);
        const dir = path125.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 p2 = this;
        for (const part of dirParts) {
          p2 = p2.child(part);
        }
        return p2;
      }
      /**
       * 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 cached2 = this.#children.get(this);
        if (cached2) {
          return cached2;
        }
        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 p2 of children) {
          if (p2.#matchName === name3) {
            return p2;
          }
        }
        const s5 = this.parent ? this.sep : "";
        const fullpath = this.#fullpath ? this.#fullpath + s5 + 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 p2 = this.parent;
        if (!p2) {
          return this.#relative = this.name;
        }
        const pv = p2.relative();
        return pv + (!pv || !p2.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 p2 = this.parent;
        if (!p2) {
          return this.#relativePosix = this.fullpathPosix();
        }
        const pv = p2.relativePosix();
        return pv + (!pv || !p2.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 p2 = this.parent;
        if (!p2) {
          return this.#fullpath = this.name;
        }
        const pv = p2.fullpath();
        const fp = pv + (!p2.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 p3 = this.fullpath().replace(/\\/g, "/");
          if (/^[a-z]:\//i.test(p3)) {
            return this.#fullpathPosix = `//?/${p3}`;
          } else {
            return this.#fullpathPosix = p3;
          }
        }
        const p2 = this.parent;
        const pfpp = p2.fullpathPosix();
        const fpp = pfpp + (!pfpp || !p2.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(n3) {
        return !this.nocase ? this.#matchName === normalize3(n3) : this.#matchName === normalizeNocase(n3);
      }
      /**
       * 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 read3 = await this.#fs.promises.readlink(this.fullpath());
          const linkTarget = (await this.parent.realpath())?.resolve(read3);
          if (linkTarget) {
            return this.#linkTarget = linkTarget;
          }
        } catch (er2) {
          this.#readlinkFail(er2.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 read3 = this.#fs.readlinkSync(this.fullpath());
          const linkTarget = this.parent.realpathSync()?.resolve(read3);
          if (linkTarget) {
            return this.#linkTarget = linkTarget;
          }
        } catch (er2) {
          this.#readlinkFail(er2.code);
          return void 0;
        }
      }
      #readdirSuccess(children) {
        this.#type |= READDIR_CALLED;
        for (let p2 = children.provisional; p2 < children.length; p2++) {
          const c4 = children[p2];
          if (c4)
            c4.#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 p2 of children) {
          p2.#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 t5 = this.#type;
        if ((t5 & IFMT) === IFDIR)
          t5 &= IFMT_UNKNOWN;
        this.#type = t5 | 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 p2 = this.parent;
          p2.#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(e4, c4) {
        return this.#readdirMaybePromoteChild(e4, c4) || this.#readdirAddNewChild(e4, c4);
      }
      #readdirAddNewChild(e4, c4) {
        const type = entToType(e4);
        const child = this.newChild(e4.name, type, { parent: this });
        const ifmt = child.#type & IFMT;
        if (ifmt !== IFDIR && ifmt !== IFLNK && ifmt !== UNKNOWN) {
          child.#type |= ENOTDIR;
        }
        c4.unshift(child);
        c4.provisional++;
        return child;
      }
      #readdirMaybePromoteChild(e4, c4) {
        for (let p2 = c4.provisional; p2 < c4.length; p2++) {
          const pchild = c4[p2];
          const name3 = this.nocase ? normalizeNocase(e4.name) : normalize3(e4.name);
          if (name3 !== pchild.#matchName) {
            continue;
          }
          return this.#readdirPromoteChild(e4, pchild, p2, c4);
        }
      }
      #readdirPromoteChild(e4, p2, index, c4) {
        const v2 = p2.name;
        p2.#type = p2.#type & IFMT_UNKNOWN | entToType(e4);
        if (v2 !== e4.name)
          p2.name = e4.name;
        if (index !== c4.provisional) {
          if (index === c4.length - 1)
            c4.pop();
          else
            c4.splice(index, 1);
          c4.unshift(p2);
        }
        c4.provisional++;
        return p2;
      }
      /**
       * 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 (er2) {
            this.#lstatFail(er2.code);
          }
        }
      }
      /**
       * synchronous {@link PathBase.lstat}
       */
      lstatSync() {
        if ((this.#type & ENOENT) === 0) {
          try {
            this.#applyStat(this.#fs.lstatSync(this.fullpath()));
            return this;
          } catch (er2) {
            this.#lstatFail(er2.code);
          }
        }
      }
      #applyStat(st2) {
        const { atime, atimeMs, birthtime, birthtimeMs, blksize, blocks, ctime, ctimeMs, dev, gid, ino, mode, mtime, mtimeMs, nlink, rdev, size, uid } = st2;
        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(st2);
        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 c4 = children.slice(0, children.provisional);
          if (allowZalgo)
            cb(null, c4);
          else
            queueMicrotask(() => cb(null, c4));
          return;
        }
        this.#onReaddirCB.push(cb);
        if (this.#readdirCBInFlight) {
          return;
        }
        this.#readdirCBInFlight = true;
        const fullpath = this.fullpath();
        this.#fs.readdir(fullpath, { withFileTypes: true }, (er2, entries) => {
          if (er2) {
            this.#readdirFail(er2.code);
            children.provisional = 0;
          } else {
            for (const e4 of entries) {
              this.#readdirAddChild(e4, 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 resolve30 = /* @__PURE__ */ __name(() => {
          }, "resolve");
          this.#asyncReaddirInFlight = new Promise((res) => resolve30 = res);
          try {
            for (const e4 of await this.#fs.promises.readdir(fullpath, {
              withFileTypes: true
            })) {
              this.#readdirAddChild(e4, children);
            }
            this.#readdirSuccess(children);
          } catch (er2) {
            this.#readdirFail(er2.code);
            children.provisional = 0;
          }
          this.#asyncReaddirInFlight = void 0;
          resolve30();
        }
        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 e4 of this.#fs.readdirSync(fullpath, {
            withFileTypes: true
          })) {
            this.#readdirAddChild(e4, children);
          }
          this.#readdirSuccess(children);
        } catch (er2) {
          this.#readdirFail(er2.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 (_2) {
          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 (_2) {
          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 p2 = this;
        while (p2 && p2.parent) {
          changed.add(p2);
          p2.#relative = rp.join(this.sep);
          p2.#relativePosix = rp.join("/");
          p2 = p2.parent;
          rp.push("..");
        }
        p2 = oldCwd;
        while (p2 && p2.parent && !changed.has(p2)) {
          p2.#relative = void 0;
          p2.#relativePosix = void 0;
          p2 = p2.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(path125) {
        return win32.parse(path125).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(path125) {
        return path125.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, sep9, { nocase, childrenCacheSize = 16 * 1024, fs: fs113 = defaultFS } = {}) {
        this.#fs = fsFromOption(fs113);
        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(sep9);
        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 l3 = len--;
          prev = prev.child(part, {
            relative: new Array(l3).fill("..").join(joinSep),
            relativePosix: new Array(l3).fill("..").join("/"),
            fullpath: abs += (sawFirst ? "" : joinSep) + part
          });
          sawFirst = true;
        }
        this.cwd = prev;
      }
      /**
       * Get the depth of a provided path, string, or the cwd
       */
      depth(path125 = this.cwd) {
        if (typeof path125 === "string") {
          path125 = this.cwd.resolve(path125);
        }
        return path125.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 r5 = "";
        for (let i3 = paths.length - 1; i3 >= 0; i3--) {
          const p2 = paths[i3];
          if (!p2 || p2 === ".")
            continue;
          r5 = r5 ? `${p2}/${r5}` : p2;
          if (this.isAbsolute(p2)) {
            break;
          }
        }
        const cached2 = this.#resolveCache.get(r5);
        if (cached2 !== void 0) {
          return cached2;
        }
        const result = this.cwd.resolve(r5).fullpath();
        this.#resolveCache.set(r5, 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 r5 = "";
        for (let i3 = paths.length - 1; i3 >= 0; i3--) {
          const p2 = paths[i3];
          if (!p2 || p2 === ".")
            continue;
          r5 = r5 ? `${p2}/${r5}` : p2;
          if (this.isAbsolute(p2)) {
            break;
          }
        }
        const cached2 = this.#resolvePosixCache.get(r5);
        if (cached2 !== void 0) {
          return cached2;
        }
        const result = this.cwd.resolve(r5).fullpathPosix();
        this.#resolvePosixCache.set(r5, 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 p2 = await entry.readdir();
          return withFileTypes ? p2 : p2.map((e4) => e4.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((e4) => e4.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 e4 = await entry.readlink();
        return withFileTypes ? e4 : e4?.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 e4 = entry.readlinkSync();
        return withFileTypes ? e4 : e4?.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 e4 = await entry.realpath();
        return withFileTypes ? e4 : e4?.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 e4 = entry.realpathSync();
        return withFileTypes ? e4 : e4?.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((er2, entries) => {
            if (er2) {
              return cb(er2);
            }
            let len = entries.length;
            if (!len)
              return cb();
            const next = /* @__PURE__ */ __name(() => {
              if (--len === 0) {
                cb();
              }
            }, "next");
            for (const e4 of entries) {
              if (!filter4 || filter4(e4)) {
                results.push(withFileTypes ? e4 : e4.fullpath());
              }
              if (follow && e4.isSymbolicLink()) {
                e4.realpath().then((r5) => r5?.isUnknown() ? r5.lstat() : r5).then((r5) => r5?.shouldWalk(dirs, walkFilter) ? walk(r5, next) : next());
              } else {
                if (e4.shouldWalk(dirs, walkFilter)) {
                  walk(e4, next);
                } else {
                  next();
                }
              }
            }
          }, true);
        }, "walk");
        const start = entry;
        return new Promise((res, rej) => {
          walk(start, (er2) => {
            if (er2)
              return rej(er2);
            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 e4 of entries) {
            if (!filter4 || filter4(e4)) {
              results.push(withFileTypes ? e4 : e4.fullpath());
            }
            let r5 = e4;
            if (e4.isSymbolicLink()) {
              if (!(follow && (r5 = e4.realpathSync())))
                continue;
              if (r5.isUnknown())
                r5.lstatSync();
            }
            if (r5.shouldWalk(dirs, walkFilter)) {
              dirs.add(r5);
            }
          }
        }
        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 e4 of entries) {
            if (!filter4 || filter4(e4)) {
              yield withFileTypes ? e4 : e4.fullpath();
            }
            let r5 = e4;
            if (e4.isSymbolicLink()) {
              if (!(follow && (r5 = e4.realpathSync())))
                continue;
              if (r5.isUnknown())
                r5.lstatSync();
            }
            if (r5.shouldWalk(dirs, walkFilter)) {
              dirs.add(r5);
            }
          }
        }
      }
      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 process50 = /* @__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((er2, entries, didRealpaths = false) => {
              if (er2)
                return results.emit("error", er2);
              if (follow && !didRealpaths) {
                const promises8 = [];
                for (const e4 of entries) {
                  if (e4.isSymbolicLink()) {
                    promises8.push(e4.realpath().then((r5) => r5?.isUnknown() ? r5.lstat() : r5));
                  }
                }
                if (promises8.length) {
                  Promise.all(promises8).then(() => onReaddir(null, entries, true));
                  return;
                }
              }
              for (const e4 of entries) {
                if (e4 && (!filter4 || filter4(e4))) {
                  if (!results.write(withFileTypes ? e4 : e4.fullpath())) {
                    paused = true;
                  }
                }
              }
              processing--;
              for (const e4 of entries) {
                const r5 = e4.realpathCached() || e4;
                if (r5.shouldWalk(dirs, walkFilter)) {
                  queue.push(r5);
                }
              }
              if (paused && !results.flowing) {
                results.once("drain", process50);
              } else if (!sync2) {
                process50();
              }
            }, "onReaddir");
            let sync2 = true;
            dir.readdirCB(onReaddir, true);
            sync2 = false;
          }
        }, "process");
        process50();
        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 process50 = /* @__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 e4 of entries) {
              if (!filter4 || filter4(e4)) {
                if (!results.write(withFileTypes ? e4 : e4.fullpath())) {
                  paused = true;
                }
              }
            }
            processing--;
            for (const e4 of entries) {
              let r5 = e4;
              if (e4.isSymbolicLink()) {
                if (!(follow && (r5 = e4.realpathSync())))
                  continue;
                if (r5.isUnknown())
                  r5.lstatSync();
              }
              if (r5.shouldWalk(dirs, walkFilter)) {
                queue.push(r5);
              }
            }
          }
          if (paused && !results.flowing)
            results.once("drain", process50);
        }, "process");
        process50();
        return results;
      }
      chdir(path125 = this.cwd) {
        const oldCwd = this.cwd;
        this.cwd = typeof path125 === "string" ? this.cwd.resolve(path125) : path125;
        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 p2 = this.cwd; p2; p2 = p2.parent) {
          p2.nocase = this.nocase;
        }
      }
      /**
       * @internal
       */
      parseRootPath(dir) {
        return win32.parse(dir).root.toUpperCase();
      }
      /**
       * @internal
       */
      newRoot(fs113) {
        return new PathWin32(this.rootPath, IFDIR, void 0, this.roots, this.nocase, this.childrenCache(), { fs: fs113 });
      }
      /**
       * Return true if the provided path string is an absolute path
       */
      isAbsolute(p2) {
        return p2.startsWith("/") || p2.startsWith("\\") || /^[a-z]:(\/|\\)/i.test(p2);
      }
    };
    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(fs113) {
        return new PathPosix(this.rootPath, IFDIR, void 0, this.roots, this.nocase, this.childrenCache(), { fs: fs113 });
      }
      /**
       * Return true if the provided path string is an absolute path
       */
      isAbsolute(p2) {
        return p2.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_esm7();
    isPatternList = /* @__PURE__ */ __name((pl2) => pl2.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, platform16) {
        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 = platform16;
        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 p4 = [p0, p1, p2, p3, ""].join("/");
            const g4 = [g0, g1, g2, g3, ""].join("/");
            this.#patternList = [p4, ...prest];
            this.#globList = [g4, ...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 p2 = p1 + "/";
            const g2 = g1 + "/";
            this.#patternList = [p2, ...prest];
            this.#globList = [g2, ...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 pl2 = this.#patternList;
        return this.#isUNC !== void 0 ? this.#isUNC : this.#isUNC = this.#platform === "win32" && this.#index === 0 && pl2[0] === "" && pl2[1] === "" && typeof pl2[2] === "string" && !!pl2[2] && typeof pl2[3] === "string" && !!pl2[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 pl2 = this.#patternList;
        return this.#isDrive !== void 0 ? this.#isDrive : this.#isDrive = this.#platform === "win32" && this.#index === 0 && this.length > 1 && typeof pl2[0] === "string" && /^[a-z]:$/i.test(pl2[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 pl2 = this.#patternList;
        return this.#isAbsolute !== void 0 ? this.#isAbsolute : this.#isAbsolute = pl2[0] === "" && pl2.length > 1 || this.isDrive() || this.isUNC();
      }
      /**
       * consume the root of the pattern, and return it
       */
      root() {
        const p2 = this.#patternList[0];
        return typeof p2 === "string" && this.isAbsolute() && this.#index === 0 ? p2 : "";
      }
      /**
       * 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_esm7();
    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: platform16 = defaultPlatform2 }) {
        this.relative = [];
        this.absolute = [];
        this.relativeChildren = [];
        this.absoluteChildren = [];
        this.platform = platform16;
        this.mmopts = {
          dot: true,
          nobrace,
          nocase,
          noext,
          noglobstar,
          optimizationLevel: 2,
          platform: platform16,
          nocomment: true,
          nonegate: true
        };
        for (const ign of ignored)
          this.add(ign);
      }
      add(ign) {
        const mm = new Minimatch(ign, this.mmopts);
        for (let i3 = 0; i3 < mm.set.length; i3++) {
          const parsed = mm.set[i3];
          const globParts = mm.globParts[i3];
          if (!parsed || !globParts) {
            throw new Error("invalid pattern object");
          }
          while (parsed[0] === "." && globParts[0] === ".") {
            parsed.shift();
            globParts.shift();
          }
          const p2 = new Pattern(parsed, globParts, 0, this.platform);
          const m3 = new Minimatch(p2.globString(), this.mmopts);
          const children = globParts[globParts.length - 1] === "**";
          const absolute = p2.isAbsolute();
          if (absolute)
            this.absolute.push(m3);
          else
            this.relative.push(m3);
          if (children) {
            if (absolute)
              this.absoluteChildren.push(m3);
            else
              this.relativeChildren.push(m3);
          }
        }
      }
      ignored(p2) {
        const fullpath = p2.fullpath();
        const fullpaths = `${fullpath}/`;
        const relative11 = p2.relative() || ".";
        const relatives = `${relative11}/`;
        for (const m3 of this.relative) {
          if (m3.match(relative11) || m3.match(relatives))
            return true;
        }
        for (const m3 of this.absolute) {
          if (m3.match(fullpath) || m3.match(fullpaths))
            return true;
        }
        return false;
      }
      childrenIgnored(p2) {
        const fullpath = p2.fullpath() + "/";
        const relative11 = (p2.relative() || ".") + "/";
        for (const m3 of this.relativeChildren) {
          if (m3.match(relative11))
            return true;
        }
        for (const m3 of this.absoluteChildren) {
          if (m3.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_esm7();
    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 cached2 = this.store.get(fullpath);
        if (cached2)
          cached2.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 n3 = (absolute ? 2 : 0) | (ifDir ? 1 : 0);
        const current = this.store.get(target);
        this.store.set(target, current === void 0 ? n3 : n3 & current);
      }
      // match, absolute, ifdir
      entries() {
        return [...this.store.entries()].map(([path125, n3]) => [
          path125,
          !!(n3 & 2),
          !!(n3 & 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((p2) => p2.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((k2) => [k2, this.store.get(k2)]);
      }
      keys() {
        return [...this.store.keys()].filter((t5) => t5.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((p2) => [target, p2]);
        for (let [t5, pattern] of processingSet) {
          this.hasWalkedCache.storeWalked(t5, pattern);
          const root = pattern.root();
          const absolute = pattern.isAbsolute() && this.opts.absolute !== false;
          if (root) {
            t5 = t5.resolve(root === "/" && this.opts.root !== void 0 ? this.opts.root : root);
            const rest2 = pattern.rest();
            if (!rest2) {
              this.matches.add(t5, true, false);
              continue;
            } else {
              pattern = rest2;
            }
          }
          if (t5.isENOENT())
            continue;
          let p2;
          let rest;
          let changed = false;
          while (typeof (p2 = pattern.pattern()) === "string" && (rest = pattern.rest())) {
            const c4 = t5.resolve(p2);
            t5 = c4;
            pattern = rest;
            changed = true;
          }
          p2 = pattern.pattern();
          rest = pattern.rest();
          if (changed) {
            if (this.hasWalkedCache.hasWalked(t5, pattern))
              continue;
            this.hasWalkedCache.storeWalked(t5, pattern);
          }
          if (typeof p2 === "string") {
            const ifDir = p2 === ".." || p2 === "" || p2 === ".";
            this.matches.add(t5.resolve(p2), absolute, ifDir);
            continue;
          } else if (p2 === GLOBSTAR) {
            if (!t5.isSymbolicLink() || this.follow || pattern.checkFollowGlobstar()) {
              this.subwalks.add(t5, pattern);
            }
            const rp = rest?.pattern();
            const rrest = rest?.rest();
            if (!rest || (rp === "" || rp === ".") && !rrest) {
              this.matches.add(t5, absolute, rp === "" || rp === ".");
            } else {
              if (rp === "..") {
                const tp = t5.parent || t5;
                if (!rrest)
                  this.matches.add(tp, absolute, true);
                else if (!this.hasWalkedCache.hasWalked(tp, rrest)) {
                  this.subwalks.add(tp, rrest);
                }
              }
            }
          } else if (p2 instanceof RegExp) {
            this.subwalks.add(t5, 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 e4 of entries) {
          for (const pattern of patterns) {
            const absolute = pattern.isAbsolute();
            const p2 = pattern.pattern();
            const rest = pattern.rest();
            if (p2 === GLOBSTAR) {
              results.testGlobstar(e4, pattern, rest, absolute);
            } else if (p2 instanceof RegExp) {
              results.testRegExp(e4, p2, rest, absolute);
            } else {
              results.testString(e4, p2, rest, absolute);
            }
          }
        }
        return results;
      }
      testGlobstar(e4, pattern, rest, absolute) {
        if (this.dot || !e4.name.startsWith(".")) {
          if (!pattern.hasMore()) {
            this.matches.add(e4, absolute, false);
          }
          if (e4.canReaddir()) {
            if (this.follow || !e4.isSymbolicLink()) {
              this.subwalks.add(e4, pattern);
            } else if (e4.isSymbolicLink()) {
              if (rest && pattern.checkFollowGlobstar()) {
                this.subwalks.add(e4, rest);
              } else if (pattern.markFollowGlobstar()) {
                this.subwalks.add(e4, pattern);
              }
            }
          }
        }
        if (rest) {
          const rp = rest.pattern();
          if (typeof rp === "string" && // dots and empty were handled already
          rp !== ".." && rp !== "" && rp !== ".") {
            this.testString(e4, rp, rest.rest(), absolute);
          } else if (rp === "..") {
            const ep = e4.parent || e4;
            this.subwalks.add(ep, rest);
          } else if (rp instanceof RegExp) {
            this.testRegExp(e4, rp, rest.rest(), absolute);
          }
        }
      }
      testRegExp(e4, p2, rest, absolute) {
        if (!p2.test(e4.name))
          return;
        if (!rest) {
          this.matches.add(e4, absolute, false);
        } else {
          this.subwalks.add(e4, rest);
        }
      }
      testString(e4, p2, rest, absolute) {
        if (!e4.isNamed(p2))
          return;
        if (!rest) {
          this.matches.add(e4, absolute, false);
        } else {
          this.subwalks.add(e4, 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_esm9();
    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, path125, opts) {
        this.patterns = patterns;
        this.path = path125;
        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 m3 = "cannot ignore child matches, ignore lacks add() method.";
            throw new Error(m3);
          }
        }
        this.maxDepth = opts.maxDepth || Infinity;
        if (opts.signal) {
          this.signal = opts.signal;
          this.signal.addEventListener("abort", () => {
            this.#onResume.length = 0;
          });
        }
      }
      #ignored(path125) {
        return this.seen.has(path125) || !!this.#ignore?.ignored?.(path125);
      }
      #childrenIgnored(path125) {
        return !!this.#ignore?.childrenIgnored?.(path125);
      }
      // 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(e4, ifDir) {
        if (ifDir && this.opts.nodir)
          return void 0;
        let rpc;
        if (this.opts.realpath) {
          rpc = e4.realpathCached() || await e4.realpath();
          if (!rpc)
            return void 0;
          e4 = rpc;
        }
        const needStat = e4.isUnknown() || this.opts.stat;
        const s5 = needStat ? await e4.lstat() : e4;
        if (this.opts.follow && this.opts.nodir && s5?.isSymbolicLink()) {
          const target = await s5.realpath();
          if (target && (target.isUnknown() || this.opts.stat)) {
            await target.lstat();
          }
        }
        return this.matchCheckTest(s5, ifDir);
      }
      matchCheckTest(e4, ifDir) {
        return e4 && (this.maxDepth === Infinity || e4.depth() <= this.maxDepth) && (!ifDir || e4.canReaddir()) && (!this.opts.nodir || !e4.isDirectory()) && (!this.opts.nodir || !this.opts.follow || !e4.isSymbolicLink() || !e4.realpathCached()?.isDirectory()) && !this.#ignored(e4) ? e4 : void 0;
      }
      matchCheckSync(e4, ifDir) {
        if (ifDir && this.opts.nodir)
          return void 0;
        let rpc;
        if (this.opts.realpath) {
          rpc = e4.realpathCached() || e4.realpathSync();
          if (!rpc)
            return void 0;
          e4 = rpc;
        }
        const needStat = e4.isUnknown() || this.opts.stat;
        const s5 = needStat ? e4.lstatSync() : e4;
        if (this.opts.follow && this.opts.nodir && s5?.isSymbolicLink()) {
          const target = s5.realpathSync();
          if (target && (target?.isUnknown() || this.opts.stat)) {
            target.lstatSync();
          }
        }
        return this.matchCheckTest(s5, ifDir);
      }
      matchFinish(e4, absolute) {
        if (this.#ignored(e4))
          return;
        if (!this.includeChildMatches && this.#ignore?.add) {
          const ign = `${e4.relativePosix()}/**`;
          this.#ignore.add(ign);
        }
        const abs = this.opts.absolute === void 0 ? absolute : this.opts.absolute;
        this.seen.add(e4);
        const mark = this.opts.mark && e4.isDirectory() ? this.#sep : "";
        if (this.opts.withFileTypes) {
          this.matchEmit(e4);
        } else if (abs) {
          const abs2 = this.opts.posix ? e4.fullpathPosix() : e4.fullpath();
          this.matchEmit(abs2 + mark);
        } else {
          const rel = this.opts.posix ? e4.relativePosix() : e4.relative();
          const pre = this.opts.dotRelative && !rel.startsWith(".." + this.#sep) ? "." + this.#sep : "";
          this.matchEmit(!rel ? "." + mark : pre + rel + mark);
        }
      }
      async match(e4, absolute, ifDir) {
        const p2 = await this.matchCheck(e4, ifDir);
        if (p2)
          this.matchFinish(p2, absolute);
      }
      matchSync(e4, absolute, ifDir) {
        const p2 = this.matchCheckSync(e4, ifDir);
        if (p2)
          this.matchFinish(p2, 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 [m3, absolute, ifDir] of processor.matches.entries()) {
          if (this.#ignored(m3))
            continue;
          tasks++;
          this.match(m3, absolute, ifDir).then(() => next());
        }
        for (const t5 of processor.subwalkTargets()) {
          if (this.maxDepth !== Infinity && t5.depth() >= this.maxDepth) {
            continue;
          }
          tasks++;
          const childrenCached = t5.readdirCached();
          if (t5.calledReaddir())
            this.walkCB3(t5, childrenCached, processor, next);
          else {
            t5.readdirCB((_2, entries) => this.walkCB3(t5, 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 [m3, absolute, ifDir] of processor.matches.entries()) {
          if (this.#ignored(m3))
            continue;
          tasks++;
          this.match(m3, 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 [m3, absolute, ifDir] of processor.matches.entries()) {
          if (this.#ignored(m3))
            continue;
          this.matchSync(m3, absolute, ifDir);
        }
        for (const t5 of processor.subwalkTargets()) {
          if (this.maxDepth !== Infinity && t5.depth() >= this.maxDepth) {
            continue;
          }
          tasks++;
          const children = t5.readdirSync();
          this.walkCB3Sync(t5, 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 [m3, absolute, ifDir] of processor.matches.entries()) {
          if (this.#ignored(m3))
            continue;
          this.matchSync(m3, 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, path125, opts) {
        super(patterns, path125, opts);
      }
      matchEmit(e4) {
        this.matches.add(e4);
      }
      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, path125, opts) {
        super(patterns, path125, opts);
        this.results = new Minipass({
          signal: this.signal,
          objectMode: true
        });
        this.results.on("drain", () => this.resume());
        this.results.on("resume", () => this.resume());
      }
      matchEmit(e4) {
        this.results.write(e4);
        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_esm7();
    init_esm10();
    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((p2) => p2.replace(/\\/g, "/"));
        }
        if (this.matchBase) {
          if (opts.noglobstar) {
            throw new TypeError("base matching requires globstar");
          }
          pattern = pattern.map((p2) => p2.includes("/") ? p2 : `./**/${p2}`);
        }
        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((p2) => new Minimatch(p2, mmo));
        const [matchSet, globParts] = mms.reduce((set, m3) => {
          set[0].push(...m3.set);
          set[1].push(...m3.globParts);
          return set;
        }, [[], []]);
        this.patterns = matchSet.map((set, i3) => {
          const g2 = globParts[i3];
          if (!g2)
            throw new Error("invalid pattern object");
          return new Pattern(set, g2, 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_esm7();
    hasMagic = /* @__PURE__ */ __name((pattern, options2 = {}) => {
      if (!Array.isArray(pattern)) {
        pattern = [pattern];
      }
      for (const p2 of pattern) {
        if (new Minimatch(p2, 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_esm11 = __esm({
  "node_modules/glob/dist/esm/index.js"() {
    init_esbuild_shims();
    init_esm7();
    init_glob();
    init_has_magic();
    init_esm7();
    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: escape2,
      unescape: unescape2
    });
    glob.glob = glob;
  }
});

// packages/core/dist/src/services/fileSystemService.js
import fs30 from "node:fs/promises";
import * as path25 from "node:path";
function hasUTF8BOM(buffer) {
  return buffer.length >= 3 && buffer[0] === 239 && buffer[1] === 187 && buffer[2] === 191;
}
var FileEncoding, StandardFileSystemService;
var init_fileSystemService = __esm({
  "packages/core/dist/src/services/fileSystemService.js"() {
    "use strict";
    init_esbuild_shims();
    init_esm11();
    FileEncoding = {
      UTF8: "utf-8",
      UTF8_BOM: "utf-8-bom"
    };
    __name(hasUTF8BOM, "hasUTF8BOM");
    StandardFileSystemService = class {
      static {
        __name(this, "StandardFileSystemService");
      }
      async readTextFile(filePath) {
        return fs30.readFile(filePath, FileEncoding.UTF8);
      }
      async writeTextFile(filePath, content, options2) {
        const bom = options2?.bom ?? false;
        if (bom) {
          const normalizedContent = content.charCodeAt(0) === 65279 ? content.slice(1) : content;
          const bomBuffer = Buffer.from([239, 187, 191]);
          const contentBuffer = Buffer.from(normalizedContent, "utf-8");
          await fs30.writeFile(filePath, Buffer.concat([bomBuffer, contentBuffer]));
        } else {
          await fs30.writeFile(filePath, content, "utf-8");
        }
      }
      async detectFileBOM(filePath) {
        let fd;
        try {
          fd = await fs30.open(filePath, "r");
          const buffer = Buffer.alloc(3);
          const { bytesRead } = await fd.read(buffer, 0, 3, 0);
          if (bytesRead < 3) {
            return false;
          }
          return hasUTF8BOM(buffer);
        } catch {
          return false;
        } finally {
          await fd?.close();
        }
      }
      findFiles(fileName, searchPaths) {
        return searchPaths.flatMap((searchPath) => {
          const pattern = path25.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 check2(path125, isFile3, isDirectory) {
      log(`checking %s`, path125);
      try {
        const stat10 = fs_1.statSync(path125);
        if (stat10.isFile() && isFile3) {
          log(`[OK] path represents a file`);
          return true;
        }
        if (stat10.isDirectory() && isDirectory) {
          log(`[OK] path represents a directory`);
          return true;
        }
        log(`[FAIL] path represents something other than a file or directory`);
        return false;
      } catch (e4) {
        if (e4.code === "ENOENT") {
          log(`[FAIL] path is not accessible: %o`, e4);
          return false;
        }
        log(`[FATAL] %o`, e4);
        throw e4;
      }
    }
    __name(check2, "check");
    function exists2(path125, type = exports2.READABLE) {
      return check2(path125, (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(m3) {
      for (var p2 in m3) if (!exports2.hasOwnProperty(p2)) exports2[p2] = m3[p2];
    }
    __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(error2) {
          if (status === "pending") {
            status = "rejected";
            fail(error2);
          }
        },
        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 EventEmitter5 } from "node:events";
function pathspec(...paths) {
  const key = new String(paths);
  cache.set(key, paths);
  return key;
}
function isPathSpec(path125) {
  return path125 instanceof String && cache.has(path125);
}
function toPaths(pathSpec) {
  return cache.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(path125) {
  return (0, import_file_exists.exists)(path125, 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 i3 = 0, max = input.length; i3 < max; i3++) {
    output.push(prefix, input[i3]);
  }
  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(duration3 = 0) {
  return new Promise((done) => setTimeout(done, duration3));
}
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, omit2) {
  const type = isPathSpec(input) ? "string" : typeof input;
  return /number|string|boolean/.test(type) && (!omit2 || !omit2.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 config2 = Object.assign(
    { baseDir, ...defaultOptions2 },
    ...options2.filter((o3) => typeof o3 === "object" && o3)
  );
  config2.baseDir = config2.baseDir || baseDir;
  config2.trimmed = config2.trimmed === true;
  return config2;
}
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 v2 of value) {
        if (!filterPrimitives(v2, ["string", "number"])) {
          commands2.push(key + "=" + v2);
        }
      }
    } else {
      commands2.push(key);
    }
    return commands2;
  }, commands);
}
function getTrailingOptions(args, initialPrimitive = 0, objectOnly = false) {
  const command2 = [];
  for (let i3 = 0, max = initialPrimitive < 0 ? args.length : initialPrimitive; i3 < max; i3++) {
    if ("string|number".includes(typeof args[i3])) {
      command2.push(String(args[i3]));
    }
  }
  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), i3 = 0, max = lines.length; i3 < max; i3++) {
      const line = /* @__PURE__ */ __name((offset = 0) => {
        if (i3 + offset >= max) {
          return;
        }
        return lines[i3 + offset];
      }, "line");
      parsers12.some(({ parse: parse14 }) => parse14(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(path125) {
      return /^\.(git)?$/.test(path125.trim());
    }
  };
}
function checkIsBareRepoTask() {
  const commands = ["rev-parse", "--is-bare-repository"];
  return {
    commands,
    format: "utf-8",
    onError,
    parser
  };
}
function isNotRepoMessage(error2) {
  return /(Not a git repository|Kein Git-Repository)/i.test(String(error2));
}
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(error2) {
  return {
    commands: EMPTY_COMMANDS,
    format: "empty",
    parser() {
      throw typeof error2 === "string" ? new TaskConfigurationError(error2) : error2;
    }
  };
}
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 config2 = new ConfigList();
  for (const item of configParser(text)) {
    config2.addValue(item.file, String(item.key), item.value);
  }
  return config2;
}
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 i3 = 0, max = lines.length - 1; i3 < max; ) {
    const file = configFilePath(lines[i3++]);
    let value = lines[i3++];
    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 [path125, line, preview] = input.split(NULL2);
    paths.add(path125);
    (results[path125] = results[path125] || []).push({
      line: asNumber(line),
      path: path125,
      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 debug22 = debugDebugger && prefixedLogger(debugDebugger, stepPrefix) || NOOP;
    const info = prefixedLogger(infoDebugger, `${labelPrefix} ${stepPrefix}`, debug22);
    return Object.assign(debugDebugger ? debug22 : 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, path125, text) {
  const response = String(text).trim();
  let result;
  if (result = initResponseRegex.exec(response)) {
    return new InitSummary(bare, path125, false, result[1]);
  }
  if (result = reInitResponseRegex.exec(response)) {
    return new InitSummary(bare, path125, 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, path125, /^re/i.test(response), gitDir);
}
function hasBareCommand(command2) {
  return command2.includes(bareCommand);
}
function initTask(bare = false, path125, 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"), path125, text);
    }
  };
}
function logFormatFromCommand(customArgs) {
  for (let i3 = 0; i3 < customArgs.length; i3++) {
    const format4 = logFormatRegex.exec(customArgs[i3]);
    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 merge4 = parseMergeResult(stdOut, stdErr);
      if (merge4.failed) {
        throw new GitResponseError(merge4);
      }
      return merge4;
    }
  };
}
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((y2) => parser3(indexX, y2, (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, path125) {
    const raw2 = `${index}${workingDir}`;
    const handler = parsers6.get(raw2);
    if (handler) {
      handler(result, path125);
    }
    if (raw2 !== "##" && raw2 !== "!!") {
      result.files.push(new FileStatusSummary(path125, 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_default() {
  return {
    version() {
      return this._runTask({
        commands: ["--version"],
        format: "utf-8",
        parser: versionParser,
        onError(result, error2, done, fail) {
          if (result.exitCode === -2) {
            return done(Buffer.from(NOT_INSTALLED));
          }
          fail(error2);
        }
      });
    }
  };
}
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 }, error2, done, fail) {
      if (!hasBranchDeletionError(String(error2), exitCode)) {
        return fail(error2);
      }
      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 }, error2, _2, fail) {
      if (!hasBranchDeletionError(String(error2), exitCode)) {
        return fail(error2);
      }
      throw new GitResponseError(
        task.parser(bufferToString(stdOut), bufferToString(stdErr)),
        String(error2)
      );
    }
  };
  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, path125) {
  return subModuleTask(["add", repo, path125]);
}
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(a2, b2) {
  const aIsNum = isNaN(a2);
  const bIsNum = isNaN(b2);
  if (aIsNum !== bIsNum) {
    return aIsNum ? 1 : -1;
  }
  return aIsNum ? sorted(a2, b2) : 0;
}
function sorted(a2, b2) {
  return a2 === b2 ? 0 : a2 > b2 ? 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 config2 = toBinaryConfig(asArray(input), allowUnsafe);
  plugins.on("binary", (input2) => {
    config2 = toBinaryConfig(asArray(input2), allowUnsafe);
  });
  plugins.append("spawn.binary", () => {
    return config2.binary;
  });
  plugins.append("spawn.args", (data) => {
    return config2.prefix ? [config2.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 (error2, result) => {
    if (!overwrite && error2 || !isError(result)) {
      return error2;
    }
    return errorMessage(result);
  };
}
function errorDetectionPlugin(config2) {
  return {
    type: "task.error",
    action(data, context2) {
      const error2 = config2(data.error, {
        stdErr: context2.stdErr,
        stdOut: context2.stdOut,
        exitCode: context2.exitCode
      });
      if (Buffer.isBuffer(error2)) {
        return { error: new GitError(void 0, error2.toString("utf-8")) };
      }
      return {
        error: error2
      };
    }
  };
}
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 i3 = 0; i3 < data.length; i3++) {
        const param = data[i3];
        if (isPathSpec(param)) {
          append2(toPaths(param));
          continue;
        }
        if (param === "--") {
          append2(
            data.slice(i3 + 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 config2 = createInstanceConfig(
    baseDir && (typeof baseDir === "string" ? { baseDir } : baseDir) || {},
    options2
  );
  if (!folderExists(config2.baseDir)) {
    throw new GitConstructError(
      config2,
      `Cannot use simple-git on a directory that does not exist`
    );
  }
  if (Array.isArray(config2.config)) {
    plugins.add(commandConfigPrefixingPlugin(config2.config));
  }
  plugins.add(blockUnsafeOperationsPlugin(config2.unsafe));
  plugins.add(suffixPathsPlugin());
  plugins.add(completionDetectionPlugin(config2.completion));
  config2.abort && plugins.add(abortPlugin(config2.abort));
  config2.progress && plugins.add(progressMonitorPlugin(config2.progress));
  config2.timeout && plugins.add(timeoutPlugin(config2.timeout));
  config2.spawnOptions && plugins.add(spawnOptionsPlugin(config2.spawnOptions));
  plugins.add(errorDetectionPlugin(errorDetectionHandler(true)));
  config2.errors && plugins.add(errorDetectionPlugin(config2.errors));
  customBinaryPlugin(plugins, config2.binary, config2.unsafe?.allowUnsafeCustomBinary);
  return new Git(config2, plugins);
}
var import_file_exists, import_debug, import_promise_deferred, import_promise_deferred2, __defProp2, __getOwnPropDesc2, __getOwnPropNames2, __hasOwnProp2, __esm2, __commonJS2, __export2, __copyProps2, __toCommonJS2, cache, 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, defaultOptions2, 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, _a4, 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_fetch2, 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_esm12 = __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";
        cache = /* @__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";
        defaultOptions2 = {
          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 }, error2, done, fail) => {
          if (exitCode === 128 && isNotRepoMessage(error2)) {
            return done(Buffer.from("false"));
          }
          fail(error2);
        }, "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[_a4] = [];
          }
          *[(_a4 = 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 (e4) {
              throw this.onFatalException(task, e4);
            } finally {
              onQueueComplete();
              onScheduleComplete();
            }
          }
          onFatalException(task, e4) {
            const gitError = e4 instanceof GitError ? Object.assign(e4, { task }) : new GitError(task, e4 && String(e4));
            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: error2 } = this._plugins.exec(
                "task.error",
                { error: rejection },
                {
                  ...pluginContext(task, args),
                  ...result
                }
              );
              if (error2 && task.onError) {
                logger6.info(`exitCode=%s handling with custom error handler`);
                return task.onError(
                  result,
                  error2,
                  (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 (error2) {
                logger6.info(
                  `handling as error: exitCode=%s stdErr=%s rejection=%o`,
                  exitCode,
                  stdErr.length,
                  rejection
                );
                return fail(error2);
              }
              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 email2 = parts.pop();
            if (!email2 || !email2.includes("@")) {
              return;
            }
            result.author = {
              email: email2.substr(0, email2.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, path125, existing, gitDir) {
            this.bare = bare;
            this.path = path125;
            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(path125, index, working_dir) {
            this.path = path125;
            this.index = index;
            this.working_dir = working_dir;
            if (index === "R" || working_dir === "R") {
              const detail = fromPathRegex.exec(path125) || [null, path125, path125];
              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, _file2) => {
            append(_result.ignored = _result.ignored || [], _file2);
          }),
          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 i3 = 0, l3 = lines.length; i3 < l3; ) {
            let line = lines[i3++].trim();
            if (!line) {
              continue;
            }
            if (line.charAt(0) === "R") {
              line += NULL2 + (lines[i3++] || "");
            }
            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_default, "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(path125, write2) {
            return this._runTask(
              hashObjectTask(path125, 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_default()
        );
      }
    });
    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_fetch2 = __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 i3 = 0, l3 = Math.max(partsA.length, partsB.length); i3 < l3; i3++) {
                const diff4 = sorted(toNumber(partsA[i3]), toNumber(partsB[i3]));
                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_fetch2(), __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 i3 = 0; i3 < command2.length && createRestCommands; i3++) {
            if (!filterPrimitives2(command2[i3])) {
              command2.splice(i3, command2.length - i3);
              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, path125, then) {
          return this._runTask(addSubModuleTask2(repo, path125), 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(config2, message) {
        super(void 0, message);
        this.config = config2;
      }
    };
    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 EventEmitter5();
      }
      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 fs31 from "node:fs/promises";
import * as path26 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_esm12();
    init_errors();
    GitService = class {
      static {
        __name(this, "GitService");
      }
      projectRoot;
      storage;
      constructor(projectRoot, storage) {
        this.projectRoot = path26.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 (error2) {
          throw new Error(`Failed to initialize checkpointing: ${error2 instanceof Error ? error2.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 = path26.join(repoDir, ".gitconfig");
        await fs31.mkdir(repoDir, { recursive: true });
        const gitConfigContent = "[user]\n  name = Qwen Code\n  email = qwen-code@qwen.ai\n[commit]\n  gpgsign = false\n";
        await fs31.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 = path26.join(this.projectRoot, ".gitignore");
        const shadowGitIgnorePath = path26.join(repoDir, ".gitignore");
        let userGitIgnoreContent = "";
        try {
          userGitIgnoreContent = await fs31.readFile(userGitIgnorePath, "utf-8");
        } catch (error2) {
          if (isNodeError(error2) && error2.code !== "ENOENT") {
            throw error2;
          }
        }
        await fs31.writeFile(shadowGitIgnorePath, userGitIgnoreContent);
      }
      get shadowGitRepository() {
        const repoDir = this.getHistoryDir();
        return simpleGit(this.projectRoot).env({
          GIT_DIR: path26.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 (error2) {
          throw new Error(`Failed to create checkpoint snapshot: ${error2 instanceof Error ? error2.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 types4, standard_default;
var init_standard = __esm({
  "packages/core/node_modules/mime/dist/types/standard.js"() {
    init_esbuild_shims();
    types4 = {
      "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(types4);
    standard_default = types4;
  }
});

// packages/core/node_modules/mime/dist/src/Mime.js
var __classPrivateFieldGet10, _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();
    __classPrivateFieldGet10 = function(receiver, state, kind2, f5) {
      if (kind2 === "a" && !f5) throw new TypeError("Private accessor was defined without a getter");
      if (typeof state === "function" ? receiver !== state || !f5 : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
      return kind2 === "m" ? f5 : kind2 === "a" ? f5.call(receiver) : f5 ? f5.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 (!__classPrivateFieldGet10(this, _Mime_typeToExtensions, "f").has(type)) {
            __classPrivateFieldGet10(this, _Mime_typeToExtensions, "f").set(type, /* @__PURE__ */ new Set());
          }
          const allExtensions = __classPrivateFieldGet10(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) {
              __classPrivateFieldGet10(this, _Mime_typeToExtension, "f").set(type, extension);
            }
            first2 = false;
            if (starred)
              continue;
            const currentType = __classPrivateFieldGet10(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.`);
            }
            __classPrivateFieldGet10(this, _Mime_extensionToType, "f").set(extension, type);
          }
        }
        return this;
      }
      getType(path125) {
        if (typeof path125 !== "string")
          return null;
        const last2 = path125.replace(/^.*[/\\]/s, "").toLowerCase();
        const ext2 = last2.replace(/^.*\./s, "").toLowerCase();
        const hasPath = last2.length < path125.length;
        const hasDot = ext2.length < last2.length - 1;
        if (!hasDot && hasPath)
          return null;
        return __classPrivateFieldGet10(this, _Mime_extensionToType, "f").get(ext2) ?? null;
      }
      getExtension(type) {
        if (typeof type !== "string")
          return null;
        type = type?.split?.(";")[0];
        return (type && __classPrivateFieldGet10(this, _Mime_typeToExtension, "f").get(type.trim().toLowerCase())) ?? null;
      }
      getAllExtensions(type) {
        if (typeof type !== "string")
          return null;
        return __classPrivateFieldGet10(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 __classPrivateFieldGet10(this, _Mime_typeToExtensions, "f").values()) {
          Object.freeze(extensions);
        }
        return this;
      }
      _getTestState() {
        return {
          types: __classPrivateFieldGet10(this, _Mime_extensionToType, "f"),
          extensions: __classPrivateFieldGet10(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 path27 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 = path27.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(config2) {
        this.config = config2;
      }
      /**
       * 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 fs32 from "node:fs";
import fsPromises from "node:fs/promises";
import path28 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 i3 = 0; i3 < usable; i3 += 4) {
    const cp3 = littleEndian ? (buf[i3] | buf[i3 + 1] << 8 | buf[i3 + 2] << 16 | buf[i3 + 3] << 24) >>> 0 : (buf[i3 + 3] | buf[i3 + 2] << 8 | buf[i3 + 1] << 16 | buf[i3] << 24) >>> 0;
    if (cp3 <= 1114111 && !(cp3 >= 55296 && cp3 <= 57343)) {
      out += String.fromCodePoint(cp3);
    } else {
      out += "\uFFFD";
    }
  }
  return out;
}
async function readFileWithEncoding(filePath) {
  const full = await fs32.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 = path28.resolve(pathToCheck);
  const normalizedRootDirectory = path28.resolve(rootDirectory);
  const rootWithSeparator = normalizedRootDirectory === path28.sep || normalizedRootDirectory.endsWith(path28.sep) ? normalizedRootDirectory : normalizedRootDirectory + path28.sep;
  return normalizedPathToCheck === normalizedRootDirectory || normalizedPathToCheck.startsWith(rootWithSeparator);
}
async function isBinaryFile(filePath) {
  let fh = null;
  try {
    fh = await fs32.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 i3 = 0; i3 < bytesRead; i3++) {
      if (buf[i3] === 0)
        return true;
      if (buf[i3] < 9 || buf[i3] > 13 && buf[i3] < 32) {
        nonPrintableCount++;
      }
    }
    return nonPrintableCount / bytesRead > 0.3;
  } catch (error2) {
    debugLogger33.warn(`Failed to check if file is binary: ${filePath}`, error2 instanceof Error ? error2.message : String(error2));
    return false;
  } finally {
    if (fh) {
      try {
        await fh.close();
      } catch (closeError) {
        debugLogger33.warn(`Failed to close file handle for: ${filePath}`, closeError instanceof Error ? closeError.message : String(closeError));
      }
    }
  }
}
async function detectFileType(filePath) {
  const ext2 = path28.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, config2, offset, limit2) {
  const rootDirectory = config2.getTargetDir();
  try {
    if (!fs32.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 fs32.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 = path28.relative(rootDirectory, filePath).replace(/\\/g, "/");
    const displayName = path28.basename(filePath);
    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 = config2.getTruncateToolOutputLines();
        const configCharLimit = config2.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 sep9 = linesIncluded > 0 ? 1 : 0;
            linesIncluded++;
            const projectedLength = currentLength + line.length + sep9;
            if (projectedLength <= configCharLimit) {
              formattedLines.push(line);
              currentLength = projectedLength;
            } else {
              const remaining = Math.max(configCharLimit - currentLength - sep9, 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 "audio":
      case "video":
      case "pdf": {
        const contentBuffer = await fs32.promises.readFile(filePath);
        const base64Data = contentBuffer.toString("base64");
        return {
          llmContent: {
            inlineData: {
              data: base64Data,
              mimeType: index_lite_default.getType(filePath) || "application/octet-stream",
              displayName
            }
          },
          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 (error2) {
    const errorMessage = error2 instanceof Error ? error2.message : String(error2);
    const displayPath = path28.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, fs32.constants.F_OK);
    return true;
  } catch (_2) {
    return false;
  }
}
var debugLogger33;
var init_fileUtils = __esm({
  "packages/core/dist/src/utils/fileUtils.js"() {
    "use strict";
    init_esbuild_shims();
    init_index_lite();
    init_tool_error();
    init_ignorePatterns();
    init_debugLogger();
    debugLogger33 = createDebugLogger("FILE_UTILS");
    __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 path29 from "node:path";
function getLanguageFromFilePath(filePath) {
  const extension = path29.extname(filePath).toLowerCase();
  if (extension) {
    return extensionToLanguageMap[extension];
  }
  const filename = path29.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 path30 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_types();
    init_paths();
    init_storage();
    ReadFileToolInvocation = class extends BaseToolInvocation {
      static {
        __name(this, "ReadFileToolInvocation");
      }
      config;
      constructor(config2, params) {
        super(params);
        this.config = config2;
      }
      getDescription() {
        const relativePath = makeRelative(this.params.absolute_path, this.config.getTargetDir());
        const shortPath = shortenPath(relativePath);
        const { offset, limit: limit2 } = this.params;
        if (offset !== void 0 && limit2 !== void 0) {
          return `${shortPath} (lines ${offset + 1}-${offset + limit2})`;
        } else if (offset !== void 0) {
          return `${shortPath} (from line ${offset + 1})`;
        } else if (limit2 !== void 0) {
          return `${shortPath} (first ${limit2} lines)`;
        }
        return shortPath;
      }
      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, path30.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(config2) {
        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 = config2;
      }
      validateToolParamValues(params) {
        const filePath = params.absolute_path;
        if (params.absolute_path.trim() === "") {
          return "The 'absolute_path' parameter must be non-empty.";
        }
        if (!path30.isAbsolute(filePath)) {
          return `File path must be absolute, but was relative: ${filePath}. You must provide an absolute path.`;
        }
        const workspaceContext = this.config.getWorkspaceContext();
        const globalTempDir = Storage.getGlobalTempDir();
        const projectTempDir = this.config.storage.getProjectTempDir();
        const userSkillsDir = this.config.storage.getUserSkillsDir();
        const resolvedFilePath = path30.resolve(filePath);
        const isWithinTempDir = isSubpath(projectTempDir, resolvedFilePath) || isSubpath(globalTempDir, resolvedFilePath);
        const isWithinUserSkills = isSubpath(userSkillsDir, resolvedFilePath);
        if (!workspaceContext.isPathWithinWorkspace(filePath) && !isWithinTempDir && !isWithinUserSkills) {
          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, execFile as execFile7 } from "node:child_process";
import { promisify as promisify7 } from "node:util";
import os14 from "node:os";
import path31 from "node:path";
async function getProcessInfo(pid) {
  try {
    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 parts = trimmedStdout.split(/\s+/);
    const ppidString = parts[0];
    const parentPid = parseInt(ppidString, 10);
    const fullCommand = trimmedStdout.substring(ppidString.length).trim();
    const processName = path31.basename(fullCommand.split(" ")[0]);
    return {
      parentPid: isNaN(parentPid) ? 1 : parentPid,
      name: processName,
      command: fullCommand
    };
  } catch (_e2) {
    return { parentPid: 0, name: "", command: "" };
  }
}
async function getIdeProcessInfoForUnix() {
  const shells = ["zsh", "bash", "sh", "tcsh", "csh", "ksh", "fish", "dash"];
  let currentPid = process.pid;
  for (let i3 = 0; i3 < MAX_TRAVERSAL_DEPTH; i3++) {
    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: ideCommand2 } = await getProcessInfo(idePid);
        return { pid: idePid, command: ideCommand2 };
      }
      if (parentPid <= 1) {
        break;
      }
      currentPid = parentPid;
    } catch (_e2) {
      break;
    }
  }
  const { command: command2 } = await getProcessInfo(currentPid);
  return { pid: currentPid, command: command2 };
}
async function getProcessTableWindows() {
  const processMap = /* @__PURE__ */ new Map();
  try {
    const powershellCommand = "Get-CimInstance Win32_Process | Select-Object ProcessId,ParentProcessId,Name,CommandLine | ConvertTo-Json -Compress";
    const { stdout } = await execFileAsync5("powershell", ["-NoProfile", "-NonInteractive", "-Command", powershellCommand], { maxBuffer: 10 * 1024 * 1024 });
    if (!stdout.trim()) {
      return processMap;
    }
    let processes;
    try {
      processes = JSON.parse(stdout);
    } catch (_e2) {
      return processMap;
    }
    if (!Array.isArray(processes)) {
      processes = [processes];
    }
    for (const p2 of processes) {
      if (p2 && typeof p2.ProcessId === "number") {
        processMap.set(p2.ProcessId, {
          pid: p2.ProcessId,
          parentPid: p2.ParentProcessId || 0,
          name: p2.Name || "",
          command: p2.CommandLine || ""
        });
      }
    }
  } catch (_e2) {
  }
  return processMap;
}
async function getIdeProcessInfoForWindows() {
  const processMap = await getProcessTableWindows();
  const myPid = process.pid;
  const myProc = processMap.get(myPid);
  if (!myProc) {
    return { pid: myPid, command: "" };
  }
  const ancestors = [];
  let curr = myProc;
  for (let i3 = 0; i3 < MAX_TRAVERSAL_DEPTH && curr; i3++) {
    ancestors.push(curr);
    if (curr.parentPid === 0 || !processMap.has(curr.parentPid)) {
      break;
    }
    curr = processMap.get(curr.parentPid);
  }
  if (ancestors.length >= 3) {
    const target = ancestors[ancestors.length - 3];
    return { pid: target.pid, command: target.command };
  } else if (ancestors.length > 0) {
    const target = ancestors[ancestors.length - 1];
    return { pid: target.pid, command: target.command };
  }
  return { pid: myPid, command: myProc.command };
}
async function getIdeProcessInfo() {
  const platform16 = os14.platform();
  if (platform16 === "win32") {
    return getIdeProcessInfoForWindows();
  }
  return getIdeProcessInfoForUnix();
}
var execAsync, execFileAsync5, MAX_TRAVERSAL_DEPTH;
var init_process_utils = __esm({
  "packages/core/dist/src/ide/process-utils.js"() {
    "use strict";
    init_esbuild_shims();
    execAsync = promisify7(exec);
    execFileAsync5 = promisify7(execFile7);
    MAX_TRAVERSAL_DEPTH = 32;
    __name(getProcessInfo, "getProcessInfo");
    __name(getIdeProcessInfoForUnix, "getIdeProcessInfoForUnix");
    __name(getProcessTableWindows, "getProcessTableWindows");
    __name(getIdeProcessInfoForWindows, "getIdeProcessInfoForWindows");
    __name(getIdeProcessInfo, "getIdeProcessInfo");
  }
});

// node_modules/zod/v4/core/core.js
// @__NO_SIDE_EFFECTS__
function $constructor(name3, initializer3, params) {
  function init(inst, def2) {
    var _a7;
    Object.defineProperty(inst, "_zod", {
      value: inst._zod ?? {},
      enumerable: false
    });
    (_a7 = inst._zod).traits ?? (_a7.traits = /* @__PURE__ */ new Set());
    inst._zod.traits.add(name3);
    initializer3(inst, def2);
    for (const k2 in _2.prototype) {
      if (!(k2 in inst))
        Object.defineProperty(inst, k2, { value: _2.prototype[k2].bind(inst) });
    }
    inst._zod.constr = _2;
    inst._zod.def = def2;
  }
  __name(init, "init");
  const Parent = params?.Parent ?? Object;
  class Definition extends Parent {
    static {
      __name(this, "Definition");
    }
  }
  Object.defineProperty(Definition, "name", { value: name3 });
  function _2(def2) {
    var _a7;
    const inst = params?.Parent ? new Definition() : this;
    init(inst, def2);
    (_a7 = inst._zod).deferred ?? (_a7.deferred = []);
    for (const fn of inst._zod.deferred) {
      fn();
    }
    return inst;
  }
  __name(_2, "_");
  Object.defineProperty(_2, "init", { value: init });
  Object.defineProperty(_2, Symbol.hasInstance, {
    value: /* @__PURE__ */ __name((inst) => {
      if (params?.Parent && inst instanceof params.Parent)
        return true;
      return inst?._zod?.traits?.has(name3);
    }, "value")
  });
  Object.defineProperty(_2, "name", { value: name3 });
  return _2;
}
function config(newConfig) {
  if (newConfig)
    Object.assign(globalConfig, newConfig);
  return globalConfig;
}
var NEVER2, $brand, $ZodAsyncError, globalConfig;
var init_core2 = __esm({
  "node_modules/zod/v4/core/core.js"() {
    init_esbuild_shims();
    NEVER2 = Object.freeze({
      status: "aborted"
    });
    __name($constructor, "$constructor");
    $brand = Symbol("zod_brand");
    $ZodAsyncError = class extends Error {
      static {
        __name(this, "$ZodAsyncError");
      }
      constructor() {
        super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`);
      }
    };
    globalConfig = {};
    __name(config, "config");
  }
});

// node_modules/zod/v4/core/util.js
var util_exports = {};
__export(util_exports, {
  BIGINT_FORMAT_RANGES: () => BIGINT_FORMAT_RANGES,
  Class: () => Class,
  NUMBER_FORMAT_RANGES: () => NUMBER_FORMAT_RANGES,
  aborted: () => aborted,
  allowsEval: () => allowsEval,
  assert: () => assert,
  assertEqual: () => assertEqual,
  assertIs: () => assertIs,
  assertNever: () => assertNever3,
  assertNotEqual: () => assertNotEqual,
  assignProp: () => assignProp,
  cached: () => cached,
  captureStackTrace: () => captureStackTrace,
  cleanEnum: () => cleanEnum,
  cleanRegex: () => cleanRegex,
  clone: () => clone2,
  createTransparentProxy: () => createTransparentProxy,
  defineLazy: () => defineLazy,
  esc: () => esc,
  escapeRegex: () => escapeRegex,
  extend: () => extend,
  finalizeIssue: () => finalizeIssue,
  floatSafeRemainder: () => floatSafeRemainder2,
  getElementAtPath: () => getElementAtPath,
  getEnumValues: () => getEnumValues,
  getLengthableOrigin: () => getLengthableOrigin,
  getParsedType: () => getParsedType2,
  getSizableOrigin: () => getSizableOrigin,
  isObject: () => isObject,
  isPlainObject: () => isPlainObject3,
  issue: () => issue,
  joinValues: () => joinValues,
  jsonStringifyReplacer: () => jsonStringifyReplacer,
  merge: () => merge,
  normalizeParams: () => normalizeParams,
  nullish: () => nullish,
  numKeys: () => numKeys,
  omit: () => omit,
  optionalKeys: () => optionalKeys,
  partial: () => partial,
  pick: () => pick2,
  prefixIssues: () => prefixIssues,
  primitiveTypes: () => primitiveTypes,
  promiseAllObject: () => promiseAllObject,
  propertyKeyTypes: () => propertyKeyTypes,
  randomString: () => randomString,
  required: () => required,
  stringifyPrimitive: () => stringifyPrimitive,
  unwrapMessage: () => unwrapMessage
});
function assertEqual(val) {
  return val;
}
function assertNotEqual(val) {
  return val;
}
function assertIs(_arg) {
}
function assertNever3(_x) {
  throw new Error();
}
function assert(_2) {
}
function getEnumValues(entries) {
  const numericValues = Object.values(entries).filter((v2) => typeof v2 === "number");
  const values = Object.entries(entries).filter(([k2, _2]) => numericValues.indexOf(+k2) === -1).map(([_2, v2]) => v2);
  return values;
}
function joinValues(array2, separator = "|") {
  return array2.map((val) => stringifyPrimitive(val)).join(separator);
}
function jsonStringifyReplacer(_2, value) {
  if (typeof value === "bigint")
    return value.toString();
  return value;
}
function cached(getter) {
  const set = false;
  return {
    get value() {
      if (!set) {
        const value = getter();
        Object.defineProperty(this, "value", { value });
        return value;
      }
      throw new Error("cached value already set");
    }
  };
}
function nullish(input) {
  return input === null || input === void 0;
}
function cleanRegex(source2) {
  const start = source2.startsWith("^") ? 1 : 0;
  const end = source2.endsWith("$") ? source2.length - 1 : source2.length;
  return source2.slice(start, end);
}
function floatSafeRemainder2(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 defineLazy(object3, key, getter) {
  const set = false;
  Object.defineProperty(object3, key, {
    get() {
      if (!set) {
        const value = getter();
        object3[key] = value;
        return value;
      }
      throw new Error("cached value already set");
    },
    set(v2) {
      Object.defineProperty(object3, key, {
        value: v2
        // configurable: true,
      });
    },
    configurable: true
  });
}
function assignProp(target, prop, value) {
  Object.defineProperty(target, prop, {
    value,
    writable: true,
    enumerable: true,
    configurable: true
  });
}
function getElementAtPath(obj, path125) {
  if (!path125)
    return obj;
  return path125.reduce((acc, key) => acc?.[key], obj);
}
function promiseAllObject(promisesObj) {
  const keys = Object.keys(promisesObj);
  const promises8 = keys.map((key) => promisesObj[key]);
  return Promise.all(promises8).then((results) => {
    const resolvedObj = {};
    for (let i3 = 0; i3 < keys.length; i3++) {
      resolvedObj[keys[i3]] = results[i3];
    }
    return resolvedObj;
  });
}
function randomString(length = 10) {
  const chars = "abcdefghijklmnopqrstuvwxyz";
  let str2 = "";
  for (let i3 = 0; i3 < length; i3++) {
    str2 += chars[Math.floor(Math.random() * chars.length)];
  }
  return str2;
}
function esc(str2) {
  return JSON.stringify(str2);
}
function isObject(data) {
  return typeof data === "object" && data !== null && !Array.isArray(data);
}
function isPlainObject3(o3) {
  if (isObject(o3) === false)
    return false;
  const ctor = o3.constructor;
  if (ctor === void 0)
    return true;
  const prot = ctor.prototype;
  if (isObject(prot) === false)
    return false;
  if (Object.prototype.hasOwnProperty.call(prot, "isPrototypeOf") === false) {
    return false;
  }
  return true;
}
function numKeys(data) {
  let keyCount = 0;
  for (const key in data) {
    if (Object.prototype.hasOwnProperty.call(data, key)) {
      keyCount++;
    }
  }
  return keyCount;
}
function escapeRegex(str2) {
  return str2.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
}
function clone2(inst, def2, params) {
  const cl = new inst._zod.constr(def2 ?? inst._zod.def);
  if (!def2 || params?.parent)
    cl._zod.parent = inst;
  return cl;
}
function normalizeParams(_params) {
  const params = _params;
  if (!params)
    return {};
  if (typeof params === "string")
    return { error: /* @__PURE__ */ __name(() => params, "error") };
  if (params?.message !== void 0) {
    if (params?.error !== void 0)
      throw new Error("Cannot specify both `message` and `error` params");
    params.error = params.message;
  }
  delete params.message;
  if (typeof params.error === "string")
    return { ...params, error: /* @__PURE__ */ __name(() => params.error, "error") };
  return params;
}
function createTransparentProxy(getter) {
  let target;
  return new Proxy({}, {
    get(_2, prop, receiver) {
      target ?? (target = getter());
      return Reflect.get(target, prop, receiver);
    },
    set(_2, prop, value, receiver) {
      target ?? (target = getter());
      return Reflect.set(target, prop, value, receiver);
    },
    has(_2, prop) {
      target ?? (target = getter());
      return Reflect.has(target, prop);
    },
    deleteProperty(_2, prop) {
      target ?? (target = getter());
      return Reflect.deleteProperty(target, prop);
    },
    ownKeys(_2) {
      target ?? (target = getter());
      return Reflect.ownKeys(target);
    },
    getOwnPropertyDescriptor(_2, prop) {
      target ?? (target = getter());
      return Reflect.getOwnPropertyDescriptor(target, prop);
    },
    defineProperty(_2, prop, descriptor2) {
      target ?? (target = getter());
      return Reflect.defineProperty(target, prop, descriptor2);
    }
  });
}
function stringifyPrimitive(value) {
  if (typeof value === "bigint")
    return value.toString() + "n";
  if (typeof value === "string")
    return `"${value}"`;
  return `${value}`;
}
function optionalKeys(shape) {
  return Object.keys(shape).filter((k2) => {
    return shape[k2]._zod.optin === "optional" && shape[k2]._zod.optout === "optional";
  });
}
function pick2(schema, mask) {
  const newShape = {};
  const currDef = schema._zod.def;
  for (const key in mask) {
    if (!(key in currDef.shape)) {
      throw new Error(`Unrecognized key: "${key}"`);
    }
    if (!mask[key])
      continue;
    newShape[key] = currDef.shape[key];
  }
  return clone2(schema, {
    ...schema._zod.def,
    shape: newShape,
    checks: []
  });
}
function omit(schema, mask) {
  const newShape = { ...schema._zod.def.shape };
  const currDef = schema._zod.def;
  for (const key in mask) {
    if (!(key in currDef.shape)) {
      throw new Error(`Unrecognized key: "${key}"`);
    }
    if (!mask[key])
      continue;
    delete newShape[key];
  }
  return clone2(schema, {
    ...schema._zod.def,
    shape: newShape,
    checks: []
  });
}
function extend(schema, shape) {
  if (!isPlainObject3(shape)) {
    throw new Error("Invalid input to extend: expected a plain object");
  }
  const def2 = {
    ...schema._zod.def,
    get shape() {
      const _shape = { ...schema._zod.def.shape, ...shape };
      assignProp(this, "shape", _shape);
      return _shape;
    },
    checks: []
    // delete existing checks
  };
  return clone2(schema, def2);
}
function merge(a2, b2) {
  return clone2(a2, {
    ...a2._zod.def,
    get shape() {
      const _shape = { ...a2._zod.def.shape, ...b2._zod.def.shape };
      assignProp(this, "shape", _shape);
      return _shape;
    },
    catchall: b2._zod.def.catchall,
    checks: []
    // delete existing checks
  });
}
function partial(Class2, schema, mask) {
  const oldShape = schema._zod.def.shape;
  const shape = { ...oldShape };
  if (mask) {
    for (const key in mask) {
      if (!(key in oldShape)) {
        throw new Error(`Unrecognized key: "${key}"`);
      }
      if (!mask[key])
        continue;
      shape[key] = Class2 ? new Class2({
        type: "optional",
        innerType: oldShape[key]
      }) : oldShape[key];
    }
  } else {
    for (const key in oldShape) {
      shape[key] = Class2 ? new Class2({
        type: "optional",
        innerType: oldShape[key]
      }) : oldShape[key];
    }
  }
  return clone2(schema, {
    ...schema._zod.def,
    shape,
    checks: []
  });
}
function required(Class2, schema, mask) {
  const oldShape = schema._zod.def.shape;
  const shape = { ...oldShape };
  if (mask) {
    for (const key in mask) {
      if (!(key in shape)) {
        throw new Error(`Unrecognized key: "${key}"`);
      }
      if (!mask[key])
        continue;
      shape[key] = new Class2({
        type: "nonoptional",
        innerType: oldShape[key]
      });
    }
  } else {
    for (const key in oldShape) {
      shape[key] = new Class2({
        type: "nonoptional",
        innerType: oldShape[key]
      });
    }
  }
  return clone2(schema, {
    ...schema._zod.def,
    shape,
    // optional: [],
    checks: []
  });
}
function aborted(x3, startIndex = 0) {
  for (let i3 = startIndex; i3 < x3.issues.length; i3++) {
    if (x3.issues[i3]?.continue !== true)
      return true;
  }
  return false;
}
function prefixIssues(path125, issues) {
  return issues.map((iss) => {
    var _a7;
    (_a7 = iss).path ?? (_a7.path = []);
    iss.path.unshift(path125);
    return iss;
  });
}
function unwrapMessage(message) {
  return typeof message === "string" ? message : message?.message;
}
function finalizeIssue(iss, ctx, config2) {
  const full = { ...iss, path: iss.path ?? [] };
  if (!iss.message) {
    const message = unwrapMessage(iss.inst?._zod.def?.error?.(iss)) ?? unwrapMessage(ctx?.error?.(iss)) ?? unwrapMessage(config2.customError?.(iss)) ?? unwrapMessage(config2.localeError?.(iss)) ?? "Invalid input";
    full.message = message;
  }
  delete full.inst;
  delete full.continue;
  if (!ctx?.reportInput) {
    delete full.input;
  }
  return full;
}
function getSizableOrigin(input) {
  if (input instanceof Set)
    return "set";
  if (input instanceof Map)
    return "map";
  if (input instanceof File)
    return "file";
  return "unknown";
}
function getLengthableOrigin(input) {
  if (Array.isArray(input))
    return "array";
  if (typeof input === "string")
    return "string";
  return "unknown";
}
function issue(...args) {
  const [iss, input, inst] = args;
  if (typeof iss === "string") {
    return {
      message: iss,
      code: "custom",
      input,
      inst
    };
  }
  return { ...iss };
}
function cleanEnum(obj) {
  return Object.entries(obj).filter(([k2, _2]) => {
    return Number.isNaN(Number.parseInt(k2, 10));
  }).map((el) => el[1]);
}
var captureStackTrace, allowsEval, getParsedType2, propertyKeyTypes, primitiveTypes, NUMBER_FORMAT_RANGES, BIGINT_FORMAT_RANGES, Class;
var init_util4 = __esm({
  "node_modules/zod/v4/core/util.js"() {
    init_esbuild_shims();
    __name(assertEqual, "assertEqual");
    __name(assertNotEqual, "assertNotEqual");
    __name(assertIs, "assertIs");
    __name(assertNever3, "assertNever");
    __name(assert, "assert");
    __name(getEnumValues, "getEnumValues");
    __name(joinValues, "joinValues");
    __name(jsonStringifyReplacer, "jsonStringifyReplacer");
    __name(cached, "cached");
    __name(nullish, "nullish");
    __name(cleanRegex, "cleanRegex");
    __name(floatSafeRemainder2, "floatSafeRemainder");
    __name(defineLazy, "defineLazy");
    __name(assignProp, "assignProp");
    __name(getElementAtPath, "getElementAtPath");
    __name(promiseAllObject, "promiseAllObject");
    __name(randomString, "randomString");
    __name(esc, "esc");
    captureStackTrace = Error.captureStackTrace ? Error.captureStackTrace : (..._args) => {
    };
    __name(isObject, "isObject");
    allowsEval = cached(() => {
      if (typeof navigator !== "undefined" && navigator?.userAgent?.includes("Cloudflare")) {
        return false;
      }
      try {
        const F4 = Function;
        new F4("");
        return true;
      } catch (_2) {
        return false;
      }
    });
    __name(isPlainObject3, "isPlainObject");
    __name(numKeys, "numKeys");
    getParsedType2 = /* @__PURE__ */ __name((data) => {
      const t5 = typeof data;
      switch (t5) {
        case "undefined":
          return "undefined";
        case "string":
          return "string";
        case "number":
          return Number.isNaN(data) ? "nan" : "number";
        case "boolean":
          return "boolean";
        case "function":
          return "function";
        case "bigint":
          return "bigint";
        case "symbol":
          return "symbol";
        case "object":
          if (Array.isArray(data)) {
            return "array";
          }
          if (data === null) {
            return "null";
          }
          if (data.then && typeof data.then === "function" && data.catch && typeof data.catch === "function") {
            return "promise";
          }
          if (typeof Map !== "undefined" && data instanceof Map) {
            return "map";
          }
          if (typeof Set !== "undefined" && data instanceof Set) {
            return "set";
          }
          if (typeof Date !== "undefined" && data instanceof Date) {
            return "date";
          }
          if (typeof File !== "undefined" && data instanceof File) {
            return "file";
          }
          return "object";
        default:
          throw new Error(`Unknown data type: ${t5}`);
      }
    }, "getParsedType");
    propertyKeyTypes = /* @__PURE__ */ new Set(["string", "number", "symbol"]);
    primitiveTypes = /* @__PURE__ */ new Set(["string", "number", "bigint", "boolean", "symbol", "undefined"]);
    __name(escapeRegex, "escapeRegex");
    __name(clone2, "clone");
    __name(normalizeParams, "normalizeParams");
    __name(createTransparentProxy, "createTransparentProxy");
    __name(stringifyPrimitive, "stringifyPrimitive");
    __name(optionalKeys, "optionalKeys");
    NUMBER_FORMAT_RANGES = {
      safeint: [Number.MIN_SAFE_INTEGER, Number.MAX_SAFE_INTEGER],
      int32: [-2147483648, 2147483647],
      uint32: [0, 4294967295],
      float32: [-34028234663852886e22, 34028234663852886e22],
      float64: [-Number.MAX_VALUE, Number.MAX_VALUE]
    };
    BIGINT_FORMAT_RANGES = {
      int64: [/* @__PURE__ */ BigInt("-9223372036854775808"), /* @__PURE__ */ BigInt("9223372036854775807")],
      uint64: [/* @__PURE__ */ BigInt(0), /* @__PURE__ */ BigInt("18446744073709551615")]
    };
    __name(pick2, "pick");
    __name(omit, "omit");
    __name(extend, "extend");
    __name(merge, "merge");
    __name(partial, "partial");
    __name(required, "required");
    __name(aborted, "aborted");
    __name(prefixIssues, "prefixIssues");
    __name(unwrapMessage, "unwrapMessage");
    __name(finalizeIssue, "finalizeIssue");
    __name(getSizableOrigin, "getSizableOrigin");
    __name(getLengthableOrigin, "getLengthableOrigin");
    __name(issue, "issue");
    __name(cleanEnum, "cleanEnum");
    Class = class {
      static {
        __name(this, "Class");
      }
      constructor(..._args) {
      }
    };
  }
});

// node_modules/zod/v4/core/errors.js
function flattenError(error2, mapper = (issue2) => issue2.message) {
  const fieldErrors = {};
  const formErrors = [];
  for (const sub of error2.issues) {
    if (sub.path.length > 0) {
      fieldErrors[sub.path[0]] = fieldErrors[sub.path[0]] || [];
      fieldErrors[sub.path[0]].push(mapper(sub));
    } else {
      formErrors.push(mapper(sub));
    }
  }
  return { formErrors, fieldErrors };
}
function formatError(error2, _mapper) {
  const mapper = _mapper || function(issue2) {
    return issue2.message;
  };
  const fieldErrors = { _errors: [] };
  const processError = /* @__PURE__ */ __name((error3) => {
    for (const issue2 of error3.issues) {
      if (issue2.code === "invalid_union" && issue2.errors.length) {
        issue2.errors.map((issues) => processError({ issues }));
      } else if (issue2.code === "invalid_key") {
        processError({ issues: issue2.issues });
      } else if (issue2.code === "invalid_element") {
        processError({ issues: issue2.issues });
      } else if (issue2.path.length === 0) {
        fieldErrors._errors.push(mapper(issue2));
      } else {
        let curr = fieldErrors;
        let i3 = 0;
        while (i3 < issue2.path.length) {
          const el = issue2.path[i3];
          const terminal = i3 === issue2.path.length - 1;
          if (!terminal) {
            curr[el] = curr[el] || { _errors: [] };
          } else {
            curr[el] = curr[el] || { _errors: [] };
            curr[el]._errors.push(mapper(issue2));
          }
          curr = curr[el];
          i3++;
        }
      }
    }
  }, "processError");
  processError(error2);
  return fieldErrors;
}
var initializer, $ZodError, $ZodRealError;
var init_errors4 = __esm({
  "node_modules/zod/v4/core/errors.js"() {
    init_esbuild_shims();
    init_core2();
    init_util4();
    initializer = /* @__PURE__ */ __name((inst, def2) => {
      inst.name = "$ZodError";
      Object.defineProperty(inst, "_zod", {
        value: inst._zod,
        enumerable: false
      });
      Object.defineProperty(inst, "issues", {
        value: def2,
        enumerable: false
      });
      Object.defineProperty(inst, "message", {
        get() {
          return JSON.stringify(def2, jsonStringifyReplacer, 2);
        },
        enumerable: true
        // configurable: false,
      });
      Object.defineProperty(inst, "toString", {
        value: /* @__PURE__ */ __name(() => inst.message, "value"),
        enumerable: false
      });
    }, "initializer");
    $ZodError = $constructor("$ZodError", initializer);
    $ZodRealError = $constructor("$ZodError", initializer, { Parent: Error });
    __name(flattenError, "flattenError");
    __name(formatError, "formatError");
  }
});

// node_modules/zod/v4/core/parse.js
var _parse, _parseAsync, _safeParse, safeParse, _safeParseAsync, safeParseAsync;
var init_parse2 = __esm({
  "node_modules/zod/v4/core/parse.js"() {
    init_esbuild_shims();
    init_core2();
    init_errors4();
    init_util4();
    _parse = /* @__PURE__ */ __name((_Err) => (schema, value, _ctx, _params) => {
      const ctx = _ctx ? Object.assign(_ctx, { async: false }) : { async: false };
      const result = schema._zod.run({ value, issues: [] }, ctx);
      if (result instanceof Promise) {
        throw new $ZodAsyncError();
      }
      if (result.issues.length) {
        const e4 = new (_params?.Err ?? _Err)(result.issues.map((iss) => finalizeIssue(iss, ctx, config())));
        captureStackTrace(e4, _params?.callee);
        throw e4;
      }
      return result.value;
    }, "_parse");
    _parseAsync = /* @__PURE__ */ __name((_Err) => async (schema, value, _ctx, params) => {
      const ctx = _ctx ? Object.assign(_ctx, { async: true }) : { async: true };
      let result = schema._zod.run({ value, issues: [] }, ctx);
      if (result instanceof Promise)
        result = await result;
      if (result.issues.length) {
        const e4 = new (params?.Err ?? _Err)(result.issues.map((iss) => finalizeIssue(iss, ctx, config())));
        captureStackTrace(e4, params?.callee);
        throw e4;
      }
      return result.value;
    }, "_parseAsync");
    _safeParse = /* @__PURE__ */ __name((_Err) => (schema, value, _ctx) => {
      const ctx = _ctx ? { ..._ctx, async: false } : { async: false };
      const result = schema._zod.run({ value, issues: [] }, ctx);
      if (result instanceof Promise) {
        throw new $ZodAsyncError();
      }
      return result.issues.length ? {
        success: false,
        error: new (_Err ?? $ZodError)(result.issues.map((iss) => finalizeIssue(iss, ctx, config())))
      } : { success: true, data: result.value };
    }, "_safeParse");
    safeParse = /* @__PURE__ */ _safeParse($ZodRealError);
    _safeParseAsync = /* @__PURE__ */ __name((_Err) => async (schema, value, _ctx) => {
      const ctx = _ctx ? Object.assign(_ctx, { async: true }) : { async: true };
      let result = schema._zod.run({ value, issues: [] }, ctx);
      if (result instanceof Promise)
        result = await result;
      return result.issues.length ? {
        success: false,
        error: new _Err(result.issues.map((iss) => finalizeIssue(iss, ctx, config())))
      } : { success: true, data: result.value };
    }, "_safeParseAsync");
    safeParseAsync = /* @__PURE__ */ _safeParseAsync($ZodRealError);
  }
});

// node_modules/zod/v4/core/regexes.js
function emoji() {
  return new RegExp(_emoji, "u");
}
function timeSource(args) {
  const hhmm = `(?:[01]\\d|2[0-3]):[0-5]\\d`;
  const regex3 = typeof args.precision === "number" ? args.precision === -1 ? `${hhmm}` : args.precision === 0 ? `${hhmm}:[0-5]\\d` : `${hhmm}:[0-5]\\d\\.\\d{${args.precision}}` : `${hhmm}(?::[0-5]\\d(?:\\.\\d+)?)?`;
  return regex3;
}
function time(args) {
  return new RegExp(`^${timeSource(args)}$`);
}
function datetime(args) {
  const time3 = timeSource({ precision: args.precision });
  const opts = ["Z"];
  if (args.local)
    opts.push("");
  if (args.offset)
    opts.push(`([+-]\\d{2}:\\d{2})`);
  const timeRegex2 = `${time3}(?:${opts.join("|")})`;
  return new RegExp(`^${dateSource}T(?:${timeRegex2})$`);
}
var cuid, cuid2, ulid, xid, ksuid, nanoid, duration, guid, uuid, email, _emoji, ipv4, ipv6, cidrv4, cidrv6, base64, base64url, hostname2, e164, dateSource, date, string, bigint, integer, number, boolean, _null, lowercase, uppercase;
var init_regexes = __esm({
  "node_modules/zod/v4/core/regexes.js"() {
    init_esbuild_shims();
    cuid = /^[cC][^\s-]{8,}$/;
    cuid2 = /^[0-9a-z]+$/;
    ulid = /^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/;
    xid = /^[0-9a-vA-V]{20}$/;
    ksuid = /^[A-Za-z0-9]{27}$/;
    nanoid = /^[a-zA-Z0-9_-]{21}$/;
    duration = /^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;
    guid = /^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/;
    uuid = /* @__PURE__ */ __name((version2) => {
      if (!version2)
        return /^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000)$/;
      return new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${version2}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`);
    }, "uuid");
    email = /^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;
    _emoji = `^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`;
    __name(emoji, "emoji");
    ipv4 = /^(?:(?: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])$/;
    ipv6 = /^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})$/;
    cidrv4 = /^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/;
    cidrv6 = /^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/;
    base64 = /^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/;
    base64url = /^[A-Za-z0-9_-]*$/;
    hostname2 = /^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/;
    e164 = /^\+(?:[0-9]){6,14}[0-9]$/;
    dateSource = `(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))`;
    date = /* @__PURE__ */ new RegExp(`^${dateSource}$`);
    __name(timeSource, "timeSource");
    __name(time, "time");
    __name(datetime, "datetime");
    string = /* @__PURE__ */ __name((params) => {
      const regex3 = params ? `[\\s\\S]{${params?.minimum ?? 0},${params?.maximum ?? ""}}` : `[\\s\\S]*`;
      return new RegExp(`^${regex3}$`);
    }, "string");
    bigint = /^\d+n?$/;
    integer = /^\d+$/;
    number = /^-?\d+(?:\.\d+)?/i;
    boolean = /true|false/i;
    _null = /null/i;
    lowercase = /^[^A-Z]*$/;
    uppercase = /^[^a-z]*$/;
  }
});

// node_modules/zod/v4/core/checks.js
var $ZodCheck, numericOriginMap, $ZodCheckLessThan, $ZodCheckGreaterThan, $ZodCheckMultipleOf, $ZodCheckNumberFormat, $ZodCheckMaxLength, $ZodCheckMinLength, $ZodCheckLengthEquals, $ZodCheckStringFormat, $ZodCheckRegex, $ZodCheckLowerCase, $ZodCheckUpperCase, $ZodCheckIncludes, $ZodCheckStartsWith, $ZodCheckEndsWith, $ZodCheckOverwrite;
var init_checks = __esm({
  "node_modules/zod/v4/core/checks.js"() {
    init_esbuild_shims();
    init_core2();
    init_regexes();
    init_util4();
    $ZodCheck = /* @__PURE__ */ $constructor("$ZodCheck", (inst, def2) => {
      var _a7;
      inst._zod ?? (inst._zod = {});
      inst._zod.def = def2;
      (_a7 = inst._zod).onattach ?? (_a7.onattach = []);
    });
    numericOriginMap = {
      number: "number",
      bigint: "bigint",
      object: "date"
    };
    $ZodCheckLessThan = /* @__PURE__ */ $constructor("$ZodCheckLessThan", (inst, def2) => {
      $ZodCheck.init(inst, def2);
      const origin = numericOriginMap[typeof def2.value];
      inst._zod.onattach.push((inst2) => {
        const bag = inst2._zod.bag;
        const curr = (def2.inclusive ? bag.maximum : bag.exclusiveMaximum) ?? Number.POSITIVE_INFINITY;
        if (def2.value < curr) {
          if (def2.inclusive)
            bag.maximum = def2.value;
          else
            bag.exclusiveMaximum = def2.value;
        }
      });
      inst._zod.check = (payload) => {
        if (def2.inclusive ? payload.value <= def2.value : payload.value < def2.value) {
          return;
        }
        payload.issues.push({
          origin,
          code: "too_big",
          maximum: def2.value,
          input: payload.value,
          inclusive: def2.inclusive,
          inst,
          continue: !def2.abort
        });
      };
    });
    $ZodCheckGreaterThan = /* @__PURE__ */ $constructor("$ZodCheckGreaterThan", (inst, def2) => {
      $ZodCheck.init(inst, def2);
      const origin = numericOriginMap[typeof def2.value];
      inst._zod.onattach.push((inst2) => {
        const bag = inst2._zod.bag;
        const curr = (def2.inclusive ? bag.minimum : bag.exclusiveMinimum) ?? Number.NEGATIVE_INFINITY;
        if (def2.value > curr) {
          if (def2.inclusive)
            bag.minimum = def2.value;
          else
            bag.exclusiveMinimum = def2.value;
        }
      });
      inst._zod.check = (payload) => {
        if (def2.inclusive ? payload.value >= def2.value : payload.value > def2.value) {
          return;
        }
        payload.issues.push({
          origin,
          code: "too_small",
          minimum: def2.value,
          input: payload.value,
          inclusive: def2.inclusive,
          inst,
          continue: !def2.abort
        });
      };
    });
    $ZodCheckMultipleOf = /* @__PURE__ */ $constructor("$ZodCheckMultipleOf", (inst, def2) => {
      $ZodCheck.init(inst, def2);
      inst._zod.onattach.push((inst2) => {
        var _a7;
        (_a7 = inst2._zod.bag).multipleOf ?? (_a7.multipleOf = def2.value);
      });
      inst._zod.check = (payload) => {
        if (typeof payload.value !== typeof def2.value)
          throw new Error("Cannot mix number and bigint in multiple_of check.");
        const isMultiple = typeof payload.value === "bigint" ? payload.value % def2.value === BigInt(0) : floatSafeRemainder2(payload.value, def2.value) === 0;
        if (isMultiple)
          return;
        payload.issues.push({
          origin: typeof payload.value,
          code: "not_multiple_of",
          divisor: def2.value,
          input: payload.value,
          inst,
          continue: !def2.abort
        });
      };
    });
    $ZodCheckNumberFormat = /* @__PURE__ */ $constructor("$ZodCheckNumberFormat", (inst, def2) => {
      $ZodCheck.init(inst, def2);
      def2.format = def2.format || "float64";
      const isInt = def2.format?.includes("int");
      const origin = isInt ? "int" : "number";
      const [minimum, maximum] = NUMBER_FORMAT_RANGES[def2.format];
      inst._zod.onattach.push((inst2) => {
        const bag = inst2._zod.bag;
        bag.format = def2.format;
        bag.minimum = minimum;
        bag.maximum = maximum;
        if (isInt)
          bag.pattern = integer;
      });
      inst._zod.check = (payload) => {
        const input = payload.value;
        if (isInt) {
          if (!Number.isInteger(input)) {
            payload.issues.push({
              expected: origin,
              format: def2.format,
              code: "invalid_type",
              input,
              inst
            });
            return;
          }
          if (!Number.isSafeInteger(input)) {
            if (input > 0) {
              payload.issues.push({
                input,
                code: "too_big",
                maximum: Number.MAX_SAFE_INTEGER,
                note: "Integers must be within the safe integer range.",
                inst,
                origin,
                continue: !def2.abort
              });
            } else {
              payload.issues.push({
                input,
                code: "too_small",
                minimum: Number.MIN_SAFE_INTEGER,
                note: "Integers must be within the safe integer range.",
                inst,
                origin,
                continue: !def2.abort
              });
            }
            return;
          }
        }
        if (input < minimum) {
          payload.issues.push({
            origin: "number",
            input,
            code: "too_small",
            minimum,
            inclusive: true,
            inst,
            continue: !def2.abort
          });
        }
        if (input > maximum) {
          payload.issues.push({
            origin: "number",
            input,
            code: "too_big",
            maximum,
            inst
          });
        }
      };
    });
    $ZodCheckMaxLength = /* @__PURE__ */ $constructor("$ZodCheckMaxLength", (inst, def2) => {
      var _a7;
      $ZodCheck.init(inst, def2);
      (_a7 = inst._zod.def).when ?? (_a7.when = (payload) => {
        const val = payload.value;
        return !nullish(val) && val.length !== void 0;
      });
      inst._zod.onattach.push((inst2) => {
        const curr = inst2._zod.bag.maximum ?? Number.POSITIVE_INFINITY;
        if (def2.maximum < curr)
          inst2._zod.bag.maximum = def2.maximum;
      });
      inst._zod.check = (payload) => {
        const input = payload.value;
        const length = input.length;
        if (length <= def2.maximum)
          return;
        const origin = getLengthableOrigin(input);
        payload.issues.push({
          origin,
          code: "too_big",
          maximum: def2.maximum,
          inclusive: true,
          input,
          inst,
          continue: !def2.abort
        });
      };
    });
    $ZodCheckMinLength = /* @__PURE__ */ $constructor("$ZodCheckMinLength", (inst, def2) => {
      var _a7;
      $ZodCheck.init(inst, def2);
      (_a7 = inst._zod.def).when ?? (_a7.when = (payload) => {
        const val = payload.value;
        return !nullish(val) && val.length !== void 0;
      });
      inst._zod.onattach.push((inst2) => {
        const curr = inst2._zod.bag.minimum ?? Number.NEGATIVE_INFINITY;
        if (def2.minimum > curr)
          inst2._zod.bag.minimum = def2.minimum;
      });
      inst._zod.check = (payload) => {
        const input = payload.value;
        const length = input.length;
        if (length >= def2.minimum)
          return;
        const origin = getLengthableOrigin(input);
        payload.issues.push({
          origin,
          code: "too_small",
          minimum: def2.minimum,
          inclusive: true,
          input,
          inst,
          continue: !def2.abort
        });
      };
    });
    $ZodCheckLengthEquals = /* @__PURE__ */ $constructor("$ZodCheckLengthEquals", (inst, def2) => {
      var _a7;
      $ZodCheck.init(inst, def2);
      (_a7 = inst._zod.def).when ?? (_a7.when = (payload) => {
        const val = payload.value;
        return !nullish(val) && val.length !== void 0;
      });
      inst._zod.onattach.push((inst2) => {
        const bag = inst2._zod.bag;
        bag.minimum = def2.length;
        bag.maximum = def2.length;
        bag.length = def2.length;
      });
      inst._zod.check = (payload) => {
        const input = payload.value;
        const length = input.length;
        if (length === def2.length)
          return;
        const origin = getLengthableOrigin(input);
        const tooBig = length > def2.length;
        payload.issues.push({
          origin,
          ...tooBig ? { code: "too_big", maximum: def2.length } : { code: "too_small", minimum: def2.length },
          inclusive: true,
          exact: true,
          input: payload.value,
          inst,
          continue: !def2.abort
        });
      };
    });
    $ZodCheckStringFormat = /* @__PURE__ */ $constructor("$ZodCheckStringFormat", (inst, def2) => {
      var _a7, _b2;
      $ZodCheck.init(inst, def2);
      inst._zod.onattach.push((inst2) => {
        const bag = inst2._zod.bag;
        bag.format = def2.format;
        if (def2.pattern) {
          bag.patterns ?? (bag.patterns = /* @__PURE__ */ new Set());
          bag.patterns.add(def2.pattern);
        }
      });
      if (def2.pattern)
        (_a7 = inst._zod).check ?? (_a7.check = (payload) => {
          def2.pattern.lastIndex = 0;
          if (def2.pattern.test(payload.value))
            return;
          payload.issues.push({
            origin: "string",
            code: "invalid_format",
            format: def2.format,
            input: payload.value,
            ...def2.pattern ? { pattern: def2.pattern.toString() } : {},
            inst,
            continue: !def2.abort
          });
        });
      else
        (_b2 = inst._zod).check ?? (_b2.check = () => {
        });
    });
    $ZodCheckRegex = /* @__PURE__ */ $constructor("$ZodCheckRegex", (inst, def2) => {
      $ZodCheckStringFormat.init(inst, def2);
      inst._zod.check = (payload) => {
        def2.pattern.lastIndex = 0;
        if (def2.pattern.test(payload.value))
          return;
        payload.issues.push({
          origin: "string",
          code: "invalid_format",
          format: "regex",
          input: payload.value,
          pattern: def2.pattern.toString(),
          inst,
          continue: !def2.abort
        });
      };
    });
    $ZodCheckLowerCase = /* @__PURE__ */ $constructor("$ZodCheckLowerCase", (inst, def2) => {
      def2.pattern ?? (def2.pattern = lowercase);
      $ZodCheckStringFormat.init(inst, def2);
    });
    $ZodCheckUpperCase = /* @__PURE__ */ $constructor("$ZodCheckUpperCase", (inst, def2) => {
      def2.pattern ?? (def2.pattern = uppercase);
      $ZodCheckStringFormat.init(inst, def2);
    });
    $ZodCheckIncludes = /* @__PURE__ */ $constructor("$ZodCheckIncludes", (inst, def2) => {
      $ZodCheck.init(inst, def2);
      const escapedRegex = escapeRegex(def2.includes);
      const pattern = new RegExp(typeof def2.position === "number" ? `^.{${def2.position}}${escapedRegex}` : escapedRegex);
      def2.pattern = pattern;
      inst._zod.onattach.push((inst2) => {
        const bag = inst2._zod.bag;
        bag.patterns ?? (bag.patterns = /* @__PURE__ */ new Set());
        bag.patterns.add(pattern);
      });
      inst._zod.check = (payload) => {
        if (payload.value.includes(def2.includes, def2.position))
          return;
        payload.issues.push({
          origin: "string",
          code: "invalid_format",
          format: "includes",
          includes: def2.includes,
          input: payload.value,
          inst,
          continue: !def2.abort
        });
      };
    });
    $ZodCheckStartsWith = /* @__PURE__ */ $constructor("$ZodCheckStartsWith", (inst, def2) => {
      $ZodCheck.init(inst, def2);
      const pattern = new RegExp(`^${escapeRegex(def2.prefix)}.*`);
      def2.pattern ?? (def2.pattern = pattern);
      inst._zod.onattach.push((inst2) => {
        const bag = inst2._zod.bag;
        bag.patterns ?? (bag.patterns = /* @__PURE__ */ new Set());
        bag.patterns.add(pattern);
      });
      inst._zod.check = (payload) => {
        if (payload.value.startsWith(def2.prefix))
          return;
        payload.issues.push({
          origin: "string",
          code: "invalid_format",
          format: "starts_with",
          prefix: def2.prefix,
          input: payload.value,
          inst,
          continue: !def2.abort
        });
      };
    });
    $ZodCheckEndsWith = /* @__PURE__ */ $constructor("$ZodCheckEndsWith", (inst, def2) => {
      $ZodCheck.init(inst, def2);
      const pattern = new RegExp(`.*${escapeRegex(def2.suffix)}$`);
      def2.pattern ?? (def2.pattern = pattern);
      inst._zod.onattach.push((inst2) => {
        const bag = inst2._zod.bag;
        bag.patterns ?? (bag.patterns = /* @__PURE__ */ new Set());
        bag.patterns.add(pattern);
      });
      inst._zod.check = (payload) => {
        if (payload.value.endsWith(def2.suffix))
          return;
        payload.issues.push({
          origin: "string",
          code: "invalid_format",
          format: "ends_with",
          suffix: def2.suffix,
          input: payload.value,
          inst,
          continue: !def2.abort
        });
      };
    });
    $ZodCheckOverwrite = /* @__PURE__ */ $constructor("$ZodCheckOverwrite", (inst, def2) => {
      $ZodCheck.init(inst, def2);
      inst._zod.check = (payload) => {
        payload.value = def2.tx(payload.value);
      };
    });
  }
});

// node_modules/zod/v4/core/doc.js
var Doc;
var init_doc = __esm({
  "node_modules/zod/v4/core/doc.js"() {
    init_esbuild_shims();
    Doc = class {
      static {
        __name(this, "Doc");
      }
      constructor(args = []) {
        this.content = [];
        this.indent = 0;
        if (this)
          this.args = args;
      }
      indented(fn) {
        this.indent += 1;
        fn(this);
        this.indent -= 1;
      }
      write(arg) {
        if (typeof arg === "function") {
          arg(this, { execution: "sync" });
          arg(this, { execution: "async" });
          return;
        }
        const content = arg;
        const lines = content.split("\n").filter((x3) => x3);
        const minIndent = Math.min(...lines.map((x3) => x3.length - x3.trimStart().length));
        const dedented = lines.map((x3) => x3.slice(minIndent)).map((x3) => " ".repeat(this.indent * 2) + x3);
        for (const line of dedented) {
          this.content.push(line);
        }
      }
      compile() {
        const F4 = Function;
        const args = this?.args;
        const content = this?.content ?? [``];
        const lines = [...content.map((x3) => `  ${x3}`)];
        return new F4(...args, lines.join("\n"));
      }
    };
  }
});

// node_modules/zod/v4/core/versions.js
var version;
var init_versions = __esm({
  "node_modules/zod/v4/core/versions.js"() {
    init_esbuild_shims();
    version = {
      major: 4,
      minor: 0,
      patch: 0
    };
  }
});

// node_modules/zod/v4/core/schemas.js
function isValidBase64(data) {
  if (data === "")
    return true;
  if (data.length % 4 !== 0)
    return false;
  try {
    atob(data);
    return true;
  } catch {
    return false;
  }
}
function isValidBase64URL(data) {
  if (!base64url.test(data))
    return false;
  const base642 = data.replace(/[-_]/g, (c4) => c4 === "-" ? "+" : "/");
  const padded = base642.padEnd(Math.ceil(base642.length / 4) * 4, "=");
  return isValidBase64(padded);
}
function isValidJWT2(token2, algorithm = null) {
  try {
    const tokensParts = token2.split(".");
    if (tokensParts.length !== 3)
      return false;
    const [header] = tokensParts;
    if (!header)
      return false;
    const parsedHeader = JSON.parse(atob(header));
    if ("typ" in parsedHeader && parsedHeader?.typ !== "JWT")
      return false;
    if (!parsedHeader.alg)
      return false;
    if (algorithm && (!("alg" in parsedHeader) || parsedHeader.alg !== algorithm))
      return false;
    return true;
  } catch {
    return false;
  }
}
function handleArrayResult(result, final, index) {
  if (result.issues.length) {
    final.issues.push(...prefixIssues(index, result.issues));
  }
  final.value[index] = result.value;
}
function handleObjectResult(result, final, key) {
  if (result.issues.length) {
    final.issues.push(...prefixIssues(key, result.issues));
  }
  final.value[key] = result.value;
}
function handleOptionalObjectResult(result, final, key, input) {
  if (result.issues.length) {
    if (input[key] === void 0) {
      if (key in input) {
        final.value[key] = void 0;
      } else {
        final.value[key] = result.value;
      }
    } else {
      final.issues.push(...prefixIssues(key, result.issues));
    }
  } else if (result.value === void 0) {
    if (key in input)
      final.value[key] = void 0;
  } else {
    final.value[key] = result.value;
  }
}
function handleUnionResults(results, final, inst, ctx) {
  for (const result of results) {
    if (result.issues.length === 0) {
      final.value = result.value;
      return final;
    }
  }
  final.issues.push({
    code: "invalid_union",
    input: final.value,
    inst,
    errors: results.map((result) => result.issues.map((iss) => finalizeIssue(iss, ctx, config())))
  });
  return final;
}
function mergeValues2(a2, b2) {
  if (a2 === b2) {
    return { valid: true, data: a2 };
  }
  if (a2 instanceof Date && b2 instanceof Date && +a2 === +b2) {
    return { valid: true, data: a2 };
  }
  if (isPlainObject3(a2) && isPlainObject3(b2)) {
    const bKeys = Object.keys(b2);
    const sharedKeys = Object.keys(a2).filter((key) => bKeys.indexOf(key) !== -1);
    const newObj = { ...a2, ...b2 };
    for (const key of sharedKeys) {
      const sharedValue = mergeValues2(a2[key], b2[key]);
      if (!sharedValue.valid) {
        return {
          valid: false,
          mergeErrorPath: [key, ...sharedValue.mergeErrorPath]
        };
      }
      newObj[key] = sharedValue.data;
    }
    return { valid: true, data: newObj };
  }
  if (Array.isArray(a2) && Array.isArray(b2)) {
    if (a2.length !== b2.length) {
      return { valid: false, mergeErrorPath: [] };
    }
    const newArray = [];
    for (let index = 0; index < a2.length; index++) {
      const itemA = a2[index];
      const itemB = b2[index];
      const sharedValue = mergeValues2(itemA, itemB);
      if (!sharedValue.valid) {
        return {
          valid: false,
          mergeErrorPath: [index, ...sharedValue.mergeErrorPath]
        };
      }
      newArray.push(sharedValue.data);
    }
    return { valid: true, data: newArray };
  }
  return { valid: false, mergeErrorPath: [] };
}
function handleIntersectionResults(result, left3, right3) {
  if (left3.issues.length) {
    result.issues.push(...left3.issues);
  }
  if (right3.issues.length) {
    result.issues.push(...right3.issues);
  }
  if (aborted(result))
    return result;
  const merged = mergeValues2(left3.value, right3.value);
  if (!merged.valid) {
    throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(merged.mergeErrorPath)}`);
  }
  result.value = merged.data;
  return result;
}
function handleDefaultResult(payload, def2) {
  if (payload.value === void 0) {
    payload.value = def2.defaultValue;
  }
  return payload;
}
function handleNonOptionalResult(payload, inst) {
  if (!payload.issues.length && payload.value === void 0) {
    payload.issues.push({
      code: "invalid_type",
      expected: "nonoptional",
      input: payload.value,
      inst
    });
  }
  return payload;
}
function handlePipeResult(left3, def2, ctx) {
  if (aborted(left3)) {
    return left3;
  }
  return def2.out._zod.run({ value: left3.value, issues: left3.issues }, ctx);
}
function handleReadonlyResult(payload) {
  payload.value = Object.freeze(payload.value);
  return payload;
}
function handleRefineResult(result, payload, input, inst) {
  if (!result) {
    const _iss = {
      code: "custom",
      input,
      inst,
      // incorporates params.error into issue reporting
      path: [...inst._zod.def.path ?? []],
      // incorporates params.error into issue reporting
      continue: !inst._zod.def.abort
      // params: inst._zod.def.params,
    };
    if (inst._zod.def.params)
      _iss.params = inst._zod.def.params;
    payload.issues.push(issue(_iss));
  }
}
var $ZodType, $ZodString, $ZodStringFormat, $ZodGUID, $ZodUUID, $ZodEmail, $ZodURL, $ZodEmoji, $ZodNanoID, $ZodCUID, $ZodCUID2, $ZodULID, $ZodXID, $ZodKSUID, $ZodISODateTime, $ZodISODate, $ZodISOTime, $ZodISODuration, $ZodIPv4, $ZodIPv6, $ZodCIDRv4, $ZodCIDRv6, $ZodBase64, $ZodBase64URL, $ZodE164, $ZodJWT, $ZodNumber, $ZodNumberFormat, $ZodBoolean, $ZodBigInt, $ZodNull, $ZodAny, $ZodUnknown, $ZodNever, $ZodDate, $ZodArray, $ZodObject, $ZodUnion, $ZodDiscriminatedUnion, $ZodIntersection, $ZodRecord, $ZodEnum, $ZodLiteral, $ZodTransform, $ZodOptional, $ZodNullable, $ZodDefault, $ZodPrefault, $ZodNonOptional, $ZodCatch, $ZodPipe, $ZodReadonly, $ZodCustom;
var init_schemas = __esm({
  "node_modules/zod/v4/core/schemas.js"() {
    init_esbuild_shims();
    init_checks();
    init_core2();
    init_doc();
    init_parse2();
    init_regexes();
    init_util4();
    init_versions();
    init_util4();
    $ZodType = /* @__PURE__ */ $constructor("$ZodType", (inst, def2) => {
      var _a7;
      inst ?? (inst = {});
      inst._zod.def = def2;
      inst._zod.bag = inst._zod.bag || {};
      inst._zod.version = version;
      const checks = [...inst._zod.def.checks ?? []];
      if (inst._zod.traits.has("$ZodCheck")) {
        checks.unshift(inst);
      }
      for (const ch of checks) {
        for (const fn of ch._zod.onattach) {
          fn(inst);
        }
      }
      if (checks.length === 0) {
        (_a7 = inst._zod).deferred ?? (_a7.deferred = []);
        inst._zod.deferred?.push(() => {
          inst._zod.run = inst._zod.parse;
        });
      } else {
        const runChecks = /* @__PURE__ */ __name((payload, checks2, ctx) => {
          let isAborted2 = aborted(payload);
          let asyncResult;
          for (const ch of checks2) {
            if (ch._zod.def.when) {
              const shouldRun = ch._zod.def.when(payload);
              if (!shouldRun)
                continue;
            } else if (isAborted2) {
              continue;
            }
            const currLen = payload.issues.length;
            const _2 = ch._zod.check(payload);
            if (_2 instanceof Promise && ctx?.async === false) {
              throw new $ZodAsyncError();
            }
            if (asyncResult || _2 instanceof Promise) {
              asyncResult = (asyncResult ?? Promise.resolve()).then(async () => {
                await _2;
                const nextLen = payload.issues.length;
                if (nextLen === currLen)
                  return;
                if (!isAborted2)
                  isAborted2 = aborted(payload, currLen);
              });
            } else {
              const nextLen = payload.issues.length;
              if (nextLen === currLen)
                continue;
              if (!isAborted2)
                isAborted2 = aborted(payload, currLen);
            }
          }
          if (asyncResult) {
            return asyncResult.then(() => {
              return payload;
            });
          }
          return payload;
        }, "runChecks");
        inst._zod.run = (payload, ctx) => {
          const result = inst._zod.parse(payload, ctx);
          if (result instanceof Promise) {
            if (ctx.async === false)
              throw new $ZodAsyncError();
            return result.then((result2) => runChecks(result2, checks, ctx));
          }
          return runChecks(result, checks, ctx);
        };
      }
      inst["~standard"] = {
        validate: /* @__PURE__ */ __name((value) => {
          try {
            const r5 = safeParse(inst, value);
            return r5.success ? { value: r5.data } : { issues: r5.error?.issues };
          } catch (_2) {
            return safeParseAsync(inst, value).then((r5) => r5.success ? { value: r5.data } : { issues: r5.error?.issues });
          }
        }, "validate"),
        vendor: "zod",
        version: 1
      };
    });
    $ZodString = /* @__PURE__ */ $constructor("$ZodString", (inst, def2) => {
      $ZodType.init(inst, def2);
      inst._zod.pattern = [...inst?._zod.bag?.patterns ?? []].pop() ?? string(inst._zod.bag);
      inst._zod.parse = (payload, _2) => {
        if (def2.coerce)
          try {
            payload.value = String(payload.value);
          } catch (_3) {
          }
        if (typeof payload.value === "string")
          return payload;
        payload.issues.push({
          expected: "string",
          code: "invalid_type",
          input: payload.value,
          inst
        });
        return payload;
      };
    });
    $ZodStringFormat = /* @__PURE__ */ $constructor("$ZodStringFormat", (inst, def2) => {
      $ZodCheckStringFormat.init(inst, def2);
      $ZodString.init(inst, def2);
    });
    $ZodGUID = /* @__PURE__ */ $constructor("$ZodGUID", (inst, def2) => {
      def2.pattern ?? (def2.pattern = guid);
      $ZodStringFormat.init(inst, def2);
    });
    $ZodUUID = /* @__PURE__ */ $constructor("$ZodUUID", (inst, def2) => {
      if (def2.version) {
        const versionMap = {
          v1: 1,
          v2: 2,
          v3: 3,
          v4: 4,
          v5: 5,
          v6: 6,
          v7: 7,
          v8: 8
        };
        const v2 = versionMap[def2.version];
        if (v2 === void 0)
          throw new Error(`Invalid UUID version: "${def2.version}"`);
        def2.pattern ?? (def2.pattern = uuid(v2));
      } else
        def2.pattern ?? (def2.pattern = uuid());
      $ZodStringFormat.init(inst, def2);
    });
    $ZodEmail = /* @__PURE__ */ $constructor("$ZodEmail", (inst, def2) => {
      def2.pattern ?? (def2.pattern = email);
      $ZodStringFormat.init(inst, def2);
    });
    $ZodURL = /* @__PURE__ */ $constructor("$ZodURL", (inst, def2) => {
      $ZodStringFormat.init(inst, def2);
      inst._zod.check = (payload) => {
        try {
          const orig = payload.value;
          const url2 = new URL(orig);
          const href = url2.href;
          if (def2.hostname) {
            def2.hostname.lastIndex = 0;
            if (!def2.hostname.test(url2.hostname)) {
              payload.issues.push({
                code: "invalid_format",
                format: "url",
                note: "Invalid hostname",
                pattern: hostname2.source,
                input: payload.value,
                inst,
                continue: !def2.abort
              });
            }
          }
          if (def2.protocol) {
            def2.protocol.lastIndex = 0;
            if (!def2.protocol.test(url2.protocol.endsWith(":") ? url2.protocol.slice(0, -1) : url2.protocol)) {
              payload.issues.push({
                code: "invalid_format",
                format: "url",
                note: "Invalid protocol",
                pattern: def2.protocol.source,
                input: payload.value,
                inst,
                continue: !def2.abort
              });
            }
          }
          if (!orig.endsWith("/") && href.endsWith("/")) {
            payload.value = href.slice(0, -1);
          } else {
            payload.value = href;
          }
          return;
        } catch (_2) {
          payload.issues.push({
            code: "invalid_format",
            format: "url",
            input: payload.value,
            inst,
            continue: !def2.abort
          });
        }
      };
    });
    $ZodEmoji = /* @__PURE__ */ $constructor("$ZodEmoji", (inst, def2) => {
      def2.pattern ?? (def2.pattern = emoji());
      $ZodStringFormat.init(inst, def2);
    });
    $ZodNanoID = /* @__PURE__ */ $constructor("$ZodNanoID", (inst, def2) => {
      def2.pattern ?? (def2.pattern = nanoid);
      $ZodStringFormat.init(inst, def2);
    });
    $ZodCUID = /* @__PURE__ */ $constructor("$ZodCUID", (inst, def2) => {
      def2.pattern ?? (def2.pattern = cuid);
      $ZodStringFormat.init(inst, def2);
    });
    $ZodCUID2 = /* @__PURE__ */ $constructor("$ZodCUID2", (inst, def2) => {
      def2.pattern ?? (def2.pattern = cuid2);
      $ZodStringFormat.init(inst, def2);
    });
    $ZodULID = /* @__PURE__ */ $constructor("$ZodULID", (inst, def2) => {
      def2.pattern ?? (def2.pattern = ulid);
      $ZodStringFormat.init(inst, def2);
    });
    $ZodXID = /* @__PURE__ */ $constructor("$ZodXID", (inst, def2) => {
      def2.pattern ?? (def2.pattern = xid);
      $ZodStringFormat.init(inst, def2);
    });
    $ZodKSUID = /* @__PURE__ */ $constructor("$ZodKSUID", (inst, def2) => {
      def2.pattern ?? (def2.pattern = ksuid);
      $ZodStringFormat.init(inst, def2);
    });
    $ZodISODateTime = /* @__PURE__ */ $constructor("$ZodISODateTime", (inst, def2) => {
      def2.pattern ?? (def2.pattern = datetime(def2));
      $ZodStringFormat.init(inst, def2);
    });
    $ZodISODate = /* @__PURE__ */ $constructor("$ZodISODate", (inst, def2) => {
      def2.pattern ?? (def2.pattern = date);
      $ZodStringFormat.init(inst, def2);
    });
    $ZodISOTime = /* @__PURE__ */ $constructor("$ZodISOTime", (inst, def2) => {
      def2.pattern ?? (def2.pattern = time(def2));
      $ZodStringFormat.init(inst, def2);
    });
    $ZodISODuration = /* @__PURE__ */ $constructor("$ZodISODuration", (inst, def2) => {
      def2.pattern ?? (def2.pattern = duration);
      $ZodStringFormat.init(inst, def2);
    });
    $ZodIPv4 = /* @__PURE__ */ $constructor("$ZodIPv4", (inst, def2) => {
      def2.pattern ?? (def2.pattern = ipv4);
      $ZodStringFormat.init(inst, def2);
      inst._zod.onattach.push((inst2) => {
        const bag = inst2._zod.bag;
        bag.format = `ipv4`;
      });
    });
    $ZodIPv6 = /* @__PURE__ */ $constructor("$ZodIPv6", (inst, def2) => {
      def2.pattern ?? (def2.pattern = ipv6);
      $ZodStringFormat.init(inst, def2);
      inst._zod.onattach.push((inst2) => {
        const bag = inst2._zod.bag;
        bag.format = `ipv6`;
      });
      inst._zod.check = (payload) => {
        try {
          new URL(`http://[${payload.value}]`);
        } catch {
          payload.issues.push({
            code: "invalid_format",
            format: "ipv6",
            input: payload.value,
            inst,
            continue: !def2.abort
          });
        }
      };
    });
    $ZodCIDRv4 = /* @__PURE__ */ $constructor("$ZodCIDRv4", (inst, def2) => {
      def2.pattern ?? (def2.pattern = cidrv4);
      $ZodStringFormat.init(inst, def2);
    });
    $ZodCIDRv6 = /* @__PURE__ */ $constructor("$ZodCIDRv6", (inst, def2) => {
      def2.pattern ?? (def2.pattern = cidrv6);
      $ZodStringFormat.init(inst, def2);
      inst._zod.check = (payload) => {
        const [address, prefix] = payload.value.split("/");
        try {
          if (!prefix)
            throw new Error();
          const prefixNum = Number(prefix);
          if (`${prefixNum}` !== prefix)
            throw new Error();
          if (prefixNum < 0 || prefixNum > 128)
            throw new Error();
          new URL(`http://[${address}]`);
        } catch {
          payload.issues.push({
            code: "invalid_format",
            format: "cidrv6",
            input: payload.value,
            inst,
            continue: !def2.abort
          });
        }
      };
    });
    __name(isValidBase64, "isValidBase64");
    $ZodBase64 = /* @__PURE__ */ $constructor("$ZodBase64", (inst, def2) => {
      def2.pattern ?? (def2.pattern = base64);
      $ZodStringFormat.init(inst, def2);
      inst._zod.onattach.push((inst2) => {
        inst2._zod.bag.contentEncoding = "base64";
      });
      inst._zod.check = (payload) => {
        if (isValidBase64(payload.value))
          return;
        payload.issues.push({
          code: "invalid_format",
          format: "base64",
          input: payload.value,
          inst,
          continue: !def2.abort
        });
      };
    });
    __name(isValidBase64URL, "isValidBase64URL");
    $ZodBase64URL = /* @__PURE__ */ $constructor("$ZodBase64URL", (inst, def2) => {
      def2.pattern ?? (def2.pattern = base64url);
      $ZodStringFormat.init(inst, def2);
      inst._zod.onattach.push((inst2) => {
        inst2._zod.bag.contentEncoding = "base64url";
      });
      inst._zod.check = (payload) => {
        if (isValidBase64URL(payload.value))
          return;
        payload.issues.push({
          code: "invalid_format",
          format: "base64url",
          input: payload.value,
          inst,
          continue: !def2.abort
        });
      };
    });
    $ZodE164 = /* @__PURE__ */ $constructor("$ZodE164", (inst, def2) => {
      def2.pattern ?? (def2.pattern = e164);
      $ZodStringFormat.init(inst, def2);
    });
    __name(isValidJWT2, "isValidJWT");
    $ZodJWT = /* @__PURE__ */ $constructor("$ZodJWT", (inst, def2) => {
      $ZodStringFormat.init(inst, def2);
      inst._zod.check = (payload) => {
        if (isValidJWT2(payload.value, def2.alg))
          return;
        payload.issues.push({
          code: "invalid_format",
          format: "jwt",
          input: payload.value,
          inst,
          continue: !def2.abort
        });
      };
    });
    $ZodNumber = /* @__PURE__ */ $constructor("$ZodNumber", (inst, def2) => {
      $ZodType.init(inst, def2);
      inst._zod.pattern = inst._zod.bag.pattern ?? number;
      inst._zod.parse = (payload, _ctx) => {
        if (def2.coerce)
          try {
            payload.value = Number(payload.value);
          } catch (_2) {
          }
        const input = payload.value;
        if (typeof input === "number" && !Number.isNaN(input) && Number.isFinite(input)) {
          return payload;
        }
        const received = typeof input === "number" ? Number.isNaN(input) ? "NaN" : !Number.isFinite(input) ? "Infinity" : void 0 : void 0;
        payload.issues.push({
          expected: "number",
          code: "invalid_type",
          input,
          inst,
          ...received ? { received } : {}
        });
        return payload;
      };
    });
    $ZodNumberFormat = /* @__PURE__ */ $constructor("$ZodNumber", (inst, def2) => {
      $ZodCheckNumberFormat.init(inst, def2);
      $ZodNumber.init(inst, def2);
    });
    $ZodBoolean = /* @__PURE__ */ $constructor("$ZodBoolean", (inst, def2) => {
      $ZodType.init(inst, def2);
      inst._zod.pattern = boolean;
      inst._zod.parse = (payload, _ctx) => {
        if (def2.coerce)
          try {
            payload.value = Boolean(payload.value);
          } catch (_2) {
          }
        const input = payload.value;
        if (typeof input === "boolean")
          return payload;
        payload.issues.push({
          expected: "boolean",
          code: "invalid_type",
          input,
          inst
        });
        return payload;
      };
    });
    $ZodBigInt = /* @__PURE__ */ $constructor("$ZodBigInt", (inst, def2) => {
      $ZodType.init(inst, def2);
      inst._zod.pattern = bigint;
      inst._zod.parse = (payload, _ctx) => {
        if (def2.coerce)
          try {
            payload.value = BigInt(payload.value);
          } catch (_2) {
          }
        if (typeof payload.value === "bigint")
          return payload;
        payload.issues.push({
          expected: "bigint",
          code: "invalid_type",
          input: payload.value,
          inst
        });
        return payload;
      };
    });
    $ZodNull = /* @__PURE__ */ $constructor("$ZodNull", (inst, def2) => {
      $ZodType.init(inst, def2);
      inst._zod.pattern = _null;
      inst._zod.values = /* @__PURE__ */ new Set([null]);
      inst._zod.parse = (payload, _ctx) => {
        const input = payload.value;
        if (input === null)
          return payload;
        payload.issues.push({
          expected: "null",
          code: "invalid_type",
          input,
          inst
        });
        return payload;
      };
    });
    $ZodAny = /* @__PURE__ */ $constructor("$ZodAny", (inst, def2) => {
      $ZodType.init(inst, def2);
      inst._zod.parse = (payload) => payload;
    });
    $ZodUnknown = /* @__PURE__ */ $constructor("$ZodUnknown", (inst, def2) => {
      $ZodType.init(inst, def2);
      inst._zod.parse = (payload) => payload;
    });
    $ZodNever = /* @__PURE__ */ $constructor("$ZodNever", (inst, def2) => {
      $ZodType.init(inst, def2);
      inst._zod.parse = (payload, _ctx) => {
        payload.issues.push({
          expected: "never",
          code: "invalid_type",
          input: payload.value,
          inst
        });
        return payload;
      };
    });
    $ZodDate = /* @__PURE__ */ $constructor("$ZodDate", (inst, def2) => {
      $ZodType.init(inst, def2);
      inst._zod.parse = (payload, _ctx) => {
        if (def2.coerce) {
          try {
            payload.value = new Date(payload.value);
          } catch (_err) {
          }
        }
        const input = payload.value;
        const isDate = input instanceof Date;
        const isValidDate = isDate && !Number.isNaN(input.getTime());
        if (isValidDate)
          return payload;
        payload.issues.push({
          expected: "date",
          code: "invalid_type",
          input,
          ...isDate ? { received: "Invalid Date" } : {},
          inst
        });
        return payload;
      };
    });
    __name(handleArrayResult, "handleArrayResult");
    $ZodArray = /* @__PURE__ */ $constructor("$ZodArray", (inst, def2) => {
      $ZodType.init(inst, def2);
      inst._zod.parse = (payload, ctx) => {
        const input = payload.value;
        if (!Array.isArray(input)) {
          payload.issues.push({
            expected: "array",
            code: "invalid_type",
            input,
            inst
          });
          return payload;
        }
        payload.value = Array(input.length);
        const proms = [];
        for (let i3 = 0; i3 < input.length; i3++) {
          const item = input[i3];
          const result = def2.element._zod.run({
            value: item,
            issues: []
          }, ctx);
          if (result instanceof Promise) {
            proms.push(result.then((result2) => handleArrayResult(result2, payload, i3)));
          } else {
            handleArrayResult(result, payload, i3);
          }
        }
        if (proms.length) {
          return Promise.all(proms).then(() => payload);
        }
        return payload;
      };
    });
    __name(handleObjectResult, "handleObjectResult");
    __name(handleOptionalObjectResult, "handleOptionalObjectResult");
    $ZodObject = /* @__PURE__ */ $constructor("$ZodObject", (inst, def2) => {
      $ZodType.init(inst, def2);
      const _normalized = cached(() => {
        const keys = Object.keys(def2.shape);
        for (const k2 of keys) {
          if (!(def2.shape[k2] instanceof $ZodType)) {
            throw new Error(`Invalid element at key "${k2}": expected a Zod schema`);
          }
        }
        const okeys = optionalKeys(def2.shape);
        return {
          shape: def2.shape,
          keys,
          keySet: new Set(keys),
          numKeys: keys.length,
          optionalKeys: new Set(okeys)
        };
      });
      defineLazy(inst._zod, "propValues", () => {
        const shape = def2.shape;
        const propValues = {};
        for (const key in shape) {
          const field = shape[key]._zod;
          if (field.values) {
            propValues[key] ?? (propValues[key] = /* @__PURE__ */ new Set());
            for (const v2 of field.values)
              propValues[key].add(v2);
          }
        }
        return propValues;
      });
      const generateFastpass = /* @__PURE__ */ __name((shape) => {
        const doc = new Doc(["shape", "payload", "ctx"]);
        const normalized2 = _normalized.value;
        const parseStr = /* @__PURE__ */ __name((key) => {
          const k2 = esc(key);
          return `shape[${k2}]._zod.run({ value: input[${k2}], issues: [] }, ctx)`;
        }, "parseStr");
        doc.write(`const input = payload.value;`);
        const ids = /* @__PURE__ */ Object.create(null);
        let counter = 0;
        for (const key of normalized2.keys) {
          ids[key] = `key_${counter++}`;
        }
        doc.write(`const newResult = {}`);
        for (const key of normalized2.keys) {
          if (normalized2.optionalKeys.has(key)) {
            const id = ids[key];
            doc.write(`const ${id} = ${parseStr(key)};`);
            const k2 = esc(key);
            doc.write(`
        if (${id}.issues.length) {
          if (input[${k2}] === undefined) {
            if (${k2} in input) {
              newResult[${k2}] = undefined;
            }
          } else {
            payload.issues = payload.issues.concat(
              ${id}.issues.map((iss) => ({
                ...iss,
                path: iss.path ? [${k2}, ...iss.path] : [${k2}],
              }))
            );
          }
        } else if (${id}.value === undefined) {
          if (${k2} in input) newResult[${k2}] = undefined;
        } else {
          newResult[${k2}] = ${id}.value;
        }
        `);
          } else {
            const id = ids[key];
            doc.write(`const ${id} = ${parseStr(key)};`);
            doc.write(`
          if (${id}.issues.length) payload.issues = payload.issues.concat(${id}.issues.map(iss => ({
            ...iss,
            path: iss.path ? [${esc(key)}, ...iss.path] : [${esc(key)}]
          })));`);
            doc.write(`newResult[${esc(key)}] = ${id}.value`);
          }
        }
        doc.write(`payload.value = newResult;`);
        doc.write(`return payload;`);
        const fn = doc.compile();
        return (payload, ctx) => fn(shape, payload, ctx);
      }, "generateFastpass");
      let fastpass;
      const isObject4 = isObject;
      const jit = !globalConfig.jitless;
      const allowsEval2 = allowsEval;
      const fastEnabled = jit && allowsEval2.value;
      const catchall = def2.catchall;
      let value;
      inst._zod.parse = (payload, ctx) => {
        value ?? (value = _normalized.value);
        const input = payload.value;
        if (!isObject4(input)) {
          payload.issues.push({
            expected: "object",
            code: "invalid_type",
            input,
            inst
          });
          return payload;
        }
        const proms = [];
        if (jit && fastEnabled && ctx?.async === false && ctx.jitless !== true) {
          if (!fastpass)
            fastpass = generateFastpass(def2.shape);
          payload = fastpass(payload, ctx);
        } else {
          payload.value = {};
          const shape = value.shape;
          for (const key of value.keys) {
            const el = shape[key];
            const r5 = el._zod.run({ value: input[key], issues: [] }, ctx);
            const isOptional = el._zod.optin === "optional" && el._zod.optout === "optional";
            if (r5 instanceof Promise) {
              proms.push(r5.then((r6) => isOptional ? handleOptionalObjectResult(r6, payload, key, input) : handleObjectResult(r6, payload, key)));
            } else if (isOptional) {
              handleOptionalObjectResult(r5, payload, key, input);
            } else {
              handleObjectResult(r5, payload, key);
            }
          }
        }
        if (!catchall) {
          return proms.length ? Promise.all(proms).then(() => payload) : payload;
        }
        const unrecognized = [];
        const keySet = value.keySet;
        const _catchall = catchall._zod;
        const t5 = _catchall.def.type;
        for (const key of Object.keys(input)) {
          if (keySet.has(key))
            continue;
          if (t5 === "never") {
            unrecognized.push(key);
            continue;
          }
          const r5 = _catchall.run({ value: input[key], issues: [] }, ctx);
          if (r5 instanceof Promise) {
            proms.push(r5.then((r6) => handleObjectResult(r6, payload, key)));
          } else {
            handleObjectResult(r5, payload, key);
          }
        }
        if (unrecognized.length) {
          payload.issues.push({
            code: "unrecognized_keys",
            keys: unrecognized,
            input,
            inst
          });
        }
        if (!proms.length)
          return payload;
        return Promise.all(proms).then(() => {
          return payload;
        });
      };
    });
    __name(handleUnionResults, "handleUnionResults");
    $ZodUnion = /* @__PURE__ */ $constructor("$ZodUnion", (inst, def2) => {
      $ZodType.init(inst, def2);
      defineLazy(inst._zod, "optin", () => def2.options.some((o3) => o3._zod.optin === "optional") ? "optional" : void 0);
      defineLazy(inst._zod, "optout", () => def2.options.some((o3) => o3._zod.optout === "optional") ? "optional" : void 0);
      defineLazy(inst._zod, "values", () => {
        if (def2.options.every((o3) => o3._zod.values)) {
          return new Set(def2.options.flatMap((option2) => Array.from(option2._zod.values)));
        }
        return void 0;
      });
      defineLazy(inst._zod, "pattern", () => {
        if (def2.options.every((o3) => o3._zod.pattern)) {
          const patterns = def2.options.map((o3) => o3._zod.pattern);
          return new RegExp(`^(${patterns.map((p2) => cleanRegex(p2.source)).join("|")})$`);
        }
        return void 0;
      });
      inst._zod.parse = (payload, ctx) => {
        let async = false;
        const results = [];
        for (const option2 of def2.options) {
          const result = option2._zod.run({
            value: payload.value,
            issues: []
          }, ctx);
          if (result instanceof Promise) {
            results.push(result);
            async = true;
          } else {
            if (result.issues.length === 0)
              return result;
            results.push(result);
          }
        }
        if (!async)
          return handleUnionResults(results, payload, inst, ctx);
        return Promise.all(results).then((results2) => {
          return handleUnionResults(results2, payload, inst, ctx);
        });
      };
    });
    $ZodDiscriminatedUnion = /* @__PURE__ */ $constructor("$ZodDiscriminatedUnion", (inst, def2) => {
      $ZodUnion.init(inst, def2);
      const _super = inst._zod.parse;
      defineLazy(inst._zod, "propValues", () => {
        const propValues = {};
        for (const option2 of def2.options) {
          const pv = option2._zod.propValues;
          if (!pv || Object.keys(pv).length === 0)
            throw new Error(`Invalid discriminated union option at index "${def2.options.indexOf(option2)}"`);
          for (const [k2, v2] of Object.entries(pv)) {
            if (!propValues[k2])
              propValues[k2] = /* @__PURE__ */ new Set();
            for (const val of v2) {
              propValues[k2].add(val);
            }
          }
        }
        return propValues;
      });
      const disc = cached(() => {
        const opts = def2.options;
        const map2 = /* @__PURE__ */ new Map();
        for (const o3 of opts) {
          const values = o3._zod.propValues[def2.discriminator];
          if (!values || values.size === 0)
            throw new Error(`Invalid discriminated union option at index "${def2.options.indexOf(o3)}"`);
          for (const v2 of values) {
            if (map2.has(v2)) {
              throw new Error(`Duplicate discriminator value "${String(v2)}"`);
            }
            map2.set(v2, o3);
          }
        }
        return map2;
      });
      inst._zod.parse = (payload, ctx) => {
        const input = payload.value;
        if (!isObject(input)) {
          payload.issues.push({
            code: "invalid_type",
            expected: "object",
            input,
            inst
          });
          return payload;
        }
        const opt = disc.value.get(input?.[def2.discriminator]);
        if (opt) {
          return opt._zod.run(payload, ctx);
        }
        if (def2.unionFallback) {
          return _super(payload, ctx);
        }
        payload.issues.push({
          code: "invalid_union",
          errors: [],
          note: "No matching discriminator",
          input,
          path: [def2.discriminator],
          inst
        });
        return payload;
      };
    });
    $ZodIntersection = /* @__PURE__ */ $constructor("$ZodIntersection", (inst, def2) => {
      $ZodType.init(inst, def2);
      inst._zod.parse = (payload, ctx) => {
        const input = payload.value;
        const left3 = def2.left._zod.run({ value: input, issues: [] }, ctx);
        const right3 = def2.right._zod.run({ value: input, issues: [] }, ctx);
        const async = left3 instanceof Promise || right3 instanceof Promise;
        if (async) {
          return Promise.all([left3, right3]).then(([left4, right4]) => {
            return handleIntersectionResults(payload, left4, right4);
          });
        }
        return handleIntersectionResults(payload, left3, right3);
      };
    });
    __name(mergeValues2, "mergeValues");
    __name(handleIntersectionResults, "handleIntersectionResults");
    $ZodRecord = /* @__PURE__ */ $constructor("$ZodRecord", (inst, def2) => {
      $ZodType.init(inst, def2);
      inst._zod.parse = (payload, ctx) => {
        const input = payload.value;
        if (!isPlainObject3(input)) {
          payload.issues.push({
            expected: "record",
            code: "invalid_type",
            input,
            inst
          });
          return payload;
        }
        const proms = [];
        if (def2.keyType._zod.values) {
          const values = def2.keyType._zod.values;
          payload.value = {};
          for (const key of values) {
            if (typeof key === "string" || typeof key === "number" || typeof key === "symbol") {
              const result = def2.valueType._zod.run({ value: input[key], issues: [] }, ctx);
              if (result instanceof Promise) {
                proms.push(result.then((result2) => {
                  if (result2.issues.length) {
                    payload.issues.push(...prefixIssues(key, result2.issues));
                  }
                  payload.value[key] = result2.value;
                }));
              } else {
                if (result.issues.length) {
                  payload.issues.push(...prefixIssues(key, result.issues));
                }
                payload.value[key] = result.value;
              }
            }
          }
          let unrecognized;
          for (const key in input) {
            if (!values.has(key)) {
              unrecognized = unrecognized ?? [];
              unrecognized.push(key);
            }
          }
          if (unrecognized && unrecognized.length > 0) {
            payload.issues.push({
              code: "unrecognized_keys",
              input,
              inst,
              keys: unrecognized
            });
          }
        } else {
          payload.value = {};
          for (const key of Reflect.ownKeys(input)) {
            if (key === "__proto__")
              continue;
            const keyResult = def2.keyType._zod.run({ value: key, issues: [] }, ctx);
            if (keyResult instanceof Promise) {
              throw new Error("Async schemas not supported in object keys currently");
            }
            if (keyResult.issues.length) {
              payload.issues.push({
                origin: "record",
                code: "invalid_key",
                issues: keyResult.issues.map((iss) => finalizeIssue(iss, ctx, config())),
                input: key,
                path: [key],
                inst
              });
              payload.value[keyResult.value] = keyResult.value;
              continue;
            }
            const result = def2.valueType._zod.run({ value: input[key], issues: [] }, ctx);
            if (result instanceof Promise) {
              proms.push(result.then((result2) => {
                if (result2.issues.length) {
                  payload.issues.push(...prefixIssues(key, result2.issues));
                }
                payload.value[keyResult.value] = result2.value;
              }));
            } else {
              if (result.issues.length) {
                payload.issues.push(...prefixIssues(key, result.issues));
              }
              payload.value[keyResult.value] = result.value;
            }
          }
        }
        if (proms.length) {
          return Promise.all(proms).then(() => payload);
        }
        return payload;
      };
    });
    $ZodEnum = /* @__PURE__ */ $constructor("$ZodEnum", (inst, def2) => {
      $ZodType.init(inst, def2);
      const values = getEnumValues(def2.entries);
      inst._zod.values = new Set(values);
      inst._zod.pattern = new RegExp(`^(${values.filter((k2) => propertyKeyTypes.has(typeof k2)).map((o3) => typeof o3 === "string" ? escapeRegex(o3) : o3.toString()).join("|")})$`);
      inst._zod.parse = (payload, _ctx) => {
        const input = payload.value;
        if (inst._zod.values.has(input)) {
          return payload;
        }
        payload.issues.push({
          code: "invalid_value",
          values,
          input,
          inst
        });
        return payload;
      };
    });
    $ZodLiteral = /* @__PURE__ */ $constructor("$ZodLiteral", (inst, def2) => {
      $ZodType.init(inst, def2);
      inst._zod.values = new Set(def2.values);
      inst._zod.pattern = new RegExp(`^(${def2.values.map((o3) => typeof o3 === "string" ? escapeRegex(o3) : o3 ? o3.toString() : String(o3)).join("|")})$`);
      inst._zod.parse = (payload, _ctx) => {
        const input = payload.value;
        if (inst._zod.values.has(input)) {
          return payload;
        }
        payload.issues.push({
          code: "invalid_value",
          values: def2.values,
          input,
          inst
        });
        return payload;
      };
    });
    $ZodTransform = /* @__PURE__ */ $constructor("$ZodTransform", (inst, def2) => {
      $ZodType.init(inst, def2);
      inst._zod.parse = (payload, _ctx) => {
        const _out = def2.transform(payload.value, payload);
        if (_ctx.async) {
          const output = _out instanceof Promise ? _out : Promise.resolve(_out);
          return output.then((output2) => {
            payload.value = output2;
            return payload;
          });
        }
        if (_out instanceof Promise) {
          throw new $ZodAsyncError();
        }
        payload.value = _out;
        return payload;
      };
    });
    $ZodOptional = /* @__PURE__ */ $constructor("$ZodOptional", (inst, def2) => {
      $ZodType.init(inst, def2);
      inst._zod.optin = "optional";
      inst._zod.optout = "optional";
      defineLazy(inst._zod, "values", () => {
        return def2.innerType._zod.values ? /* @__PURE__ */ new Set([...def2.innerType._zod.values, void 0]) : void 0;
      });
      defineLazy(inst._zod, "pattern", () => {
        const pattern = def2.innerType._zod.pattern;
        return pattern ? new RegExp(`^(${cleanRegex(pattern.source)})?$`) : void 0;
      });
      inst._zod.parse = (payload, ctx) => {
        if (def2.innerType._zod.optin === "optional") {
          return def2.innerType._zod.run(payload, ctx);
        }
        if (payload.value === void 0) {
          return payload;
        }
        return def2.innerType._zod.run(payload, ctx);
      };
    });
    $ZodNullable = /* @__PURE__ */ $constructor("$ZodNullable", (inst, def2) => {
      $ZodType.init(inst, def2);
      defineLazy(inst._zod, "optin", () => def2.innerType._zod.optin);
      defineLazy(inst._zod, "optout", () => def2.innerType._zod.optout);
      defineLazy(inst._zod, "pattern", () => {
        const pattern = def2.innerType._zod.pattern;
        return pattern ? new RegExp(`^(${cleanRegex(pattern.source)}|null)$`) : void 0;
      });
      defineLazy(inst._zod, "values", () => {
        return def2.innerType._zod.values ? /* @__PURE__ */ new Set([...def2.innerType._zod.values, null]) : void 0;
      });
      inst._zod.parse = (payload, ctx) => {
        if (payload.value === null)
          return payload;
        return def2.innerType._zod.run(payload, ctx);
      };
    });
    $ZodDefault = /* @__PURE__ */ $constructor("$ZodDefault", (inst, def2) => {
      $ZodType.init(inst, def2);
      inst._zod.optin = "optional";
      defineLazy(inst._zod, "values", () => def2.innerType._zod.values);
      inst._zod.parse = (payload, ctx) => {
        if (payload.value === void 0) {
          payload.value = def2.defaultValue;
          return payload;
        }
        const result = def2.innerType._zod.run(payload, ctx);
        if (result instanceof Promise) {
          return result.then((result2) => handleDefaultResult(result2, def2));
        }
        return handleDefaultResult(result, def2);
      };
    });
    __name(handleDefaultResult, "handleDefaultResult");
    $ZodPrefault = /* @__PURE__ */ $constructor("$ZodPrefault", (inst, def2) => {
      $ZodType.init(inst, def2);
      inst._zod.optin = "optional";
      defineLazy(inst._zod, "values", () => def2.innerType._zod.values);
      inst._zod.parse = (payload, ctx) => {
        if (payload.value === void 0) {
          payload.value = def2.defaultValue;
        }
        return def2.innerType._zod.run(payload, ctx);
      };
    });
    $ZodNonOptional = /* @__PURE__ */ $constructor("$ZodNonOptional", (inst, def2) => {
      $ZodType.init(inst, def2);
      defineLazy(inst._zod, "values", () => {
        const v2 = def2.innerType._zod.values;
        return v2 ? new Set([...v2].filter((x3) => x3 !== void 0)) : void 0;
      });
      inst._zod.parse = (payload, ctx) => {
        const result = def2.innerType._zod.run(payload, ctx);
        if (result instanceof Promise) {
          return result.then((result2) => handleNonOptionalResult(result2, inst));
        }
        return handleNonOptionalResult(result, inst);
      };
    });
    __name(handleNonOptionalResult, "handleNonOptionalResult");
    $ZodCatch = /* @__PURE__ */ $constructor("$ZodCatch", (inst, def2) => {
      $ZodType.init(inst, def2);
      inst._zod.optin = "optional";
      defineLazy(inst._zod, "optout", () => def2.innerType._zod.optout);
      defineLazy(inst._zod, "values", () => def2.innerType._zod.values);
      inst._zod.parse = (payload, ctx) => {
        const result = def2.innerType._zod.run(payload, ctx);
        if (result instanceof Promise) {
          return result.then((result2) => {
            payload.value = result2.value;
            if (result2.issues.length) {
              payload.value = def2.catchValue({
                ...payload,
                error: {
                  issues: result2.issues.map((iss) => finalizeIssue(iss, ctx, config()))
                },
                input: payload.value
              });
              payload.issues = [];
            }
            return payload;
          });
        }
        payload.value = result.value;
        if (result.issues.length) {
          payload.value = def2.catchValue({
            ...payload,
            error: {
              issues: result.issues.map((iss) => finalizeIssue(iss, ctx, config()))
            },
            input: payload.value
          });
          payload.issues = [];
        }
        return payload;
      };
    });
    $ZodPipe = /* @__PURE__ */ $constructor("$ZodPipe", (inst, def2) => {
      $ZodType.init(inst, def2);
      defineLazy(inst._zod, "values", () => def2.in._zod.values);
      defineLazy(inst._zod, "optin", () => def2.in._zod.optin);
      defineLazy(inst._zod, "optout", () => def2.out._zod.optout);
      inst._zod.parse = (payload, ctx) => {
        const left3 = def2.in._zod.run(payload, ctx);
        if (left3 instanceof Promise) {
          return left3.then((left4) => handlePipeResult(left4, def2, ctx));
        }
        return handlePipeResult(left3, def2, ctx);
      };
    });
    __name(handlePipeResult, "handlePipeResult");
    $ZodReadonly = /* @__PURE__ */ $constructor("$ZodReadonly", (inst, def2) => {
      $ZodType.init(inst, def2);
      defineLazy(inst._zod, "propValues", () => def2.innerType._zod.propValues);
      defineLazy(inst._zod, "values", () => def2.innerType._zod.values);
      defineLazy(inst._zod, "optin", () => def2.innerType._zod.optin);
      defineLazy(inst._zod, "optout", () => def2.innerType._zod.optout);
      inst._zod.parse = (payload, ctx) => {
        const result = def2.innerType._zod.run(payload, ctx);
        if (result instanceof Promise) {
          return result.then(handleReadonlyResult);
        }
        return handleReadonlyResult(result);
      };
    });
    __name(handleReadonlyResult, "handleReadonlyResult");
    $ZodCustom = /* @__PURE__ */ $constructor("$ZodCustom", (inst, def2) => {
      $ZodCheck.init(inst, def2);
      $ZodType.init(inst, def2);
      inst._zod.parse = (payload, _2) => {
        return payload;
      };
      inst._zod.check = (payload) => {
        const input = payload.value;
        const r5 = def2.fn(input);
        if (r5 instanceof Promise) {
          return r5.then((r6) => handleRefineResult(r6, payload, input, inst));
        }
        handleRefineResult(r5, payload, input, inst);
        return;
      };
    });
    __name(handleRefineResult, "handleRefineResult");
  }
});

// node_modules/zod/v4/locales/en.js
function en_default2() {
  return {
    localeError: error()
  };
}
var parsedType, error;
var init_en2 = __esm({
  "node_modules/zod/v4/locales/en.js"() {
    init_esbuild_shims();
    init_util4();
    parsedType = /* @__PURE__ */ __name((data) => {
      const t5 = typeof data;
      switch (t5) {
        case "number": {
          return Number.isNaN(data) ? "NaN" : "number";
        }
        case "object": {
          if (Array.isArray(data)) {
            return "array";
          }
          if (data === null) {
            return "null";
          }
          if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) {
            return data.constructor.name;
          }
        }
      }
      return t5;
    }, "parsedType");
    error = /* @__PURE__ */ __name(() => {
      const Sizable = {
        string: { unit: "characters", verb: "to have" },
        file: { unit: "bytes", verb: "to have" },
        array: { unit: "items", verb: "to have" },
        set: { unit: "items", verb: "to have" }
      };
      function getSizing(origin) {
        return Sizable[origin] ?? null;
      }
      __name(getSizing, "getSizing");
      const Nouns = {
        regex: "input",
        email: "email address",
        url: "URL",
        emoji: "emoji",
        uuid: "UUID",
        uuidv4: "UUIDv4",
        uuidv6: "UUIDv6",
        nanoid: "nanoid",
        guid: "GUID",
        cuid: "cuid",
        cuid2: "cuid2",
        ulid: "ULID",
        xid: "XID",
        ksuid: "KSUID",
        datetime: "ISO datetime",
        date: "ISO date",
        time: "ISO time",
        duration: "ISO duration",
        ipv4: "IPv4 address",
        ipv6: "IPv6 address",
        cidrv4: "IPv4 range",
        cidrv6: "IPv6 range",
        base64: "base64-encoded string",
        base64url: "base64url-encoded string",
        json_string: "JSON string",
        e164: "E.164 number",
        jwt: "JWT",
        template_literal: "input"
      };
      return (issue2) => {
        switch (issue2.code) {
          case "invalid_type":
            return `Invalid input: expected ${issue2.expected}, received ${parsedType(issue2.input)}`;
          case "invalid_value":
            if (issue2.values.length === 1)
              return `Invalid input: expected ${stringifyPrimitive(issue2.values[0])}`;
            return `Invalid option: expected one of ${joinValues(issue2.values, "|")}`;
          case "too_big": {
            const adj = issue2.inclusive ? "<=" : "<";
            const sizing = getSizing(issue2.origin);
            if (sizing)
              return `Too big: expected ${issue2.origin ?? "value"} to have ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "elements"}`;
            return `Too big: expected ${issue2.origin ?? "value"} to be ${adj}${issue2.maximum.toString()}`;
          }
          case "too_small": {
            const adj = issue2.inclusive ? ">=" : ">";
            const sizing = getSizing(issue2.origin);
            if (sizing) {
              return `Too small: expected ${issue2.origin} to have ${adj}${issue2.minimum.toString()} ${sizing.unit}`;
            }
            return `Too small: expected ${issue2.origin} to be ${adj}${issue2.minimum.toString()}`;
          }
          case "invalid_format": {
            const _issue = issue2;
            if (_issue.format === "starts_with") {
              return `Invalid string: must start with "${_issue.prefix}"`;
            }
            if (_issue.format === "ends_with")
              return `Invalid string: must end with "${_issue.suffix}"`;
            if (_issue.format === "includes")
              return `Invalid string: must include "${_issue.includes}"`;
            if (_issue.format === "regex")
              return `Invalid string: must match pattern ${_issue.pattern}`;
            return `Invalid ${Nouns[_issue.format] ?? issue2.format}`;
          }
          case "not_multiple_of":
            return `Invalid number: must be a multiple of ${issue2.divisor}`;
          case "unrecognized_keys":
            return `Unrecognized key${issue2.keys.length > 1 ? "s" : ""}: ${joinValues(issue2.keys, ", ")}`;
          case "invalid_key":
            return `Invalid key in ${issue2.origin}`;
          case "invalid_union":
            return "Invalid input";
          case "invalid_element":
            return `Invalid value in ${issue2.origin}`;
          default:
            return `Invalid input`;
        }
      };
    }, "error");
    __name(en_default2, "default");
  }
});

// node_modules/zod/v4/locales/index.js
var init_locales = __esm({
  "node_modules/zod/v4/locales/index.js"() {
    init_esbuild_shims();
  }
});

// node_modules/zod/v4/core/registries.js
function registry() {
  return new $ZodRegistry();
}
var $output, $input, $ZodRegistry, globalRegistry;
var init_registries = __esm({
  "node_modules/zod/v4/core/registries.js"() {
    init_esbuild_shims();
    $output = Symbol("ZodOutput");
    $input = Symbol("ZodInput");
    $ZodRegistry = class {
      static {
        __name(this, "$ZodRegistry");
      }
      constructor() {
        this._map = /* @__PURE__ */ new Map();
        this._idmap = /* @__PURE__ */ new Map();
      }
      add(schema, ..._meta) {
        const meta = _meta[0];
        this._map.set(schema, meta);
        if (meta && typeof meta === "object" && "id" in meta) {
          if (this._idmap.has(meta.id)) {
            throw new Error(`ID ${meta.id} already exists in the registry`);
          }
          this._idmap.set(meta.id, schema);
        }
        return this;
      }
      clear() {
        this._map = /* @__PURE__ */ new Map();
        this._idmap = /* @__PURE__ */ new Map();
        return this;
      }
      remove(schema) {
        const meta = this._map.get(schema);
        if (meta && typeof meta === "object" && "id" in meta) {
          this._idmap.delete(meta.id);
        }
        this._map.delete(schema);
        return this;
      }
      get(schema) {
        const p2 = schema._zod.parent;
        if (p2) {
          const pm = { ...this.get(p2) ?? {} };
          delete pm.id;
          return { ...pm, ...this._map.get(schema) };
        }
        return this._map.get(schema);
      }
      has(schema) {
        return this._map.has(schema);
      }
    };
    __name(registry, "registry");
    globalRegistry = /* @__PURE__ */ registry();
  }
});

// node_modules/zod/v4/core/api.js
function _string(Class2, params) {
  return new Class2({
    type: "string",
    ...normalizeParams(params)
  });
}
function _coercedString(Class2, params) {
  return new Class2({
    type: "string",
    coerce: true,
    ...normalizeParams(params)
  });
}
function _email(Class2, params) {
  return new Class2({
    type: "string",
    format: "email",
    check: "string_format",
    abort: false,
    ...normalizeParams(params)
  });
}
function _guid(Class2, params) {
  return new Class2({
    type: "string",
    format: "guid",
    check: "string_format",
    abort: false,
    ...normalizeParams(params)
  });
}
function _uuid(Class2, params) {
  return new Class2({
    type: "string",
    format: "uuid",
    check: "string_format",
    abort: false,
    ...normalizeParams(params)
  });
}
function _uuidv4(Class2, params) {
  return new Class2({
    type: "string",
    format: "uuid",
    check: "string_format",
    abort: false,
    version: "v4",
    ...normalizeParams(params)
  });
}
function _uuidv6(Class2, params) {
  return new Class2({
    type: "string",
    format: "uuid",
    check: "string_format",
    abort: false,
    version: "v6",
    ...normalizeParams(params)
  });
}
function _uuidv7(Class2, params) {
  return new Class2({
    type: "string",
    format: "uuid",
    check: "string_format",
    abort: false,
    version: "v7",
    ...normalizeParams(params)
  });
}
function _url(Class2, params) {
  return new Class2({
    type: "string",
    format: "url",
    check: "string_format",
    abort: false,
    ...normalizeParams(params)
  });
}
function _emoji2(Class2, params) {
  return new Class2({
    type: "string",
    format: "emoji",
    check: "string_format",
    abort: false,
    ...normalizeParams(params)
  });
}
function _nanoid(Class2, params) {
  return new Class2({
    type: "string",
    format: "nanoid",
    check: "string_format",
    abort: false,
    ...normalizeParams(params)
  });
}
function _cuid(Class2, params) {
  return new Class2({
    type: "string",
    format: "cuid",
    check: "string_format",
    abort: false,
    ...normalizeParams(params)
  });
}
function _cuid2(Class2, params) {
  return new Class2({
    type: "string",
    format: "cuid2",
    check: "string_format",
    abort: false,
    ...normalizeParams(params)
  });
}
function _ulid(Class2, params) {
  return new Class2({
    type: "string",
    format: "ulid",
    check: "string_format",
    abort: false,
    ...normalizeParams(params)
  });
}
function _xid(Class2, params) {
  return new Class2({
    type: "string",
    format: "xid",
    check: "string_format",
    abort: false,
    ...normalizeParams(params)
  });
}
function _ksuid(Class2, params) {
  return new Class2({
    type: "string",
    format: "ksuid",
    check: "string_format",
    abort: false,
    ...normalizeParams(params)
  });
}
function _ipv4(Class2, params) {
  return new Class2({
    type: "string",
    format: "ipv4",
    check: "string_format",
    abort: false,
    ...normalizeParams(params)
  });
}
function _ipv6(Class2, params) {
  return new Class2({
    type: "string",
    format: "ipv6",
    check: "string_format",
    abort: false,
    ...normalizeParams(params)
  });
}
function _cidrv4(Class2, params) {
  return new Class2({
    type: "string",
    format: "cidrv4",
    check: "string_format",
    abort: false,
    ...normalizeParams(params)
  });
}
function _cidrv6(Class2, params) {
  return new Class2({
    type: "string",
    format: "cidrv6",
    check: "string_format",
    abort: false,
    ...normalizeParams(params)
  });
}
function _base64(Class2, params) {
  return new Class2({
    type: "string",
    format: "base64",
    check: "string_format",
    abort: false,
    ...normalizeParams(params)
  });
}
function _base64url(Class2, params) {
  return new Class2({
    type: "string",
    format: "base64url",
    check: "string_format",
    abort: false,
    ...normalizeParams(params)
  });
}
function _e164(Class2, params) {
  return new Class2({
    type: "string",
    format: "e164",
    check: "string_format",
    abort: false,
    ...normalizeParams(params)
  });
}
function _jwt(Class2, params) {
  return new Class2({
    type: "string",
    format: "jwt",
    check: "string_format",
    abort: false,
    ...normalizeParams(params)
  });
}
function _isoDateTime(Class2, params) {
  return new Class2({
    type: "string",
    format: "datetime",
    check: "string_format",
    offset: false,
    local: false,
    precision: null,
    ...normalizeParams(params)
  });
}
function _isoDate(Class2, params) {
  return new Class2({
    type: "string",
    format: "date",
    check: "string_format",
    ...normalizeParams(params)
  });
}
function _isoTime(Class2, params) {
  return new Class2({
    type: "string",
    format: "time",
    check: "string_format",
    precision: null,
    ...normalizeParams(params)
  });
}
function _isoDuration(Class2, params) {
  return new Class2({
    type: "string",
    format: "duration",
    check: "string_format",
    ...normalizeParams(params)
  });
}
function _number(Class2, params) {
  return new Class2({
    type: "number",
    checks: [],
    ...normalizeParams(params)
  });
}
function _coercedNumber(Class2, params) {
  return new Class2({
    type: "number",
    coerce: true,
    checks: [],
    ...normalizeParams(params)
  });
}
function _int(Class2, params) {
  return new Class2({
    type: "number",
    check: "number_format",
    abort: false,
    format: "safeint",
    ...normalizeParams(params)
  });
}
function _boolean(Class2, params) {
  return new Class2({
    type: "boolean",
    ...normalizeParams(params)
  });
}
function _coercedBoolean(Class2, params) {
  return new Class2({
    type: "boolean",
    coerce: true,
    ...normalizeParams(params)
  });
}
function _coercedBigint(Class2, params) {
  return new Class2({
    type: "bigint",
    coerce: true,
    ...normalizeParams(params)
  });
}
function _null2(Class2, params) {
  return new Class2({
    type: "null",
    ...normalizeParams(params)
  });
}
function _any(Class2) {
  return new Class2({
    type: "any"
  });
}
function _unknown(Class2) {
  return new Class2({
    type: "unknown"
  });
}
function _never(Class2, params) {
  return new Class2({
    type: "never",
    ...normalizeParams(params)
  });
}
function _coercedDate(Class2, params) {
  return new Class2({
    type: "date",
    coerce: true,
    ...normalizeParams(params)
  });
}
function _lt(value, params) {
  return new $ZodCheckLessThan({
    check: "less_than",
    ...normalizeParams(params),
    value,
    inclusive: false
  });
}
function _lte(value, params) {
  return new $ZodCheckLessThan({
    check: "less_than",
    ...normalizeParams(params),
    value,
    inclusive: true
  });
}
function _gt(value, params) {
  return new $ZodCheckGreaterThan({
    check: "greater_than",
    ...normalizeParams(params),
    value,
    inclusive: false
  });
}
function _gte(value, params) {
  return new $ZodCheckGreaterThan({
    check: "greater_than",
    ...normalizeParams(params),
    value,
    inclusive: true
  });
}
function _multipleOf(value, params) {
  return new $ZodCheckMultipleOf({
    check: "multiple_of",
    ...normalizeParams(params),
    value
  });
}
function _maxLength(maximum, params) {
  const ch = new $ZodCheckMaxLength({
    check: "max_length",
    ...normalizeParams(params),
    maximum
  });
  return ch;
}
function _minLength(minimum, params) {
  return new $ZodCheckMinLength({
    check: "min_length",
    ...normalizeParams(params),
    minimum
  });
}
function _length(length, params) {
  return new $ZodCheckLengthEquals({
    check: "length_equals",
    ...normalizeParams(params),
    length
  });
}
function _regex(pattern, params) {
  return new $ZodCheckRegex({
    check: "string_format",
    format: "regex",
    ...normalizeParams(params),
    pattern
  });
}
function _lowercase(params) {
  return new $ZodCheckLowerCase({
    check: "string_format",
    format: "lowercase",
    ...normalizeParams(params)
  });
}
function _uppercase(params) {
  return new $ZodCheckUpperCase({
    check: "string_format",
    format: "uppercase",
    ...normalizeParams(params)
  });
}
function _includes(includes, params) {
  return new $ZodCheckIncludes({
    check: "string_format",
    format: "includes",
    ...normalizeParams(params),
    includes
  });
}
function _startsWith(prefix, params) {
  return new $ZodCheckStartsWith({
    check: "string_format",
    format: "starts_with",
    ...normalizeParams(params),
    prefix
  });
}
function _endsWith(suffix, params) {
  return new $ZodCheckEndsWith({
    check: "string_format",
    format: "ends_with",
    ...normalizeParams(params),
    suffix
  });
}
function _overwrite(tx) {
  return new $ZodCheckOverwrite({
    check: "overwrite",
    tx
  });
}
function _normalize(form) {
  return _overwrite((input) => input.normalize(form));
}
function _trim() {
  return _overwrite((input) => input.trim());
}
function _toLowerCase() {
  return _overwrite((input) => input.toLowerCase());
}
function _toUpperCase() {
  return _overwrite((input) => input.toUpperCase());
}
function _array(Class2, element, params) {
  return new Class2({
    type: "array",
    element,
    // get element() {
    //   return element;
    // },
    ...normalizeParams(params)
  });
}
function _custom2(Class2, fn, _params) {
  const norm = normalizeParams(_params);
  norm.abort ?? (norm.abort = true);
  const schema = new Class2({
    type: "custom",
    check: "custom",
    fn,
    ...norm
  });
  return schema;
}
function _refine(Class2, fn, _params) {
  const schema = new Class2({
    type: "custom",
    check: "custom",
    fn,
    ...normalizeParams(_params)
  });
  return schema;
}
var init_api = __esm({
  "node_modules/zod/v4/core/api.js"() {
    init_esbuild_shims();
    init_checks();
    init_util4();
    __name(_string, "_string");
    __name(_coercedString, "_coercedString");
    __name(_email, "_email");
    __name(_guid, "_guid");
    __name(_uuid, "_uuid");
    __name(_uuidv4, "_uuidv4");
    __name(_uuidv6, "_uuidv6");
    __name(_uuidv7, "_uuidv7");
    __name(_url, "_url");
    __name(_emoji2, "_emoji");
    __name(_nanoid, "_nanoid");
    __name(_cuid, "_cuid");
    __name(_cuid2, "_cuid2");
    __name(_ulid, "_ulid");
    __name(_xid, "_xid");
    __name(_ksuid, "_ksuid");
    __name(_ipv4, "_ipv4");
    __name(_ipv6, "_ipv6");
    __name(_cidrv4, "_cidrv4");
    __name(_cidrv6, "_cidrv6");
    __name(_base64, "_base64");
    __name(_base64url, "_base64url");
    __name(_e164, "_e164");
    __name(_jwt, "_jwt");
    __name(_isoDateTime, "_isoDateTime");
    __name(_isoDate, "_isoDate");
    __name(_isoTime, "_isoTime");
    __name(_isoDuration, "_isoDuration");
    __name(_number, "_number");
    __name(_coercedNumber, "_coercedNumber");
    __name(_int, "_int");
    __name(_boolean, "_boolean");
    __name(_coercedBoolean, "_coercedBoolean");
    __name(_coercedBigint, "_coercedBigint");
    __name(_null2, "_null");
    __name(_any, "_any");
    __name(_unknown, "_unknown");
    __name(_never, "_never");
    __name(_coercedDate, "_coercedDate");
    __name(_lt, "_lt");
    __name(_lte, "_lte");
    __name(_gt, "_gt");
    __name(_gte, "_gte");
    __name(_multipleOf, "_multipleOf");
    __name(_maxLength, "_maxLength");
    __name(_minLength, "_minLength");
    __name(_length, "_length");
    __name(_regex, "_regex");
    __name(_lowercase, "_lowercase");
    __name(_uppercase, "_uppercase");
    __name(_includes, "_includes");
    __name(_startsWith, "_startsWith");
    __name(_endsWith, "_endsWith");
    __name(_overwrite, "_overwrite");
    __name(_normalize, "_normalize");
    __name(_trim, "_trim");
    __name(_toLowerCase, "_toLowerCase");
    __name(_toUpperCase, "_toUpperCase");
    __name(_array, "_array");
    __name(_custom2, "_custom");
    __name(_refine, "_refine");
  }
});

// node_modules/zod/v4/core/function.js
var init_function = __esm({
  "node_modules/zod/v4/core/function.js"() {
    init_esbuild_shims();
  }
});

// node_modules/zod/v4/core/to-json-schema.js
var init_to_json_schema = __esm({
  "node_modules/zod/v4/core/to-json-schema.js"() {
    init_esbuild_shims();
  }
});

// node_modules/zod/v4/core/json-schema.js
var init_json_schema = __esm({
  "node_modules/zod/v4/core/json-schema.js"() {
    init_esbuild_shims();
  }
});

// node_modules/zod/v4/core/index.js
var init_core3 = __esm({
  "node_modules/zod/v4/core/index.js"() {
    init_esbuild_shims();
    init_core2();
    init_parse2();
    init_errors4();
    init_schemas();
    init_checks();
    init_versions();
    init_util4();
    init_regexes();
    init_locales();
    init_registries();
    init_doc();
    init_function();
    init_api();
    init_to_json_schema();
    init_json_schema();
  }
});

// node_modules/zod/v4/mini/parse.js
var init_parse3 = __esm({
  "node_modules/zod/v4/mini/parse.js"() {
    init_esbuild_shims();
    init_core3();
  }
});

// node_modules/zod/v4/mini/schemas.js
var init_schemas2 = __esm({
  "node_modules/zod/v4/mini/schemas.js"() {
    init_esbuild_shims();
  }
});

// node_modules/zod/v4/mini/checks.js
var init_checks2 = __esm({
  "node_modules/zod/v4/mini/checks.js"() {
    init_esbuild_shims();
  }
});

// node_modules/zod/v4/mini/iso.js
var init_iso = __esm({
  "node_modules/zod/v4/mini/iso.js"() {
    init_esbuild_shims();
  }
});

// node_modules/zod/v4/mini/coerce.js
var init_coerce = __esm({
  "node_modules/zod/v4/mini/coerce.js"() {
    init_esbuild_shims();
  }
});

// node_modules/zod/v4/mini/external.js
var init_external2 = __esm({
  "node_modules/zod/v4/mini/external.js"() {
    init_esbuild_shims();
    init_core3();
    init_parse3();
    init_schemas2();
    init_checks2();
    init_locales();
    init_iso();
    init_coerce();
  }
});

// node_modules/zod/v4/mini/index.js
var init_mini = __esm({
  "node_modules/zod/v4/mini/index.js"() {
    init_esbuild_shims();
    init_external2();
  }
});

// node_modules/zod/v4-mini/index.js
var init_v4_mini = __esm({
  "node_modules/zod/v4-mini/index.js"() {
    init_esbuild_shims();
    init_mini();
  }
});

// packages/core/node_modules/@modelcontextprotocol/sdk/dist/esm/server/zod-compat.js
function isZ4Schema(s5) {
  const schema = s5;
  return !!schema._zod;
}
function safeParse2(schema, data) {
  if (isZ4Schema(schema)) {
    const result2 = safeParse(schema, data);
    return result2;
  }
  const v3Schema = schema;
  const result = v3Schema.safeParse(data);
  return result;
}
function getObjectShape(schema) {
  if (!schema)
    return void 0;
  let rawShape;
  if (isZ4Schema(schema)) {
    const v4Schema = schema;
    rawShape = v4Schema._zod?.def?.shape;
  } else {
    const v3Schema = schema;
    rawShape = v3Schema.shape;
  }
  if (!rawShape)
    return void 0;
  if (typeof rawShape === "function") {
    try {
      return rawShape();
    } catch {
      return void 0;
    }
  }
  return rawShape;
}
function getLiteralValue(schema) {
  if (isZ4Schema(schema)) {
    const v4Schema = schema;
    const def3 = v4Schema._zod?.def;
    if (def3) {
      if (def3.value !== void 0)
        return def3.value;
      if (Array.isArray(def3.values) && def3.values.length > 0) {
        return def3.values[0];
      }
    }
  }
  const v3Schema = schema;
  const def2 = v3Schema._def;
  if (def2) {
    if (def2.value !== void 0)
      return def2.value;
    if (Array.isArray(def2.values) && def2.values.length > 0) {
      return def2.values[0];
    }
  }
  const directValue = schema.value;
  if (directValue !== void 0)
    return directValue;
  return void 0;
}
var init_zod_compat = __esm({
  "packages/core/node_modules/@modelcontextprotocol/sdk/dist/esm/server/zod-compat.js"() {
    init_esbuild_shims();
    init_v4_mini();
    __name(isZ4Schema, "isZ4Schema");
    __name(safeParse2, "safeParse");
    __name(getObjectShape, "getObjectShape");
    __name(getLiteralValue, "getLiteralValue");
  }
});

// node_modules/zod/v4/classic/checks.js
var init_checks3 = __esm({
  "node_modules/zod/v4/classic/checks.js"() {
    init_esbuild_shims();
    init_core3();
  }
});

// node_modules/zod/v4/classic/iso.js
var iso_exports2 = {};
__export(iso_exports2, {
  ZodISODate: () => ZodISODate,
  ZodISODateTime: () => ZodISODateTime,
  ZodISODuration: () => ZodISODuration,
  ZodISOTime: () => ZodISOTime,
  date: () => date2,
  datetime: () => datetime2,
  duration: () => duration2,
  time: () => time2
});
function datetime2(params) {
  return _isoDateTime(ZodISODateTime, params);
}
function date2(params) {
  return _isoDate(ZodISODate, params);
}
function time2(params) {
  return _isoTime(ZodISOTime, params);
}
function duration2(params) {
  return _isoDuration(ZodISODuration, params);
}
var ZodISODateTime, ZodISODate, ZodISOTime, ZodISODuration;
var init_iso2 = __esm({
  "node_modules/zod/v4/classic/iso.js"() {
    init_esbuild_shims();
    init_core3();
    init_schemas3();
    ZodISODateTime = /* @__PURE__ */ $constructor("ZodISODateTime", (inst, def2) => {
      $ZodISODateTime.init(inst, def2);
      ZodStringFormat.init(inst, def2);
    });
    __name(datetime2, "datetime");
    ZodISODate = /* @__PURE__ */ $constructor("ZodISODate", (inst, def2) => {
      $ZodISODate.init(inst, def2);
      ZodStringFormat.init(inst, def2);
    });
    __name(date2, "date");
    ZodISOTime = /* @__PURE__ */ $constructor("ZodISOTime", (inst, def2) => {
      $ZodISOTime.init(inst, def2);
      ZodStringFormat.init(inst, def2);
    });
    __name(time2, "time");
    ZodISODuration = /* @__PURE__ */ $constructor("ZodISODuration", (inst, def2) => {
      $ZodISODuration.init(inst, def2);
      ZodStringFormat.init(inst, def2);
    });
    __name(duration2, "duration");
  }
});

// node_modules/zod/v4/classic/errors.js
var initializer2, ZodError2, ZodRealError;
var init_errors5 = __esm({
  "node_modules/zod/v4/classic/errors.js"() {
    init_esbuild_shims();
    init_core3();
    init_core3();
    initializer2 = /* @__PURE__ */ __name((inst, issues) => {
      $ZodError.init(inst, issues);
      inst.name = "ZodError";
      Object.defineProperties(inst, {
        format: {
          value: /* @__PURE__ */ __name((mapper) => formatError(inst, mapper), "value")
          // enumerable: false,
        },
        flatten: {
          value: /* @__PURE__ */ __name((mapper) => flattenError(inst, mapper), "value")
          // enumerable: false,
        },
        addIssue: {
          value: /* @__PURE__ */ __name((issue2) => inst.issues.push(issue2), "value")
          // enumerable: false,
        },
        addIssues: {
          value: /* @__PURE__ */ __name((issues2) => inst.issues.push(...issues2), "value")
          // enumerable: false,
        },
        isEmpty: {
          get() {
            return inst.issues.length === 0;
          }
          // enumerable: false,
        }
      });
    }, "initializer");
    ZodError2 = $constructor("ZodError", initializer2);
    ZodRealError = $constructor("ZodError", initializer2, {
      Parent: Error
    });
  }
});

// node_modules/zod/v4/classic/parse.js
var parse3, parseAsync2, safeParse3, safeParseAsync2;
var init_parse4 = __esm({
  "node_modules/zod/v4/classic/parse.js"() {
    init_esbuild_shims();
    init_core3();
    init_errors5();
    parse3 = /* @__PURE__ */ _parse(ZodRealError);
    parseAsync2 = /* @__PURE__ */ _parseAsync(ZodRealError);
    safeParse3 = /* @__PURE__ */ _safeParse(ZodRealError);
    safeParseAsync2 = /* @__PURE__ */ _safeParseAsync(ZodRealError);
  }
});

// node_modules/zod/v4/classic/schemas.js
function string2(params) {
  return _string(ZodString2, params);
}
function url(params) {
  return _url(ZodURL, params);
}
function number2(params) {
  return _number(ZodNumber2, params);
}
function int(params) {
  return _int(ZodNumberFormat, params);
}
function boolean2(params) {
  return _boolean(ZodBoolean2, params);
}
function _null3(params) {
  return _null2(ZodNull2, params);
}
function any() {
  return _any(ZodAny2);
}
function unknown() {
  return _unknown(ZodUnknown2);
}
function never2(params) {
  return _never(ZodNever2, params);
}
function array(element, params) {
  return _array(ZodArray2, element, params);
}
function object2(shape, params) {
  const def2 = {
    type: "object",
    get shape() {
      util_exports.assignProp(this, "shape", { ...shape });
      return this.shape;
    },
    ...util_exports.normalizeParams(params)
  };
  return new ZodObject2(def2);
}
function looseObject(shape, params) {
  return new ZodObject2({
    type: "object",
    get shape() {
      util_exports.assignProp(this, "shape", { ...shape });
      return this.shape;
    },
    catchall: unknown(),
    ...util_exports.normalizeParams(params)
  });
}
function union(options2, params) {
  return new ZodUnion2({
    type: "union",
    options: options2,
    ...util_exports.normalizeParams(params)
  });
}
function discriminatedUnion(discriminator, options2, params) {
  return new ZodDiscriminatedUnion2({
    type: "union",
    options: options2,
    discriminator,
    ...util_exports.normalizeParams(params)
  });
}
function intersection(left3, right3) {
  return new ZodIntersection2({
    type: "intersection",
    left: left3,
    right: right3
  });
}
function record(keyType, valueType, params) {
  return new ZodRecord2({
    type: "record",
    keyType,
    valueType,
    ...util_exports.normalizeParams(params)
  });
}
function _enum(values, params) {
  const entries = Array.isArray(values) ? Object.fromEntries(values.map((v2) => [v2, v2])) : values;
  return new ZodEnum2({
    type: "enum",
    entries,
    ...util_exports.normalizeParams(params)
  });
}
function literal(value, params) {
  return new ZodLiteral2({
    type: "literal",
    values: Array.isArray(value) ? value : [value],
    ...util_exports.normalizeParams(params)
  });
}
function transform(fn) {
  return new ZodTransform({
    type: "transform",
    transform: fn
  });
}
function optional(innerType) {
  return new ZodOptional2({
    type: "optional",
    innerType
  });
}
function nullable(innerType) {
  return new ZodNullable2({
    type: "nullable",
    innerType
  });
}
function _default(innerType, defaultValue) {
  return new ZodDefault2({
    type: "default",
    innerType,
    get defaultValue() {
      return typeof defaultValue === "function" ? defaultValue() : defaultValue;
    }
  });
}
function prefault(innerType, defaultValue) {
  return new ZodPrefault({
    type: "prefault",
    innerType,
    get defaultValue() {
      return typeof defaultValue === "function" ? defaultValue() : defaultValue;
    }
  });
}
function nonoptional(innerType, params) {
  return new ZodNonOptional({
    type: "nonoptional",
    innerType,
    ...util_exports.normalizeParams(params)
  });
}
function _catch(innerType, catchValue) {
  return new ZodCatch2({
    type: "catch",
    innerType,
    catchValue: typeof catchValue === "function" ? catchValue : () => catchValue
  });
}
function pipe(in_, out) {
  return new ZodPipe({
    type: "pipe",
    in: in_,
    out
    // ...util.normalizeParams(params),
  });
}
function readonly(innerType) {
  return new ZodReadonly2({
    type: "readonly",
    innerType
  });
}
function check(fn) {
  const ch = new $ZodCheck({
    check: "custom"
    // ...util.normalizeParams(params),
  });
  ch._zod.check = fn;
  return ch;
}
function custom2(fn, _params) {
  return _custom2(ZodCustom, fn ?? (() => true), _params);
}
function refine(fn, _params = {}) {
  return _refine(ZodCustom, fn, _params);
}
function superRefine(fn) {
  const ch = check((payload) => {
    payload.addIssue = (issue2) => {
      if (typeof issue2 === "string") {
        payload.issues.push(util_exports.issue(issue2, payload.value, ch._zod.def));
      } else {
        const _issue = issue2;
        if (_issue.fatal)
          _issue.continue = false;
        _issue.code ?? (_issue.code = "custom");
        _issue.input ?? (_issue.input = payload.value);
        _issue.inst ?? (_issue.inst = ch);
        _issue.continue ?? (_issue.continue = !ch._zod.def.abort);
        payload.issues.push(util_exports.issue(_issue));
      }
    };
    return fn(payload.value, payload);
  });
  return ch;
}
function preprocess(fn, schema) {
  return pipe(transform(fn), schema);
}
var ZodType2, _ZodString, ZodString2, ZodStringFormat, ZodEmail, ZodGUID, ZodUUID, ZodURL, ZodEmoji, ZodNanoID, ZodCUID, ZodCUID2, ZodULID, ZodXID, ZodKSUID, ZodIPv4, ZodIPv6, ZodCIDRv4, ZodCIDRv6, ZodBase64, ZodBase64URL, ZodE164, ZodJWT, ZodNumber2, ZodNumberFormat, ZodBoolean2, ZodBigInt2, ZodNull2, ZodAny2, ZodUnknown2, ZodNever2, ZodDate2, ZodArray2, ZodObject2, ZodUnion2, ZodDiscriminatedUnion2, ZodIntersection2, ZodRecord2, ZodEnum2, ZodLiteral2, ZodTransform, ZodOptional2, ZodNullable2, ZodDefault2, ZodPrefault, ZodNonOptional, ZodCatch2, ZodPipe, ZodReadonly2, ZodCustom;
var init_schemas3 = __esm({
  "node_modules/zod/v4/classic/schemas.js"() {
    init_esbuild_shims();
    init_core3();
    init_core3();
    init_checks3();
    init_iso2();
    init_parse4();
    ZodType2 = /* @__PURE__ */ $constructor("ZodType", (inst, def2) => {
      $ZodType.init(inst, def2);
      inst.def = def2;
      Object.defineProperty(inst, "_def", { value: def2 });
      inst.check = (...checks) => {
        return inst.clone(
          {
            ...def2,
            checks: [
              ...def2.checks ?? [],
              ...checks.map((ch) => typeof ch === "function" ? { _zod: { check: ch, def: { check: "custom" }, onattach: [] } } : ch)
            ]
          }
          // { parent: true }
        );
      };
      inst.clone = (def3, params) => clone2(inst, def3, params);
      inst.brand = () => inst;
      inst.register = (reg, meta) => {
        reg.add(inst, meta);
        return inst;
      };
      inst.parse = (data, params) => parse3(inst, data, params, { callee: inst.parse });
      inst.safeParse = (data, params) => safeParse3(inst, data, params);
      inst.parseAsync = async (data, params) => parseAsync2(inst, data, params, { callee: inst.parseAsync });
      inst.safeParseAsync = async (data, params) => safeParseAsync2(inst, data, params);
      inst.spa = inst.safeParseAsync;
      inst.refine = (check2, params) => inst.check(refine(check2, params));
      inst.superRefine = (refinement) => inst.check(superRefine(refinement));
      inst.overwrite = (fn) => inst.check(_overwrite(fn));
      inst.optional = () => optional(inst);
      inst.nullable = () => nullable(inst);
      inst.nullish = () => optional(nullable(inst));
      inst.nonoptional = (params) => nonoptional(inst, params);
      inst.array = () => array(inst);
      inst.or = (arg) => union([inst, arg]);
      inst.and = (arg) => intersection(inst, arg);
      inst.transform = (tx) => pipe(inst, transform(tx));
      inst.default = (def3) => _default(inst, def3);
      inst.prefault = (def3) => prefault(inst, def3);
      inst.catch = (params) => _catch(inst, params);
      inst.pipe = (target) => pipe(inst, target);
      inst.readonly = () => readonly(inst);
      inst.describe = (description) => {
        const cl = inst.clone();
        globalRegistry.add(cl, { description });
        return cl;
      };
      Object.defineProperty(inst, "description", {
        get() {
          return globalRegistry.get(inst)?.description;
        },
        configurable: true
      });
      inst.meta = (...args) => {
        if (args.length === 0) {
          return globalRegistry.get(inst);
        }
        const cl = inst.clone();
        globalRegistry.add(cl, args[0]);
        return cl;
      };
      inst.isOptional = () => inst.safeParse(void 0).success;
      inst.isNullable = () => inst.safeParse(null).success;
      return inst;
    });
    _ZodString = /* @__PURE__ */ $constructor("_ZodString", (inst, def2) => {
      $ZodString.init(inst, def2);
      ZodType2.init(inst, def2);
      const bag = inst._zod.bag;
      inst.format = bag.format ?? null;
      inst.minLength = bag.minimum ?? null;
      inst.maxLength = bag.maximum ?? null;
      inst.regex = (...args) => inst.check(_regex(...args));
      inst.includes = (...args) => inst.check(_includes(...args));
      inst.startsWith = (...args) => inst.check(_startsWith(...args));
      inst.endsWith = (...args) => inst.check(_endsWith(...args));
      inst.min = (...args) => inst.check(_minLength(...args));
      inst.max = (...args) => inst.check(_maxLength(...args));
      inst.length = (...args) => inst.check(_length(...args));
      inst.nonempty = (...args) => inst.check(_minLength(1, ...args));
      inst.lowercase = (params) => inst.check(_lowercase(params));
      inst.uppercase = (params) => inst.check(_uppercase(params));
      inst.trim = () => inst.check(_trim());
      inst.normalize = (...args) => inst.check(_normalize(...args));
      inst.toLowerCase = () => inst.check(_toLowerCase());
      inst.toUpperCase = () => inst.check(_toUpperCase());
    });
    ZodString2 = /* @__PURE__ */ $constructor("ZodString", (inst, def2) => {
      $ZodString.init(inst, def2);
      _ZodString.init(inst, def2);
      inst.email = (params) => inst.check(_email(ZodEmail, params));
      inst.url = (params) => inst.check(_url(ZodURL, params));
      inst.jwt = (params) => inst.check(_jwt(ZodJWT, params));
      inst.emoji = (params) => inst.check(_emoji2(ZodEmoji, params));
      inst.guid = (params) => inst.check(_guid(ZodGUID, params));
      inst.uuid = (params) => inst.check(_uuid(ZodUUID, params));
      inst.uuidv4 = (params) => inst.check(_uuidv4(ZodUUID, params));
      inst.uuidv6 = (params) => inst.check(_uuidv6(ZodUUID, params));
      inst.uuidv7 = (params) => inst.check(_uuidv7(ZodUUID, params));
      inst.nanoid = (params) => inst.check(_nanoid(ZodNanoID, params));
      inst.guid = (params) => inst.check(_guid(ZodGUID, params));
      inst.cuid = (params) => inst.check(_cuid(ZodCUID, params));
      inst.cuid2 = (params) => inst.check(_cuid2(ZodCUID2, params));
      inst.ulid = (params) => inst.check(_ulid(ZodULID, params));
      inst.base64 = (params) => inst.check(_base64(ZodBase64, params));
      inst.base64url = (params) => inst.check(_base64url(ZodBase64URL, params));
      inst.xid = (params) => inst.check(_xid(ZodXID, params));
      inst.ksuid = (params) => inst.check(_ksuid(ZodKSUID, params));
      inst.ipv4 = (params) => inst.check(_ipv4(ZodIPv4, params));
      inst.ipv6 = (params) => inst.check(_ipv6(ZodIPv6, params));
      inst.cidrv4 = (params) => inst.check(_cidrv4(ZodCIDRv4, params));
      inst.cidrv6 = (params) => inst.check(_cidrv6(ZodCIDRv6, params));
      inst.e164 = (params) => inst.check(_e164(ZodE164, params));
      inst.datetime = (params) => inst.check(datetime2(params));
      inst.date = (params) => inst.check(date2(params));
      inst.time = (params) => inst.check(time2(params));
      inst.duration = (params) => inst.check(duration2(params));
    });
    __name(string2, "string");
    ZodStringFormat = /* @__PURE__ */ $constructor("ZodStringFormat", (inst, def2) => {
      $ZodStringFormat.init(inst, def2);
      _ZodString.init(inst, def2);
    });
    ZodEmail = /* @__PURE__ */ $constructor("ZodEmail", (inst, def2) => {
      $ZodEmail.init(inst, def2);
      ZodStringFormat.init(inst, def2);
    });
    ZodGUID = /* @__PURE__ */ $constructor("ZodGUID", (inst, def2) => {
      $ZodGUID.init(inst, def2);
      ZodStringFormat.init(inst, def2);
    });
    ZodUUID = /* @__PURE__ */ $constructor("ZodUUID", (inst, def2) => {
      $ZodUUID.init(inst, def2);
      ZodStringFormat.init(inst, def2);
    });
    ZodURL = /* @__PURE__ */ $constructor("ZodURL", (inst, def2) => {
      $ZodURL.init(inst, def2);
      ZodStringFormat.init(inst, def2);
    });
    __name(url, "url");
    ZodEmoji = /* @__PURE__ */ $constructor("ZodEmoji", (inst, def2) => {
      $ZodEmoji.init(inst, def2);
      ZodStringFormat.init(inst, def2);
    });
    ZodNanoID = /* @__PURE__ */ $constructor("ZodNanoID", (inst, def2) => {
      $ZodNanoID.init(inst, def2);
      ZodStringFormat.init(inst, def2);
    });
    ZodCUID = /* @__PURE__ */ $constructor("ZodCUID", (inst, def2) => {
      $ZodCUID.init(inst, def2);
      ZodStringFormat.init(inst, def2);
    });
    ZodCUID2 = /* @__PURE__ */ $constructor("ZodCUID2", (inst, def2) => {
      $ZodCUID2.init(inst, def2);
      ZodStringFormat.init(inst, def2);
    });
    ZodULID = /* @__PURE__ */ $constructor("ZodULID", (inst, def2) => {
      $ZodULID.init(inst, def2);
      ZodStringFormat.init(inst, def2);
    });
    ZodXID = /* @__PURE__ */ $constructor("ZodXID", (inst, def2) => {
      $ZodXID.init(inst, def2);
      ZodStringFormat.init(inst, def2);
    });
    ZodKSUID = /* @__PURE__ */ $constructor("ZodKSUID", (inst, def2) => {
      $ZodKSUID.init(inst, def2);
      ZodStringFormat.init(inst, def2);
    });
    ZodIPv4 = /* @__PURE__ */ $constructor("ZodIPv4", (inst, def2) => {
      $ZodIPv4.init(inst, def2);
      ZodStringFormat.init(inst, def2);
    });
    ZodIPv6 = /* @__PURE__ */ $constructor("ZodIPv6", (inst, def2) => {
      $ZodIPv6.init(inst, def2);
      ZodStringFormat.init(inst, def2);
    });
    ZodCIDRv4 = /* @__PURE__ */ $constructor("ZodCIDRv4", (inst, def2) => {
      $ZodCIDRv4.init(inst, def2);
      ZodStringFormat.init(inst, def2);
    });
    ZodCIDRv6 = /* @__PURE__ */ $constructor("ZodCIDRv6", (inst, def2) => {
      $ZodCIDRv6.init(inst, def2);
      ZodStringFormat.init(inst, def2);
    });
    ZodBase64 = /* @__PURE__ */ $constructor("ZodBase64", (inst, def2) => {
      $ZodBase64.init(inst, def2);
      ZodStringFormat.init(inst, def2);
    });
    ZodBase64URL = /* @__PURE__ */ $constructor("ZodBase64URL", (inst, def2) => {
      $ZodBase64URL.init(inst, def2);
      ZodStringFormat.init(inst, def2);
    });
    ZodE164 = /* @__PURE__ */ $constructor("ZodE164", (inst, def2) => {
      $ZodE164.init(inst, def2);
      ZodStringFormat.init(inst, def2);
    });
    ZodJWT = /* @__PURE__ */ $constructor("ZodJWT", (inst, def2) => {
      $ZodJWT.init(inst, def2);
      ZodStringFormat.init(inst, def2);
    });
    ZodNumber2 = /* @__PURE__ */ $constructor("ZodNumber", (inst, def2) => {
      $ZodNumber.init(inst, def2);
      ZodType2.init(inst, def2);
      inst.gt = (value, params) => inst.check(_gt(value, params));
      inst.gte = (value, params) => inst.check(_gte(value, params));
      inst.min = (value, params) => inst.check(_gte(value, params));
      inst.lt = (value, params) => inst.check(_lt(value, params));
      inst.lte = (value, params) => inst.check(_lte(value, params));
      inst.max = (value, params) => inst.check(_lte(value, params));
      inst.int = (params) => inst.check(int(params));
      inst.safe = (params) => inst.check(int(params));
      inst.positive = (params) => inst.check(_gt(0, params));
      inst.nonnegative = (params) => inst.check(_gte(0, params));
      inst.negative = (params) => inst.check(_lt(0, params));
      inst.nonpositive = (params) => inst.check(_lte(0, params));
      inst.multipleOf = (value, params) => inst.check(_multipleOf(value, params));
      inst.step = (value, params) => inst.check(_multipleOf(value, params));
      inst.finite = () => inst;
      const bag = inst._zod.bag;
      inst.minValue = Math.max(bag.minimum ?? Number.NEGATIVE_INFINITY, bag.exclusiveMinimum ?? Number.NEGATIVE_INFINITY) ?? null;
      inst.maxValue = Math.min(bag.maximum ?? Number.POSITIVE_INFINITY, bag.exclusiveMaximum ?? Number.POSITIVE_INFINITY) ?? null;
      inst.isInt = (bag.format ?? "").includes("int") || Number.isSafeInteger(bag.multipleOf ?? 0.5);
      inst.isFinite = true;
      inst.format = bag.format ?? null;
    });
    __name(number2, "number");
    ZodNumberFormat = /* @__PURE__ */ $constructor("ZodNumberFormat", (inst, def2) => {
      $ZodNumberFormat.init(inst, def2);
      ZodNumber2.init(inst, def2);
    });
    __name(int, "int");
    ZodBoolean2 = /* @__PURE__ */ $constructor("ZodBoolean", (inst, def2) => {
      $ZodBoolean.init(inst, def2);
      ZodType2.init(inst, def2);
    });
    __name(boolean2, "boolean");
    ZodBigInt2 = /* @__PURE__ */ $constructor("ZodBigInt", (inst, def2) => {
      $ZodBigInt.init(inst, def2);
      ZodType2.init(inst, def2);
      inst.gte = (value, params) => inst.check(_gte(value, params));
      inst.min = (value, params) => inst.check(_gte(value, params));
      inst.gt = (value, params) => inst.check(_gt(value, params));
      inst.gte = (value, params) => inst.check(_gte(value, params));
      inst.min = (value, params) => inst.check(_gte(value, params));
      inst.lt = (value, params) => inst.check(_lt(value, params));
      inst.lte = (value, params) => inst.check(_lte(value, params));
      inst.max = (value, params) => inst.check(_lte(value, params));
      inst.positive = (params) => inst.check(_gt(BigInt(0), params));
      inst.negative = (params) => inst.check(_lt(BigInt(0), params));
      inst.nonpositive = (params) => inst.check(_lte(BigInt(0), params));
      inst.nonnegative = (params) => inst.check(_gte(BigInt(0), params));
      inst.multipleOf = (value, params) => inst.check(_multipleOf(value, params));
      const bag = inst._zod.bag;
      inst.minValue = bag.minimum ?? null;
      inst.maxValue = bag.maximum ?? null;
      inst.format = bag.format ?? null;
    });
    ZodNull2 = /* @__PURE__ */ $constructor("ZodNull", (inst, def2) => {
      $ZodNull.init(inst, def2);
      ZodType2.init(inst, def2);
    });
    __name(_null3, "_null");
    ZodAny2 = /* @__PURE__ */ $constructor("ZodAny", (inst, def2) => {
      $ZodAny.init(inst, def2);
      ZodType2.init(inst, def2);
    });
    __name(any, "any");
    ZodUnknown2 = /* @__PURE__ */ $constructor("ZodUnknown", (inst, def2) => {
      $ZodUnknown.init(inst, def2);
      ZodType2.init(inst, def2);
    });
    __name(unknown, "unknown");
    ZodNever2 = /* @__PURE__ */ $constructor("ZodNever", (inst, def2) => {
      $ZodNever.init(inst, def2);
      ZodType2.init(inst, def2);
    });
    __name(never2, "never");
    ZodDate2 = /* @__PURE__ */ $constructor("ZodDate", (inst, def2) => {
      $ZodDate.init(inst, def2);
      ZodType2.init(inst, def2);
      inst.min = (value, params) => inst.check(_gte(value, params));
      inst.max = (value, params) => inst.check(_lte(value, params));
      const c4 = inst._zod.bag;
      inst.minDate = c4.minimum ? new Date(c4.minimum) : null;
      inst.maxDate = c4.maximum ? new Date(c4.maximum) : null;
    });
    ZodArray2 = /* @__PURE__ */ $constructor("ZodArray", (inst, def2) => {
      $ZodArray.init(inst, def2);
      ZodType2.init(inst, def2);
      inst.element = def2.element;
      inst.min = (minLength, params) => inst.check(_minLength(minLength, params));
      inst.nonempty = (params) => inst.check(_minLength(1, params));
      inst.max = (maxLength, params) => inst.check(_maxLength(maxLength, params));
      inst.length = (len, params) => inst.check(_length(len, params));
      inst.unwrap = () => inst.element;
    });
    __name(array, "array");
    ZodObject2 = /* @__PURE__ */ $constructor("ZodObject", (inst, def2) => {
      $ZodObject.init(inst, def2);
      ZodType2.init(inst, def2);
      util_exports.defineLazy(inst, "shape", () => def2.shape);
      inst.keyof = () => _enum(Object.keys(inst._zod.def.shape));
      inst.catchall = (catchall) => inst.clone({ ...inst._zod.def, catchall });
      inst.passthrough = () => inst.clone({ ...inst._zod.def, catchall: unknown() });
      inst.loose = () => inst.clone({ ...inst._zod.def, catchall: unknown() });
      inst.strict = () => inst.clone({ ...inst._zod.def, catchall: never2() });
      inst.strip = () => inst.clone({ ...inst._zod.def, catchall: void 0 });
      inst.extend = (incoming) => {
        return util_exports.extend(inst, incoming);
      };
      inst.merge = (other2) => util_exports.merge(inst, other2);
      inst.pick = (mask) => util_exports.pick(inst, mask);
      inst.omit = (mask) => util_exports.omit(inst, mask);
      inst.partial = (...args) => util_exports.partial(ZodOptional2, inst, args[0]);
      inst.required = (...args) => util_exports.required(ZodNonOptional, inst, args[0]);
    });
    __name(object2, "object");
    __name(looseObject, "looseObject");
    ZodUnion2 = /* @__PURE__ */ $constructor("ZodUnion", (inst, def2) => {
      $ZodUnion.init(inst, def2);
      ZodType2.init(inst, def2);
      inst.options = def2.options;
    });
    __name(union, "union");
    ZodDiscriminatedUnion2 = /* @__PURE__ */ $constructor("ZodDiscriminatedUnion", (inst, def2) => {
      ZodUnion2.init(inst, def2);
      $ZodDiscriminatedUnion.init(inst, def2);
    });
    __name(discriminatedUnion, "discriminatedUnion");
    ZodIntersection2 = /* @__PURE__ */ $constructor("ZodIntersection", (inst, def2) => {
      $ZodIntersection.init(inst, def2);
      ZodType2.init(inst, def2);
    });
    __name(intersection, "intersection");
    ZodRecord2 = /* @__PURE__ */ $constructor("ZodRecord", (inst, def2) => {
      $ZodRecord.init(inst, def2);
      ZodType2.init(inst, def2);
      inst.keyType = def2.keyType;
      inst.valueType = def2.valueType;
    });
    __name(record, "record");
    ZodEnum2 = /* @__PURE__ */ $constructor("ZodEnum", (inst, def2) => {
      $ZodEnum.init(inst, def2);
      ZodType2.init(inst, def2);
      inst.enum = def2.entries;
      inst.options = Object.values(def2.entries);
      const keys = new Set(Object.keys(def2.entries));
      inst.extract = (values, params) => {
        const newEntries = {};
        for (const value of values) {
          if (keys.has(value)) {
            newEntries[value] = def2.entries[value];
          } else
            throw new Error(`Key ${value} not found in enum`);
        }
        return new ZodEnum2({
          ...def2,
          checks: [],
          ...util_exports.normalizeParams(params),
          entries: newEntries
        });
      };
      inst.exclude = (values, params) => {
        const newEntries = { ...def2.entries };
        for (const value of values) {
          if (keys.has(value)) {
            delete newEntries[value];
          } else
            throw new Error(`Key ${value} not found in enum`);
        }
        return new ZodEnum2({
          ...def2,
          checks: [],
          ...util_exports.normalizeParams(params),
          entries: newEntries
        });
      };
    });
    __name(_enum, "_enum");
    ZodLiteral2 = /* @__PURE__ */ $constructor("ZodLiteral", (inst, def2) => {
      $ZodLiteral.init(inst, def2);
      ZodType2.init(inst, def2);
      inst.values = new Set(def2.values);
      Object.defineProperty(inst, "value", {
        get() {
          if (def2.values.length > 1) {
            throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");
          }
          return def2.values[0];
        }
      });
    });
    __name(literal, "literal");
    ZodTransform = /* @__PURE__ */ $constructor("ZodTransform", (inst, def2) => {
      $ZodTransform.init(inst, def2);
      ZodType2.init(inst, def2);
      inst._zod.parse = (payload, _ctx) => {
        payload.addIssue = (issue2) => {
          if (typeof issue2 === "string") {
            payload.issues.push(util_exports.issue(issue2, payload.value, def2));
          } else {
            const _issue = issue2;
            if (_issue.fatal)
              _issue.continue = false;
            _issue.code ?? (_issue.code = "custom");
            _issue.input ?? (_issue.input = payload.value);
            _issue.inst ?? (_issue.inst = inst);
            _issue.continue ?? (_issue.continue = true);
            payload.issues.push(util_exports.issue(_issue));
          }
        };
        const output = def2.transform(payload.value, payload);
        if (output instanceof Promise) {
          return output.then((output2) => {
            payload.value = output2;
            return payload;
          });
        }
        payload.value = output;
        return payload;
      };
    });
    __name(transform, "transform");
    ZodOptional2 = /* @__PURE__ */ $constructor("ZodOptional", (inst, def2) => {
      $ZodOptional.init(inst, def2);
      ZodType2.init(inst, def2);
      inst.unwrap = () => inst._zod.def.innerType;
    });
    __name(optional, "optional");
    ZodNullable2 = /* @__PURE__ */ $constructor("ZodNullable", (inst, def2) => {
      $ZodNullable.init(inst, def2);
      ZodType2.init(inst, def2);
      inst.unwrap = () => inst._zod.def.innerType;
    });
    __name(nullable, "nullable");
    ZodDefault2 = /* @__PURE__ */ $constructor("ZodDefault", (inst, def2) => {
      $ZodDefault.init(inst, def2);
      ZodType2.init(inst, def2);
      inst.unwrap = () => inst._zod.def.innerType;
      inst.removeDefault = inst.unwrap;
    });
    __name(_default, "_default");
    ZodPrefault = /* @__PURE__ */ $constructor("ZodPrefault", (inst, def2) => {
      $ZodPrefault.init(inst, def2);
      ZodType2.init(inst, def2);
      inst.unwrap = () => inst._zod.def.innerType;
    });
    __name(prefault, "prefault");
    ZodNonOptional = /* @__PURE__ */ $constructor("ZodNonOptional", (inst, def2) => {
      $ZodNonOptional.init(inst, def2);
      ZodType2.init(inst, def2);
      inst.unwrap = () => inst._zod.def.innerType;
    });
    __name(nonoptional, "nonoptional");
    ZodCatch2 = /* @__PURE__ */ $constructor("ZodCatch", (inst, def2) => {
      $ZodCatch.init(inst, def2);
      ZodType2.init(inst, def2);
      inst.unwrap = () => inst._zod.def.innerType;
      inst.removeCatch = inst.unwrap;
    });
    __name(_catch, "_catch");
    ZodPipe = /* @__PURE__ */ $constructor("ZodPipe", (inst, def2) => {
      $ZodPipe.init(inst, def2);
      ZodType2.init(inst, def2);
      inst.in = def2.in;
      inst.out = def2.out;
    });
    __name(pipe, "pipe");
    ZodReadonly2 = /* @__PURE__ */ $constructor("ZodReadonly", (inst, def2) => {
      $ZodReadonly.init(inst, def2);
      ZodType2.init(inst, def2);
    });
    __name(readonly, "readonly");
    ZodCustom = /* @__PURE__ */ $constructor("ZodCustom", (inst, def2) => {
      $ZodCustom.init(inst, def2);
      ZodType2.init(inst, def2);
    });
    __name(check, "check");
    __name(custom2, "custom");
    __name(refine, "refine");
    __name(superRefine, "superRefine");
    __name(preprocess, "preprocess");
  }
});

// node_modules/zod/v4/classic/compat.js
var ZodIssueCode2;
var init_compat = __esm({
  "node_modules/zod/v4/classic/compat.js"() {
    init_esbuild_shims();
    ZodIssueCode2 = {
      invalid_type: "invalid_type",
      too_big: "too_big",
      too_small: "too_small",
      invalid_format: "invalid_format",
      not_multiple_of: "not_multiple_of",
      unrecognized_keys: "unrecognized_keys",
      invalid_union: "invalid_union",
      invalid_key: "invalid_key",
      invalid_element: "invalid_element",
      invalid_value: "invalid_value",
      custom: "custom"
    };
  }
});

// node_modules/zod/v4/classic/coerce.js
var coerce_exports2 = {};
__export(coerce_exports2, {
  bigint: () => bigint2,
  boolean: () => boolean3,
  date: () => date3,
  number: () => number3,
  string: () => string3
});
function string3(params) {
  return _coercedString(ZodString2, params);
}
function number3(params) {
  return _coercedNumber(ZodNumber2, params);
}
function boolean3(params) {
  return _coercedBoolean(ZodBoolean2, params);
}
function bigint2(params) {
  return _coercedBigint(ZodBigInt2, params);
}
function date3(params) {
  return _coercedDate(ZodDate2, params);
}
var init_coerce2 = __esm({
  "node_modules/zod/v4/classic/coerce.js"() {
    init_esbuild_shims();
    init_core3();
    init_schemas3();
    __name(string3, "string");
    __name(number3, "number");
    __name(boolean3, "boolean");
    __name(bigint2, "bigint");
    __name(date3, "date");
  }
});

// node_modules/zod/v4/classic/external.js
var init_external3 = __esm({
  "node_modules/zod/v4/classic/external.js"() {
    init_esbuild_shims();
    init_core3();
    init_schemas3();
    init_checks3();
    init_errors5();
    init_parse4();
    init_compat();
    init_core3();
    init_en2();
    init_core3();
    init_locales();
    init_iso2();
    init_coerce2();
    config(en_default2());
  }
});

// node_modules/zod/v4/classic/index.js
var init_classic = __esm({
  "node_modules/zod/v4/classic/index.js"() {
    init_esbuild_shims();
    init_external3();
  }
});

// node_modules/zod/v4/index.js
var init_v42 = __esm({
  "node_modules/zod/v4/index.js"() {
    init_esbuild_shims();
    init_classic();
  }
});

// packages/core/node_modules/@modelcontextprotocol/sdk/dist/esm/types.js
var LATEST_PROTOCOL_VERSION, SUPPORTED_PROTOCOL_VERSIONS, RELATED_TASK_META_KEY, JSONRPC_VERSION, AssertObjectSchema, ProgressTokenSchema, CursorSchema, TaskCreationParamsSchema, TaskMetadataSchema, RelatedTaskMetadataSchema, RequestMetaSchema, BaseRequestParamsSchema, TaskAugmentedRequestParamsSchema, isTaskAugmentedRequestParams, RequestSchema, NotificationsParamsSchema, NotificationSchema, ResultSchema, RequestIdSchema, JSONRPCRequestSchema, isJSONRPCRequest, JSONRPCNotificationSchema, isJSONRPCNotification, JSONRPCResultResponseSchema, isJSONRPCResultResponse, ErrorCode, JSONRPCErrorResponseSchema, isJSONRPCErrorResponse, JSONRPCMessageSchema, JSONRPCResponseSchema, EmptyResultSchema, CancelledNotificationParamsSchema, CancelledNotificationSchema, IconSchema, IconsSchema, BaseMetadataSchema, ImplementationSchema, FormElicitationCapabilitySchema, ElicitationCapabilitySchema, ClientTasksCapabilitySchema, ServerTasksCapabilitySchema, ClientCapabilitiesSchema, InitializeRequestParamsSchema, InitializeRequestSchema, ServerCapabilitiesSchema, InitializeResultSchema, InitializedNotificationSchema, isInitializedNotification, PingRequestSchema, ProgressSchema, ProgressNotificationParamsSchema, ProgressNotificationSchema, PaginatedRequestParamsSchema, PaginatedRequestSchema, PaginatedResultSchema, TaskStatusSchema, TaskSchema, CreateTaskResultSchema, TaskStatusNotificationParamsSchema, TaskStatusNotificationSchema, GetTaskRequestSchema, GetTaskResultSchema, GetTaskPayloadRequestSchema, GetTaskPayloadResultSchema, ListTasksRequestSchema, ListTasksResultSchema, CancelTaskRequestSchema, CancelTaskResultSchema, ResourceContentsSchema, TextResourceContentsSchema, Base64Schema, BlobResourceContentsSchema, RoleSchema, AnnotationsSchema, ResourceSchema, ResourceTemplateSchema, ListResourcesRequestSchema, ListResourcesResultSchema, ListResourceTemplatesRequestSchema, ListResourceTemplatesResultSchema, ResourceRequestParamsSchema, ReadResourceRequestParamsSchema, ReadResourceRequestSchema, ReadResourceResultSchema, ResourceListChangedNotificationSchema, SubscribeRequestParamsSchema, SubscribeRequestSchema, UnsubscribeRequestParamsSchema, UnsubscribeRequestSchema, ResourceUpdatedNotificationParamsSchema, ResourceUpdatedNotificationSchema, PromptArgumentSchema, PromptSchema, ListPromptsRequestSchema, ListPromptsResultSchema, GetPromptRequestParamsSchema, GetPromptRequestSchema, TextContentSchema, ImageContentSchema, AudioContentSchema, ToolUseContentSchema, EmbeddedResourceSchema, ResourceLinkSchema, ContentBlockSchema, PromptMessageSchema, GetPromptResultSchema, PromptListChangedNotificationSchema, ToolAnnotationsSchema, ToolExecutionSchema, ToolSchema, ListToolsRequestSchema, ListToolsResultSchema, CallToolResultSchema, CompatibilityCallToolResultSchema, CallToolRequestParamsSchema, CallToolRequestSchema, ToolListChangedNotificationSchema, ListChangedOptionsBaseSchema, LoggingLevelSchema, SetLevelRequestParamsSchema, SetLevelRequestSchema, LoggingMessageNotificationParamsSchema, LoggingMessageNotificationSchema, ModelHintSchema, ModelPreferencesSchema, ToolChoiceSchema, ToolResultContentSchema, SamplingContentSchema, SamplingMessageContentBlockSchema, SamplingMessageSchema, CreateMessageRequestParamsSchema, CreateMessageRequestSchema, CreateMessageResultSchema, CreateMessageResultWithToolsSchema, BooleanSchemaSchema, StringSchemaSchema, NumberSchemaSchema, UntitledSingleSelectEnumSchemaSchema, TitledSingleSelectEnumSchemaSchema, LegacyTitledEnumSchemaSchema, SingleSelectEnumSchemaSchema, UntitledMultiSelectEnumSchemaSchema, TitledMultiSelectEnumSchemaSchema, MultiSelectEnumSchemaSchema, EnumSchemaSchema, PrimitiveSchemaDefinitionSchema, ElicitRequestFormParamsSchema, ElicitRequestURLParamsSchema, ElicitRequestParamsSchema, ElicitRequestSchema, ElicitationCompleteNotificationParamsSchema, ElicitationCompleteNotificationSchema, ElicitResultSchema, ResourceTemplateReferenceSchema, PromptReferenceSchema, CompleteRequestParamsSchema, CompleteRequestSchema, CompleteResultSchema, RootSchema, ListRootsRequestSchema, ListRootsResultSchema, RootsListChangedNotificationSchema, ClientRequestSchema, ClientNotificationSchema, ClientResultSchema, ServerRequestSchema, ServerNotificationSchema, ServerResultSchema, McpError, UrlElicitationRequiredError;
var init_types8 = __esm({
  "packages/core/node_modules/@modelcontextprotocol/sdk/dist/esm/types.js"() {
    init_esbuild_shims();
    init_v42();
    LATEST_PROTOCOL_VERSION = "2025-11-25";
    SUPPORTED_PROTOCOL_VERSIONS = [LATEST_PROTOCOL_VERSION, "2025-06-18", "2025-03-26", "2024-11-05", "2024-10-07"];
    RELATED_TASK_META_KEY = "io.modelcontextprotocol/related-task";
    JSONRPC_VERSION = "2.0";
    AssertObjectSchema = custom2((v2) => v2 !== null && (typeof v2 === "object" || typeof v2 === "function"));
    ProgressTokenSchema = union([string2(), number2().int()]);
    CursorSchema = string2();
    TaskCreationParamsSchema = looseObject({
      /**
       * Time in milliseconds to keep task results available after completion.
       * If null, the task has unlimited lifetime until manually cleaned up.
       */
      ttl: union([number2(), _null3()]).optional(),
      /**
       * Time in milliseconds to wait between task status requests.
       */
      pollInterval: number2().optional()
    });
    TaskMetadataSchema = object2({
      ttl: number2().optional()
    });
    RelatedTaskMetadataSchema = object2({
      taskId: string2()
    });
    RequestMetaSchema = looseObject({
      /**
       * If specified, the caller is requesting out-of-band progress notifications for this request (as represented by notifications/progress). The value of this parameter is an opaque token that will be attached to any subsequent notifications. The receiver is not obligated to provide these notifications.
       */
      progressToken: ProgressTokenSchema.optional(),
      /**
       * If specified, this request is related to the provided task.
       */
      [RELATED_TASK_META_KEY]: RelatedTaskMetadataSchema.optional()
    });
    BaseRequestParamsSchema = object2({
      /**
       * See [General fields: `_meta`](/specification/draft/basic/index#meta) for notes on `_meta` usage.
       */
      _meta: RequestMetaSchema.optional()
    });
    TaskAugmentedRequestParamsSchema = BaseRequestParamsSchema.extend({
      /**
       * If specified, the caller is requesting task-augmented execution for this request.
       * The request will return a CreateTaskResult immediately, and the actual result can be
       * retrieved later via tasks/result.
       *
       * Task augmentation is subject to capability negotiation - receivers MUST declare support
       * for task augmentation of specific request types in their capabilities.
       */
      task: TaskMetadataSchema.optional()
    });
    isTaskAugmentedRequestParams = /* @__PURE__ */ __name((value) => TaskAugmentedRequestParamsSchema.safeParse(value).success, "isTaskAugmentedRequestParams");
    RequestSchema = object2({
      method: string2(),
      params: BaseRequestParamsSchema.loose().optional()
    });
    NotificationsParamsSchema = object2({
      /**
       * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)
       * for notes on _meta usage.
       */
      _meta: RequestMetaSchema.optional()
    });
    NotificationSchema = object2({
      method: string2(),
      params: NotificationsParamsSchema.loose().optional()
    });
    ResultSchema = looseObject({
      /**
       * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)
       * for notes on _meta usage.
       */
      _meta: RequestMetaSchema.optional()
    });
    RequestIdSchema = union([string2(), number2().int()]);
    JSONRPCRequestSchema = object2({
      jsonrpc: literal(JSONRPC_VERSION),
      id: RequestIdSchema,
      ...RequestSchema.shape
    }).strict();
    isJSONRPCRequest = /* @__PURE__ */ __name((value) => JSONRPCRequestSchema.safeParse(value).success, "isJSONRPCRequest");
    JSONRPCNotificationSchema = object2({
      jsonrpc: literal(JSONRPC_VERSION),
      ...NotificationSchema.shape
    }).strict();
    isJSONRPCNotification = /* @__PURE__ */ __name((value) => JSONRPCNotificationSchema.safeParse(value).success, "isJSONRPCNotification");
    JSONRPCResultResponseSchema = object2({
      jsonrpc: literal(JSONRPC_VERSION),
      id: RequestIdSchema,
      result: ResultSchema
    }).strict();
    isJSONRPCResultResponse = /* @__PURE__ */ __name((value) => JSONRPCResultResponseSchema.safeParse(value).success, "isJSONRPCResultResponse");
    (function(ErrorCode3) {
      ErrorCode3[ErrorCode3["ConnectionClosed"] = -32e3] = "ConnectionClosed";
      ErrorCode3[ErrorCode3["RequestTimeout"] = -32001] = "RequestTimeout";
      ErrorCode3[ErrorCode3["ParseError"] = -32700] = "ParseError";
      ErrorCode3[ErrorCode3["InvalidRequest"] = -32600] = "InvalidRequest";
      ErrorCode3[ErrorCode3["MethodNotFound"] = -32601] = "MethodNotFound";
      ErrorCode3[ErrorCode3["InvalidParams"] = -32602] = "InvalidParams";
      ErrorCode3[ErrorCode3["InternalError"] = -32603] = "InternalError";
      ErrorCode3[ErrorCode3["UrlElicitationRequired"] = -32042] = "UrlElicitationRequired";
    })(ErrorCode || (ErrorCode = {}));
    JSONRPCErrorResponseSchema = object2({
      jsonrpc: literal(JSONRPC_VERSION),
      id: RequestIdSchema.optional(),
      error: object2({
        /**
         * The error type that occurred.
         */
        code: number2().int(),
        /**
         * A short description of the error. The message SHOULD be limited to a concise single sentence.
         */
        message: string2(),
        /**
         * Additional information about the error. The value of this member is defined by the sender (e.g. detailed error information, nested errors etc.).
         */
        data: unknown().optional()
      })
    }).strict();
    isJSONRPCErrorResponse = /* @__PURE__ */ __name((value) => JSONRPCErrorResponseSchema.safeParse(value).success, "isJSONRPCErrorResponse");
    JSONRPCMessageSchema = union([
      JSONRPCRequestSchema,
      JSONRPCNotificationSchema,
      JSONRPCResultResponseSchema,
      JSONRPCErrorResponseSchema
    ]);
    JSONRPCResponseSchema = union([JSONRPCResultResponseSchema, JSONRPCErrorResponseSchema]);
    EmptyResultSchema = ResultSchema.strict();
    CancelledNotificationParamsSchema = NotificationsParamsSchema.extend({
      /**
       * The ID of the request to cancel.
       *
       * This MUST correspond to the ID of a request previously issued in the same direction.
       */
      requestId: RequestIdSchema.optional(),
      /**
       * An optional string describing the reason for the cancellation. This MAY be logged or presented to the user.
       */
      reason: string2().optional()
    });
    CancelledNotificationSchema = NotificationSchema.extend({
      method: literal("notifications/cancelled"),
      params: CancelledNotificationParamsSchema
    });
    IconSchema = object2({
      /**
       * URL or data URI for the icon.
       */
      src: string2(),
      /**
       * Optional MIME type for the icon.
       */
      mimeType: string2().optional(),
      /**
       * Optional array of strings that specify sizes at which the icon can be used.
       * Each string should be in WxH format (e.g., `"48x48"`, `"96x96"`) or `"any"` for scalable formats like SVG.
       *
       * If not provided, the client should assume that the icon can be used at any size.
       */
      sizes: array(string2()).optional(),
      /**
       * Optional specifier for the theme this icon is designed for. `light` indicates
       * the icon is designed to be used with a light background, and `dark` indicates
       * the icon is designed to be used with a dark background.
       *
       * If not provided, the client should assume the icon can be used with any theme.
       */
      theme: _enum(["light", "dark"]).optional()
    });
    IconsSchema = object2({
      /**
       * Optional set of sized icons that the client can display in a user interface.
       *
       * Clients that support rendering icons MUST support at least the following MIME types:
       * - `image/png` - PNG images (safe, universal compatibility)
       * - `image/jpeg` (and `image/jpg`) - JPEG images (safe, universal compatibility)
       *
       * Clients that support rendering icons SHOULD also support:
       * - `image/svg+xml` - SVG images (scalable but requires security precautions)
       * - `image/webp` - WebP images (modern, efficient format)
       */
      icons: array(IconSchema).optional()
    });
    BaseMetadataSchema = object2({
      /** Intended for programmatic or logical use, but used as a display name in past specs or fallback */
      name: string2(),
      /**
       * 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: string2().optional()
    });
    ImplementationSchema = BaseMetadataSchema.extend({
      ...BaseMetadataSchema.shape,
      ...IconsSchema.shape,
      version: string2(),
      /**
       * An optional URL of the website for this implementation.
       */
      websiteUrl: string2().optional(),
      /**
       * An optional human-readable description of what this implementation does.
       *
       * This can be used by clients or servers to provide context about their purpose
       * and capabilities. For example, a server might describe the types of resources
       * or tools it provides, while a client might describe its intended use case.
       */
      description: string2().optional()
    });
    FormElicitationCapabilitySchema = intersection(object2({
      applyDefaults: boolean2().optional()
    }), record(string2(), unknown()));
    ElicitationCapabilitySchema = preprocess((value) => {
      if (value && typeof value === "object" && !Array.isArray(value)) {
        if (Object.keys(value).length === 0) {
          return { form: {} };
        }
      }
      return value;
    }, intersection(object2({
      form: FormElicitationCapabilitySchema.optional(),
      url: AssertObjectSchema.optional()
    }), record(string2(), unknown()).optional()));
    ClientTasksCapabilitySchema = looseObject({
      /**
       * Present if the client supports listing tasks.
       */
      list: AssertObjectSchema.optional(),
      /**
       * Present if the client supports cancelling tasks.
       */
      cancel: AssertObjectSchema.optional(),
      /**
       * Capabilities for task creation on specific request types.
       */
      requests: looseObject({
        /**
         * Task support for sampling requests.
         */
        sampling: looseObject({
          createMessage: AssertObjectSchema.optional()
        }).optional(),
        /**
         * Task support for elicitation requests.
         */
        elicitation: looseObject({
          create: AssertObjectSchema.optional()
        }).optional()
      }).optional()
    });
    ServerTasksCapabilitySchema = looseObject({
      /**
       * Present if the server supports listing tasks.
       */
      list: AssertObjectSchema.optional(),
      /**
       * Present if the server supports cancelling tasks.
       */
      cancel: AssertObjectSchema.optional(),
      /**
       * Capabilities for task creation on specific request types.
       */
      requests: looseObject({
        /**
         * Task support for tool requests.
         */
        tools: looseObject({
          call: AssertObjectSchema.optional()
        }).optional()
      }).optional()
    });
    ClientCapabilitiesSchema = object2({
      /**
       * Experimental, non-standard capabilities that the client supports.
       */
      experimental: record(string2(), AssertObjectSchema).optional(),
      /**
       * Present if the client supports sampling from an LLM.
       */
      sampling: object2({
        /**
         * Present if the client supports context inclusion via includeContext parameter.
         * If not declared, servers SHOULD only use `includeContext: "none"` (or omit it).
         */
        context: AssertObjectSchema.optional(),
        /**
         * Present if the client supports tool use via tools and toolChoice parameters.
         */
        tools: AssertObjectSchema.optional()
      }).optional(),
      /**
       * Present if the client supports eliciting user input.
       */
      elicitation: ElicitationCapabilitySchema.optional(),
      /**
       * Present if the client supports listing roots.
       */
      roots: object2({
        /**
         * Whether the client supports issuing notifications for changes to the roots list.
         */
        listChanged: boolean2().optional()
      }).optional(),
      /**
       * Present if the client supports task creation.
       */
      tasks: ClientTasksCapabilitySchema.optional()
    });
    InitializeRequestParamsSchema = BaseRequestParamsSchema.extend({
      /**
       * The latest version of the Model Context Protocol that the client supports. The client MAY decide to support older versions as well.
       */
      protocolVersion: string2(),
      capabilities: ClientCapabilitiesSchema,
      clientInfo: ImplementationSchema
    });
    InitializeRequestSchema = RequestSchema.extend({
      method: literal("initialize"),
      params: InitializeRequestParamsSchema
    });
    ServerCapabilitiesSchema = object2({
      /**
       * Experimental, non-standard capabilities that the server supports.
       */
      experimental: record(string2(), AssertObjectSchema).optional(),
      /**
       * Present if the server supports sending log messages to the client.
       */
      logging: AssertObjectSchema.optional(),
      /**
       * Present if the server supports sending completions to the client.
       */
      completions: AssertObjectSchema.optional(),
      /**
       * Present if the server offers any prompt templates.
       */
      prompts: object2({
        /**
         * Whether this server supports issuing notifications for changes to the prompt list.
         */
        listChanged: boolean2().optional()
      }).optional(),
      /**
       * Present if the server offers any resources to read.
       */
      resources: object2({
        /**
         * Whether this server supports clients subscribing to resource updates.
         */
        subscribe: boolean2().optional(),
        /**
         * Whether this server supports issuing notifications for changes to the resource list.
         */
        listChanged: boolean2().optional()
      }).optional(),
      /**
       * Present if the server offers any tools to call.
       */
      tools: object2({
        /**
         * Whether this server supports issuing notifications for changes to the tool list.
         */
        listChanged: boolean2().optional()
      }).optional(),
      /**
       * Present if the server supports task creation.
       */
      tasks: ServerTasksCapabilitySchema.optional()
    });
    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: string2(),
      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: string2().optional()
    });
    InitializedNotificationSchema = NotificationSchema.extend({
      method: literal("notifications/initialized"),
      params: NotificationsParamsSchema.optional()
    });
    isInitializedNotification = /* @__PURE__ */ __name((value) => InitializedNotificationSchema.safeParse(value).success, "isInitializedNotification");
    PingRequestSchema = RequestSchema.extend({
      method: literal("ping"),
      params: BaseRequestParamsSchema.optional()
    });
    ProgressSchema = object2({
      /**
       * The progress thus far. This should increase every time progress is made, even if the total is unknown.
       */
      progress: number2(),
      /**
       * Total number of items to process (or total progress required), if known.
       */
      total: optional(number2()),
      /**
       * An optional message describing the current progress.
       */
      message: optional(string2())
    });
    ProgressNotificationParamsSchema = object2({
      ...NotificationsParamsSchema.shape,
      ...ProgressSchema.shape,
      /**
       * The progress token which was given in the initial request, used to associate this notification with the request that is proceeding.
       */
      progressToken: ProgressTokenSchema
    });
    ProgressNotificationSchema = NotificationSchema.extend({
      method: literal("notifications/progress"),
      params: ProgressNotificationParamsSchema
    });
    PaginatedRequestParamsSchema = BaseRequestParamsSchema.extend({
      /**
       * An opaque token representing the current pagination position.
       * If provided, the server should return results starting after this cursor.
       */
      cursor: CursorSchema.optional()
    });
    PaginatedRequestSchema = RequestSchema.extend({
      params: PaginatedRequestParamsSchema.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: CursorSchema.optional()
    });
    TaskStatusSchema = _enum(["working", "input_required", "completed", "failed", "cancelled"]);
    TaskSchema = object2({
      taskId: string2(),
      status: TaskStatusSchema,
      /**
       * Time in milliseconds to keep task results available after completion.
       * If null, the task has unlimited lifetime until manually cleaned up.
       */
      ttl: union([number2(), _null3()]),
      /**
       * ISO 8601 timestamp when the task was created.
       */
      createdAt: string2(),
      /**
       * ISO 8601 timestamp when the task was last updated.
       */
      lastUpdatedAt: string2(),
      pollInterval: optional(number2()),
      /**
       * Optional diagnostic message for failed tasks or other status information.
       */
      statusMessage: optional(string2())
    });
    CreateTaskResultSchema = ResultSchema.extend({
      task: TaskSchema
    });
    TaskStatusNotificationParamsSchema = NotificationsParamsSchema.merge(TaskSchema);
    TaskStatusNotificationSchema = NotificationSchema.extend({
      method: literal("notifications/tasks/status"),
      params: TaskStatusNotificationParamsSchema
    });
    GetTaskRequestSchema = RequestSchema.extend({
      method: literal("tasks/get"),
      params: BaseRequestParamsSchema.extend({
        taskId: string2()
      })
    });
    GetTaskResultSchema = ResultSchema.merge(TaskSchema);
    GetTaskPayloadRequestSchema = RequestSchema.extend({
      method: literal("tasks/result"),
      params: BaseRequestParamsSchema.extend({
        taskId: string2()
      })
    });
    GetTaskPayloadResultSchema = ResultSchema.loose();
    ListTasksRequestSchema = PaginatedRequestSchema.extend({
      method: literal("tasks/list")
    });
    ListTasksResultSchema = PaginatedResultSchema.extend({
      tasks: array(TaskSchema)
    });
    CancelTaskRequestSchema = RequestSchema.extend({
      method: literal("tasks/cancel"),
      params: BaseRequestParamsSchema.extend({
        taskId: string2()
      })
    });
    CancelTaskResultSchema = ResultSchema.merge(TaskSchema);
    ResourceContentsSchema = object2({
      /**
       * The URI of this resource.
       */
      uri: string2(),
      /**
       * The MIME type of this resource, if known.
       */
      mimeType: optional(string2()),
      /**
       * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)
       * for notes on _meta usage.
       */
      _meta: record(string2(), unknown()).optional()
    });
    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: string2()
    });
    Base64Schema = string2().refine((val) => {
      try {
        atob(val);
        return true;
      } catch {
        return false;
      }
    }, { message: "Invalid Base64 string" });
    BlobResourceContentsSchema = ResourceContentsSchema.extend({
      /**
       * A base64-encoded string representing the binary data of the item.
       */
      blob: Base64Schema
    });
    RoleSchema = _enum(["user", "assistant"]);
    AnnotationsSchema = object2({
      /**
       * Intended audience(s) for the resource.
       */
      audience: array(RoleSchema).optional(),
      /**
       * Importance hint for the resource, from 0 (least) to 1 (most).
       */
      priority: number2().min(0).max(1).optional(),
      /**
       * ISO 8601 timestamp for the most recent modification.
       */
      lastModified: iso_exports2.datetime({ offset: true }).optional()
    });
    ResourceSchema = object2({
      ...BaseMetadataSchema.shape,
      ...IconsSchema.shape,
      /**
       * The URI of this resource.
       */
      uri: string2(),
      /**
       * A description of what this resource represents.
       *
       * This can be used by clients to improve the LLM's understanding of available resources. It can be thought of like a "hint" to the model.
       */
      description: optional(string2()),
      /**
       * The MIME type of this resource, if known.
       */
      mimeType: optional(string2()),
      /**
       * Optional annotations for the client.
       */
      annotations: AnnotationsSchema.optional(),
      /**
       * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)
       * for notes on _meta usage.
       */
      _meta: optional(looseObject({}))
    });
    ResourceTemplateSchema = object2({
      ...BaseMetadataSchema.shape,
      ...IconsSchema.shape,
      /**
       * A URI template (according to RFC 6570) that can be used to construct resource URIs.
       */
      uriTemplate: string2(),
      /**
       * A description of what this template is for.
       *
       * This can be used by clients to improve the LLM's understanding of available resources. It can be thought of like a "hint" to the model.
       */
      description: optional(string2()),
      /**
       * The MIME type for all resources that match this template. This should only be included if all resources matching this template have the same type.
       */
      mimeType: optional(string2()),
      /**
       * Optional annotations for the client.
       */
      annotations: AnnotationsSchema.optional(),
      /**
       * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)
       * for notes on _meta usage.
       */
      _meta: optional(looseObject({}))
    });
    ListResourcesRequestSchema = PaginatedRequestSchema.extend({
      method: literal("resources/list")
    });
    ListResourcesResultSchema = PaginatedResultSchema.extend({
      resources: array(ResourceSchema)
    });
    ListResourceTemplatesRequestSchema = PaginatedRequestSchema.extend({
      method: literal("resources/templates/list")
    });
    ListResourceTemplatesResultSchema = PaginatedResultSchema.extend({
      resourceTemplates: array(ResourceTemplateSchema)
    });
    ResourceRequestParamsSchema = BaseRequestParamsSchema.extend({
      /**
       * The URI of the resource to read. The URI can use any protocol; it is up to the server how to interpret it.
       *
       * @format uri
       */
      uri: string2()
    });
    ReadResourceRequestParamsSchema = ResourceRequestParamsSchema;
    ReadResourceRequestSchema = RequestSchema.extend({
      method: literal("resources/read"),
      params: ReadResourceRequestParamsSchema
    });
    ReadResourceResultSchema = ResultSchema.extend({
      contents: array(union([TextResourceContentsSchema, BlobResourceContentsSchema]))
    });
    ResourceListChangedNotificationSchema = NotificationSchema.extend({
      method: literal("notifications/resources/list_changed"),
      params: NotificationsParamsSchema.optional()
    });
    SubscribeRequestParamsSchema = ResourceRequestParamsSchema;
    SubscribeRequestSchema = RequestSchema.extend({
      method: literal("resources/subscribe"),
      params: SubscribeRequestParamsSchema
    });
    UnsubscribeRequestParamsSchema = ResourceRequestParamsSchema;
    UnsubscribeRequestSchema = RequestSchema.extend({
      method: literal("resources/unsubscribe"),
      params: UnsubscribeRequestParamsSchema
    });
    ResourceUpdatedNotificationParamsSchema = NotificationsParamsSchema.extend({
      /**
       * The URI of the resource that has been updated. This might be a sub-resource of the one that the client actually subscribed to.
       */
      uri: string2()
    });
    ResourceUpdatedNotificationSchema = NotificationSchema.extend({
      method: literal("notifications/resources/updated"),
      params: ResourceUpdatedNotificationParamsSchema
    });
    PromptArgumentSchema = object2({
      /**
       * The name of the argument.
       */
      name: string2(),
      /**
       * A human-readable description of the argument.
       */
      description: optional(string2()),
      /**
       * Whether this argument must be provided.
       */
      required: optional(boolean2())
    });
    PromptSchema = object2({
      ...BaseMetadataSchema.shape,
      ...IconsSchema.shape,
      /**
       * An optional description of what this prompt provides
       */
      description: optional(string2()),
      /**
       * A list of arguments to use for templating the prompt.
       */
      arguments: optional(array(PromptArgumentSchema)),
      /**
       * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)
       * for notes on _meta usage.
       */
      _meta: optional(looseObject({}))
    });
    ListPromptsRequestSchema = PaginatedRequestSchema.extend({
      method: literal("prompts/list")
    });
    ListPromptsResultSchema = PaginatedResultSchema.extend({
      prompts: array(PromptSchema)
    });
    GetPromptRequestParamsSchema = BaseRequestParamsSchema.extend({
      /**
       * The name of the prompt or prompt template.
       */
      name: string2(),
      /**
       * Arguments to use for templating the prompt.
       */
      arguments: record(string2(), string2()).optional()
    });
    GetPromptRequestSchema = RequestSchema.extend({
      method: literal("prompts/get"),
      params: GetPromptRequestParamsSchema
    });
    TextContentSchema = object2({
      type: literal("text"),
      /**
       * The text content of the message.
       */
      text: string2(),
      /**
       * Optional annotations for the client.
       */
      annotations: AnnotationsSchema.optional(),
      /**
       * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)
       * for notes on _meta usage.
       */
      _meta: record(string2(), unknown()).optional()
    });
    ImageContentSchema = object2({
      type: literal("image"),
      /**
       * The base64-encoded image data.
       */
      data: Base64Schema,
      /**
       * The MIME type of the image. Different providers may support different image types.
       */
      mimeType: string2(),
      /**
       * Optional annotations for the client.
       */
      annotations: AnnotationsSchema.optional(),
      /**
       * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)
       * for notes on _meta usage.
       */
      _meta: record(string2(), unknown()).optional()
    });
    AudioContentSchema = object2({
      type: literal("audio"),
      /**
       * The base64-encoded audio data.
       */
      data: Base64Schema,
      /**
       * The MIME type of the audio. Different providers may support different audio types.
       */
      mimeType: string2(),
      /**
       * Optional annotations for the client.
       */
      annotations: AnnotationsSchema.optional(),
      /**
       * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)
       * for notes on _meta usage.
       */
      _meta: record(string2(), unknown()).optional()
    });
    ToolUseContentSchema = object2({
      type: literal("tool_use"),
      /**
       * The name of the tool to invoke.
       * Must match a tool name from the request's tools array.
       */
      name: string2(),
      /**
       * Unique identifier for this tool call.
       * Used to correlate with ToolResultContent in subsequent messages.
       */
      id: string2(),
      /**
       * Arguments to pass to the tool.
       * Must conform to the tool's inputSchema.
       */
      input: record(string2(), unknown()),
      /**
       * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)
       * for notes on _meta usage.
       */
      _meta: record(string2(), unknown()).optional()
    });
    EmbeddedResourceSchema = object2({
      type: literal("resource"),
      resource: union([TextResourceContentsSchema, BlobResourceContentsSchema]),
      /**
       * Optional annotations for the client.
       */
      annotations: AnnotationsSchema.optional(),
      /**
       * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)
       * for notes on _meta usage.
       */
      _meta: record(string2(), unknown()).optional()
    });
    ResourceLinkSchema = ResourceSchema.extend({
      type: literal("resource_link")
    });
    ContentBlockSchema = union([
      TextContentSchema,
      ImageContentSchema,
      AudioContentSchema,
      ResourceLinkSchema,
      EmbeddedResourceSchema
    ]);
    PromptMessageSchema = object2({
      role: RoleSchema,
      content: ContentBlockSchema
    });
    GetPromptResultSchema = ResultSchema.extend({
      /**
       * An optional description for the prompt.
       */
      description: string2().optional(),
      messages: array(PromptMessageSchema)
    });
    PromptListChangedNotificationSchema = NotificationSchema.extend({
      method: literal("notifications/prompts/list_changed"),
      params: NotificationsParamsSchema.optional()
    });
    ToolAnnotationsSchema = object2({
      /**
       * A human-readable title for the tool.
       */
      title: string2().optional(),
      /**
       * If true, the tool does not modify its environment.
       *
       * Default: false
       */
      readOnlyHint: boolean2().optional(),
      /**
       * If true, the tool may perform destructive updates to its environment.
       * If false, the tool performs only additive updates.
       *
       * (This property is meaningful only when `readOnlyHint == false`)
       *
       * Default: true
       */
      destructiveHint: boolean2().optional(),
      /**
       * If true, calling the tool repeatedly with the same arguments
       * will have no additional effect on the its environment.
       *
       * (This property is meaningful only when `readOnlyHint == false`)
       *
       * Default: false
       */
      idempotentHint: boolean2().optional(),
      /**
       * If true, this tool may interact with an "open world" of external
       * entities. If false, the tool's domain of interaction is closed.
       * For example, the world of a web search tool is open, whereas that
       * of a memory tool is not.
       *
       * Default: true
       */
      openWorldHint: boolean2().optional()
    });
    ToolExecutionSchema = object2({
      /**
       * Indicates the tool's preference for task-augmented execution.
       * - "required": Clients MUST invoke the tool as a task
       * - "optional": Clients MAY invoke the tool as a task or normal request
       * - "forbidden": Clients MUST NOT attempt to invoke the tool as a task
       *
       * If not present, defaults to "forbidden".
       */
      taskSupport: _enum(["required", "optional", "forbidden"]).optional()
    });
    ToolSchema = object2({
      ...BaseMetadataSchema.shape,
      ...IconsSchema.shape,
      /**
       * A human-readable description of the tool.
       */
      description: string2().optional(),
      /**
       * A JSON Schema 2020-12 object defining the expected parameters for the tool.
       * Must have type: 'object' at the root level per MCP spec.
       */
      inputSchema: object2({
        type: literal("object"),
        properties: record(string2(), AssertObjectSchema).optional(),
        required: array(string2()).optional()
      }).catchall(unknown()),
      /**
       * An optional JSON Schema 2020-12 object defining the structure of the tool's output
       * returned in the structuredContent field of a CallToolResult.
       * Must have type: 'object' at the root level per MCP spec.
       */
      outputSchema: object2({
        type: literal("object"),
        properties: record(string2(), AssertObjectSchema).optional(),
        required: array(string2()).optional()
      }).catchall(unknown()).optional(),
      /**
       * Optional additional tool information.
       */
      annotations: ToolAnnotationsSchema.optional(),
      /**
       * Execution-related properties for this tool.
       */
      execution: ToolExecutionSchema.optional(),
      /**
       * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)
       * for notes on _meta usage.
       */
      _meta: record(string2(), unknown()).optional()
    });
    ListToolsRequestSchema = PaginatedRequestSchema.extend({
      method: literal("tools/list")
    });
    ListToolsResultSchema = PaginatedResultSchema.extend({
      tools: 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: array(ContentBlockSchema).default([]),
      /**
       * An object containing structured tool output.
       *
       * If the Tool defines an outputSchema, this field MUST be present in the result, and contain a JSON object that matches the schema.
       */
      structuredContent: record(string2(), unknown()).optional(),
      /**
       * Whether the tool call ended in an error.
       *
       * If not set, this is assumed to be false (the call was successful).
       *
       * Any errors that originate from the tool SHOULD be reported inside the result
       * object, with `isError` set to true, _not_ as an MCP protocol-level error
       * response. Otherwise, the LLM would not be able to see that an error occurred
       * and self-correct.
       *
       * However, any errors in _finding_ the tool, an error indicating that the
       * server does not support tool calls, or any other exceptional conditions,
       * should be reported as an MCP error response.
       */
      isError: boolean2().optional()
    });
    CompatibilityCallToolResultSchema = CallToolResultSchema.or(ResultSchema.extend({
      toolResult: unknown()
    }));
    CallToolRequestParamsSchema = TaskAugmentedRequestParamsSchema.extend({
      /**
       * The name of the tool to call.
       */
      name: string2(),
      /**
       * Arguments to pass to the tool.
       */
      arguments: record(string2(), unknown()).optional()
    });
    CallToolRequestSchema = RequestSchema.extend({
      method: literal("tools/call"),
      params: CallToolRequestParamsSchema
    });
    ToolListChangedNotificationSchema = NotificationSchema.extend({
      method: literal("notifications/tools/list_changed"),
      params: NotificationsParamsSchema.optional()
    });
    ListChangedOptionsBaseSchema = object2({
      /**
       * If true, the list will be refreshed automatically when a list changed notification is received.
       * The callback will be called with the updated list.
       *
       * If false, the callback will be called with null items, allowing manual refresh.
       *
       * @default true
       */
      autoRefresh: boolean2().default(true),
      /**
       * Debounce time in milliseconds for list changed notification processing.
       *
       * Multiple notifications received within this timeframe will only trigger one refresh.
       * Set to 0 to disable debouncing.
       *
       * @default 300
       */
      debounceMs: number2().int().nonnegative().default(300)
    });
    LoggingLevelSchema = _enum(["debug", "info", "notice", "warning", "error", "critical", "alert", "emergency"]);
    SetLevelRequestParamsSchema = BaseRequestParamsSchema.extend({
      /**
       * The level of logging that the client wants to receive from the server. The server should send all logs at this level and higher (i.e., more severe) to the client as notifications/logging/message.
       */
      level: LoggingLevelSchema
    });
    SetLevelRequestSchema = RequestSchema.extend({
      method: literal("logging/setLevel"),
      params: SetLevelRequestParamsSchema
    });
    LoggingMessageNotificationParamsSchema = NotificationsParamsSchema.extend({
      /**
       * The severity of this log message.
       */
      level: LoggingLevelSchema,
      /**
       * An optional name of the logger issuing this message.
       */
      logger: string2().optional(),
      /**
       * The data to be logged, such as a string message or an object. Any JSON serializable type is allowed here.
       */
      data: unknown()
    });
    LoggingMessageNotificationSchema = NotificationSchema.extend({
      method: literal("notifications/message"),
      params: LoggingMessageNotificationParamsSchema
    });
    ModelHintSchema = object2({
      /**
       * A hint for a model name.
       */
      name: string2().optional()
    });
    ModelPreferencesSchema = object2({
      /**
       * Optional hints to use for model selection.
       */
      hints: array(ModelHintSchema).optional(),
      /**
       * How much to prioritize cost when selecting a model.
       */
      costPriority: number2().min(0).max(1).optional(),
      /**
       * How much to prioritize sampling speed (latency) when selecting a model.
       */
      speedPriority: number2().min(0).max(1).optional(),
      /**
       * How much to prioritize intelligence and capabilities when selecting a model.
       */
      intelligencePriority: number2().min(0).max(1).optional()
    });
    ToolChoiceSchema = object2({
      /**
       * Controls when tools are used:
       * - "auto": Model decides whether to use tools (default)
       * - "required": Model MUST use at least one tool before completing
       * - "none": Model MUST NOT use any tools
       */
      mode: _enum(["auto", "required", "none"]).optional()
    });
    ToolResultContentSchema = object2({
      type: literal("tool_result"),
      toolUseId: string2().describe("The unique identifier for the corresponding tool call."),
      content: array(ContentBlockSchema).default([]),
      structuredContent: object2({}).loose().optional(),
      isError: boolean2().optional(),
      /**
       * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)
       * for notes on _meta usage.
       */
      _meta: record(string2(), unknown()).optional()
    });
    SamplingContentSchema = discriminatedUnion("type", [TextContentSchema, ImageContentSchema, AudioContentSchema]);
    SamplingMessageContentBlockSchema = discriminatedUnion("type", [
      TextContentSchema,
      ImageContentSchema,
      AudioContentSchema,
      ToolUseContentSchema,
      ToolResultContentSchema
    ]);
    SamplingMessageSchema = object2({
      role: RoleSchema,
      content: union([SamplingMessageContentBlockSchema, array(SamplingMessageContentBlockSchema)]),
      /**
       * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)
       * for notes on _meta usage.
       */
      _meta: record(string2(), unknown()).optional()
    });
    CreateMessageRequestParamsSchema = TaskAugmentedRequestParamsSchema.extend({
      messages: array(SamplingMessageSchema),
      /**
       * The server's preferences for which model to select. The client MAY modify or omit this request.
       */
      modelPreferences: ModelPreferencesSchema.optional(),
      /**
       * An optional system prompt the server wants to use for sampling. The client MAY modify or omit this prompt.
       */
      systemPrompt: string2().optional(),
      /**
       * A request to include context from one or more MCP servers (including the caller), to be attached to the prompt.
       * The client MAY ignore this request.
       *
       * Default is "none". Values "thisServer" and "allServers" are soft-deprecated. Servers SHOULD only use these values if the client
       * declares ClientCapabilities.sampling.context. These values may be removed in future spec releases.
       */
      includeContext: _enum(["none", "thisServer", "allServers"]).optional(),
      temperature: number2().optional(),
      /**
       * The requested maximum number of tokens to sample (to prevent runaway completions).
       *
       * The client MAY choose to sample fewer tokens than the requested maximum.
       */
      maxTokens: number2().int(),
      stopSequences: array(string2()).optional(),
      /**
       * Optional metadata to pass through to the LLM provider. The format of this metadata is provider-specific.
       */
      metadata: AssertObjectSchema.optional(),
      /**
       * Tools that the model may use during generation.
       * The client MUST return an error if this field is provided but ClientCapabilities.sampling.tools is not declared.
       */
      tools: array(ToolSchema).optional(),
      /**
       * Controls how the model uses tools.
       * The client MUST return an error if this field is provided but ClientCapabilities.sampling.tools is not declared.
       * Default is `{ mode: "auto" }`.
       */
      toolChoice: ToolChoiceSchema.optional()
    });
    CreateMessageRequestSchema = RequestSchema.extend({
      method: literal("sampling/createMessage"),
      params: CreateMessageRequestParamsSchema
    });
    CreateMessageResultSchema = ResultSchema.extend({
      /**
       * The name of the model that generated the message.
       */
      model: string2(),
      /**
       * The reason why sampling stopped, if known.
       *
       * Standard values:
       * - "endTurn": Natural end of the assistant's turn
       * - "stopSequence": A stop sequence was encountered
       * - "maxTokens": Maximum token limit was reached
       *
       * This field is an open string to allow for provider-specific stop reasons.
       */
      stopReason: optional(_enum(["endTurn", "stopSequence", "maxTokens"]).or(string2())),
      role: RoleSchema,
      /**
       * Response content. Single content block (text, image, or audio).
       */
      content: SamplingContentSchema
    });
    CreateMessageResultWithToolsSchema = ResultSchema.extend({
      /**
       * The name of the model that generated the message.
       */
      model: string2(),
      /**
       * The reason why sampling stopped, if known.
       *
       * Standard values:
       * - "endTurn": Natural end of the assistant's turn
       * - "stopSequence": A stop sequence was encountered
       * - "maxTokens": Maximum token limit was reached
       * - "toolUse": The model wants to use one or more tools
       *
       * This field is an open string to allow for provider-specific stop reasons.
       */
      stopReason: optional(_enum(["endTurn", "stopSequence", "maxTokens", "toolUse"]).or(string2())),
      role: RoleSchema,
      /**
       * Response content. May be a single block or array. May include ToolUseContent if stopReason is "toolUse".
       */
      content: union([SamplingMessageContentBlockSchema, array(SamplingMessageContentBlockSchema)])
    });
    BooleanSchemaSchema = object2({
      type: literal("boolean"),
      title: string2().optional(),
      description: string2().optional(),
      default: boolean2().optional()
    });
    StringSchemaSchema = object2({
      type: literal("string"),
      title: string2().optional(),
      description: string2().optional(),
      minLength: number2().optional(),
      maxLength: number2().optional(),
      format: _enum(["email", "uri", "date", "date-time"]).optional(),
      default: string2().optional()
    });
    NumberSchemaSchema = object2({
      type: _enum(["number", "integer"]),
      title: string2().optional(),
      description: string2().optional(),
      minimum: number2().optional(),
      maximum: number2().optional(),
      default: number2().optional()
    });
    UntitledSingleSelectEnumSchemaSchema = object2({
      type: literal("string"),
      title: string2().optional(),
      description: string2().optional(),
      enum: array(string2()),
      default: string2().optional()
    });
    TitledSingleSelectEnumSchemaSchema = object2({
      type: literal("string"),
      title: string2().optional(),
      description: string2().optional(),
      oneOf: array(object2({
        const: string2(),
        title: string2()
      })),
      default: string2().optional()
    });
    LegacyTitledEnumSchemaSchema = object2({
      type: literal("string"),
      title: string2().optional(),
      description: string2().optional(),
      enum: array(string2()),
      enumNames: array(string2()).optional(),
      default: string2().optional()
    });
    SingleSelectEnumSchemaSchema = union([UntitledSingleSelectEnumSchemaSchema, TitledSingleSelectEnumSchemaSchema]);
    UntitledMultiSelectEnumSchemaSchema = object2({
      type: literal("array"),
      title: string2().optional(),
      description: string2().optional(),
      minItems: number2().optional(),
      maxItems: number2().optional(),
      items: object2({
        type: literal("string"),
        enum: array(string2())
      }),
      default: array(string2()).optional()
    });
    TitledMultiSelectEnumSchemaSchema = object2({
      type: literal("array"),
      title: string2().optional(),
      description: string2().optional(),
      minItems: number2().optional(),
      maxItems: number2().optional(),
      items: object2({
        anyOf: array(object2({
          const: string2(),
          title: string2()
        }))
      }),
      default: array(string2()).optional()
    });
    MultiSelectEnumSchemaSchema = union([UntitledMultiSelectEnumSchemaSchema, TitledMultiSelectEnumSchemaSchema]);
    EnumSchemaSchema = union([LegacyTitledEnumSchemaSchema, SingleSelectEnumSchemaSchema, MultiSelectEnumSchemaSchema]);
    PrimitiveSchemaDefinitionSchema = union([EnumSchemaSchema, BooleanSchemaSchema, StringSchemaSchema, NumberSchemaSchema]);
    ElicitRequestFormParamsSchema = TaskAugmentedRequestParamsSchema.extend({
      /**
       * The elicitation mode.
       *
       * Optional for backward compatibility. Clients MUST treat missing mode as "form".
       */
      mode: literal("form").optional(),
      /**
       * The message to present to the user describing what information is being requested.
       */
      message: string2(),
      /**
       * A restricted subset of JSON Schema.
       * Only top-level properties are allowed, without nesting.
       */
      requestedSchema: object2({
        type: literal("object"),
        properties: record(string2(), PrimitiveSchemaDefinitionSchema),
        required: array(string2()).optional()
      })
    });
    ElicitRequestURLParamsSchema = TaskAugmentedRequestParamsSchema.extend({
      /**
       * The elicitation mode.
       */
      mode: literal("url"),
      /**
       * The message to present to the user explaining why the interaction is needed.
       */
      message: string2(),
      /**
       * The ID of the elicitation, which must be unique within the context of the server.
       * The client MUST treat this ID as an opaque value.
       */
      elicitationId: string2(),
      /**
       * The URL that the user should navigate to.
       */
      url: string2().url()
    });
    ElicitRequestParamsSchema = union([ElicitRequestFormParamsSchema, ElicitRequestURLParamsSchema]);
    ElicitRequestSchema = RequestSchema.extend({
      method: literal("elicitation/create"),
      params: ElicitRequestParamsSchema
    });
    ElicitationCompleteNotificationParamsSchema = NotificationsParamsSchema.extend({
      /**
       * The ID of the elicitation that completed.
       */
      elicitationId: string2()
    });
    ElicitationCompleteNotificationSchema = NotificationSchema.extend({
      method: literal("notifications/elicitation/complete"),
      params: ElicitationCompleteNotificationParamsSchema
    });
    ElicitResultSchema = ResultSchema.extend({
      /**
       * The user action in response to the elicitation.
       * - "accept": User submitted the form/confirmed the action
       * - "decline": User explicitly decline the action
       * - "cancel": User dismissed without making an explicit choice
       */
      action: _enum(["accept", "decline", "cancel"]),
      /**
       * The submitted form data, only present when action is "accept".
       * Contains values matching the requested schema.
       * Per MCP spec, content is "typically omitted" for decline/cancel actions.
       * We normalize null to undefined for leniency while maintaining type compatibility.
       */
      content: preprocess((val) => val === null ? void 0 : val, record(string2(), union([string2(), number2(), boolean2(), array(string2())])).optional())
    });
    ResourceTemplateReferenceSchema = object2({
      type: literal("ref/resource"),
      /**
       * The URI or URI template of the resource.
       */
      uri: string2()
    });
    PromptReferenceSchema = object2({
      type: literal("ref/prompt"),
      /**
       * The name of the prompt or prompt template
       */
      name: string2()
    });
    CompleteRequestParamsSchema = BaseRequestParamsSchema.extend({
      ref: union([PromptReferenceSchema, ResourceTemplateReferenceSchema]),
      /**
       * The argument's information
       */
      argument: object2({
        /**
         * The name of the argument
         */
        name: string2(),
        /**
         * The value of the argument to use for completion matching.
         */
        value: string2()
      }),
      context: object2({
        /**
         * Previously-resolved variables in a URI template or prompt.
         */
        arguments: record(string2(), string2()).optional()
      }).optional()
    });
    CompleteRequestSchema = RequestSchema.extend({
      method: literal("completion/complete"),
      params: CompleteRequestParamsSchema
    });
    CompleteResultSchema = ResultSchema.extend({
      completion: looseObject({
        /**
         * An array of completion values. Must not exceed 100 items.
         */
        values: array(string2()).max(100),
        /**
         * The total number of completion options available. This can exceed the number of values actually sent in the response.
         */
        total: optional(number2().int()),
        /**
         * Indicates whether there are additional completion options beyond those provided in the current response, even if the exact total is unknown.
         */
        hasMore: optional(boolean2())
      })
    });
    RootSchema = object2({
      /**
       * The URI identifying the root. This *must* start with file:// for now.
       */
      uri: string2().startsWith("file://"),
      /**
       * An optional name for the root.
       */
      name: string2().optional(),
      /**
       * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)
       * for notes on _meta usage.
       */
      _meta: record(string2(), unknown()).optional()
    });
    ListRootsRequestSchema = RequestSchema.extend({
      method: literal("roots/list"),
      params: BaseRequestParamsSchema.optional()
    });
    ListRootsResultSchema = ResultSchema.extend({
      roots: array(RootSchema)
    });
    RootsListChangedNotificationSchema = NotificationSchema.extend({
      method: literal("notifications/roots/list_changed"),
      params: NotificationsParamsSchema.optional()
    });
    ClientRequestSchema = union([
      PingRequestSchema,
      InitializeRequestSchema,
      CompleteRequestSchema,
      SetLevelRequestSchema,
      GetPromptRequestSchema,
      ListPromptsRequestSchema,
      ListResourcesRequestSchema,
      ListResourceTemplatesRequestSchema,
      ReadResourceRequestSchema,
      SubscribeRequestSchema,
      UnsubscribeRequestSchema,
      CallToolRequestSchema,
      ListToolsRequestSchema,
      GetTaskRequestSchema,
      GetTaskPayloadRequestSchema,
      ListTasksRequestSchema,
      CancelTaskRequestSchema
    ]);
    ClientNotificationSchema = union([
      CancelledNotificationSchema,
      ProgressNotificationSchema,
      InitializedNotificationSchema,
      RootsListChangedNotificationSchema,
      TaskStatusNotificationSchema
    ]);
    ClientResultSchema = union([
      EmptyResultSchema,
      CreateMessageResultSchema,
      CreateMessageResultWithToolsSchema,
      ElicitResultSchema,
      ListRootsResultSchema,
      GetTaskResultSchema,
      ListTasksResultSchema,
      CreateTaskResultSchema
    ]);
    ServerRequestSchema = union([
      PingRequestSchema,
      CreateMessageRequestSchema,
      ElicitRequestSchema,
      ListRootsRequestSchema,
      GetTaskRequestSchema,
      GetTaskPayloadRequestSchema,
      ListTasksRequestSchema,
      CancelTaskRequestSchema
    ]);
    ServerNotificationSchema = union([
      CancelledNotificationSchema,
      ProgressNotificationSchema,
      LoggingMessageNotificationSchema,
      ResourceUpdatedNotificationSchema,
      ResourceListChangedNotificationSchema,
      ToolListChangedNotificationSchema,
      PromptListChangedNotificationSchema,
      TaskStatusNotificationSchema,
      ElicitationCompleteNotificationSchema
    ]);
    ServerResultSchema = union([
      EmptyResultSchema,
      InitializeResultSchema,
      CompleteResultSchema,
      GetPromptResultSchema,
      ListPromptsResultSchema,
      ListResourcesResultSchema,
      ListResourceTemplatesResultSchema,
      ReadResourceResultSchema,
      CallToolResultSchema,
      ListToolsResultSchema,
      GetTaskResultSchema,
      ListTasksResultSchema,
      CreateTaskResultSchema
    ]);
    McpError = class _McpError extends Error {
      static {
        __name(this, "McpError");
      }
      constructor(code2, message, data) {
        super(`MCP error ${code2}: ${message}`);
        this.code = code2;
        this.data = data;
        this.name = "McpError";
      }
      /**
       * Factory method to create the appropriate error type based on the error code and data
       */
      static fromError(code2, message, data) {
        if (code2 === ErrorCode.UrlElicitationRequired && data) {
          const errorData = data;
          if (errorData.elicitations) {
            return new UrlElicitationRequiredError(errorData.elicitations, message);
          }
        }
        return new _McpError(code2, message, data);
      }
    };
    UrlElicitationRequiredError = class extends McpError {
      static {
        __name(this, "UrlElicitationRequiredError");
      }
      constructor(elicitations, message = `URL elicitation${elicitations.length > 1 ? "s" : ""} required`) {
        super(ErrorCode.UrlElicitationRequired, message, {
          elicitations
        });
      }
      get elicitations() {
        return this.data?.elicitations ?? [];
      }
    };
  }
});

// packages/core/node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/interfaces.js
function isTerminal(status) {
  return status === "completed" || status === "failed" || status === "cancelled";
}
var init_interfaces = __esm({
  "packages/core/node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/interfaces.js"() {
    init_esbuild_shims();
    __name(isTerminal, "isTerminal");
  }
});

// packages/core/node_modules/zod-to-json-schema/dist/esm/Options.js
var ignoreOverride;
var init_Options = __esm({
  "packages/core/node_modules/zod-to-json-schema/dist/esm/Options.js"() {
    init_esbuild_shims();
    ignoreOverride = Symbol("Let zodToJsonSchema decide on which parser to use");
  }
});

// packages/core/node_modules/zod-to-json-schema/dist/esm/Refs.js
var init_Refs = __esm({
  "packages/core/node_modules/zod-to-json-schema/dist/esm/Refs.js"() {
    init_esbuild_shims();
    init_Options();
  }
});

// packages/core/node_modules/zod-to-json-schema/dist/esm/errorMessages.js
var init_errorMessages = __esm({
  "packages/core/node_modules/zod-to-json-schema/dist/esm/errorMessages.js"() {
    init_esbuild_shims();
  }
});

// packages/core/node_modules/zod-to-json-schema/dist/esm/getRelativePath.js
var init_getRelativePath = __esm({
  "packages/core/node_modules/zod-to-json-schema/dist/esm/getRelativePath.js"() {
    init_esbuild_shims();
  }
});

// packages/core/node_modules/zod-to-json-schema/dist/esm/parsers/any.js
var init_any = __esm({
  "packages/core/node_modules/zod-to-json-schema/dist/esm/parsers/any.js"() {
    init_esbuild_shims();
    init_getRelativePath();
  }
});

// packages/core/node_modules/zod-to-json-schema/dist/esm/parsers/array.js
var init_array = __esm({
  "packages/core/node_modules/zod-to-json-schema/dist/esm/parsers/array.js"() {
    init_esbuild_shims();
    init_errorMessages();
    init_parseDef();
  }
});

// packages/core/node_modules/zod-to-json-schema/dist/esm/parsers/bigint.js
var init_bigint = __esm({
  "packages/core/node_modules/zod-to-json-schema/dist/esm/parsers/bigint.js"() {
    init_esbuild_shims();
    init_errorMessages();
  }
});

// packages/core/node_modules/zod-to-json-schema/dist/esm/parsers/boolean.js
var init_boolean = __esm({
  "packages/core/node_modules/zod-to-json-schema/dist/esm/parsers/boolean.js"() {
    init_esbuild_shims();
  }
});

// packages/core/node_modules/zod-to-json-schema/dist/esm/parsers/branded.js
var init_branded = __esm({
  "packages/core/node_modules/zod-to-json-schema/dist/esm/parsers/branded.js"() {
    init_esbuild_shims();
    init_parseDef();
  }
});

// packages/core/node_modules/zod-to-json-schema/dist/esm/parsers/catch.js
var init_catch = __esm({
  "packages/core/node_modules/zod-to-json-schema/dist/esm/parsers/catch.js"() {
    init_esbuild_shims();
    init_parseDef();
  }
});

// packages/core/node_modules/zod-to-json-schema/dist/esm/parsers/date.js
var init_date = __esm({
  "packages/core/node_modules/zod-to-json-schema/dist/esm/parsers/date.js"() {
    init_esbuild_shims();
    init_errorMessages();
  }
});

// packages/core/node_modules/zod-to-json-schema/dist/esm/parsers/default.js
var init_default2 = __esm({
  "packages/core/node_modules/zod-to-json-schema/dist/esm/parsers/default.js"() {
    init_esbuild_shims();
    init_parseDef();
  }
});

// packages/core/node_modules/zod-to-json-schema/dist/esm/parsers/effects.js
var init_effects = __esm({
  "packages/core/node_modules/zod-to-json-schema/dist/esm/parsers/effects.js"() {
    init_esbuild_shims();
    init_parseDef();
    init_any();
  }
});

// packages/core/node_modules/zod-to-json-schema/dist/esm/parsers/enum.js
var init_enum = __esm({
  "packages/core/node_modules/zod-to-json-schema/dist/esm/parsers/enum.js"() {
    init_esbuild_shims();
  }
});

// packages/core/node_modules/zod-to-json-schema/dist/esm/parsers/intersection.js
var init_intersection = __esm({
  "packages/core/node_modules/zod-to-json-schema/dist/esm/parsers/intersection.js"() {
    init_esbuild_shims();
    init_parseDef();
  }
});

// packages/core/node_modules/zod-to-json-schema/dist/esm/parsers/literal.js
var init_literal = __esm({
  "packages/core/node_modules/zod-to-json-schema/dist/esm/parsers/literal.js"() {
    init_esbuild_shims();
  }
});

// packages/core/node_modules/zod-to-json-schema/dist/esm/parsers/string.js
var ALPHA_NUMERIC;
var init_string = __esm({
  "packages/core/node_modules/zod-to-json-schema/dist/esm/parsers/string.js"() {
    init_esbuild_shims();
    init_errorMessages();
    ALPHA_NUMERIC = new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");
  }
});

// packages/core/node_modules/zod-to-json-schema/dist/esm/parsers/record.js
var init_record = __esm({
  "packages/core/node_modules/zod-to-json-schema/dist/esm/parsers/record.js"() {
    init_esbuild_shims();
    init_parseDef();
    init_string();
    init_branded();
    init_any();
  }
});

// packages/core/node_modules/zod-to-json-schema/dist/esm/parsers/map.js
var init_map = __esm({
  "packages/core/node_modules/zod-to-json-schema/dist/esm/parsers/map.js"() {
    init_esbuild_shims();
    init_parseDef();
    init_record();
    init_any();
  }
});

// packages/core/node_modules/zod-to-json-schema/dist/esm/parsers/nativeEnum.js
var init_nativeEnum = __esm({
  "packages/core/node_modules/zod-to-json-schema/dist/esm/parsers/nativeEnum.js"() {
    init_esbuild_shims();
  }
});

// packages/core/node_modules/zod-to-json-schema/dist/esm/parsers/never.js
var init_never = __esm({
  "packages/core/node_modules/zod-to-json-schema/dist/esm/parsers/never.js"() {
    init_esbuild_shims();
    init_any();
  }
});

// packages/core/node_modules/zod-to-json-schema/dist/esm/parsers/null.js
var init_null = __esm({
  "packages/core/node_modules/zod-to-json-schema/dist/esm/parsers/null.js"() {
    init_esbuild_shims();
  }
});

// packages/core/node_modules/zod-to-json-schema/dist/esm/parsers/union.js
var init_union = __esm({
  "packages/core/node_modules/zod-to-json-schema/dist/esm/parsers/union.js"() {
    init_esbuild_shims();
    init_parseDef();
  }
});

// packages/core/node_modules/zod-to-json-schema/dist/esm/parsers/nullable.js
var init_nullable = __esm({
  "packages/core/node_modules/zod-to-json-schema/dist/esm/parsers/nullable.js"() {
    init_esbuild_shims();
    init_parseDef();
    init_union();
  }
});

// packages/core/node_modules/zod-to-json-schema/dist/esm/parsers/number.js
var init_number = __esm({
  "packages/core/node_modules/zod-to-json-schema/dist/esm/parsers/number.js"() {
    init_esbuild_shims();
    init_errorMessages();
  }
});

// packages/core/node_modules/zod-to-json-schema/dist/esm/parsers/object.js
var init_object = __esm({
  "packages/core/node_modules/zod-to-json-schema/dist/esm/parsers/object.js"() {
    init_esbuild_shims();
    init_parseDef();
  }
});

// packages/core/node_modules/zod-to-json-schema/dist/esm/parsers/optional.js
var init_optional = __esm({
  "packages/core/node_modules/zod-to-json-schema/dist/esm/parsers/optional.js"() {
    init_esbuild_shims();
    init_parseDef();
    init_any();
  }
});

// packages/core/node_modules/zod-to-json-schema/dist/esm/parsers/pipeline.js
var init_pipeline2 = __esm({
  "packages/core/node_modules/zod-to-json-schema/dist/esm/parsers/pipeline.js"() {
    init_esbuild_shims();
    init_parseDef();
  }
});

// packages/core/node_modules/zod-to-json-schema/dist/esm/parsers/promise.js
var init_promise = __esm({
  "packages/core/node_modules/zod-to-json-schema/dist/esm/parsers/promise.js"() {
    init_esbuild_shims();
    init_parseDef();
  }
});

// packages/core/node_modules/zod-to-json-schema/dist/esm/parsers/set.js
var init_set = __esm({
  "packages/core/node_modules/zod-to-json-schema/dist/esm/parsers/set.js"() {
    init_esbuild_shims();
    init_errorMessages();
    init_parseDef();
  }
});

// packages/core/node_modules/zod-to-json-schema/dist/esm/parsers/tuple.js
var init_tuple = __esm({
  "packages/core/node_modules/zod-to-json-schema/dist/esm/parsers/tuple.js"() {
    init_esbuild_shims();
    init_parseDef();
  }
});

// packages/core/node_modules/zod-to-json-schema/dist/esm/parsers/undefined.js
var init_undefined = __esm({
  "packages/core/node_modules/zod-to-json-schema/dist/esm/parsers/undefined.js"() {
    init_esbuild_shims();
    init_any();
  }
});

// packages/core/node_modules/zod-to-json-schema/dist/esm/parsers/unknown.js
var init_unknown = __esm({
  "packages/core/node_modules/zod-to-json-schema/dist/esm/parsers/unknown.js"() {
    init_esbuild_shims();
    init_any();
  }
});

// packages/core/node_modules/zod-to-json-schema/dist/esm/parsers/readonly.js
var init_readonly = __esm({
  "packages/core/node_modules/zod-to-json-schema/dist/esm/parsers/readonly.js"() {
    init_esbuild_shims();
    init_parseDef();
  }
});

// packages/core/node_modules/zod-to-json-schema/dist/esm/selectParser.js
var init_selectParser = __esm({
  "packages/core/node_modules/zod-to-json-schema/dist/esm/selectParser.js"() {
    init_esbuild_shims();
    init_any();
    init_array();
    init_bigint();
    init_boolean();
    init_branded();
    init_catch();
    init_date();
    init_default2();
    init_effects();
    init_enum();
    init_intersection();
    init_literal();
    init_map();
    init_nativeEnum();
    init_never();
    init_null();
    init_nullable();
    init_number();
    init_object();
    init_optional();
    init_pipeline2();
    init_promise();
    init_record();
    init_set();
    init_string();
    init_tuple();
    init_undefined();
    init_union();
    init_unknown();
    init_readonly();
  }
});

// packages/core/node_modules/zod-to-json-schema/dist/esm/parseDef.js
var init_parseDef = __esm({
  "packages/core/node_modules/zod-to-json-schema/dist/esm/parseDef.js"() {
    init_esbuild_shims();
    init_Options();
    init_selectParser();
    init_getRelativePath();
    init_any();
  }
});

// packages/core/node_modules/zod-to-json-schema/dist/esm/parseTypes.js
var init_parseTypes = __esm({
  "packages/core/node_modules/zod-to-json-schema/dist/esm/parseTypes.js"() {
    init_esbuild_shims();
  }
});

// packages/core/node_modules/zod-to-json-schema/dist/esm/zodToJsonSchema.js
var init_zodToJsonSchema = __esm({
  "packages/core/node_modules/zod-to-json-schema/dist/esm/zodToJsonSchema.js"() {
    init_esbuild_shims();
    init_parseDef();
    init_Refs();
    init_any();
  }
});

// packages/core/node_modules/zod-to-json-schema/dist/esm/index.js
var init_esm13 = __esm({
  "packages/core/node_modules/zod-to-json-schema/dist/esm/index.js"() {
    init_esbuild_shims();
    init_Options();
    init_Refs();
    init_errorMessages();
    init_getRelativePath();
    init_parseDef();
    init_parseTypes();
    init_any();
    init_array();
    init_bigint();
    init_boolean();
    init_branded();
    init_catch();
    init_date();
    init_default2();
    init_effects();
    init_enum();
    init_intersection();
    init_literal();
    init_map();
    init_nativeEnum();
    init_never();
    init_null();
    init_nullable();
    init_number();
    init_object();
    init_optional();
    init_pipeline2();
    init_promise();
    init_readonly();
    init_record();
    init_set();
    init_string();
    init_tuple();
    init_undefined();
    init_union();
    init_unknown();
    init_selectParser();
    init_zodToJsonSchema();
    init_zodToJsonSchema();
  }
});

// packages/core/node_modules/@modelcontextprotocol/sdk/dist/esm/server/zod-json-schema-compat.js
function getMethodLiteral(schema) {
  const shape = getObjectShape(schema);
  const methodSchema = shape?.method;
  if (!methodSchema) {
    throw new Error("Schema is missing a method literal");
  }
  const value = getLiteralValue(methodSchema);
  if (typeof value !== "string") {
    throw new Error("Schema method literal must be a string");
  }
  return value;
}
function parseWithCompat(schema, data) {
  const result = safeParse2(schema, data);
  if (!result.success) {
    throw result.error;
  }
  return result.data;
}
var init_zod_json_schema_compat = __esm({
  "packages/core/node_modules/@modelcontextprotocol/sdk/dist/esm/server/zod-json-schema-compat.js"() {
    init_esbuild_shims();
    init_zod_compat();
    init_esm13();
    __name(getMethodLiteral, "getMethodLiteral");
    __name(parseWithCompat, "parseWithCompat");
  }
});

// packages/core/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/protocol.js
function isPlainObject4(value) {
  return value !== null && typeof value === "object" && !Array.isArray(value);
}
function mergeCapabilities(base, additional) {
  const result = { ...base };
  for (const key in additional) {
    const k2 = key;
    const addValue = additional[k2];
    if (addValue === void 0)
      continue;
    const baseValue = result[k2];
    if (isPlainObject4(baseValue) && isPlainObject4(addValue)) {
      result[k2] = { ...baseValue, ...addValue };
    } else {
      result[k2] = addValue;
    }
  }
  return result;
}
var DEFAULT_REQUEST_TIMEOUT_MSEC, Protocol;
var init_protocol = __esm({
  "packages/core/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/protocol.js"() {
    init_esbuild_shims();
    init_zod_compat();
    init_types8();
    init_interfaces();
    init_zod_json_schema_compat();
    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._pendingDebouncedNotifications = /* @__PURE__ */ new Set();
        this._taskProgressTokens = /* @__PURE__ */ new Map();
        this._requestResolvers = /* @__PURE__ */ new Map();
        this.setNotificationHandler(CancelledNotificationSchema, (notification) => {
          this._oncancel(notification);
        });
        this.setNotificationHandler(ProgressNotificationSchema, (notification) => {
          this._onprogress(notification);
        });
        this.setRequestHandler(
          PingRequestSchema,
          // Automatic pong by default.
          (_request) => ({})
        );
        this._taskStore = _options?.taskStore;
        this._taskMessageQueue = _options?.taskMessageQueue;
        if (this._taskStore) {
          this.setRequestHandler(GetTaskRequestSchema, async (request4, extra) => {
            const task = await this._taskStore.getTask(request4.params.taskId, extra.sessionId);
            if (!task) {
              throw new McpError(ErrorCode.InvalidParams, "Failed to retrieve task: Task not found");
            }
            return {
              ...task
            };
          });
          this.setRequestHandler(GetTaskPayloadRequestSchema, async (request4, extra) => {
            const handleTaskResult = /* @__PURE__ */ __name(async () => {
              const taskId = request4.params.taskId;
              if (this._taskMessageQueue) {
                let queuedMessage;
                while (queuedMessage = await this._taskMessageQueue.dequeue(taskId, extra.sessionId)) {
                  if (queuedMessage.type === "response" || queuedMessage.type === "error") {
                    const message = queuedMessage.message;
                    const requestId = message.id;
                    const resolver = this._requestResolvers.get(requestId);
                    if (resolver) {
                      this._requestResolvers.delete(requestId);
                      if (queuedMessage.type === "response") {
                        resolver(message);
                      } else {
                        const errorMessage = message;
                        const error2 = new McpError(errorMessage.error.code, errorMessage.error.message, errorMessage.error.data);
                        resolver(error2);
                      }
                    } else {
                      const messageType = queuedMessage.type === "response" ? "Response" : "Error";
                      this._onerror(new Error(`${messageType} handler missing for request ${requestId}`));
                    }
                    continue;
                  }
                  await this._transport?.send(queuedMessage.message, { relatedRequestId: extra.requestId });
                }
              }
              const task = await this._taskStore.getTask(taskId, extra.sessionId);
              if (!task) {
                throw new McpError(ErrorCode.InvalidParams, `Task not found: ${taskId}`);
              }
              if (!isTerminal(task.status)) {
                await this._waitForTaskUpdate(taskId, extra.signal);
                return await handleTaskResult();
              }
              if (isTerminal(task.status)) {
                const result = await this._taskStore.getTaskResult(taskId, extra.sessionId);
                this._clearTaskQueue(taskId);
                return {
                  ...result,
                  _meta: {
                    ...result._meta,
                    [RELATED_TASK_META_KEY]: {
                      taskId
                    }
                  }
                };
              }
              return await handleTaskResult();
            }, "handleTaskResult");
            return await handleTaskResult();
          });
          this.setRequestHandler(ListTasksRequestSchema, async (request4, extra) => {
            try {
              const { tasks, nextCursor } = await this._taskStore.listTasks(request4.params?.cursor, extra.sessionId);
              return {
                tasks,
                nextCursor,
                _meta: {}
              };
            } catch (error2) {
              throw new McpError(ErrorCode.InvalidParams, `Failed to list tasks: ${error2 instanceof Error ? error2.message : String(error2)}`);
            }
          });
          this.setRequestHandler(CancelTaskRequestSchema, async (request4, extra) => {
            try {
              const task = await this._taskStore.getTask(request4.params.taskId, extra.sessionId);
              if (!task) {
                throw new McpError(ErrorCode.InvalidParams, `Task not found: ${request4.params.taskId}`);
              }
              if (isTerminal(task.status)) {
                throw new McpError(ErrorCode.InvalidParams, `Cannot cancel task in terminal status: ${task.status}`);
              }
              await this._taskStore.updateTaskStatus(request4.params.taskId, "cancelled", "Client cancelled task execution.", extra.sessionId);
              this._clearTaskQueue(request4.params.taskId);
              const cancelledTask = await this._taskStore.getTask(request4.params.taskId, extra.sessionId);
              if (!cancelledTask) {
                throw new McpError(ErrorCode.InvalidParams, `Task not found after cancellation: ${request4.params.taskId}`);
              }
              return {
                _meta: {},
                ...cancelledTask
              };
            } catch (error2) {
              if (error2 instanceof McpError) {
                throw error2;
              }
              throw new McpError(ErrorCode.InvalidRequest, `Failed to cancel task: ${error2 instanceof Error ? error2.message : String(error2)}`);
            }
          });
        }
      }
      async _oncancel(notification) {
        if (!notification.params.requestId) {
          return;
        }
        const controller = this._requestHandlerAbortControllers.get(notification.params.requestId);
        controller?.abort(notification.params.reason);
      }
      _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 McpError.fromError(ErrorCode.RequestTimeout, "Maximum total timeout exceeded", {
            maxTotalTimeout: info.maxTotalTimeout,
            totalElapsed
          });
        }
        clearTimeout(info.timeoutId);
        info.timeoutId = setTimeout(info.onTimeout, info.timeout);
        return true;
      }
      _cleanupTimeout(messageId) {
        const info = this._timeoutInfo.get(messageId);
        if (info) {
          clearTimeout(info.timeoutId);
          this._timeoutInfo.delete(messageId);
        }
      }
      /**
       * Attaches to the given transport, starts it, and starts listening for messages.
       *
       * The Protocol object assumes ownership of the Transport, replacing any callbacks that have already been set, and expects that it is the only user of the Transport instance going forward.
       */
      async connect(transport) {
        this._transport = transport;
        const _onclose = this.transport?.onclose;
        this._transport.onclose = () => {
          _onclose?.();
          this._onclose();
        };
        const _onerror2 = this.transport?.onerror;
        this._transport.onerror = (error2) => {
          _onerror2?.(error2);
          this._onerror(error2);
        };
        const _onmessage = this._transport?.onmessage;
        this._transport.onmessage = (message, extra) => {
          _onmessage?.(message, extra);
          if (isJSONRPCResultResponse(message) || isJSONRPCErrorResponse(message)) {
            this._onresponse(message);
          } else if (isJSONRPCRequest(message)) {
            this._onrequest(message, extra);
          } else if (isJSONRPCNotification(message)) {
            this._onnotification(message);
          } else {
            this._onerror(new Error(`Unknown message type: ${JSON.stringify(message)}`));
          }
        };
        await this._transport.start();
      }
      _onclose() {
        const responseHandlers = this._responseHandlers;
        this._responseHandlers = /* @__PURE__ */ new Map();
        this._progressHandlers.clear();
        this._taskProgressTokens.clear();
        this._pendingDebouncedNotifications.clear();
        const error2 = McpError.fromError(ErrorCode.ConnectionClosed, "Connection closed");
        this._transport = void 0;
        this.onclose?.();
        for (const handler of responseHandlers.values()) {
          handler(error2);
        }
      }
      _onerror(error2) {
        this.onerror?.(error2);
      }
      _onnotification(notification) {
        const handler = this._notificationHandlers.get(notification.method) ?? this.fallbackNotificationHandler;
        if (handler === void 0) {
          return;
        }
        Promise.resolve().then(() => handler(notification)).catch((error2) => this._onerror(new Error(`Uncaught error in notification handler: ${error2}`)));
      }
      _onrequest(request4, extra) {
        const handler = this._requestHandlers.get(request4.method) ?? this.fallbackRequestHandler;
        const capturedTransport = this._transport;
        const relatedTaskId = request4.params?._meta?.[RELATED_TASK_META_KEY]?.taskId;
        if (handler === void 0) {
          const errorResponse = {
            jsonrpc: "2.0",
            id: request4.id,
            error: {
              code: ErrorCode.MethodNotFound,
              message: "Method not found"
            }
          };
          if (relatedTaskId && this._taskMessageQueue) {
            this._enqueueTaskMessage(relatedTaskId, {
              type: "error",
              message: errorResponse,
              timestamp: Date.now()
            }, capturedTransport?.sessionId).catch((error2) => this._onerror(new Error(`Failed to enqueue error response: ${error2}`)));
          } else {
            capturedTransport?.send(errorResponse).catch((error2) => this._onerror(new Error(`Failed to send an error response: ${error2}`)));
          }
          return;
        }
        const abortController = new AbortController();
        this._requestHandlerAbortControllers.set(request4.id, abortController);
        const taskCreationParams = isTaskAugmentedRequestParams(request4.params) ? request4.params.task : void 0;
        const taskStore = this._taskStore ? this.requestTaskStore(request4, capturedTransport?.sessionId) : void 0;
        const fullExtra = {
          signal: abortController.signal,
          sessionId: capturedTransport?.sessionId,
          _meta: request4.params?._meta,
          sendNotification: /* @__PURE__ */ __name(async (notification) => {
            const notificationOptions = { relatedRequestId: request4.id };
            if (relatedTaskId) {
              notificationOptions.relatedTask = { taskId: relatedTaskId };
            }
            await this.notification(notification, notificationOptions);
          }, "sendNotification"),
          sendRequest: /* @__PURE__ */ __name(async (r5, resultSchema, options2) => {
            const requestOptions = { ...options2, relatedRequestId: request4.id };
            if (relatedTaskId && !requestOptions.relatedTask) {
              requestOptions.relatedTask = { taskId: relatedTaskId };
            }
            const effectiveTaskId = requestOptions.relatedTask?.taskId ?? relatedTaskId;
            if (effectiveTaskId && taskStore) {
              await taskStore.updateTaskStatus(effectiveTaskId, "input_required");
            }
            return await this.request(r5, resultSchema, requestOptions);
          }, "sendRequest"),
          authInfo: extra?.authInfo,
          requestId: request4.id,
          requestInfo: extra?.requestInfo,
          taskId: relatedTaskId,
          taskStore,
          taskRequestedTtl: taskCreationParams?.ttl,
          closeSSEStream: extra?.closeSSEStream,
          closeStandaloneSSEStream: extra?.closeStandaloneSSEStream
        };
        Promise.resolve().then(() => {
          if (taskCreationParams) {
            this.assertTaskHandlerCapability(request4.method);
          }
        }).then(() => handler(request4, fullExtra)).then(async (result) => {
          if (abortController.signal.aborted) {
            return;
          }
          const response = {
            result,
            jsonrpc: "2.0",
            id: request4.id
          };
          if (relatedTaskId && this._taskMessageQueue) {
            await this._enqueueTaskMessage(relatedTaskId, {
              type: "response",
              message: response,
              timestamp: Date.now()
            }, capturedTransport?.sessionId);
          } else {
            await capturedTransport?.send(response);
          }
        }, async (error2) => {
          if (abortController.signal.aborted) {
            return;
          }
          const errorResponse = {
            jsonrpc: "2.0",
            id: request4.id,
            error: {
              code: Number.isSafeInteger(error2["code"]) ? error2["code"] : ErrorCode.InternalError,
              message: error2.message ?? "Internal error",
              ...error2["data"] !== void 0 && { data: error2["data"] }
            }
          };
          if (relatedTaskId && this._taskMessageQueue) {
            await this._enqueueTaskMessage(relatedTaskId, {
              type: "error",
              message: errorResponse,
              timestamp: Date.now()
            }, capturedTransport?.sessionId);
          } else {
            await capturedTransport?.send(errorResponse);
          }
        }).catch((error2) => this._onerror(new Error(`Failed to send response: ${error2}`))).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 (error2) {
            this._responseHandlers.delete(messageId);
            this._progressHandlers.delete(messageId);
            this._cleanupTimeout(messageId);
            responseHandler(error2);
            return;
          }
        }
        handler(params);
      }
      _onresponse(response) {
        const messageId = Number(response.id);
        const resolver = this._requestResolvers.get(messageId);
        if (resolver) {
          this._requestResolvers.delete(messageId);
          if (isJSONRPCResultResponse(response)) {
            resolver(response);
          } else {
            const error2 = new McpError(response.error.code, response.error.message, response.error.data);
            resolver(error2);
          }
          return;
        }
        const handler = this._responseHandlers.get(messageId);
        if (handler === void 0) {
          this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(response)}`));
          return;
        }
        this._responseHandlers.delete(messageId);
        this._cleanupTimeout(messageId);
        let isTaskResponse = false;
        if (isJSONRPCResultResponse(response) && response.result && typeof response.result === "object") {
          const result = response.result;
          if (result.task && typeof result.task === "object") {
            const task = result.task;
            if (typeof task.taskId === "string") {
              isTaskResponse = true;
              this._taskProgressTokens.set(task.taskId, messageId);
            }
          }
        }
        if (!isTaskResponse) {
          this._progressHandlers.delete(messageId);
        }
        if (isJSONRPCResultResponse(response)) {
          handler(response);
        } else {
          const error2 = McpError.fromError(response.error.code, response.error.message, response.error.data);
          handler(error2);
        }
      }
      get transport() {
        return this._transport;
      }
      /**
       * Closes the connection.
       */
      async close() {
        await this._transport?.close();
      }
      /**
       * Sends a request and returns an AsyncGenerator that yields response messages.
       * The generator is guaranteed to end with either a 'result' or 'error' message.
       *
       * @example
       * ```typescript
       * const stream = protocol.requestStream(request, resultSchema, options);
       * for await (const message of stream) {
       *   switch (message.type) {
       *     case 'taskCreated':
       *       console.log('Task created:', message.task.taskId);
       *       break;
       *     case 'taskStatus':
       *       console.log('Task status:', message.task.status);
       *       break;
       *     case 'result':
       *       console.log('Final result:', message.result);
       *       break;
       *     case 'error':
       *       console.error('Error:', message.error);
       *       break;
       *   }
       * }
       * ```
       *
       * @experimental Use `client.experimental.tasks.requestStream()` to access this method.
       */
      async *requestStream(request4, resultSchema, options2) {
        const { task } = options2 ?? {};
        if (!task) {
          try {
            const result = await this.request(request4, resultSchema, options2);
            yield { type: "result", result };
          } catch (error2) {
            yield {
              type: "error",
              error: error2 instanceof McpError ? error2 : new McpError(ErrorCode.InternalError, String(error2))
            };
          }
          return;
        }
        let taskId;
        try {
          const createResult = await this.request(request4, CreateTaskResultSchema, options2);
          if (createResult.task) {
            taskId = createResult.task.taskId;
            yield { type: "taskCreated", task: createResult.task };
          } else {
            throw new McpError(ErrorCode.InternalError, "Task creation did not return a task");
          }
          while (true) {
            const task2 = await this.getTask({ taskId }, options2);
            yield { type: "taskStatus", task: task2 };
            if (isTerminal(task2.status)) {
              if (task2.status === "completed") {
                const result = await this.getTaskResult({ taskId }, resultSchema, options2);
                yield { type: "result", result };
              } else if (task2.status === "failed") {
                yield {
                  type: "error",
                  error: new McpError(ErrorCode.InternalError, `Task ${taskId} failed`)
                };
              } else if (task2.status === "cancelled") {
                yield {
                  type: "error",
                  error: new McpError(ErrorCode.InternalError, `Task ${taskId} was cancelled`)
                };
              }
              return;
            }
            if (task2.status === "input_required") {
              const result = await this.getTaskResult({ taskId }, resultSchema, options2);
              yield { type: "result", result };
              return;
            }
            const pollInterval = task2.pollInterval ?? this._options?.defaultTaskPollInterval ?? 1e3;
            await new Promise((resolve30) => setTimeout(resolve30, pollInterval));
            options2?.signal?.throwIfAborted();
          }
        } catch (error2) {
          yield {
            type: "error",
            error: error2 instanceof McpError ? error2 : new McpError(ErrorCode.InternalError, String(error2))
          };
        }
      }
      /**
       * Sends a request and waits for a response.
       *
       * Do not use this method to emit notifications! Use notification() instead.
       */
      request(request4, resultSchema, options2) {
        const { relatedRequestId, resumptionToken, onresumptiontoken, task, relatedTask } = options2 ?? {};
        return new Promise((resolve30, reject) => {
          const earlyReject = /* @__PURE__ */ __name((error2) => {
            reject(error2);
          }, "earlyReject");
          if (!this._transport) {
            earlyReject(new Error("Not connected"));
            return;
          }
          if (this._options?.enforceStrictCapabilities === true) {
            try {
              this.assertCapabilityForMethod(request4.method);
              if (task) {
                this.assertTaskCapability(request4.method);
              }
            } catch (e4) {
              earlyReject(e4);
              return;
            }
          }
          options2?.signal?.throwIfAborted();
          const messageId = this._requestMessageId++;
          const jsonrpcRequest = {
            ...request4,
            jsonrpc: "2.0",
            id: messageId
          };
          if (options2?.onprogress) {
            this._progressHandlers.set(messageId, options2.onprogress);
            jsonrpcRequest.params = {
              ...request4.params,
              _meta: {
                ...request4.params?._meta || {},
                progressToken: messageId
              }
            };
          }
          if (task) {
            jsonrpcRequest.params = {
              ...jsonrpcRequest.params,
              task
            };
          }
          if (relatedTask) {
            jsonrpcRequest.params = {
              ...jsonrpcRequest.params,
              _meta: {
                ...jsonrpcRequest.params?._meta || {},
                [RELATED_TASK_META_KEY]: relatedTask
              }
            };
          }
          const cancel = /* @__PURE__ */ __name((reason) => {
            this._responseHandlers.delete(messageId);
            this._progressHandlers.delete(messageId);
            this._cleanupTimeout(messageId);
            this._transport?.send({
              jsonrpc: "2.0",
              method: "notifications/cancelled",
              params: {
                requestId: messageId,
                reason: String(reason)
              }
            }, { relatedRequestId, resumptionToken, onresumptiontoken }).catch((error3) => this._onerror(new Error(`Failed to send cancellation: ${error3}`)));
            const error2 = reason instanceof McpError ? reason : new McpError(ErrorCode.RequestTimeout, String(reason));
            reject(error2);
          }, "cancel");
          this._responseHandlers.set(messageId, (response) => {
            if (options2?.signal?.aborted) {
              return;
            }
            if (response instanceof Error) {
              return reject(response);
            }
            try {
              const parseResult = safeParse2(resultSchema, response.result);
              if (!parseResult.success) {
                reject(parseResult.error);
              } else {
                resolve30(parseResult.data);
              }
            } catch (error2) {
              reject(error2);
            }
          });
          options2?.signal?.addEventListener("abort", () => {
            cancel(options2?.signal?.reason);
          });
          const timeout2 = options2?.timeout ?? DEFAULT_REQUEST_TIMEOUT_MSEC;
          const timeoutHandler = /* @__PURE__ */ __name(() => cancel(McpError.fromError(ErrorCode.RequestTimeout, "Request timed out", { timeout: timeout2 })), "timeoutHandler");
          this._setupTimeout(messageId, timeout2, options2?.maxTotalTimeout, timeoutHandler, options2?.resetTimeoutOnProgress ?? false);
          const relatedTaskId = relatedTask?.taskId;
          if (relatedTaskId) {
            const responseResolver = /* @__PURE__ */ __name((response) => {
              const handler = this._responseHandlers.get(messageId);
              if (handler) {
                handler(response);
              } else {
                this._onerror(new Error(`Response handler missing for side-channeled request ${messageId}`));
              }
            }, "responseResolver");
            this._requestResolvers.set(messageId, responseResolver);
            this._enqueueTaskMessage(relatedTaskId, {
              type: "request",
              message: jsonrpcRequest,
              timestamp: Date.now()
            }).catch((error2) => {
              this._cleanupTimeout(messageId);
              reject(error2);
            });
          } else {
            this._transport.send(jsonrpcRequest, { relatedRequestId, resumptionToken, onresumptiontoken }).catch((error2) => {
              this._cleanupTimeout(messageId);
              reject(error2);
            });
          }
        });
      }
      /**
       * Gets the current status of a task.
       *
       * @experimental Use `client.experimental.tasks.getTask()` to access this method.
       */
      async getTask(params, options2) {
        return this.request({ method: "tasks/get", params }, GetTaskResultSchema, options2);
      }
      /**
       * Retrieves the result of a completed task.
       *
       * @experimental Use `client.experimental.tasks.getTaskResult()` to access this method.
       */
      async getTaskResult(params, resultSchema, options2) {
        return this.request({ method: "tasks/result", params }, resultSchema, options2);
      }
      /**
       * Lists tasks, optionally starting from a pagination cursor.
       *
       * @experimental Use `client.experimental.tasks.listTasks()` to access this method.
       */
      async listTasks(params, options2) {
        return this.request({ method: "tasks/list", params }, ListTasksResultSchema, options2);
      }
      /**
       * Cancels a specific task.
       *
       * @experimental Use `client.experimental.tasks.cancelTask()` to access this method.
       */
      async cancelTask(params, options2) {
        return this.request({ method: "tasks/cancel", params }, CancelTaskResultSchema, options2);
      }
      /**
       * 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 relatedTaskId = options2?.relatedTask?.taskId;
        if (relatedTaskId) {
          const jsonrpcNotification2 = {
            ...notification,
            jsonrpc: "2.0",
            params: {
              ...notification.params,
              _meta: {
                ...notification.params?._meta || {},
                [RELATED_TASK_META_KEY]: options2.relatedTask
              }
            }
          };
          await this._enqueueTaskMessage(relatedTaskId, {
            type: "notification",
            message: jsonrpcNotification2,
            timestamp: Date.now()
          });
          return;
        }
        const debouncedMethods = this._options?.debouncedNotificationMethods ?? [];
        const canDebounce = debouncedMethods.includes(notification.method) && !notification.params && !options2?.relatedRequestId && !options2?.relatedTask;
        if (canDebounce) {
          if (this._pendingDebouncedNotifications.has(notification.method)) {
            return;
          }
          this._pendingDebouncedNotifications.add(notification.method);
          Promise.resolve().then(() => {
            this._pendingDebouncedNotifications.delete(notification.method);
            if (!this._transport) {
              return;
            }
            let jsonrpcNotification2 = {
              ...notification,
              jsonrpc: "2.0"
            };
            if (options2?.relatedTask) {
              jsonrpcNotification2 = {
                ...jsonrpcNotification2,
                params: {
                  ...jsonrpcNotification2.params,
                  _meta: {
                    ...jsonrpcNotification2.params?._meta || {},
                    [RELATED_TASK_META_KEY]: options2.relatedTask
                  }
                }
              };
            }
            this._transport?.send(jsonrpcNotification2, options2).catch((error2) => this._onerror(error2));
          });
          return;
        }
        let jsonrpcNotification = {
          ...notification,
          jsonrpc: "2.0"
        };
        if (options2?.relatedTask) {
          jsonrpcNotification = {
            ...jsonrpcNotification,
            params: {
              ...jsonrpcNotification.params,
              _meta: {
                ...jsonrpcNotification.params?._meta || {},
                [RELATED_TASK_META_KEY]: options2.relatedTask
              }
            }
          };
        }
        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 = getMethodLiteral(requestSchema);
        this.assertRequestHandlerCapability(method);
        this._requestHandlers.set(method, (request4, extra) => {
          const parsed = parseWithCompat(requestSchema, request4);
          return Promise.resolve(handler(parsed, extra));
        });
      }
      /**
       * Removes the request handler for the given method.
       */
      removeRequestHandler(method) {
        this._requestHandlers.delete(method);
      }
      /**
       * Asserts that a request handler has not already been set for the given method, in preparation for a new one being automatically installed.
       */
      assertCanSetRequestHandler(method) {
        if (this._requestHandlers.has(method)) {
          throw new Error(`A request handler for ${method} already exists, which would be overridden`);
        }
      }
      /**
       * Registers a handler to invoke when this protocol object receives a notification with the given method.
       *
       * Note that this will replace any previous notification handler for the same method.
       */
      setNotificationHandler(notificationSchema, handler) {
        const method = getMethodLiteral(notificationSchema);
        this._notificationHandlers.set(method, (notification) => {
          const parsed = parseWithCompat(notificationSchema, notification);
          return Promise.resolve(handler(parsed));
        });
      }
      /**
       * Removes the notification handler for the given method.
       */
      removeNotificationHandler(method) {
        this._notificationHandlers.delete(method);
      }
      /**
       * Cleans up the progress handler associated with a task.
       * This should be called when a task reaches a terminal status.
       */
      _cleanupTaskProgressHandler(taskId) {
        const progressToken = this._taskProgressTokens.get(taskId);
        if (progressToken !== void 0) {
          this._progressHandlers.delete(progressToken);
          this._taskProgressTokens.delete(taskId);
        }
      }
      /**
       * Enqueues a task-related message for side-channel delivery via tasks/result.
       * @param taskId The task ID to associate the message with
       * @param message The message to enqueue
       * @param sessionId Optional session ID for binding the operation to a specific session
       * @throws Error if taskStore is not configured or if enqueue fails (e.g., queue overflow)
       *
       * Note: If enqueue fails, it's the TaskMessageQueue implementation's responsibility to handle
       * the error appropriately (e.g., by failing the task, logging, etc.). The Protocol layer
       * simply propagates the error.
       */
      async _enqueueTaskMessage(taskId, message, sessionId) {
        if (!this._taskStore || !this._taskMessageQueue) {
          throw new Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");
        }
        const maxQueueSize = this._options?.maxTaskQueueSize;
        await this._taskMessageQueue.enqueue(taskId, message, sessionId, maxQueueSize);
      }
      /**
       * Clears the message queue for a task and rejects any pending request resolvers.
       * @param taskId The task ID whose queue should be cleared
       * @param sessionId Optional session ID for binding the operation to a specific session
       */
      async _clearTaskQueue(taskId, sessionId) {
        if (this._taskMessageQueue) {
          const messages = await this._taskMessageQueue.dequeueAll(taskId, sessionId);
          for (const message of messages) {
            if (message.type === "request" && isJSONRPCRequest(message.message)) {
              const requestId = message.message.id;
              const resolver = this._requestResolvers.get(requestId);
              if (resolver) {
                resolver(new McpError(ErrorCode.InternalError, "Task cancelled or completed"));
                this._requestResolvers.delete(requestId);
              } else {
                this._onerror(new Error(`Resolver missing for request ${requestId} during task ${taskId} cleanup`));
              }
            }
          }
        }
      }
      /**
       * Waits for a task update (new messages or status change) with abort signal support.
       * Uses polling to check for updates at the task's configured poll interval.
       * @param taskId The task ID to wait for
       * @param signal Abort signal to cancel the wait
       * @returns Promise that resolves when an update occurs or rejects if aborted
       */
      async _waitForTaskUpdate(taskId, signal) {
        let interval = this._options?.defaultTaskPollInterval ?? 1e3;
        try {
          const task = await this._taskStore?.getTask(taskId);
          if (task?.pollInterval) {
            interval = task.pollInterval;
          }
        } catch {
        }
        return new Promise((resolve30, reject) => {
          if (signal.aborted) {
            reject(new McpError(ErrorCode.InvalidRequest, "Request cancelled"));
            return;
          }
          const timeoutId = setTimeout(resolve30, interval);
          signal.addEventListener("abort", () => {
            clearTimeout(timeoutId);
            reject(new McpError(ErrorCode.InvalidRequest, "Request cancelled"));
          }, { once: true });
        });
      }
      requestTaskStore(request4, sessionId) {
        const taskStore = this._taskStore;
        if (!taskStore) {
          throw new Error("No task store configured");
        }
        return {
          createTask: /* @__PURE__ */ __name(async (taskParams) => {
            if (!request4) {
              throw new Error("No request provided");
            }
            return await taskStore.createTask(taskParams, request4.id, {
              method: request4.method,
              params: request4.params
            }, sessionId);
          }, "createTask"),
          getTask: /* @__PURE__ */ __name(async (taskId) => {
            const task = await taskStore.getTask(taskId, sessionId);
            if (!task) {
              throw new McpError(ErrorCode.InvalidParams, "Failed to retrieve task: Task not found");
            }
            return task;
          }, "getTask"),
          storeTaskResult: /* @__PURE__ */ __name(async (taskId, status, result) => {
            await taskStore.storeTaskResult(taskId, status, result, sessionId);
            const task = await taskStore.getTask(taskId, sessionId);
            if (task) {
              const notification = TaskStatusNotificationSchema.parse({
                method: "notifications/tasks/status",
                params: task
              });
              await this.notification(notification);
              if (isTerminal(task.status)) {
                this._cleanupTaskProgressHandler(taskId);
              }
            }
          }, "storeTaskResult"),
          getTaskResult: /* @__PURE__ */ __name((taskId) => {
            return taskStore.getTaskResult(taskId, sessionId);
          }, "getTaskResult"),
          updateTaskStatus: /* @__PURE__ */ __name(async (taskId, status, statusMessage) => {
            const task = await taskStore.getTask(taskId, sessionId);
            if (!task) {
              throw new McpError(ErrorCode.InvalidParams, `Task "${taskId}" not found - it may have been cleaned up`);
            }
            if (isTerminal(task.status)) {
              throw new McpError(ErrorCode.InvalidParams, `Cannot update task "${taskId}" from terminal status "${task.status}" to "${status}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);
            }
            await taskStore.updateTaskStatus(taskId, status, statusMessage, sessionId);
            const updatedTask = await taskStore.getTask(taskId, sessionId);
            if (updatedTask) {
              const notification = TaskStatusNotificationSchema.parse({
                method: "notifications/tasks/status",
                params: updatedTask
              });
              await this.notification(notification);
              if (isTerminal(updatedTask.status)) {
                this._cleanupTaskProgressHandler(taskId);
              }
            }
          }, "updateTaskStatus"),
          listTasks: /* @__PURE__ */ __name((cursor) => {
            return taskStore.listTasks(cursor, sessionId);
          }, "listTasks")
        };
      }
    };
    __name(isPlainObject4, "isPlainObject");
    __name(mergeCapabilities, "mergeCapabilities");
  }
});

// packages/core/node_modules/@modelcontextprotocol/sdk/dist/esm/validation/ajv-provider.js
function createDefaultAjvInstance() {
  const ajv = new import_ajv2.default({
    strict: false,
    validateFormats: true,
    validateSchema: false,
    allErrors: true
  });
  const addFormats2 = import_ajv_formats.default;
  addFormats2(ajv);
  return ajv;
}
var import_ajv2, import_ajv_formats, AjvJsonSchemaValidator;
var init_ajv_provider = __esm({
  "packages/core/node_modules/@modelcontextprotocol/sdk/dist/esm/validation/ajv-provider.js"() {
    init_esbuild_shims();
    import_ajv2 = __toESM(require_ajv(), 1);
    import_ajv_formats = __toESM(require_dist3(), 1);
    __name(createDefaultAjvInstance, "createDefaultAjvInstance");
    AjvJsonSchemaValidator = class {
      static {
        __name(this, "AjvJsonSchemaValidator");
      }
      /**
       * Create an AJV validator
       *
       * @param ajv - Optional pre-configured AJV instance. If not provided, a default instance will be created.
       *
       * @example
       * ```typescript
       * // Use default configuration (recommended for most cases)
       * import { AjvJsonSchemaValidator } from '@modelcontextprotocol/sdk/validation/ajv';
       * const validator = new AjvJsonSchemaValidator();
       *
       * // Or provide custom AJV instance for advanced configuration
       * import { Ajv } from 'ajv';
       * import addFormats from 'ajv-formats';
       *
       * const ajv = new Ajv({ validateFormats: true });
       * addFormats(ajv);
       * const validator = new AjvJsonSchemaValidator(ajv);
       * ```
       */
      constructor(ajv) {
        this._ajv = ajv ?? createDefaultAjvInstance();
      }
      /**
       * Create a validator for the given JSON Schema
       *
       * The validator is compiled once and can be reused multiple times.
       * If the schema has an $id, it will be cached by AJV automatically.
       *
       * @param schema - Standard JSON Schema object
       * @returns A validator function that validates input data
       */
      getValidator(schema) {
        const ajvValidator = "$id" in schema && typeof schema.$id === "string" ? this._ajv.getSchema(schema.$id) ?? this._ajv.compile(schema) : this._ajv.compile(schema);
        return (input) => {
          const valid = ajvValidator(input);
          if (valid) {
            return {
              valid: true,
              data: input,
              errorMessage: void 0
            };
          } else {
            return {
              valid: false,
              data: void 0,
              errorMessage: this._ajv.errorsText(ajvValidator.errors)
            };
          }
        };
      }
    };
  }
});

// packages/core/node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/client.js
var ExperimentalClientTasks;
var init_client3 = __esm({
  "packages/core/node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/client.js"() {
    init_esbuild_shims();
    init_types8();
    ExperimentalClientTasks = class {
      static {
        __name(this, "ExperimentalClientTasks");
      }
      constructor(_client) {
        this._client = _client;
      }
      /**
       * Calls a tool and returns an AsyncGenerator that yields response messages.
       * The generator is guaranteed to end with either a 'result' or 'error' message.
       *
       * This method provides streaming access to tool execution, allowing you to
       * observe intermediate task status updates for long-running tool calls.
       * Automatically validates structured output if the tool has an outputSchema.
       *
       * @example
       * ```typescript
       * const stream = client.experimental.tasks.callToolStream({ name: 'myTool', arguments: {} });
       * for await (const message of stream) {
       *   switch (message.type) {
       *     case 'taskCreated':
       *       console.log('Tool execution started:', message.task.taskId);
       *       break;
       *     case 'taskStatus':
       *       console.log('Tool status:', message.task.status);
       *       break;
       *     case 'result':
       *       console.log('Tool result:', message.result);
       *       break;
       *     case 'error':
       *       console.error('Tool error:', message.error);
       *       break;
       *   }
       * }
       * ```
       *
       * @param params - Tool call parameters (name and arguments)
       * @param resultSchema - Zod schema for validating the result (defaults to CallToolResultSchema)
       * @param options - Optional request options (timeout, signal, task creation params, etc.)
       * @returns AsyncGenerator that yields ResponseMessage objects
       *
       * @experimental
       */
      async *callToolStream(params, resultSchema = CallToolResultSchema, options2) {
        const clientInternal = this._client;
        const optionsWithTask = {
          ...options2,
          // We check if the tool is known to be a task during auto-configuration, but assume
          // the caller knows what they're doing if they pass this explicitly
          task: options2?.task ?? (clientInternal.isToolTask(params.name) ? {} : void 0)
        };
        const stream2 = clientInternal.requestStream({ method: "tools/call", params }, resultSchema, optionsWithTask);
        const validator = clientInternal.getToolOutputValidator(params.name);
        for await (const message of stream2) {
          if (message.type === "result" && validator) {
            const result = message.result;
            if (!result.structuredContent && !result.isError) {
              yield {
                type: "error",
                error: new McpError(ErrorCode.InvalidRequest, `Tool ${params.name} has an output schema but did not return structured content`)
              };
              return;
            }
            if (result.structuredContent) {
              try {
                const validationResult = validator(result.structuredContent);
                if (!validationResult.valid) {
                  yield {
                    type: "error",
                    error: new McpError(ErrorCode.InvalidParams, `Structured content does not match the tool's output schema: ${validationResult.errorMessage}`)
                  };
                  return;
                }
              } catch (error2) {
                if (error2 instanceof McpError) {
                  yield { type: "error", error: error2 };
                  return;
                }
                yield {
                  type: "error",
                  error: new McpError(ErrorCode.InvalidParams, `Failed to validate structured content: ${error2 instanceof Error ? error2.message : String(error2)}`)
                };
                return;
              }
            }
          }
          yield message;
        }
      }
      /**
       * Gets the current status of a task.
       *
       * @param taskId - The task identifier
       * @param options - Optional request options
       * @returns The task status
       *
       * @experimental
       */
      async getTask(taskId, options2) {
        return this._client.getTask({ taskId }, options2);
      }
      /**
       * Retrieves the result of a completed task.
       *
       * @param taskId - The task identifier
       * @param resultSchema - Zod schema for validating the result
       * @param options - Optional request options
       * @returns The task result
       *
       * @experimental
       */
      async getTaskResult(taskId, resultSchema, options2) {
        return this._client.getTaskResult({ taskId }, resultSchema, options2);
      }
      /**
       * Lists tasks with optional pagination.
       *
       * @param cursor - Optional pagination cursor
       * @param options - Optional request options
       * @returns List of tasks with optional next cursor
       *
       * @experimental
       */
      async listTasks(cursor, options2) {
        return this._client.listTasks(cursor ? { cursor } : void 0, options2);
      }
      /**
       * Cancels a running task.
       *
       * @param taskId - The task identifier
       * @param options - Optional request options
       *
       * @experimental
       */
      async cancelTask(taskId, options2) {
        return this._client.cancelTask({ taskId }, options2);
      }
      /**
       * Sends a request and returns an AsyncGenerator that yields response messages.
       * The generator is guaranteed to end with either a 'result' or 'error' message.
       *
       * This method provides streaming access to request processing, allowing you to
       * observe intermediate task status updates for task-augmented requests.
       *
       * @param request - The request to send
       * @param resultSchema - Zod schema for validating the result
       * @param options - Optional request options (timeout, signal, task creation params, etc.)
       * @returns AsyncGenerator that yields ResponseMessage objects
       *
       * @experimental
       */
      requestStream(request4, resultSchema, options2) {
        return this._client.requestStream(request4, resultSchema, options2);
      }
    };
  }
});

// packages/core/node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/helpers.js
function assertToolsCallTaskCapability(requests, method, entityName) {
  if (!requests) {
    throw new Error(`${entityName} does not support task creation (required for ${method})`);
  }
  switch (method) {
    case "tools/call":
      if (!requests.tools?.call) {
        throw new Error(`${entityName} does not support task creation for tools/call (required for ${method})`);
      }
      break;
    default:
      break;
  }
}
function assertClientRequestTaskCapability(requests, method, entityName) {
  if (!requests) {
    throw new Error(`${entityName} does not support task creation (required for ${method})`);
  }
  switch (method) {
    case "sampling/createMessage":
      if (!requests.sampling?.createMessage) {
        throw new Error(`${entityName} does not support task creation for sampling/createMessage (required for ${method})`);
      }
      break;
    case "elicitation/create":
      if (!requests.elicitation?.create) {
        throw new Error(`${entityName} does not support task creation for elicitation/create (required for ${method})`);
      }
      break;
    default:
      break;
  }
}
var init_helpers = __esm({
  "packages/core/node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/helpers.js"() {
    init_esbuild_shims();
    __name(assertToolsCallTaskCapability, "assertToolsCallTaskCapability");
    __name(assertClientRequestTaskCapability, "assertClientRequestTaskCapability");
  }
});

// packages/core/node_modules/@modelcontextprotocol/sdk/dist/esm/client/index.js
function applyElicitationDefaults(schema, data) {
  if (!schema || data === null || typeof data !== "object")
    return;
  if (schema.type === "object" && schema.properties && typeof schema.properties === "object") {
    const obj = data;
    const props = schema.properties;
    for (const key of Object.keys(props)) {
      const propSchema = props[key];
      if (obj[key] === void 0 && Object.prototype.hasOwnProperty.call(propSchema, "default")) {
        obj[key] = propSchema.default;
      }
      if (obj[key] !== void 0) {
        applyElicitationDefaults(propSchema, obj[key]);
      }
    }
  }
  if (Array.isArray(schema.anyOf)) {
    for (const sub of schema.anyOf) {
      if (typeof sub !== "boolean") {
        applyElicitationDefaults(sub, data);
      }
    }
  }
  if (Array.isArray(schema.oneOf)) {
    for (const sub of schema.oneOf) {
      if (typeof sub !== "boolean") {
        applyElicitationDefaults(sub, data);
      }
    }
  }
}
function getSupportedElicitationModes(capabilities) {
  if (!capabilities) {
    return { supportsFormMode: false, supportsUrlMode: false };
  }
  const hasFormCapability = capabilities.form !== void 0;
  const hasUrlCapability = capabilities.url !== void 0;
  const supportsFormMode = hasFormCapability || !hasFormCapability && !hasUrlCapability;
  const supportsUrlMode = hasUrlCapability;
  return { supportsFormMode, supportsUrlMode };
}
var Client;
var init_client4 = __esm({
  "packages/core/node_modules/@modelcontextprotocol/sdk/dist/esm/client/index.js"() {
    init_esbuild_shims();
    init_protocol();
    init_types8();
    init_ajv_provider();
    init_zod_compat();
    init_client3();
    init_helpers();
    __name(applyElicitationDefaults, "applyElicitationDefaults");
    __name(getSupportedElicitationModes, "getSupportedElicitationModes");
    Client = class extends Protocol {
      static {
        __name(this, "Client");
      }
      /**
       * Initializes this client with the given name and version information.
       */
      constructor(_clientInfo, options2) {
        super(options2);
        this._clientInfo = _clientInfo;
        this._cachedToolOutputValidators = /* @__PURE__ */ new Map();
        this._cachedKnownTaskTools = /* @__PURE__ */ new Set();
        this._cachedRequiredTaskTools = /* @__PURE__ */ new Set();
        this._listChangedDebounceTimers = /* @__PURE__ */ new Map();
        this._capabilities = options2?.capabilities ?? {};
        this._jsonSchemaValidator = options2?.jsonSchemaValidator ?? new AjvJsonSchemaValidator();
        if (options2?.listChanged) {
          this._pendingListChangedConfig = options2.listChanged;
        }
      }
      /**
       * Set up handlers for list changed notifications based on config and server capabilities.
       * This should only be called after initialization when server capabilities are known.
       * Handlers are silently skipped if the server doesn't advertise the corresponding listChanged capability.
       * @internal
       */
      _setupListChangedHandlers(config2) {
        if (config2.tools && this._serverCapabilities?.tools?.listChanged) {
          this._setupListChangedHandler("tools", ToolListChangedNotificationSchema, config2.tools, async () => {
            const result = await this.listTools();
            return result.tools;
          });
        }
        if (config2.prompts && this._serverCapabilities?.prompts?.listChanged) {
          this._setupListChangedHandler("prompts", PromptListChangedNotificationSchema, config2.prompts, async () => {
            const result = await this.listPrompts();
            return result.prompts;
          });
        }
        if (config2.resources && this._serverCapabilities?.resources?.listChanged) {
          this._setupListChangedHandler("resources", ResourceListChangedNotificationSchema, config2.resources, async () => {
            const result = await this.listResources();
            return result.resources;
          });
        }
      }
      /**
       * Access experimental features.
       *
       * WARNING: These APIs are experimental and may change without notice.
       *
       * @experimental
       */
      get experimental() {
        if (!this._experimental) {
          this._experimental = {
            tasks: new ExperimentalClientTasks(this)
          };
        }
        return this._experimental;
      }
      /**
       * Registers new capabilities. This can only be called before connecting to a transport.
       *
       * The new capabilities will be merged with any existing capabilities previously given (e.g., at initialization).
       */
      registerCapabilities(capabilities) {
        if (this.transport) {
          throw new Error("Cannot register capabilities after connecting to transport");
        }
        this._capabilities = mergeCapabilities(this._capabilities, capabilities);
      }
      /**
       * Override request handler registration to enforce client-side validation for elicitation.
       */
      setRequestHandler(requestSchema, handler) {
        const shape = getObjectShape(requestSchema);
        const methodSchema = shape?.method;
        if (!methodSchema) {
          throw new Error("Schema is missing a method literal");
        }
        let methodValue;
        if (isZ4Schema(methodSchema)) {
          const v4Schema = methodSchema;
          const v4Def = v4Schema._zod?.def;
          methodValue = v4Def?.value ?? v4Schema.value;
        } else {
          const v3Schema = methodSchema;
          const legacyDef = v3Schema._def;
          methodValue = legacyDef?.value ?? v3Schema.value;
        }
        if (typeof methodValue !== "string") {
          throw new Error("Schema method literal must be a string");
        }
        const method = methodValue;
        if (method === "elicitation/create") {
          const wrappedHandler = /* @__PURE__ */ __name(async (request4, extra) => {
            const validatedRequest = safeParse2(ElicitRequestSchema, request4);
            if (!validatedRequest.success) {
              const errorMessage = validatedRequest.error instanceof Error ? validatedRequest.error.message : String(validatedRequest.error);
              throw new McpError(ErrorCode.InvalidParams, `Invalid elicitation request: ${errorMessage}`);
            }
            const { params } = validatedRequest.data;
            params.mode = params.mode ?? "form";
            const { supportsFormMode, supportsUrlMode } = getSupportedElicitationModes(this._capabilities.elicitation);
            if (params.mode === "form" && !supportsFormMode) {
              throw new McpError(ErrorCode.InvalidParams, "Client does not support form-mode elicitation requests");
            }
            if (params.mode === "url" && !supportsUrlMode) {
              throw new McpError(ErrorCode.InvalidParams, "Client does not support URL-mode elicitation requests");
            }
            const result = await Promise.resolve(handler(request4, extra));
            if (params.task) {
              const taskValidationResult = safeParse2(CreateTaskResultSchema, result);
              if (!taskValidationResult.success) {
                const errorMessage = taskValidationResult.error instanceof Error ? taskValidationResult.error.message : String(taskValidationResult.error);
                throw new McpError(ErrorCode.InvalidParams, `Invalid task creation result: ${errorMessage}`);
              }
              return taskValidationResult.data;
            }
            const validationResult = safeParse2(ElicitResultSchema, result);
            if (!validationResult.success) {
              const errorMessage = validationResult.error instanceof Error ? validationResult.error.message : String(validationResult.error);
              throw new McpError(ErrorCode.InvalidParams, `Invalid elicitation result: ${errorMessage}`);
            }
            const validatedResult = validationResult.data;
            const requestedSchema = params.mode === "form" ? params.requestedSchema : void 0;
            if (params.mode === "form" && validatedResult.action === "accept" && validatedResult.content && requestedSchema) {
              if (this._capabilities.elicitation?.form?.applyDefaults) {
                try {
                  applyElicitationDefaults(requestedSchema, validatedResult.content);
                } catch {
                }
              }
            }
            return validatedResult;
          }, "wrappedHandler");
          return super.setRequestHandler(requestSchema, wrappedHandler);
        }
        if (method === "sampling/createMessage") {
          const wrappedHandler = /* @__PURE__ */ __name(async (request4, extra) => {
            const validatedRequest = safeParse2(CreateMessageRequestSchema, request4);
            if (!validatedRequest.success) {
              const errorMessage = validatedRequest.error instanceof Error ? validatedRequest.error.message : String(validatedRequest.error);
              throw new McpError(ErrorCode.InvalidParams, `Invalid sampling request: ${errorMessage}`);
            }
            const { params } = validatedRequest.data;
            const result = await Promise.resolve(handler(request4, extra));
            if (params.task) {
              const taskValidationResult = safeParse2(CreateTaskResultSchema, result);
              if (!taskValidationResult.success) {
                const errorMessage = taskValidationResult.error instanceof Error ? taskValidationResult.error.message : String(taskValidationResult.error);
                throw new McpError(ErrorCode.InvalidParams, `Invalid task creation result: ${errorMessage}`);
              }
              return taskValidationResult.data;
            }
            const validationResult = safeParse2(CreateMessageResultSchema, result);
            if (!validationResult.success) {
              const errorMessage = validationResult.error instanceof Error ? validationResult.error.message : String(validationResult.error);
              throw new McpError(ErrorCode.InvalidParams, `Invalid sampling result: ${errorMessage}`);
            }
            return validationResult.data;
          }, "wrappedHandler");
          return super.setRequestHandler(requestSchema, wrappedHandler);
        }
        return super.setRequestHandler(requestSchema, handler);
      }
      assertCapability(capability, method) {
        if (!this._serverCapabilities?.[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"
          });
          if (this._pendingListChangedConfig) {
            this._setupListChangedHandlers(this._pendingListChangedConfig);
            this._pendingListChangedConfig = void 0;
          }
        } catch (error2) {
          void this.close();
          throw error2;
        }
      }
      /**
       * 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) {
        switch (method) {
          case "logging/setLevel":
            if (!this._serverCapabilities?.logging) {
              throw new Error(`Server does not support logging (required for ${method})`);
            }
            break;
          case "prompts/get":
          case "prompts/list":
            if (!this._serverCapabilities?.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 (!this._serverCapabilities?.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 (!this._serverCapabilities?.tools) {
              throw new Error(`Server does not support tools (required for ${method})`);
            }
            break;
          case "completion/complete":
            if (!this._serverCapabilities?.completions) {
              throw new Error(`Server does not support completions (required for ${method})`);
            }
            break;
          case "initialize":
            break;
          case "ping":
            break;
        }
      }
      assertNotificationCapability(method) {
        switch (method) {
          case "notifications/roots/list_changed":
            if (!this._capabilities.roots?.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) {
        if (!this._capabilities) {
          return;
        }
        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 "tasks/get":
          case "tasks/list":
          case "tasks/result":
          case "tasks/cancel":
            if (!this._capabilities.tasks) {
              throw new Error(`Client does not support tasks capability (required for ${method})`);
            }
            break;
          case "ping":
            break;
        }
      }
      assertTaskCapability(method) {
        assertToolsCallTaskCapability(this._serverCapabilities?.tasks?.requests, method, "Server");
      }
      assertTaskHandlerCapability(method) {
        if (!this._capabilities) {
          return;
        }
        assertClientRequestTaskCapability(this._capabilities.tasks?.requests, method, "Client");
      }
      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);
      }
      /**
       * Calls a tool and waits for the result. Automatically validates structured output if the tool has an outputSchema.
       *
       * For task-based execution with streaming behavior, use client.experimental.tasks.callToolStream() instead.
       */
      async callTool(params, resultSchema = CallToolResultSchema, options2) {
        if (this.isToolTaskRequired(params.name)) {
          throw new McpError(ErrorCode.InvalidRequest, `Tool "${params.name}" requires task-based execution. Use client.experimental.tasks.callToolStream() instead.`);
        }
        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 validationResult = validator(result.structuredContent);
              if (!validationResult.valid) {
                throw new McpError(ErrorCode.InvalidParams, `Structured content does not match the tool's output schema: ${validationResult.errorMessage}`);
              }
            } catch (error2) {
              if (error2 instanceof McpError) {
                throw error2;
              }
              throw new McpError(ErrorCode.InvalidParams, `Failed to validate structured content: ${error2 instanceof Error ? error2.message : String(error2)}`);
            }
          }
        }
        return result;
      }
      isToolTask(toolName) {
        if (!this._serverCapabilities?.tasks?.requests?.tools?.call) {
          return false;
        }
        return this._cachedKnownTaskTools.has(toolName);
      }
      /**
       * Check if a tool requires task-based execution.
       * Unlike isToolTask which includes 'optional' tools, this only checks for 'required'.
       */
      isToolTaskRequired(toolName) {
        return this._cachedRequiredTaskTools.has(toolName);
      }
      /**
       * Cache validators for tool output schemas.
       * Called after listTools() to pre-compile validators for better performance.
       */
      cacheToolMetadata(tools) {
        this._cachedToolOutputValidators.clear();
        this._cachedKnownTaskTools.clear();
        this._cachedRequiredTaskTools.clear();
        for (const tool of tools) {
          if (tool.outputSchema) {
            const toolValidator = this._jsonSchemaValidator.getValidator(tool.outputSchema);
            this._cachedToolOutputValidators.set(tool.name, toolValidator);
          }
          const taskSupport = tool.execution?.taskSupport;
          if (taskSupport === "required" || taskSupport === "optional") {
            this._cachedKnownTaskTools.add(tool.name);
          }
          if (taskSupport === "required") {
            this._cachedRequiredTaskTools.add(tool.name);
          }
        }
      }
      /**
       * Get cached validator for a tool
       */
      getToolOutputValidator(toolName) {
        return this._cachedToolOutputValidators.get(toolName);
      }
      async listTools(params, options2) {
        const result = await this.request({ method: "tools/list", params }, ListToolsResultSchema, options2);
        this.cacheToolMetadata(result.tools);
        return result;
      }
      /**
       * Set up a single list changed handler.
       * @internal
       */
      _setupListChangedHandler(listType, notificationSchema, options2, fetcher) {
        const parseResult = ListChangedOptionsBaseSchema.safeParse(options2);
        if (!parseResult.success) {
          throw new Error(`Invalid ${listType} listChanged options: ${parseResult.error.message}`);
        }
        if (typeof options2.onChanged !== "function") {
          throw new Error(`Invalid ${listType} listChanged options: onChanged must be a function`);
        }
        const { autoRefresh, debounceMs } = parseResult.data;
        const { onChanged } = options2;
        const refresh = /* @__PURE__ */ __name(async () => {
          if (!autoRefresh) {
            onChanged(null, null);
            return;
          }
          try {
            const items = await fetcher();
            onChanged(null, items);
          } catch (e4) {
            const error2 = e4 instanceof Error ? e4 : new Error(String(e4));
            onChanged(error2, null);
          }
        }, "refresh");
        const handler = /* @__PURE__ */ __name(() => {
          if (debounceMs) {
            const existingTimer = this._listChangedDebounceTimers.get(listType);
            if (existingTimer) {
              clearTimeout(existingTimer);
            }
            const timer = setTimeout(refresh, debounceMs);
            this._listChangedDebounceTimers.set(listType, timer);
          } else {
            refresh();
          }
        }, "handler");
        this.setNotificationHandler(notificationSchema, handler);
      }
      async sendRootsListChanged() {
        return this.notification({ method: "notifications/roots/list_changed" });
      }
    };
  }
});

// packages/core/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/transport.js
function normalizeHeaders(headers) {
  if (!headers)
    return {};
  if (headers instanceof Headers) {
    return Object.fromEntries(headers.entries());
  }
  if (Array.isArray(headers)) {
    return Object.fromEntries(headers);
  }
  return { ...headers };
}
function createFetchWithInit(baseFetch = fetch, baseInit) {
  if (!baseInit) {
    return baseFetch;
  }
  return async (url2, init) => {
    const mergedInit = {
      ...baseInit,
      ...init,
      // Headers need special handling - merge instead of replace
      headers: init?.headers ? { ...normalizeHeaders(baseInit.headers), ...normalizeHeaders(init.headers) } : baseInit.headers
    };
    return baseFetch(url2, mergedInit);
  };
}
var init_transport = __esm({
  "packages/core/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/transport.js"() {
    init_esbuild_shims();
    __name(normalizeHeaders, "normalizeHeaders");
    __name(createFetchWithInit, "createFetchWithInit");
  }
});

// node_modules/pkce-challenge/dist/index.node.js
async function getRandomValues(size) {
  return (await crypto7).getRandomValues(new Uint8Array(size));
}
async function random(size) {
  const mask = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~";
  let result = "";
  const randomUints = await getRandomValues(size);
  for (let i3 = 0; i3 < size; i3++) {
    const randomIndex = randomUints[i3] % mask.length;
    result += mask[randomIndex];
  }
  return result;
}
async function generateVerifier(length) {
  return await random(length);
}
async function generateChallenge(code_verifier) {
  const buffer = await (await crypto7).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 crypto7;
var init_index_node = __esm({
  "node_modules/pkce-challenge/dist/index.node.js"() {
    init_esbuild_shims();
    crypto7 = globalThis.crypto?.webcrypto ?? // Node.js [18-16] REPL
    globalThis.crypto ?? // Node.js >18
    import("node:crypto").then((m3) => m3.webcrypto);
    __name(getRandomValues, "getRandomValues");
    __name(random, "random");
    __name(generateVerifier, "generateVerifier");
    __name(generateChallenge, "generateChallenge");
    __name(pkceChallenge, "pkceChallenge");
  }
});

// packages/core/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/auth.js
var SafeUrlSchema, OAuthProtectedResourceMetadataSchema, OAuthMetadataSchema, OpenIdProviderMetadataSchema, OpenIdProviderDiscoveryMetadataSchema, OAuthTokensSchema, OAuthErrorResponseSchema, OptionalSafeUrlSchema, OAuthClientMetadataSchema, OAuthClientInformationSchema, OAuthClientInformationFullSchema, OAuthClientRegistrationErrorSchema, OAuthTokenRevocationRequestSchema;
var init_auth = __esm({
  "packages/core/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/auth.js"() {
    init_esbuild_shims();
    init_v42();
    SafeUrlSchema = url().superRefine((val, ctx) => {
      if (!URL.canParse(val)) {
        ctx.addIssue({
          code: ZodIssueCode2.custom,
          message: "URL must be parseable",
          fatal: true
        });
        return NEVER2;
      }
    }).refine((url2) => {
      const u2 = new URL(url2);
      return u2.protocol !== "javascript:" && u2.protocol !== "data:" && u2.protocol !== "vbscript:";
    }, { message: "URL cannot use javascript:, data:, or vbscript: scheme" });
    OAuthProtectedResourceMetadataSchema = looseObject({
      resource: string2().url(),
      authorization_servers: array(SafeUrlSchema).optional(),
      jwks_uri: string2().url().optional(),
      scopes_supported: array(string2()).optional(),
      bearer_methods_supported: array(string2()).optional(),
      resource_signing_alg_values_supported: array(string2()).optional(),
      resource_name: string2().optional(),
      resource_documentation: string2().optional(),
      resource_policy_uri: string2().url().optional(),
      resource_tos_uri: string2().url().optional(),
      tls_client_certificate_bound_access_tokens: boolean2().optional(),
      authorization_details_types_supported: array(string2()).optional(),
      dpop_signing_alg_values_supported: array(string2()).optional(),
      dpop_bound_access_tokens_required: boolean2().optional()
    });
    OAuthMetadataSchema = looseObject({
      issuer: string2(),
      authorization_endpoint: SafeUrlSchema,
      token_endpoint: SafeUrlSchema,
      registration_endpoint: SafeUrlSchema.optional(),
      scopes_supported: array(string2()).optional(),
      response_types_supported: array(string2()),
      response_modes_supported: array(string2()).optional(),
      grant_types_supported: array(string2()).optional(),
      token_endpoint_auth_methods_supported: array(string2()).optional(),
      token_endpoint_auth_signing_alg_values_supported: array(string2()).optional(),
      service_documentation: SafeUrlSchema.optional(),
      revocation_endpoint: SafeUrlSchema.optional(),
      revocation_endpoint_auth_methods_supported: array(string2()).optional(),
      revocation_endpoint_auth_signing_alg_values_supported: array(string2()).optional(),
      introspection_endpoint: string2().optional(),
      introspection_endpoint_auth_methods_supported: array(string2()).optional(),
      introspection_endpoint_auth_signing_alg_values_supported: array(string2()).optional(),
      code_challenge_methods_supported: array(string2()).optional(),
      client_id_metadata_document_supported: boolean2().optional()
    });
    OpenIdProviderMetadataSchema = looseObject({
      issuer: string2(),
      authorization_endpoint: SafeUrlSchema,
      token_endpoint: SafeUrlSchema,
      userinfo_endpoint: SafeUrlSchema.optional(),
      jwks_uri: SafeUrlSchema,
      registration_endpoint: SafeUrlSchema.optional(),
      scopes_supported: array(string2()).optional(),
      response_types_supported: array(string2()),
      response_modes_supported: array(string2()).optional(),
      grant_types_supported: array(string2()).optional(),
      acr_values_supported: array(string2()).optional(),
      subject_types_supported: array(string2()),
      id_token_signing_alg_values_supported: array(string2()),
      id_token_encryption_alg_values_supported: array(string2()).optional(),
      id_token_encryption_enc_values_supported: array(string2()).optional(),
      userinfo_signing_alg_values_supported: array(string2()).optional(),
      userinfo_encryption_alg_values_supported: array(string2()).optional(),
      userinfo_encryption_enc_values_supported: array(string2()).optional(),
      request_object_signing_alg_values_supported: array(string2()).optional(),
      request_object_encryption_alg_values_supported: array(string2()).optional(),
      request_object_encryption_enc_values_supported: array(string2()).optional(),
      token_endpoint_auth_methods_supported: array(string2()).optional(),
      token_endpoint_auth_signing_alg_values_supported: array(string2()).optional(),
      display_values_supported: array(string2()).optional(),
      claim_types_supported: array(string2()).optional(),
      claims_supported: array(string2()).optional(),
      service_documentation: string2().optional(),
      claims_locales_supported: array(string2()).optional(),
      ui_locales_supported: array(string2()).optional(),
      claims_parameter_supported: boolean2().optional(),
      request_parameter_supported: boolean2().optional(),
      request_uri_parameter_supported: boolean2().optional(),
      require_request_uri_registration: boolean2().optional(),
      op_policy_uri: SafeUrlSchema.optional(),
      op_tos_uri: SafeUrlSchema.optional(),
      client_id_metadata_document_supported: boolean2().optional()
    });
    OpenIdProviderDiscoveryMetadataSchema = object2({
      ...OpenIdProviderMetadataSchema.shape,
      ...OAuthMetadataSchema.pick({
        code_challenge_methods_supported: true
      }).shape
    });
    OAuthTokensSchema = object2({
      access_token: string2(),
      id_token: string2().optional(),
      // Optional for OAuth 2.1, but necessary in OpenID Connect
      token_type: string2(),
      expires_in: coerce_exports2.number().optional(),
      scope: string2().optional(),
      refresh_token: string2().optional()
    }).strip();
    OAuthErrorResponseSchema = object2({
      error: string2(),
      error_description: string2().optional(),
      error_uri: string2().optional()
    });
    OptionalSafeUrlSchema = SafeUrlSchema.optional().or(literal("").transform(() => void 0));
    OAuthClientMetadataSchema = object2({
      redirect_uris: array(SafeUrlSchema),
      token_endpoint_auth_method: string2().optional(),
      grant_types: array(string2()).optional(),
      response_types: array(string2()).optional(),
      client_name: string2().optional(),
      client_uri: SafeUrlSchema.optional(),
      logo_uri: OptionalSafeUrlSchema,
      scope: string2().optional(),
      contacts: array(string2()).optional(),
      tos_uri: OptionalSafeUrlSchema,
      policy_uri: string2().optional(),
      jwks_uri: SafeUrlSchema.optional(),
      jwks: any().optional(),
      software_id: string2().optional(),
      software_version: string2().optional(),
      software_statement: string2().optional()
    }).strip();
    OAuthClientInformationSchema = object2({
      client_id: string2(),
      client_secret: string2().optional(),
      client_id_issued_at: number2().optional(),
      client_secret_expires_at: number2().optional()
    }).strip();
    OAuthClientInformationFullSchema = OAuthClientMetadataSchema.merge(OAuthClientInformationSchema);
    OAuthClientRegistrationErrorSchema = object2({
      error: string2(),
      error_description: string2().optional()
    }).strip();
    OAuthTokenRevocationRequestSchema = object2({
      token: string2(),
      token_type_hint: string2().optional()
    }).strip();
  }
});

// packages/core/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({
  "packages/core/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/auth-utils.js"() {
    init_esbuild_shims();
    __name(resourceUrlFromServerUrl, "resourceUrlFromServerUrl");
    __name(checkResourceAllowed, "checkResourceAllowed");
  }
});

// packages/core/node_modules/@modelcontextprotocol/sdk/dist/esm/server/auth/errors.js
var OAuthError, InvalidRequestError, InvalidClientError, InvalidGrantError, UnauthorizedClientError, UnsupportedGrantTypeError, InvalidScopeError, AccessDeniedError, ServerError, TemporarilyUnavailableError, UnsupportedResponseTypeError, UnsupportedTokenTypeError, InvalidTokenError, MethodNotAllowedError, TooManyRequestsError, InvalidClientMetadataError, InsufficientScopeError, InvalidTargetError, OAUTH_ERRORS;
var init_errors6 = __esm({
  "packages/core/node_modules/@modelcontextprotocol/sdk/dist/esm/server/auth/errors.js"() {
    init_esbuild_shims();
    OAuthError = class extends Error {
      static {
        __name(this, "OAuthError");
      }
      constructor(message, errorUri) {
        super(message);
        this.errorUri = errorUri;
        this.name = this.constructor.name;
      }
      /**
       * Converts the error to a standard OAuth error response object
       */
      toResponseObject() {
        const response = {
          error: this.errorCode,
          error_description: this.message
        };
        if (this.errorUri) {
          response.error_uri = this.errorUri;
        }
        return response;
      }
      get errorCode() {
        return this.constructor.errorCode;
      }
    };
    InvalidRequestError = class extends OAuthError {
      static {
        __name(this, "InvalidRequestError");
      }
    };
    InvalidRequestError.errorCode = "invalid_request";
    InvalidClientError = class extends OAuthError {
      static {
        __name(this, "InvalidClientError");
      }
    };
    InvalidClientError.errorCode = "invalid_client";
    InvalidGrantError = class extends OAuthError {
      static {
        __name(this, "InvalidGrantError");
      }
    };
    InvalidGrantError.errorCode = "invalid_grant";
    UnauthorizedClientError = class extends OAuthError {
      static {
        __name(this, "UnauthorizedClientError");
      }
    };
    UnauthorizedClientError.errorCode = "unauthorized_client";
    UnsupportedGrantTypeError = class extends OAuthError {
      static {
        __name(this, "UnsupportedGrantTypeError");
      }
    };
    UnsupportedGrantTypeError.errorCode = "unsupported_grant_type";
    InvalidScopeError = class extends OAuthError {
      static {
        __name(this, "InvalidScopeError");
      }
    };
    InvalidScopeError.errorCode = "invalid_scope";
    AccessDeniedError = class extends OAuthError {
      static {
        __name(this, "AccessDeniedError");
      }
    };
    AccessDeniedError.errorCode = "access_denied";
    ServerError = class extends OAuthError {
      static {
        __name(this, "ServerError");
      }
    };
    ServerError.errorCode = "server_error";
    TemporarilyUnavailableError = class extends OAuthError {
      static {
        __name(this, "TemporarilyUnavailableError");
      }
    };
    TemporarilyUnavailableError.errorCode = "temporarily_unavailable";
    UnsupportedResponseTypeError = class extends OAuthError {
      static {
        __name(this, "UnsupportedResponseTypeError");
      }
    };
    UnsupportedResponseTypeError.errorCode = "unsupported_response_type";
    UnsupportedTokenTypeError = class extends OAuthError {
      static {
        __name(this, "UnsupportedTokenTypeError");
      }
    };
    UnsupportedTokenTypeError.errorCode = "unsupported_token_type";
    InvalidTokenError = class extends OAuthError {
      static {
        __name(this, "InvalidTokenError");
      }
    };
    InvalidTokenError.errorCode = "invalid_token";
    MethodNotAllowedError = class extends OAuthError {
      static {
        __name(this, "MethodNotAllowedError");
      }
    };
    MethodNotAllowedError.errorCode = "method_not_allowed";
    TooManyRequestsError = class extends OAuthError {
      static {
        __name(this, "TooManyRequestsError");
      }
    };
    TooManyRequestsError.errorCode = "too_many_requests";
    InvalidClientMetadataError = class extends OAuthError {
      static {
        __name(this, "InvalidClientMetadataError");
      }
    };
    InvalidClientMetadataError.errorCode = "invalid_client_metadata";
    InsufficientScopeError = class extends OAuthError {
      static {
        __name(this, "InsufficientScopeError");
      }
    };
    InsufficientScopeError.errorCode = "insufficient_scope";
    InvalidTargetError = class extends OAuthError {
      static {
        __name(this, "InvalidTargetError");
      }
    };
    InvalidTargetError.errorCode = "invalid_target";
    OAUTH_ERRORS = {
      [InvalidRequestError.errorCode]: InvalidRequestError,
      [InvalidClientError.errorCode]: InvalidClientError,
      [InvalidGrantError.errorCode]: InvalidGrantError,
      [UnauthorizedClientError.errorCode]: UnauthorizedClientError,
      [UnsupportedGrantTypeError.errorCode]: UnsupportedGrantTypeError,
      [InvalidScopeError.errorCode]: InvalidScopeError,
      [AccessDeniedError.errorCode]: AccessDeniedError,
      [ServerError.errorCode]: ServerError,
      [TemporarilyUnavailableError.errorCode]: TemporarilyUnavailableError,
      [UnsupportedResponseTypeError.errorCode]: UnsupportedResponseTypeError,
      [UnsupportedTokenTypeError.errorCode]: UnsupportedTokenTypeError,
      [InvalidTokenError.errorCode]: InvalidTokenError,
      [MethodNotAllowedError.errorCode]: MethodNotAllowedError,
      [TooManyRequestsError.errorCode]: TooManyRequestsError,
      [InvalidClientMetadataError.errorCode]: InvalidClientMetadataError,
      [InsufficientScopeError.errorCode]: InsufficientScopeError,
      [InvalidTargetError.errorCode]: InvalidTargetError
    };
  }
});

// packages/core/node_modules/@modelcontextprotocol/sdk/dist/esm/client/auth.js
function isClientAuthMethod(method) {
  return ["client_secret_basic", "client_secret_post", "none"].includes(method);
}
function selectClientAuthMethod(clientInformation, supportedMethods) {
  const hasClientSecret = clientInformation.client_secret !== void 0;
  if (supportedMethods.length === 0) {
    return hasClientSecret ? "client_secret_post" : "none";
  }
  if ("token_endpoint_auth_method" in clientInformation && clientInformation.token_endpoint_auth_method && isClientAuthMethod(clientInformation.token_endpoint_auth_method) && supportedMethods.includes(clientInformation.token_endpoint_auth_method)) {
    return clientInformation.token_endpoint_auth_method;
  }
  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 parseErrorResponse(input) {
  const statusCode = input instanceof Response ? input.status : void 0;
  const body = input instanceof Response ? await input.text() : input;
  try {
    const result = OAuthErrorResponseSchema.parse(JSON.parse(body));
    const { error: error2, error_description, error_uri } = result;
    const errorClass = OAUTH_ERRORS[error2] || ServerError;
    return new errorClass(error_description || "", error_uri);
  } catch (error2) {
    const errorMessage = `${statusCode ? `HTTP ${statusCode}: ` : ""}Invalid OAuth error response: ${error2}. Raw body: ${body}`;
    return new ServerError(errorMessage);
  }
}
async function auth(provider, options2) {
  try {
    return await authInternal(provider, options2);
  } catch (error2) {
    if (error2 instanceof InvalidClientError || error2 instanceof UnauthorizedClientError) {
      await provider.invalidateCredentials?.("all");
      return await authInternal(provider, options2);
    } else if (error2 instanceof InvalidGrantError) {
      await provider.invalidateCredentials?.("tokens");
      return await authInternal(provider, options2);
    }
    throw error2;
  }
}
async function authInternal(provider, { serverUrl, authorizationCode, scope, resourceMetadataUrl, fetchFn }) {
  let resourceMetadata;
  let authorizationServerUrl;
  try {
    resourceMetadata = await discoverOAuthProtectedResourceMetadata(serverUrl, { resourceMetadataUrl }, fetchFn);
    if (resourceMetadata.authorization_servers && resourceMetadata.authorization_servers.length > 0) {
      authorizationServerUrl = resourceMetadata.authorization_servers[0];
    }
  } catch {
  }
  if (!authorizationServerUrl) {
    authorizationServerUrl = new URL("/", serverUrl);
  }
  const resource = await selectResourceURL(serverUrl, provider, resourceMetadata);
  const metadata = await discoverAuthorizationServerMetadata(authorizationServerUrl, {
    fetchFn
  });
  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");
    }
    const supportsUrlBasedClientId = metadata?.client_id_metadata_document_supported === true;
    const clientMetadataUrl = provider.clientMetadataUrl;
    if (clientMetadataUrl && !isHttpsUrl(clientMetadataUrl)) {
      throw new InvalidClientMetadataError(`clientMetadataUrl must be a valid HTTPS URL with a non-root pathname, got: ${clientMetadataUrl}`);
    }
    const shouldUseUrlBasedClientId = supportsUrlBasedClientId && clientMetadataUrl;
    if (shouldUseUrlBasedClientId) {
      clientInformation = {
        client_id: clientMetadataUrl
      };
      await provider.saveClientInformation?.(clientInformation);
    } else {
      if (!provider.saveClientInformation) {
        throw new Error("OAuth client information must be saveable for dynamic registration");
      }
      const fullInformation = await registerClient(authorizationServerUrl, {
        metadata,
        clientMetadata: provider.clientMetadata,
        fetchFn
      });
      await provider.saveClientInformation(fullInformation);
      clientInformation = fullInformation;
    }
  }
  const nonInteractiveFlow = !provider.redirectUrl;
  if (authorizationCode !== void 0 || nonInteractiveFlow) {
    const tokens2 = await fetchToken(provider, authorizationServerUrl, {
      metadata,
      resource,
      authorizationCode,
      fetchFn
    });
    await provider.saveTokens(tokens2);
    return "AUTHORIZED";
  }
  const tokens = await provider.tokens();
  if (tokens?.refresh_token) {
    try {
      const newTokens = await refreshAuthorization(authorizationServerUrl, {
        metadata,
        clientInformation,
        refreshToken: tokens.refresh_token,
        resource,
        addClientAuthentication: provider.addClientAuthentication,
        fetchFn
      });
      await provider.saveTokens(newTokens);
      return "AUTHORIZED";
    } catch (error2) {
      if (!(error2 instanceof OAuthError) || error2 instanceof ServerError) {
      } else {
        throw error2;
      }
    }
  }
  const state = provider.state ? await provider.state() : void 0;
  const { authorizationUrl, codeVerifier } = await startAuthorization(authorizationServerUrl, {
    metadata,
    clientInformation,
    state,
    redirectUrl: provider.redirectUrl,
    scope: scope || resourceMetadata?.scopes_supported?.join(" ") || provider.clientMetadata.scope,
    resource
  });
  await provider.saveCodeVerifier(codeVerifier);
  await provider.redirectToAuthorization(authorizationUrl);
  return "REDIRECT";
}
function isHttpsUrl(value) {
  if (!value)
    return false;
  try {
    const url2 = new URL(value);
    return url2.protocol === "https:" && url2.pathname !== "/";
  } catch {
    return false;
  }
}
async function selectResourceURL(serverUrl, provider, resourceMetadata) {
  const defaultResource = resourceUrlFromServerUrl(serverUrl);
  if (provider.validateResourceURL) {
    return await provider.validateResourceURL(defaultResource, 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 extractWWWAuthenticateParams(res) {
  const authenticateHeader = res.headers.get("WWW-Authenticate");
  if (!authenticateHeader) {
    return {};
  }
  const [type, scheme] = authenticateHeader.split(" ");
  if (type.toLowerCase() !== "bearer" || !scheme) {
    return {};
  }
  const resourceMetadataMatch = extractFieldFromWwwAuth(res, "resource_metadata") || void 0;
  let resourceMetadataUrl;
  if (resourceMetadataMatch) {
    try {
      resourceMetadataUrl = new URL(resourceMetadataMatch);
    } catch {
    }
  }
  const scope = extractFieldFromWwwAuth(res, "scope") || void 0;
  const error2 = extractFieldFromWwwAuth(res, "error") || void 0;
  return {
    resourceMetadataUrl,
    scope,
    error: error2
  };
}
function extractFieldFromWwwAuth(response, fieldName) {
  const wwwAuthHeader = response.headers.get("WWW-Authenticate");
  if (!wwwAuthHeader) {
    return null;
  }
  const pattern = new RegExp(`${fieldName}=(?:"([^"]+)"|([^\\s,]+))`);
  const match2 = wwwAuthHeader.match(pattern);
  if (match2) {
    return match2[1] || match2[2];
  }
  return null;
}
async function discoverOAuthProtectedResourceMetadata(serverUrl, opts, fetchFn = fetch) {
  const response = await discoverMetadataWithFallback(serverUrl, "oauth-protected-resource", fetchFn, {
    protocolVersion: opts?.protocolVersion,
    metadataUrl: opts?.resourceMetadataUrl
  });
  if (!response || response.status === 404) {
    await response?.body?.cancel();
    throw new Error(`Resource server does not implement OAuth 2.0 Protected Resource Metadata.`);
  }
  if (!response.ok) {
    await response.body?.cancel();
    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, fetchFn = fetch) {
  try {
    return await fetchFn(url2, { headers });
  } catch (error2) {
    if (error2 instanceof TypeError) {
      if (headers) {
        return fetchWithCorsRetry(url2, void 0, fetchFn);
      } else {
        return void 0;
      }
    }
    throw error2;
  }
}
function buildWellKnownPath(wellKnownPrefix, pathname = "", options2 = {}) {
  if (pathname.endsWith("/")) {
    pathname = pathname.slice(0, -1);
  }
  return options2.prependPathname ? `${pathname}/.well-known/${wellKnownPrefix}` : `/.well-known/${wellKnownPrefix}${pathname}`;
}
async function tryMetadataDiscovery(url2, protocolVersion, fetchFn = fetch) {
  const headers = {
    "MCP-Protocol-Version": protocolVersion
  };
  return await fetchWithCorsRetry(url2, headers, fetchFn);
}
function shouldAttemptFallback(response, pathname) {
  return !response || response.status >= 400 && response.status < 500 && pathname !== "/";
}
async function discoverMetadataWithFallback(serverUrl, wellKnownType, fetchFn, opts) {
  const issuer = new URL(serverUrl);
  const protocolVersion = opts?.protocolVersion ?? LATEST_PROTOCOL_VERSION;
  let url2;
  if (opts?.metadataUrl) {
    url2 = new URL(opts.metadataUrl);
  } else {
    const wellKnownPath = buildWellKnownPath(wellKnownType, issuer.pathname);
    url2 = new URL(wellKnownPath, opts?.metadataServerUrl ?? issuer);
    url2.search = issuer.search;
  }
  let response = await tryMetadataDiscovery(url2, protocolVersion, fetchFn);
  if (!opts?.metadataUrl && shouldAttemptFallback(response, issuer.pathname)) {
    const rootUrl = new URL(`/.well-known/${wellKnownType}`, issuer);
    response = await tryMetadataDiscovery(rootUrl, protocolVersion, fetchFn);
  }
  return response;
}
function buildDiscoveryUrls(authorizationServerUrl) {
  const url2 = typeof authorizationServerUrl === "string" ? new URL(authorizationServerUrl) : authorizationServerUrl;
  const hasPath = url2.pathname !== "/";
  const urlsToTry = [];
  if (!hasPath) {
    urlsToTry.push({
      url: new URL("/.well-known/oauth-authorization-server", url2.origin),
      type: "oauth"
    });
    urlsToTry.push({
      url: new URL(`/.well-known/openid-configuration`, url2.origin),
      type: "oidc"
    });
    return urlsToTry;
  }
  let pathname = url2.pathname;
  if (pathname.endsWith("/")) {
    pathname = pathname.slice(0, -1);
  }
  urlsToTry.push({
    url: new URL(`/.well-known/oauth-authorization-server${pathname}`, url2.origin),
    type: "oauth"
  });
  urlsToTry.push({
    url: new URL(`/.well-known/openid-configuration${pathname}`, url2.origin),
    type: "oidc"
  });
  urlsToTry.push({
    url: new URL(`${pathname}/.well-known/openid-configuration`, url2.origin),
    type: "oidc"
  });
  return urlsToTry;
}
async function discoverAuthorizationServerMetadata(authorizationServerUrl, { fetchFn = fetch, protocolVersion = LATEST_PROTOCOL_VERSION } = {}) {
  const headers = {
    "MCP-Protocol-Version": protocolVersion,
    Accept: "application/json"
  };
  const urlsToTry = buildDiscoveryUrls(authorizationServerUrl);
  for (const { url: endpointUrl, type } of urlsToTry) {
    const response = await fetchWithCorsRetry(endpointUrl, headers, fetchFn);
    if (!response) {
      continue;
    }
    if (!response.ok) {
      await response.body?.cancel();
      if (response.status >= 400 && response.status < 500) {
        continue;
      }
      throw new Error(`HTTP ${response.status} trying to load ${type === "oauth" ? "OAuth" : "OpenID provider"} metadata from ${endpointUrl}`);
    }
    if (type === "oauth") {
      return OAuthMetadataSchema.parse(await response.json());
    } else {
      return OpenIdProviderDiscoveryMetadataSchema.parse(await response.json());
    }
  }
  return void 0;
}
async function startAuthorization(authorizationServerUrl, { metadata, clientInformation, redirectUrl, scope, state, resource }) {
  let authorizationUrl;
  if (metadata) {
    authorizationUrl = new URL(metadata.authorization_endpoint);
    if (!metadata.response_types_supported.includes(AUTHORIZATION_CODE_RESPONSE_TYPE)) {
      throw new Error(`Incompatible auth server: does not support response type ${AUTHORIZATION_CODE_RESPONSE_TYPE}`);
    }
    if (metadata.code_challenge_methods_supported && !metadata.code_challenge_methods_supported.includes(AUTHORIZATION_CODE_CHALLENGE_METHOD)) {
      throw new Error(`Incompatible auth server: does not support code challenge method ${AUTHORIZATION_CODE_CHALLENGE_METHOD}`);
    }
  } 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", AUTHORIZATION_CODE_RESPONSE_TYPE);
  authorizationUrl.searchParams.set("client_id", clientInformation.client_id);
  authorizationUrl.searchParams.set("code_challenge", codeChallenge);
  authorizationUrl.searchParams.set("code_challenge_method", AUTHORIZATION_CODE_CHALLENGE_METHOD);
  authorizationUrl.searchParams.set("redirect_uri", String(redirectUrl));
  if (state) {
    authorizationUrl.searchParams.set("state", state);
  }
  if (scope) {
    authorizationUrl.searchParams.set("scope", scope);
  }
  if (scope?.includes("offline_access")) {
    authorizationUrl.searchParams.append("prompt", "consent");
  }
  if (resource) {
    authorizationUrl.searchParams.set("resource", resource.href);
  }
  return { authorizationUrl, codeVerifier };
}
function prepareAuthorizationCodeRequest(authorizationCode, codeVerifier, redirectUri) {
  return new URLSearchParams({
    grant_type: "authorization_code",
    code: authorizationCode,
    code_verifier: codeVerifier,
    redirect_uri: String(redirectUri)
  });
}
async function executeTokenRequest(authorizationServerUrl, { metadata, tokenRequestParams, clientInformation, addClientAuthentication, resource, fetchFn }) {
  const tokenUrl = metadata?.token_endpoint ? new URL(metadata.token_endpoint) : new URL("/token", authorizationServerUrl);
  const headers = new Headers({
    "Content-Type": "application/x-www-form-urlencoded",
    Accept: "application/json"
  });
  if (resource) {
    tokenRequestParams.set("resource", resource.href);
  }
  if (addClientAuthentication) {
    await addClientAuthentication(headers, tokenRequestParams, tokenUrl, metadata);
  } else if (clientInformation) {
    const supportedMethods = metadata?.token_endpoint_auth_methods_supported ?? [];
    const authMethod = selectClientAuthMethod(clientInformation, supportedMethods);
    applyClientAuthentication(authMethod, clientInformation, headers, tokenRequestParams);
  }
  const response = await (fetchFn ?? fetch)(tokenUrl, {
    method: "POST",
    headers,
    body: tokenRequestParams
  });
  if (!response.ok) {
    throw await parseErrorResponse(response);
  }
  return OAuthTokensSchema.parse(await response.json());
}
async function refreshAuthorization(authorizationServerUrl, { metadata, clientInformation, refreshToken, resource, addClientAuthentication, fetchFn }) {
  const tokenRequestParams = new URLSearchParams({
    grant_type: "refresh_token",
    refresh_token: refreshToken
  });
  const tokens = await executeTokenRequest(authorizationServerUrl, {
    metadata,
    tokenRequestParams,
    clientInformation,
    addClientAuthentication,
    resource,
    fetchFn
  });
  return { refresh_token: refreshToken, ...tokens };
}
async function fetchToken(provider, authorizationServerUrl, { metadata, resource, authorizationCode, fetchFn } = {}) {
  const scope = provider.clientMetadata.scope;
  let tokenRequestParams;
  if (provider.prepareTokenRequest) {
    tokenRequestParams = await provider.prepareTokenRequest(scope);
  }
  if (!tokenRequestParams) {
    if (!authorizationCode) {
      throw new Error("Either provider.prepareTokenRequest() or authorizationCode is required");
    }
    if (!provider.redirectUrl) {
      throw new Error("redirectUrl is required for authorization_code flow");
    }
    const codeVerifier = await provider.codeVerifier();
    tokenRequestParams = prepareAuthorizationCodeRequest(authorizationCode, codeVerifier, provider.redirectUrl);
  }
  const clientInformation = await provider.clientInformation();
  return executeTokenRequest(authorizationServerUrl, {
    metadata,
    tokenRequestParams,
    clientInformation: clientInformation ?? void 0,
    addClientAuthentication: provider.addClientAuthentication,
    resource,
    fetchFn
  });
}
async function registerClient(authorizationServerUrl, { metadata, clientMetadata, fetchFn }) {
  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 (fetchFn ?? fetch)(registrationUrl, {
    method: "POST",
    headers: {
      "Content-Type": "application/json"
    },
    body: JSON.stringify(clientMetadata)
  });
  if (!response.ok) {
    throw await parseErrorResponse(response);
  }
  return OAuthClientInformationFullSchema.parse(await response.json());
}
var UnauthorizedError2, AUTHORIZATION_CODE_RESPONSE_TYPE, AUTHORIZATION_CODE_CHALLENGE_METHOD;
var init_auth2 = __esm({
  "packages/core/node_modules/@modelcontextprotocol/sdk/dist/esm/client/auth.js"() {
    init_esbuild_shims();
    init_index_node();
    init_types8();
    init_auth();
    init_auth();
    init_auth_utils();
    init_errors6();
    UnauthorizedError2 = class extends Error {
      static {
        __name(this, "UnauthorizedError");
      }
      constructor(message) {
        super(message ?? "Unauthorized");
      }
    };
    __name(isClientAuthMethod, "isClientAuthMethod");
    AUTHORIZATION_CODE_RESPONSE_TYPE = "code";
    AUTHORIZATION_CODE_CHALLENGE_METHOD = "S256";
    __name(selectClientAuthMethod, "selectClientAuthMethod");
    __name(applyClientAuthentication, "applyClientAuthentication");
    __name(applyBasicAuth, "applyBasicAuth");
    __name(applyPostAuth, "applyPostAuth");
    __name(applyPublicAuth, "applyPublicAuth");
    __name(parseErrorResponse, "parseErrorResponse");
    __name(auth, "auth");
    __name(authInternal, "authInternal");
    __name(isHttpsUrl, "isHttpsUrl");
    __name(selectResourceURL, "selectResourceURL");
    __name(extractWWWAuthenticateParams, "extractWWWAuthenticateParams");
    __name(extractFieldFromWwwAuth, "extractFieldFromWwwAuth");
    __name(discoverOAuthProtectedResourceMetadata, "discoverOAuthProtectedResourceMetadata");
    __name(fetchWithCorsRetry, "fetchWithCorsRetry");
    __name(buildWellKnownPath, "buildWellKnownPath");
    __name(tryMetadataDiscovery, "tryMetadataDiscovery");
    __name(shouldAttemptFallback, "shouldAttemptFallback");
    __name(discoverMetadataWithFallback, "discoverMetadataWithFallback");
    __name(buildDiscoveryUrls, "buildDiscoveryUrls");
    __name(discoverAuthorizationServerMetadata, "discoverAuthorizationServerMetadata");
    __name(startAuthorization, "startAuthorization");
    __name(prepareAuthorizationCodeRequest, "prepareAuthorizationCodeRequest");
    __name(executeTokenRequest, "executeTokenRequest");
    __name(refreshAuthorization, "refreshAuthorization");
    __name(fetchToken, "fetchToken");
    __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_dist2 = __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_dist2();
    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(error2) {
                onError2 === "terminate" ? controller.error(error2) : typeof onError2 == "function" && onError2(error2);
              },
              onRetry,
              onComment
            });
          },
          transform(chunk) {
            parser6.feed(chunk);
          }
        });
      }
    };
  }
});

// packages/core/node_modules/@modelcontextprotocol/sdk/dist/esm/client/streamableHttp.js
var DEFAULT_STREAMABLE_HTTP_RECONNECTION_OPTIONS, StreamableHTTPError, StreamableHTTPClientTransport;
var init_streamableHttp = __esm({
  "packages/core/node_modules/@modelcontextprotocol/sdk/dist/esm/client/streamableHttp.js"() {
    init_esbuild_shims();
    init_transport();
    init_types8();
    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) {
        this._hasCompletedAuthFlow = false;
        this._url = url2;
        this._resourceMetadataUrl = void 0;
        this._scope = void 0;
        this._requestInit = opts?.requestInit;
        this._authProvider = opts?.authProvider;
        this._fetch = opts?.fetch;
        this._fetchWithInit = createFetchWithInit(opts?.fetch, opts?.requestInit);
        this._sessionId = opts?.sessionId;
        this._reconnectionOptions = opts?.reconnectionOptions ?? DEFAULT_STREAMABLE_HTTP_RECONNECTION_OPTIONS;
      }
      async _authThenStart() {
        if (!this._authProvider) {
          throw new UnauthorizedError2("No auth provider");
        }
        let result;
        try {
          result = await auth(this._authProvider, {
            serverUrl: this._url,
            resourceMetadataUrl: this._resourceMetadataUrl,
            scope: this._scope,
            fetchFn: this._fetchWithInit
          });
        } catch (error2) {
          this.onerror?.(error2);
          throw error2;
        }
        if (result !== "AUTHORIZED") {
          throw new UnauthorizedError2();
        }
        return await this._startOrAuthSse({ resumptionToken: void 0 });
      }
      async _commonHeaders() {
        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 = normalizeHeaders(this._requestInit?.headers);
        return new Headers({
          ...headers,
          ...extraHeaders
        });
      }
      async _startOrAuthSse(options2) {
        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 (this._fetch ?? fetch)(this._url, {
            method: "GET",
            headers,
            signal: this._abortController?.signal
          });
          if (!response.ok) {
            await response.body?.cancel();
            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, true);
        } catch (error2) {
          this.onerror?.(error2);
          throw error2;
        }
      }
      /**
       * 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) {
        if (this._serverRetryMs !== void 0) {
          return this._serverRetryMs;
        }
        const initialDelay = this._reconnectionOptions.initialReconnectionDelay;
        const growFactor = this._reconnectionOptions.reconnectionDelayGrowFactor;
        const maxDelay = this._reconnectionOptions.maxReconnectionDelay;
        return Math.min(initialDelay * Math.pow(growFactor, attempt), maxDelay);
      }
      /**
       * Schedule a reconnection attempt using server-provided retry interval or 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) {
        const maxRetries = this._reconnectionOptions.maxRetries;
        if (attemptCount >= maxRetries) {
          this.onerror?.(new Error(`Maximum reconnection attempts (${maxRetries}) exceeded.`));
          return;
        }
        const delay4 = this._getNextReconnectionDelay(attemptCount);
        this._reconnectionTimeout = setTimeout(() => {
          this._startOrAuthSse(options2).catch((error2) => {
            this.onerror?.(new Error(`Failed to reconnect SSE stream: ${error2 instanceof Error ? error2.message : String(error2)}`));
            this._scheduleReconnection(options2, attemptCount + 1);
          });
        }, delay4);
      }
      _handleSseStream(stream2, options2, isReconnectable) {
        if (!stream2) {
          return;
        }
        const { onresumptiontoken, replayMessageId } = options2;
        let lastEventId;
        let hasPrimingEvent = false;
        let receivedResponse = false;
        const processStream = /* @__PURE__ */ __name(async () => {
          try {
            const reader = stream2.pipeThrough(new TextDecoderStream()).pipeThrough(new EventSourceParserStream({
              onRetry: /* @__PURE__ */ __name((retryMs) => {
                this._serverRetryMs = retryMs;
              }, "onRetry")
            })).getReader();
            while (true) {
              const { value: event, done } = await reader.read();
              if (done) {
                break;
              }
              if (event.id) {
                lastEventId = event.id;
                hasPrimingEvent = true;
                onresumptiontoken?.(event.id);
              }
              if (!event.data) {
                continue;
              }
              if (!event.event || event.event === "message") {
                try {
                  const message = JSONRPCMessageSchema.parse(JSON.parse(event.data));
                  if (isJSONRPCResultResponse(message)) {
                    receivedResponse = true;
                    if (replayMessageId !== void 0) {
                      message.id = replayMessageId;
                    }
                  }
                  this.onmessage?.(message);
                } catch (error2) {
                  this.onerror?.(error2);
                }
              }
            }
            const canResume = isReconnectable || hasPrimingEvent;
            const needsReconnect = canResume && !receivedResponse;
            if (needsReconnect && this._abortController && !this._abortController.signal.aborted) {
              this._scheduleReconnection({
                resumptionToken: lastEventId,
                onresumptiontoken,
                replayMessageId
              }, 0);
            }
          } catch (error2) {
            this.onerror?.(new Error(`SSE stream disconnected: ${error2}`));
            const canResume = isReconnectable || hasPrimingEvent;
            const needsReconnect = canResume && !receivedResponse;
            if (needsReconnect && this._abortController && !this._abortController.signal.aborted) {
              try {
                this._scheduleReconnection({
                  resumptionToken: lastEventId,
                  onresumptiontoken,
                  replayMessageId
                }, 0);
              } catch (error3) {
                this.onerror?.(new Error(`Failed to reconnect: ${error3 instanceof Error ? error3.message : String(error3)}`));
              }
            }
          }
        }, "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,
          scope: this._scope,
          fetchFn: this._fetchWithInit
        });
        if (result !== "AUTHORIZED") {
          throw new UnauthorizedError2("Failed to authorize");
        }
      }
      async close() {
        if (this._reconnectionTimeout) {
          clearTimeout(this._reconnectionTimeout);
          this._reconnectionTimeout = void 0;
        }
        this._abortController?.abort();
        this.onclose?.();
      }
      async send(message, options2) {
        try {
          const { resumptionToken, onresumptiontoken } = options2 || {};
          if (resumptionToken) {
            this._startOrAuthSse({ resumptionToken, replayMessageId: isJSONRPCRequest(message) ? message.id : void 0 }).catch((err) => this.onerror?.(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: this._abortController?.signal
          };
          const response = await (this._fetch ?? fetch)(this._url, init);
          const sessionId = response.headers.get("mcp-session-id");
          if (sessionId) {
            this._sessionId = sessionId;
          }
          if (!response.ok) {
            const text = await response.text().catch(() => null);
            if (response.status === 401 && this._authProvider) {
              if (this._hasCompletedAuthFlow) {
                throw new StreamableHTTPError(401, "Server returned 401 after successful authentication");
              }
              const { resourceMetadataUrl, scope } = extractWWWAuthenticateParams(response);
              this._resourceMetadataUrl = resourceMetadataUrl;
              this._scope = scope;
              const result = await auth(this._authProvider, {
                serverUrl: this._url,
                resourceMetadataUrl: this._resourceMetadataUrl,
                scope: this._scope,
                fetchFn: this._fetchWithInit
              });
              if (result !== "AUTHORIZED") {
                throw new UnauthorizedError2();
              }
              this._hasCompletedAuthFlow = true;
              return this.send(message);
            }
            if (response.status === 403 && this._authProvider) {
              const { resourceMetadataUrl, scope, error: error2 } = extractWWWAuthenticateParams(response);
              if (error2 === "insufficient_scope") {
                const wwwAuthHeader = response.headers.get("WWW-Authenticate");
                if (this._lastUpscopingHeader === wwwAuthHeader) {
                  throw new StreamableHTTPError(403, "Server returned 403 after trying upscoping");
                }
                if (scope) {
                  this._scope = scope;
                }
                if (resourceMetadataUrl) {
                  this._resourceMetadataUrl = resourceMetadataUrl;
                }
                this._lastUpscopingHeader = wwwAuthHeader ?? void 0;
                const result = await auth(this._authProvider, {
                  serverUrl: this._url,
                  resourceMetadataUrl: this._resourceMetadataUrl,
                  scope: this._scope,
                  fetchFn: this._fetch
                });
                if (result !== "AUTHORIZED") {
                  throw new UnauthorizedError2();
                }
                return this.send(message);
              }
            }
            throw new StreamableHTTPError(response.status, `Error POSTing to endpoint: ${text}`);
          }
          this._hasCompletedAuthFlow = false;
          this._lastUpscopingHeader = void 0;
          if (response.status === 202) {
            await response.body?.cancel();
            if (isInitializedNotification(message)) {
              this._startOrAuthSse({ resumptionToken: void 0 }).catch((err) => this.onerror?.(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?.includes("text/event-stream")) {
              this._handleSseStream(response.body, { onresumptiontoken }, false);
            } else if (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) {
                this.onmessage?.(msg);
              }
            } else {
              await response.body?.cancel();
              throw new StreamableHTTPError(-1, `Unexpected content type: ${contentType}`);
            }
          } else {
            await response.body?.cancel();
          }
        } catch (error2) {
          this.onerror?.(error2);
          throw error2;
        }
      }
      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() {
        if (!this._sessionId) {
          return;
        }
        try {
          const headers = await this._commonHeaders();
          const init = {
            ...this._requestInit,
            method: "DELETE",
            headers,
            signal: this._abortController?.signal
          };
          const response = await (this._fetch ?? fetch)(this._url, init);
          await response.body?.cancel();
          if (!response.ok && response.status !== 405) {
            throw new StreamableHTTPError(response.status, `Failed to terminate session: ${response.statusText}`);
          }
          this._sessionId = void 0;
        } catch (error2) {
          this.onerror?.(error2);
          throw error2;
        }
      }
      setProtocolVersion(version2) {
        this._protocolVersion = version2;
      }
      get protocolVersion() {
        return this._protocolVersion;
      }
      /**
       * Resume an SSE stream from a previous event ID.
       * Opens a GET SSE connection with Last-Event-ID header to replay missed events.
       *
       * @param lastEventId The event ID to resume from
       * @param options Optional callback to receive new resumption tokens
       */
      async resumeStream(lastEventId, options2) {
        await this._startOrAuthSse({
          resumptionToken: lastEventId,
          onresumptiontoken: options2?.onresumptiontoken
        });
      }
    };
  }
});

// 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 fs113 = __require("fs");
    function checkPathExt(path125, 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 i3 = 0; i3 < pathext.length; i3++) {
        var p2 = pathext[i3].toLowerCase();
        if (p2 && path125.substr(-p2.length).toLowerCase() === p2) {
          return true;
        }
      }
      return false;
    }
    __name(checkPathExt, "checkPathExt");
    function checkStat(stat10, path125, options2) {
      if (!stat10.isSymbolicLink() && !stat10.isFile()) {
        return false;
      }
      return checkPathExt(path125, options2);
    }
    __name(checkStat, "checkStat");
    function isexe(path125, options2, cb) {
      fs113.stat(path125, function(er2, stat10) {
        cb(er2, er2 ? false : checkStat(stat10, path125, options2));
      });
    }
    __name(isexe, "isexe");
    function sync2(path125, options2) {
      return checkStat(fs113.statSync(path125), path125, 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 fs113 = __require("fs");
    function isexe(path125, options2, cb) {
      fs113.stat(path125, function(er2, stat10) {
        cb(er2, er2 ? false : checkStat(stat10, options2));
      });
    }
    __name(isexe, "isexe");
    function sync2(path125, options2) {
      return checkStat(fs113.statSync(path125), options2);
    }
    __name(sync2, "sync");
    function checkStat(stat10, options2) {
      return stat10.isFile() && checkMode(stat10, options2);
    }
    __name(checkStat, "checkStat");
    function checkMode(stat10, options2) {
      var mod2 = stat10.mode;
      var uid = stat10.uid;
      var gid = stat10.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 u2 = parseInt("100", 8);
      var g2 = parseInt("010", 8);
      var o3 = parseInt("001", 8);
      var ug = u2 | g2;
      var ret = mod2 & o3 || mod2 & g2 && gid === myGid || mod2 & u2 && 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 fs113 = __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(path125, 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(resolve30, reject) {
          isexe(path125, options2 || {}, function(er2, is) {
            if (er2) {
              reject(er2);
            } else {
              resolve30(is);
            }
          });
        });
      }
      core(path125, options2 || {}, function(er2, is) {
        if (er2) {
          if (er2.code === "EACCES" || options2 && options2.ignoreErrors) {
            er2 = null;
            is = false;
          }
        }
        cb(er2, is);
      });
    }
    __name(isexe, "isexe");
    function sync2(path125, options2) {
      try {
        return core.sync(path125, options2 || {});
      } catch (er2) {
        if (options2 && options2.ignoreErrors || er2.code === "EACCES") {
          return false;
        } else {
          throw er2;
        }
      }
    }
    __name(sync2, "sync");
  }
});

// node_modules/which/which.js
var require_which = __commonJS({
  "node_modules/which/which.js"(exports2, module2) {
    init_esbuild_shims();
    var isWindows9 = process.platform === "win32" || process.env.OSTYPE === "cygwin" || process.env.OSTYPE === "msys";
    var path125 = __require("path");
    var COLON3 = isWindows9 ? ";" : ":";
    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 || COLON3;
      const pathEnv = cmd.match(/\//) || isWindows9 && cmd.match(/\\/) ? [""] : [
        // windows always checks the cwd first
        ...isWindows9 ? [process.cwd()] : [],
        ...(opt.path || process.env.PATH || /* istanbul ignore next: very unusual */
        "").split(colon)
      ];
      const pathExtExe = isWindows9 ? opt.pathExt || process.env.PATHEXT || ".EXE;.CMD;.BAT;.COM" : "";
      const pathExt = isWindows9 ? pathExtExe.split(colon) : [""];
      if (isWindows9) {
        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((i3) => new Promise((resolve30, reject) => {
        if (i3 === pathEnv.length)
          return opt.all && found.length ? resolve30(found) : reject(getNotFoundError(cmd));
        const ppRaw = pathEnv[i3];
        const pathPart = /^".*"$/.test(ppRaw) ? ppRaw.slice(1, -1) : ppRaw;
        const pCmd = path125.join(pathPart, cmd);
        const p2 = !pathPart && /^\.[\\\/]/.test(cmd) ? cmd.slice(0, 2) + pCmd : pCmd;
        resolve30(subStep(p2, i3, 0));
      }), "step");
      const subStep = /* @__PURE__ */ __name((p2, i3, ii) => new Promise((resolve30, reject) => {
        if (ii === pathExt.length)
          return resolve30(step(i3 + 1));
        const ext2 = pathExt[ii];
        isexe(p2 + ext2, { pathExt: pathExtExe }, (er2, is) => {
          if (!er2 && is) {
            if (opt.all)
              found.push(p2 + ext2);
            else
              return resolve30(p2 + ext2);
          }
          return resolve30(subStep(p2, i3, 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 i3 = 0; i3 < pathEnv.length; i3++) {
        const ppRaw = pathEnv[i3];
        const pathPart = /^".*"$/.test(ppRaw) ? ppRaw.slice(1, -1) : ppRaw;
        const pCmd = path125.join(pathPart, cmd);
        const p2 = !pathPart && /^\.[\\\/]/.test(cmd) ? cmd.slice(0, 2) + pCmd : pCmd;
        for (let j2 = 0; j2 < pathExt.length; j2++) {
          const cur = p2 + pathExt[j2];
          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 platform16 = options2.platform || process.platform;
      if (platform16 !== "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 path125 = __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 ? path125.delimiter : void 0
        });
      } catch (e4) {
      } finally {
        if (shouldSwitchCwd) {
          process.chdir(cwd7);
        }
      }
      if (resolved) {
        resolved = path125.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 = (string4 = "") => {
      const match2 = string4.match(shebangRegex);
      if (!match2) {
        return null;
      }
      const [path125, argument] = match2[0].replace(/#! ?/, "").split(" ");
      const binary = path125.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 fs113 = __require("fs");
    var shebangCommand = require_shebang_command();
    function readShebang(command2) {
      const size = 150;
      const buffer = Buffer.alloc(size);
      let fd;
      try {
        fd = fs113.openSync(command2, "r");
        fs113.readSync(fd, buffer, 0, size, 0);
        fs113.closeSync(fd);
      } catch (e4) {
      }
      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 path125 = __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 = path125.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 parse14(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(parse14, "parse");
    module2.exports = parse14;
  }
});

// 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(cp3, parsed) {
      if (!isWin) {
        return;
      }
      const originalEmit = cp3.emit;
      cp3.emit = function(name3, arg1) {
        if (name3 === "exit") {
          const err = verifyENOENT(arg1, parsed);
          if (err) {
            return originalEmit.call(cp3, "error", err);
          }
        }
        return originalEmit.apply(cp3, 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 cp3 = __require("child_process");
    var parse14 = require_parse5();
    var enoent = require_enoent();
    function spawn13(command2, args, options2) {
      const parsed = parse14(command2, args, options2);
      const spawned = cp3.spawn(parsed.command, parsed.args, parsed.options);
      enoent.hookChildProcess(spawned, parsed);
      return spawned;
    }
    __name(spawn13, "spawn");
    function spawnSync6(command2, args, options2) {
      const parsed = parse14(command2, args, options2);
      const result = cp3.spawnSync(parsed.command, parsed.args, parsed.options);
      result.error = result.error || enoent.verifyENOENTSync(result.status, parsed);
      return result;
    }
    __name(spawnSync6, "spawnSync");
    module2.exports = spawn13;
    module2.exports.spawn = spawn13;
    module2.exports.sync = spawnSync6;
    module2.exports._parse = parse14;
    module2.exports._enoent = enoent;
  }
});

// packages/core/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({
  "packages/core/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/stdio.js"() {
    init_esbuild_shims();
    init_types8();
    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");
  }
});

// packages/core/node_modules/@modelcontextprotocol/sdk/dist/esm/client/stdio.js
import process10 from "node:process";
import { PassThrough as PassThrough3 } from "node:stream";
function getDefaultEnvironment() {
  const env7 = {};
  for (const key of DEFAULT_INHERITED_ENV_VARS) {
    const value = process10.env[key];
    if (value === void 0) {
      continue;
    }
    if (value.startsWith("()")) {
      continue;
    }
    env7[key] = value;
  }
  return env7;
}
function isElectron() {
  return "type" in process10;
}
var import_cross_spawn, DEFAULT_INHERITED_ENV_VARS, StdioClientTransport;
var init_stdio2 = __esm({
  "packages/core/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 = process10.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._readBuffer = new ReadBuffer();
        this._stderrStream = null;
        this._serverParams = server;
        if (server.stderr === "pipe" || server.stderr === "overlapped") {
          this._stderrStream = new PassThrough3();
        }
      }
      /**
       * 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((resolve30, reject) => {
          this._process = (0, import_cross_spawn.default)(this._serverParams.command, this._serverParams.args ?? [], {
            // merge default env with server env because mcp server needs some env vars
            env: {
              ...getDefaultEnvironment(),
              ...this._serverParams.env
            },
            stdio: ["pipe", "pipe", this._serverParams.stderr ?? "inherit"],
            shell: false,
            windowsHide: process10.platform === "win32" && isElectron(),
            cwd: this._serverParams.cwd
          });
          this._process.on("error", (error2) => {
            reject(error2);
            this.onerror?.(error2);
          });
          this._process.on("spawn", () => {
            resolve30();
          });
          this._process.on("close", (_code) => {
            this._process = void 0;
            this.onclose?.();
          });
          this._process.stdin?.on("error", (error2) => {
            this.onerror?.(error2);
          });
          this._process.stdout?.on("data", (chunk) => {
            this._readBuffer.append(chunk);
            this.processReadBuffer();
          });
          this._process.stdout?.on("error", (error2) => {
            this.onerror?.(error2);
          });
          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() {
        if (this._stderrStream) {
          return this._stderrStream;
        }
        return this._process?.stderr ?? null;
      }
      /**
       * The child process pid spawned by this transport.
       *
       * This is only available after the transport has been started.
       */
      get pid() {
        return this._process?.pid ?? null;
      }
      processReadBuffer() {
        while (true) {
          try {
            const message = this._readBuffer.readMessage();
            if (message === null) {
              break;
            }
            this.onmessage?.(message);
          } catch (error2) {
            this.onerror?.(error2);
          }
        }
      }
      async close() {
        if (this._process) {
          const processToClose = this._process;
          this._process = void 0;
          const closePromise = new Promise((resolve30) => {
            processToClose.once("close", () => {
              resolve30();
            });
          });
          try {
            processToClose.stdin?.end();
          } catch {
          }
          await Promise.race([closePromise, new Promise((resolve30) => setTimeout(resolve30, 2e3).unref())]);
          if (processToClose.exitCode === null) {
            try {
              processToClose.kill("SIGTERM");
            } catch {
            }
            await Promise.race([closePromise, new Promise((resolve30) => setTimeout(resolve30, 2e3).unref())]);
          }
          if (processToClose.exitCode === null) {
            try {
              processToClose.kill("SIGKILL");
            } catch {
            }
          }
        }
        this._readBuffer.clear();
      }
      send(message) {
        return new Promise((resolve30) => {
          if (!this._process?.stdin) {
            throw new Error("Not connected");
          }
          const json2 = serializeMessage(message);
          if (this._process.stdin.write(json2)) {
            resolve30();
          } else {
            this._process.stdin.once("drain", resolve30);
          }
        });
      }
    };
    __name(isElectron, "isElectron");
  }
});

// packages/core/dist/src/ide/ide-client.js
import * as fs33 from "node:fs";
import * as os15 from "node:os";
import * as path32 from "node:path";
function getRealPath(path125) {
  try {
    return fs33.realpathSync(path125);
  } catch (_e2) {
    return path125;
  }
}
function getIdeServerHost() {
  const isInContainer = fs33.existsSync("/.dockerenv") || fs33.existsSync("/run/.containerenv");
  return isInContainer ? "host.docker.internal" : "127.0.0.1";
}
var import_undici2, debugLogger34, 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_storage();
    init_types7();
    init_process_utils();
    init_client4();
    init_streamableHttp();
    init_stdio2();
    init_types8();
    import_undici2 = __toESM(require_undici(), 1);
    init_types8();
    init_constants5();
    init_debugLogger();
    debugLogger34 = createDebugLogger("IDE");
    (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: error2 } = _IdeClient.validateWorkspacePath(workspacePath, process.cwd());
        if (!isValid2) {
          this.setState(IDEConnectionStatus.Disconnected, error2, 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((resolve30, reject) => {
          if (!this.client) {
            return reject(new Error("IDE client is not connected."));
          }
          this.diffResponses.set(filePath, resolve30);
          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.`;
              debugLogger34.debug(`Request for openDiff ${filePath} failed with isError:`, errorMessage);
              this.diffResponses.delete(filePath);
              reject(new Error(errorMessage));
            }
          }).catch((err) => {
            debugLogger34.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((resolve30) => {
          release3 = resolve30;
        });
        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.`;
            debugLogger34.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 (_e2) {
              debugLogger34.debug(`Invalid JSON in closeDiff response for ${filePath}:`, textPart.text);
            }
          }
        } catch (err) {
          debugLogger34.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 {
          debugLogger34.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) {
            debugLogger34.debug(`Discovered ${this.availableTools.length} tools from IDE: ${this.availableTools.join(", ")}`);
          } else {
            debugLogger34.debug("IDE supports tool discovery, but no tools are available.");
          }
        } catch (error2) {
          if (error2 instanceof Error && !error2.message?.includes("Method not found")) {
            debugLogger34.error(`Error discovering tools from IDE: ${error2.message}`);
          } else {
            debugLogger34.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) {
              debugLogger34.error(details);
            } else {
              debugLogger34.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(path32.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 {
              debugLogger34.error("QWEN_CODE_IDE_SERVER_STDIO_ARGS must be a JSON array string.");
            }
          } catch (e4) {
            debugLogger34.error("Failed to parse QWEN_CODE_IDE_SERVER_STDIO_ARGS:", e4);
          }
        }
        return { command: command2, args };
      }
      async getConnectionConfigFromFile() {
        const portFromEnv = this.getPortFromEnv();
        if (portFromEnv) {
          try {
            const ideDir = Storage.getGlobalIdeDir();
            const lockFile = path32.join(ideDir, `${portFromEnv}.lock`);
            const lockFileContents = await fs33.promises.readFile(lockFile, "utf8");
            return JSON.parse(lockFileContents);
          } catch (_2) {
          }
        }
        return this.getLegacyConnectionConfig(portFromEnv);
      }
      // Legacy connection files were written in the global temp directory.
      async getLegacyConnectionConfig(portFromEnv) {
        if (this.ideProcessInfo) {
          try {
            const portFile = path32.join(os15.tmpdir(), `qwen-code-ide-server-${this.ideProcessInfo.pid}.json`);
            const portFileContents = await fs33.promises.readFile(portFile, "utf8");
            return JSON.parse(portFileContents);
          } catch (_2) {
          }
        }
        if (portFromEnv) {
          try {
            const portFile = path32.join(os15.tmpdir(), `qwen-code-ide-server-${portFromEnv}.json`);
            const portFileContents = await fs33.promises.readFile(portFile, "utf8");
            return JSON.parse(portFileContents);
          } catch (_2) {
          }
        }
        return void 0;
      }
      async getAllConnectionConfigs(ideDir) {
        const fileRegex = new RegExp("^\\d+\\.lock$");
        let lockFiles;
        try {
          lockFiles = (await fs33.promises.readdir(ideDir)).filter((file) => fileRegex.test(file));
        } catch (e4) {
          debugLogger34.debug("Failed to read IDE connection directory:", e4);
          return [];
        }
        const fileContents = await Promise.all(lockFiles.map(async (file) => {
          const fullPath = path32.join(ideDir, file);
          try {
            const stat10 = await fs33.promises.stat(fullPath);
            const content = await fs33.promises.readFile(fullPath, "utf8");
            try {
              const parsed = JSON.parse(content);
              return { file, mtimeMs: stat10.mtimeMs, parsed };
            } catch (e4) {
              debugLogger34.debug("Failed to parse JSON from lock file: ", e4);
              return { file, mtimeMs: stat10.mtimeMs, parsed: void 0 };
            }
          } catch (e4) {
            debugLogger34.debug("Failed to read/stat IDE lock file:", e4);
            return { file, mtimeMs: -Infinity, parsed: void 0 };
          }
        }));
        return fileContents.filter(({ parsed }) => parsed !== void 0).sort((a2, b2) => b2.mtimeMs - a2.mtimeMs).map(({ parsed }) => parsed);
      }
      createProxyAwareFetch() {
        const existingNoProxy = process.env["NO_PROXY"] || "";
        const agent = new import_undici2.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 {
            debugLogger34.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 {
            debugLogger34.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 {
            debugLogger34.debug(`No resolver found for ${filePath}`);
          }
        });
      }
      async establishHttpConnection(port) {
        let transport;
        try {
          debugLogger34.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) {
              debugLogger34.debug("Failed to close transport:", closeError);
            }
          }
          return false;
        }
      }
      async establishStdioConnection({ command: command2, args }) {
        let transport;
        try {
          debugLogger34.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) {
              debugLogger34.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 normalizeLineForComparison(value) {
  return normalizeBasicCharacters(value).trimEnd();
}
function seekSequenceWithTransform(lines, pattern, transform2) {
  if (pattern.length === 0) {
    return 0;
  }
  if (pattern.length > lines.length) {
    return null;
  }
  outer: for (let i3 = 0; i3 <= lines.length - pattern.length; i3++) {
    for (let p2 = 0; p2 < pattern.length; p2++) {
      if (transform2(lines[i3 + p2]) !== transform2(pattern[p2])) {
        continue outer;
      }
    }
    return i3;
  }
  return null;
}
function buildLineIndex(text) {
  const lines = text.split("\n");
  const offsets = new Array(lines.length + 1);
  let cursor = 0;
  for (let i3 = 0; i3 < lines.length; i3++) {
    offsets[i3] = cursor;
    cursor += lines[i3].length;
    if (i3 < 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) {
  if (fileContent === null || oldString === "") {
    return {
      oldString,
      newString
    };
  }
  const canonicalOriginal = findMatchedSlice(fileContent, oldString);
  if (canonicalOriginal !== null) {
    return {
      oldString: canonicalOriginal.slice,
      newString: adjustNewStringForTrailingLine(newString, canonicalOriginal.removedTrailingFinalEmptyLine)
    };
  }
  return {
    oldString,
    newString
  };
}
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");
    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 fs34 from "node:fs";
import * as path33 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 debugLogger35, 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_fileSystemService();
    init_diffOptions();
    init_read_file();
    init_tool_names();
    init_loggers();
    init_types();
    init_metrics2();
    init_fileUtils();
    init_language_detection();
    init_ide_client();
    init_textUtils();
    init_debugLogger();
    init_editHelper();
    debugLogger35 = createDebugLogger("EDIT");
    __name(applyReplacement, "applyReplacement");
    EditToolInvocation = class {
      static {
        __name(this, "EditToolInvocation");
      }
      config;
      params;
      constructor(config2, params) {
        this.config = config2;
        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 error2 = 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) {
          error2 = {
            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 === "") {
            error2 = {
              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) {
            error2 = {
              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) {
            error2 = {
              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) {
            error2 = {
              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 {
          error2 = {
            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 = !error2 ? applyReplacement(currentContent, finalOldString, finalNewString, isNewFile) : currentContent ?? "";
        if (!error2 && fileExists2 && currentContent === newContent) {
          error2 = {
            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: error2,
          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 (error2) {
          if (abortSignal.aborted) {
            throw error2;
          }
          const errorMsg = error2 instanceof Error ? error2.message : String(error2);
          debugLogger35.warn(`Error preparing edit: ${errorMsg}`);
          return false;
        }
        if (editData.error) {
          debugLogger35.warn(`Error: ${editData.error.display}`);
          return false;
        }
        const fileName = path33.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 (error2) {
          if (signal.aborted) {
            throw error2;
          }
          const errorMsg = error2 instanceof Error ? error2.message : String(error2);
          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);
          if (editData.isNewFile) {
            const useBOM = this.config.getDefaultFileEncoding() === FileEncoding.UTF8_BOM;
            await this.config.getFileSystemService().writeTextFile(this.params.file_path, editData.newContent, {
              bom: useBOM
            });
          } else {
            await this.config.getFileSystemService().writeTextFile(this.params.file_path, editData.newContent);
          }
          const fileName = path33.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 = path33.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 (error2) {
          const errorMsg = error2 instanceof Error ? error2.message : String(error2);
          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 = path33.dirname(filePath);
        if (!fs34.existsSync(dirName)) {
          fs34.mkdirSync(dirName, { recursive: true });
        }
      }
    };
    EditTool = class _EditTool extends BaseDeclarativeTool {
      static {
        __name(this, "EditTool");
      }
      config;
      static Name = ToolNames.EDIT;
      constructor(config2) {
        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 = config2;
      }
      /**
       * 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 (!path33.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(_2) {
        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 debugLogger36, 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();
    init_debugLogger();
    debugLogger36 = createDebugLogger("EXIT_PLAN_MODE");
    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(config2, params) {
        super(params);
        this.config = config2;
      }
      getDescription() {
        return "Plan:";
      }
      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 (error2) {
          const errorMessage = error2 instanceof Error ? error2.message : String(error2);
          debugLogger36.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 (error2) {
          const errorMessage = error2 instanceof Error ? error2.message : String(error2);
          debugLogger36.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(config2) {
        super(_ExitPlanModeTool.Name, ToolDisplayNames.EXIT_PLAN_MODE, exitPlanModeToolDescription, Kind.Think, exitPlanModeToolSchemaData.parametersJsonSchema);
        this.config = config2;
      }
      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 fs35 from "node:fs";
import path34 from "node:path";
function sortFileEntries(entries, nowTimestamp, recencyThresholdMs) {
  const sortedEntries = [...entries];
  sortedEntries.sort((a2, b2) => {
    const mtimeA = a2.mtimeMs ?? 0;
    const mtimeB = b2.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 a2.fullpath().localeCompare(b2.fullpath());
    }
  });
  return sortedEntries;
}
var debugLogger37, MAX_FILE_COUNT, GlobToolInvocation, GlobTool;
var init_glob2 = __esm({
  "packages/core/dist/src/tools/glob.js"() {
    "use strict";
    init_esbuild_shims();
    init_esm11();
    init_tools();
    init_tool_names();
    init_paths();
    init_config3();
    init_constants4();
    init_tool_error();
    init_errors();
    init_debugLogger();
    debugLogger37 = createDebugLogger("GLOB");
    MAX_FILE_COUNT = 100;
    __name(sortFileEntries, "sortFileEntries");
    GlobToolInvocation = class extends BaseToolInvocation {
      static {
        __name(this, "GlobToolInvocation");
      }
      config;
      fileService;
      constructor(config2, params) {
        super(params);
        this.config = config2;
        this.fileService = config2.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 = path34.join(searchDirAbs, pattern);
          if (fs35.existsSync(fullPath)) {
            pattern = escape2(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((p2) => path34.relative(this.config.getTargetDir(), p2.fullpath()));
          const { filteredPaths } = this.fileService.filterFilesWithReport(relativePaths, this.getFileFilteringOptions());
          const normalizePathForComparison = /* @__PURE__ */ __name((p2) => process.platform === "win32" || process.platform === "darwin" ? p2.toLowerCase() : p2, "normalizePathForComparison");
          const filteredAbsolutePaths = new Set(filteredPaths.map((p2) => normalizePathForComparison(path34.resolve(this.config.getTargetDir(), p2))));
          const filteredEntries = allEntries.filter((entry) => filteredAbsolutePaths.has(normalizePathForComparison(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 (error2) {
          const errorMessage = error2 instanceof Error ? error2.message : String(error2);
          debugLogger37.error(`GlobLogic execute Error: ${errorMessage}`, error2);
          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(config2) {
        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 = config2;
      }
      /**
       * 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 (error2) {
            return getErrorMessage(error2);
          }
        }
        return null;
      }
      createInvocation(params) {
        return new GlobToolInvocation(this.config, params);
      }
    };
  }
});

// packages/core/dist/src/tools/grep.js
import fsPromises2 from "node:fs/promises";
import path35 from "node:path";
import { EOL as EOL2 } from "node:os";
import { spawn as spawn4 } from "node:child_process";
var debugLogger38, GrepToolInvocation, GrepTool;
var init_grep2 = __esm({
  "packages/core/dist/src/tools/grep.js"() {
    "use strict";
    init_esbuild_shims();
    init_esm11();
    init_tools();
    init_tool_names();
    init_debugLogger();
    init_paths();
    init_errors();
    init_gitUtils();
    init_tool_error();
    init_shell_utils();
    debugLogger38 = createDebugLogger("GREP");
    GrepToolInvocation = class extends BaseToolInvocation {
      static {
        __name(this, "GrepToolInvocation");
      }
      config;
      fileExclusions;
      constructor(config2, params) {
        super(params);
        this.config = config2;
        this.fileExclusions = config2.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((a2, b2) => a2.lineNumber - b2.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 (error2) {
          debugLogger38.error(`Error during GrepLogic execution: ${error2}`);
          const errorMessage = getErrorMessage(error2);
          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 = path35.resolve(basePath, filePathRaw);
            const relativeFilePath = path35.relative(basePath, absoluteFilePath);
            results.push({
              filePath: relativeFilePath || path35.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((resolve30, 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)
                    resolve30(stdoutData);
                  else if (code2 === 1)
                    resolve30("");
                  else
                    reject(new Error(`git grep exited with code ${code2}: ${stderrData}`));
                });
              });
              return this.parseGrepOutput(output, absolutePath);
            } catch (gitError) {
              debugLogger38.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((resolve30, 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)
                    resolve30(stdoutData);
                  else if (code2 === 1)
                    resolve30("");
                  else {
                    if (stderrData)
                      reject(new Error(`System grep exited with code ${code2}: ${stderrData}`));
                    else
                      resolve30("");
                  }
                }, "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) {
              debugLogger38.debug(`GrepLogic: System grep failed: ${getErrorMessage(grepError)}. Falling back...`);
            }
          }
          debugLogger38.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: path35.relative(absolutePath, fileAbsolutePath) || path35.basename(fileAbsolutePath),
                    lineNumber: index + 1,
                    line
                  });
                }
              });
            } catch (readError) {
              if (!isNodeError(readError) || readError.code !== "ENOENT") {
                debugLogger38.debug(`GrepLogic: Could not read/process ${fileAbsolutePath}: ${getErrorMessage(readError)}`);
              }
            }
          }
          return allMatches;
        } catch (error2) {
          debugLogger38.error(`GrepLogic: Error in performGrepSearch (Strategy: ${strategyUsed}): ${getErrorMessage(error2)}`);
          throw error2;
        }
      }
    };
    GrepTool = class _GrepTool extends BaseDeclarativeTool {
      static {
        __name(this, "GrepTool");
      }
      config;
      static Name = ToolNames.GREP;
      constructor(config2) {
        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 = config2;
      }
      /**
       * 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 (error2) {
          return `Invalid regular expression pattern: ${params.pattern}. Error: ${getErrorMessage(error2)}`;
        }
        if (params.path) {
          try {
            resolveAndValidatePath(this.config, params.path);
          } catch (error2) {
            return getErrorMessage(error2);
          }
        }
        return null;
      }
      createInvocation(params) {
        return new GrepToolInvocation(this.config, params);
      }
    };
  }
});

// packages/core/dist/src/tools/ls.js
import fs36 from "node:fs/promises";
import path36 from "node:path";
var debugLogger39, LSToolInvocation, LSTool;
var init_ls = __esm({
  "packages/core/dist/src/tools/ls.js"() {
    "use strict";
    init_esbuild_shims();
    init_tools();
    init_paths();
    init_paths();
    init_constants4();
    init_tool_error();
    init_tool_names();
    init_debugLogger();
    debugLogger39 = createDebugLogger("LS");
    LSToolInvocation = class extends BaseToolInvocation {
      static {
        __name(this, "LSToolInvocation");
      }
      config;
      constructor(config2, params) {
        super(params);
        this.config = config2;
      }
      /**
       * 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 fs36.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 fs36.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) => path36.relative(this.config.getTargetDir(), path36.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 = path36.resolve(this.config.getTargetDir(), relativePath);
            if (this.shouldIgnore(path36.basename(fullPath), this.params.ignore)) {
              continue;
            }
            try {
              const stats2 = await fs36.stat(fullPath);
              const isDir = stats2.isDirectory();
              entries.push({
                name: path36.basename(fullPath),
                path: fullPath,
                isDirectory: isDir,
                size: isDir ? 0 : stats2.size,
                modifiedTime: stats2.mtime
              });
            } catch (error2) {
              debugLogger39.warn(`Error accessing ${fullPath}: ${error2}`);
            }
          }
          entries.sort((a2, b2) => {
            if (a2.isDirectory && !b2.isDirectory)
              return -1;
            if (!a2.isDirectory && b2.isDirectory)
              return 1;
            return a2.name.localeCompare(b2.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 (error2) {
          const errorMsg = `Error listing directory: ${error2 instanceof Error ? error2.message : String(error2)}`;
          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(config2) {
        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 = config2;
      }
      /**
       * Validates the parameters for the tool
       * @param params Parameters to validate
       * @returns An error message string if invalid, null otherwise
       */
      validateToolParamValues(params) {
        if (!path36.isAbsolute(params.path)) {
          return `Path must be absolute: ${params.path}`;
        }
        const userSkillsBase = this.config.storage.getUserSkillsDir();
        const isUnderUserSkills = isSubpath(userSkillsBase, params.path);
        const workspaceContext = this.config.getWorkspaceContext();
        if (!workspaceContext.isPathWithinWorkspace(params.path) && !isUnderUserSkills) {
          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/utils/ripgrepUtils.js
import path37 from "node:path";
import { fileURLToPath as fileURLToPath5 } from "node:url";
import { execFile as execFile8 } from "node:child_process";
function wslTimeout() {
  return process.platform === "linux" && process.env["WSL_INTEROP"] ? RIPGREP_WSL_TIMEOUT_MS : RIPGREP_RUN_TIMEOUT_MS;
}
function getPlatformString(platform16) {
  switch (platform16) {
    case "darwin":
    case "linux":
    case "win32":
      return platform16;
    default:
      return void 0;
  }
}
function getArchitectureString(arch3) {
  switch (arch3) {
    case "x64":
    case "arm64":
      return arch3;
    default:
      return void 0;
  }
}
function getBuiltinRipgrep() {
  const platform16 = getPlatformString(process.platform);
  const arch3 = getArchitectureString(process.arch);
  if (!platform16 || !arch3) {
    return null;
  }
  const binaryName = platform16 === "win32" ? "rg.exe" : "rg";
  const inSrcUtils = __filename2.includes(path37.join("src", "utils"));
  const levelsUp = !inSrcUtils ? 0 : __filename2.endsWith(".ts") ? 2 : 3;
  return path37.join(__dirname3, ...Array(levelsUp).fill(".."), "vendor", "ripgrep", `${arch3}-${platform16}`, binaryName);
}
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: error2 } = isCommandAvailable(RIPGREP_COMMAND);
  if (available) {
    cachedSelection = { mode: "system", command: RIPGREP_COMMAND };
    return cachedSelection;
  }
  if (error2) {
    throw error2;
  }
  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 (error2) {
    cachedHealth = { working: false, lastTested: Date.now(), selection };
    throw error2;
  }
}
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((resolve30) => {
    const child = execFile8(selection.command, args, {
      maxBuffer: RIPGREP_BUFFER_LIMIT,
      timeout: wslTimeout(),
      signal
    }, (error2, stdout = "", stderr = "") => {
      if (!error2) {
        resolve30({
          stdout,
          truncated: false
        });
        return;
      }
      const errorCode = error2.code;
      if (errorCode === 1) {
        resolve30({ stdout: "", truncated: false });
        return;
      }
      const wasKilled = error2.signal === "SIGTERM" || error2.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) {
        debugLogger40.warn(`ripgrep exited abnormally (signal=${error2.signal} code=${error2.code}) with stderr:
${stderr.trim() || "(empty)"}`);
      }
      resolve30({
        stdout: partialOutput,
        truncated,
        error: error2 instanceof Error ? error2 : void 0
      });
    });
    child.on("error", (err) => resolve30({ stdout: "", truncated: false, error: err }));
  });
}
var debugLogger40, 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();
    init_debugLogger();
    debugLogger40 = createDebugLogger("RIPGREP");
    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 = path37.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 fs37 from "node:fs";
import path38 from "node:path";
var debugLogger41, 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_constants4();
    init_debugLogger();
    debugLogger41 = createDebugLogger("RIPGREP");
    GrepToolInvocation2 = class extends BaseToolInvocation {
      static {
        __name(this, "GrepToolInvocation");
      }
      config;
      constructor(config2, params) {
        super(params);
        this.config = config2;
      }
      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 sep9 = includedLines > 0 ? 1 : 0;
              includedLines++;
              const projectedLength = currentLength + line.length + sep9;
              if (projectedLength <= charLimit) {
                parts.push(line);
                currentLength = projectedLength;
              } else {
                const remaining = Math.max(charLimit - currentLength - sep9, 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 (error2) {
          debugLogger41.error("Error during ripgrep search operation:", error2);
          const errorMessage = getErrorMessage(error2);
          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 = path38.join(this.config.getTargetDir(), ".qwenignore");
          if (fs37.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(config2) {
        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 = config2;
      }
      /**
       * 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 (error2) {
          return `Invalid regular expression pattern: ${params.pattern}. Error: ${getErrorMessage(error2)}`;
        }
        if (params.path) {
          try {
            resolveAndValidatePath(this.config, params.path, { allowFiles: true });
          } catch (error2) {
            return getErrorMessage(error2);
          }
        }
        return null;
      }
      createInvocation(params) {
        return new GrepToolInvocation2(this.config, params);
      }
    };
  }
});

// packages/core/dist/src/tools/skill.js
import path39 from "path";
var debugLogger42, SkillTool, SkillToolInvocation;
var init_skill = __esm({
  "packages/core/dist/src/tools/skill.js"() {
    "use strict";
    init_esbuild_shims();
    init_tools();
    init_tool_names();
    init_telemetry();
    init_debugLogger();
    debugLogger42 = createDebugLogger("SKILL");
    SkillTool = class _SkillTool extends BaseDeclarativeTool {
      static {
        __name(this, "SkillTool");
      }
      config;
      static Name = ToolNames.SKILL;
      skillManager;
      availableSkills = [];
      constructor(config2) {
        const initialSchema = {
          type: "object",
          properties: {
            skill: {
              type: "string",
              description: 'The skill name (no arguments). E.g., "pdf" or "xlsx"'
            }
          },
          required: ["skill"],
          additionalProperties: false,
          $schema: "http://json-schema.org/draft-07/schema#"
        };
        super(
          _SkillTool.Name,
          ToolDisplayNames.SKILL,
          "Execute a skill within the main conversation. Loading available skills...",
          // Initial description
          Kind.Read,
          initialSchema,
          false,
          // isOutputMarkdown
          false
        );
        this.config = config2;
        const skillManager = config2.getSkillManager();
        if (!skillManager) {
          throw new Error("SkillManager not available");
        }
        this.skillManager = skillManager;
        this.skillManager.addChangeListener(() => {
          void this.refreshSkills();
        });
        this.refreshSkills();
      }
      /**
       * Asynchronously initializes the tool by loading available skills
       * and updating the description and schema.
       */
      async refreshSkills() {
        try {
          this.availableSkills = await this.skillManager.listSkills();
          this.updateDescriptionAndSchema();
        } catch (error2) {
          debugLogger42.warn("Failed to load skills for Skills tool:", error2);
          this.availableSkills = [];
          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 skills.
       */
      updateDescriptionAndSchema() {
        let skillDescriptions = "";
        if (this.availableSkills.length === 0) {
          skillDescriptions = "No skills are currently configured. Skills can be created by adding directories with SKILL.md files to .qwen/skills/ or ~/.qwen/skills/.";
        } else {
          skillDescriptions = this.availableSkills.map((skill) => `<skill>
<name>
${skill.name}
</name>
<description>
${skill.description} (${skill.level})
</description>
<location>
${skill.level}
</location>
</skill>`).join("\n");
        }
        const baseDescription = `Execute a skill within the main conversation

<skills_instructions>
When users ask you to perform tasks, check if any of the available skills below can help complete the task more effectively. Skills provide specialized capabilities and domain knowledge.

How to invoke:
- Use this tool with the skill name only (no arguments)
- Examples:
  - \`skill: "pdf"\` - invoke the pdf skill
  - \`skill: "xlsx"\` - invoke the xlsx skill
  - \`skill: "ms-office-suite:pdf"\` - invoke using fully qualified name

Important:
- When a skill is relevant, you must invoke this tool IMMEDIATELY as your first action
- NEVER just announce or mention a skill in your text response without actually calling this tool
- This is a BLOCKING REQUIREMENT: invoke the relevant Skill tool BEFORE generating any other response about the task
- Only use skills listed in <available_skills> below
- Do not invoke a skill that is already running
- Do not use this tool for built-in CLI commands (like /help, /clear, etc.)
- When executing scripts or loading referenced files, ALWAYS resolve absolute paths from skill's base directory. Examples:
  - \`bash scripts/init.sh\` -> \`bash /path/to/skill/scripts/init.sh\`
  - \`python scripts/helper.py\` -> \`python /path/to/skill/scripts/helper.py\`
  - \`reference.md\` -> \`/path/to/skill/reference.md\`
</skills_instructions>

<available_skills>
${skillDescriptions}
</available_skills>
`;
        this.description = baseDescription;
      }
      validateToolParams(params) {
        if (!params.skill || typeof params.skill !== "string" || params.skill.trim() === "") {
          return 'Parameter "skill" must be a non-empty string.';
        }
        const skillExists = this.availableSkills.some((skill) => skill.name === params.skill);
        if (!skillExists) {
          const availableNames = this.availableSkills.map((s5) => s5.name);
          if (availableNames.length === 0) {
            return `Skill "${params.skill}" not found. No skills are currently available.`;
          }
          return `Skill "${params.skill}" not found. Available skills: ${availableNames.join(", ")}`;
        }
        return null;
      }
      createInvocation(params) {
        return new SkillToolInvocation(this.config, this.skillManager, params);
      }
      getAvailableSkillNames() {
        return this.availableSkills.map((skill) => skill.name);
      }
    };
    SkillToolInvocation = class extends BaseToolInvocation {
      static {
        __name(this, "SkillToolInvocation");
      }
      config;
      skillManager;
      constructor(config2, skillManager, params) {
        super(params);
        this.config = config2;
        this.skillManager = skillManager;
      }
      getDescription() {
        return `Use skill: "${this.params.skill}"`;
      }
      async shouldConfirmExecute() {
        return false;
      }
      async execute(_signal, _updateOutput) {
        try {
          const skill = await this.skillManager.loadSkillForRuntime(this.params.skill);
          if (!skill) {
            logSkillLaunch(this.config, new SkillLaunchEvent(this.params.skill, false));
            const parseErrors = this.skillManager.getParseErrors();
            const errorMessages = [];
            for (const [filePath, error2] of parseErrors) {
              if (filePath.includes(this.params.skill)) {
                errorMessages.push(`Parse error at ${filePath}: ${error2.message}`);
              }
            }
            const errorDetail = errorMessages.length > 0 ? `
Errors:
${errorMessages.join("\n")}` : "";
            return {
              llmContent: `Skill "${this.params.skill}" not found.${errorDetail}`,
              returnDisplay: `Skill "${this.params.skill}" not found.${errorDetail}`
            };
          }
          logSkillLaunch(this.config, new SkillLaunchEvent(this.params.skill, true));
          const baseDir = path39.dirname(skill.filePath);
          const llmContent = `Base directory for this skill: ${baseDir}
Important: ALWAYS resolve absolute paths from this base directory when working with skills.

${skill.body}
`;
          return {
            llmContent: [{ text: llmContent }],
            returnDisplay: skill.description
          };
        } catch (error2) {
          const errorMessage = error2 instanceof Error ? error2.message : String(error2);
          debugLogger42.error(`[SkillsTool] Error using skill: ${errorMessage}`);
          logSkillLaunch(this.config, new SkillLaunchEvent(this.params.skill, false));
          return {
            llmContent: `Failed to load skill "${this.params.skill}": ${errorMessage}`,
            returnDisplay: `Failed to load skill "${this.params.skill}": ${errorMessage}`
          };
        }
      }
    };
  }
});

// packages/core/dist/src/tools/todoWrite.js
import * as fs38 from "fs/promises";
import * as fsSync from "fs";
import * as path40 from "path";
import * as process11 from "process";
function getTodoFilePath(sessionId) {
  const homeDir = process11.env["HOME"] || process11.env["USERPROFILE"] || process11.cwd();
  const todoDir = path40.join(homeDir, QWEN_DIR, TODO_SUBDIR);
  const filename = `${sessionId || "default"}.json`;
  return path40.join(todoDir, filename);
}
async function writeTodosToFile(todos, sessionId) {
  const todoFilePath = getTodoFilePath(sessionId);
  const todoDir = path40.dirname(todoFilePath);
  await fs38.mkdir(todoDir, { recursive: true });
  const data = {
    todos,
    sessionId: sessionId || "default"
  };
  await fs38.writeFile(todoFilePath, JSON.stringify(data, null, 2), "utf-8");
}
var debugLogger43, 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();
    init_debugLogger();
    debugLogger43 = createDebugLogger("TODO_WRITE");
    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(config2, params, operationType = "update") {
        super(params);
        this.config = config2;
        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 sessionId = 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, sessionId);
          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 (error2) {
          const errorMessage = error2 instanceof Error ? error2.message : String(error2);
          debugLogger43.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(config2) {
        super(_TodoWriteTool.Name, ToolDisplayNames.TODO_WRITE, todoWriteToolDescription, Kind.Think, todoWriteToolSchemaData.parametersJsonSchema);
        this.config = config2;
      }
      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 sessionId = this.config.getSessionId();
        const todoFilePath = getTodoFilePath(sessionId);
        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 flattenError2(err) {
  return err instanceof Error ? "errors" in err && Array.isArray(err.errors) ? err.errors.map(flattenError2).join(", ") : "cause" in err && err.cause instanceof Error ? `${err}: ${flattenError2(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, _url2, _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_dist3 = __esm({
  "node_modules/eventsource/dist/index.js"() {
    init_esbuild_shims();
    init_dist2();
    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 _a7, _b2;
        super(type), this.code = (_a7 = errorEventInitDict == null ? void 0 : errorEventInitDict.code) != null ? _a7 : 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, inspect3) {
        return inspect3(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")](inspect3, options2) {
        return inspect3(inspectableError(this), options2);
      }
    };
    __name(syntaxError, "syntaxError");
    __name(flattenError2, "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 _a7, _b2;
        super(), __privateAdd(this, _EventSource_instances), this.CONNECTING = 0, this.OPEN = 1, this.CLOSED = 2, __privateAdd(this, _readyState), __privateAdd(this, _url2), __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 open4 = true;
          do {
            const { done, value } = await reader.read();
            value && __privateGet(this, _parser).feed(decoder.decode(value, { stream: !done })), done && (open4 = false, __privateGet(this, _parser).reset(), __privateMethod(this, _EventSource_instances, scheduleReconnect_fn).call(this));
          } while (open4);
        }), __privateAdd(this, _onFetchError, (err) => {
          __privateSet(this, _controller, void 0), !(err.name === "AbortError" || err.type === "aborted") && __privateMethod(this, _EventSource_instances, scheduleReconnect_fn).call(this, flattenError2(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, _url2).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, _url2, url2);
          else if (typeof url2 == "string")
            __privateSet(this, _url2, 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, (_a7 = eventSourceInitDict == null ? void 0 : eventSourceInitDict.fetch) != null ? _a7 : 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, _url2).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(), _url2 = /* @__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, _url2), __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 _a7;
      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: (_a7 = __privateGet(this, _controller)) == null ? void 0 : _a7.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 _a7;
      __privateGet(this, _readyState) !== this.CLOSED && __privateSet(this, _readyState, this.CLOSED);
      const errorEvent = new ErrorEvent("error", { code: code2, message });
      (_a7 = __privateGet(this, _onError)) == null || _a7.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 _a7;
      if (__privateGet(this, _readyState) === this.CLOSED)
        return;
      __privateSet(this, _readyState, this.CONNECTING);
      const errorEvent = new ErrorEvent("error", { code: code2, message });
      (_a7 = __privateGet(this, _onError)) == null || _a7.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");
  }
});

// packages/core/node_modules/@modelcontextprotocol/sdk/dist/esm/client/sse.js
var SseError, SSEClientTransport;
var init_sse = __esm({
  "packages/core/node_modules/@modelcontextprotocol/sdk/dist/esm/client/sse.js"() {
    init_esbuild_shims();
    init_dist3();
    init_transport();
    init_types8();
    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._scope = void 0;
        this._eventSourceInit = opts?.eventSourceInit;
        this._requestInit = opts?.requestInit;
        this._authProvider = opts?.authProvider;
        this._fetch = opts?.fetch;
        this._fetchWithInit = createFetchWithInit(opts?.fetch, opts?.requestInit);
      }
      async _authThenStart() {
        if (!this._authProvider) {
          throw new UnauthorizedError2("No auth provider");
        }
        let result;
        try {
          result = await auth(this._authProvider, {
            serverUrl: this._url,
            resourceMetadataUrl: this._resourceMetadataUrl,
            scope: this._scope,
            fetchFn: this._fetchWithInit
          });
        } catch (error2) {
          this.onerror?.(error2);
          throw error2;
        }
        if (result !== "AUTHORIZED") {
          throw new UnauthorizedError2();
        }
        return await this._startOrAuth();
      }
      async _commonHeaders() {
        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;
        }
        const extraHeaders = normalizeHeaders(this._requestInit?.headers);
        return new Headers({
          ...headers,
          ...extraHeaders
        });
      }
      _startOrAuth() {
        const fetchImpl = this?._eventSourceInit?.fetch ?? this._fetch ?? fetch;
        return new Promise((resolve30, 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")) {
                const { resourceMetadataUrl, scope } = extractWWWAuthenticateParams(response);
                this._resourceMetadataUrl = resourceMetadataUrl;
                this._scope = scope;
              }
              return response;
            }, "fetch")
          });
          this._abortController = new AbortController();
          this._eventSource.onerror = (event) => {
            if (event.code === 401 && this._authProvider) {
              this._authThenStart().then(resolve30, reject);
              return;
            }
            const error2 = new SseError(event.code, event.message, event);
            reject(error2);
            this.onerror?.(error2);
          };
          this._eventSource.onopen = () => {
          };
          this._eventSource.addEventListener("endpoint", (event) => {
            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 (error2) {
              reject(error2);
              this.onerror?.(error2);
              void this.close();
              return;
            }
            resolve30();
          });
          this._eventSource.onmessage = (event) => {
            const messageEvent = event;
            let message;
            try {
              message = JSONRPCMessageSchema.parse(JSON.parse(messageEvent.data));
            } catch (error2) {
              this.onerror?.(error2);
              return;
            }
            this.onmessage?.(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,
          scope: this._scope,
          fetchFn: this._fetchWithInit
        });
        if (result !== "AUTHORIZED") {
          throw new UnauthorizedError2("Failed to authorize");
        }
      }
      async close() {
        this._abortController?.abort();
        this._eventSource?.close();
        this.onclose?.();
      }
      async send(message) {
        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: this._abortController?.signal
          };
          const response = await (this._fetch ?? fetch)(this._endpoint, init);
          if (!response.ok) {
            const text = await response.text().catch(() => null);
            if (response.status === 401 && this._authProvider) {
              const { resourceMetadataUrl, scope } = extractWWWAuthenticateParams(response);
              this._resourceMetadataUrl = resourceMetadataUrl;
              this._scope = scope;
              const result = await auth(this._authProvider, {
                serverUrl: this._url,
                resourceMetadataUrl: this._resourceMetadataUrl,
                scope: this._scope,
                fetchFn: this._fetchWithInit
              });
              if (result !== "AUTHORIZED") {
                throw new UnauthorizedError2();
              }
              return this.send(message);
            }
            throw new Error(`Error POSTing to endpoint (HTTP ${response.status}): ${text}`);
          }
          await response.body?.cancel();
        } catch (error2) {
          this.onerror?.(error2);
          throw error2;
        }
      }
      setProtocolVersion(version2) {
        this._protocolVersion = version2;
      }
    };
  }
});

// packages/core/dist/src/mcp/constants.js
var MCP_OAUTH_CLIENT_NAME, MCP_SA_IMPERSONATION_CLIENT_NAME, OAUTH_REDIRECT_PORT, OAUTH_REDIRECT_PATH;
var init_constants6 = __esm({
  "packages/core/dist/src/mcp/constants.js"() {
    "use strict";
    init_esbuild_shims();
    MCP_OAUTH_CLIENT_NAME = "Qwen Code MCP Client";
    MCP_SA_IMPERSONATION_CLIENT_NAME = "Qwen Code (Service Account Impersonation)";
    OAUTH_REDIRECT_PORT = 7777;
    OAUTH_REDIRECT_PATH = "/oauth/callback";
  }
});

// packages/core/dist/src/mcp/google-auth-provider.js
var import_google_auth_library2, debugLogger44, 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_library2 = __toESM(require_src6(), 1);
    init_constants6();
    init_debugLogger();
    debugLogger44 = createDebugLogger("MCP_GOOGLE_AUTH");
    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: MCP_OAUTH_CLIENT_NAME,
        redirect_uris: [],
        grant_types: [],
        response_types: [],
        token_endpoint_auth_method: "none"
      };
      _clientInformation;
      constructor(config2) {
        this.config = config2;
        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 hostname4 = new URL(url2).hostname;
        if (!ALLOWED_HOSTS.some((pattern) => pattern.test(hostname4))) {
          throw new Error(`Host "${hostname4}" 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_library2.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) {
          debugLogger44.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_library3, debugLogger45, 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_library3 = __toESM(require_src6(), 1);
    init_constants6();
    init_debugLogger();
    debugLogger45 = createDebugLogger("MCP_SA_IMPERSONATION");
    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: MCP_SA_IMPERSONATION_CLIENT_NAME,
        redirect_uris: [],
        grant_types: [],
        response_types: [],
        token_endpoint_auth_method: "none"
      };
      _clientInformation;
      constructor(config2) {
        this.config = config2;
        if (!this.config.httpUrl && !this.config.url) {
          throw new Error("A url or httpUrl must be provided for the Service Account Impersonation provider");
        }
        if (!config2.targetAudience) {
          throw new Error("targetAudience must be provided for the Service Account Impersonation provider");
        }
        this.targetAudience = config2.targetAudience;
        if (!config2.targetServiceAccount) {
          throw new Error("targetServiceAccount must be provided for the Service Account Impersonation provider");
        }
        this.targetServiceAccount = config2.targetServiceAccount;
        this.auth = new import_google_auth_library3.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) {
            debugLogger45.error("Failed to get ID token from Google");
            return void 0;
          }
        } catch (e4) {
          debugLogger45.error(`Failed to fetch ID token from Google: ${e4}`);
          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 (e4) {
          debugLogger45.error(`Failed to parse ID token for expiry time with error: ${e4}`);
        }
        return void 0;
      }
    };
  }
});

// packages/core/dist/src/tools/sdk-control-client-transport.js
var debugLogger46, SdkControlClientTransport;
var init_sdk_control_client_transport = __esm({
  "packages/core/dist/src/tools/sdk-control-client-transport.js"() {
    "use strict";
    init_esbuild_shims();
    init_debugLogger();
    debugLogger46 = createDebugLogger("MCP_SDK_TRANSPORT");
    SdkControlClientTransport = class {
      static {
        __name(this, "SdkControlClientTransport");
      }
      serverName;
      sendMcpMessage;
      started = false;
      // Transport interface callbacks
      onmessage;
      onerror;
      onclose;
      constructor(options2) {
        this.serverName = options2.serverName;
        this.sendMcpMessage = options2.sendMcpMessage;
      }
      /**
       * Start the transport
       * For SDK transport, this just marks it as ready - no subprocess to spawn
       */
      async start() {
        if (this.started) {
          return;
        }
        this.started = true;
        debugLogger46.debug(`Started for server '${this.serverName}'`);
      }
      /**
       * Send a message to the SDK MCP server via control plane
       *
       * Routes the message through the control plane and delivers
       * the response via onmessage callback.
       */
      async send(message) {
        if (!this.started) {
          throw new Error(`SdkControlClientTransport (${this.serverName}) not started. Call start() first.`);
        }
        debugLogger46.debug(`Sending message to '${this.serverName}': ${JSON.stringify(message)}`);
        try {
          const response = await this.sendMcpMessage(this.serverName, message);
          debugLogger46.debug(`Received response from '${this.serverName}': ${JSON.stringify(response)}`);
          if (this.onmessage) {
            this.onmessage(response);
          }
        } catch (error2) {
          debugLogger46.error(`Error sending to '${this.serverName}': ${error2}`);
          if (this.onerror) {
            this.onerror(error2 instanceof Error ? error2 : new Error(String(error2)));
          }
          throw error2;
        }
      }
      /**
       * Close the transport
       */
      async close() {
        if (!this.started) {
          return;
        }
        this.started = false;
        debugLogger46.debug(`Closed for server '${this.serverName}'`);
        if (this.onclose) {
          this.onclose();
        }
      }
      /**
       * Check if transport is started
       */
      isStarted() {
        return this.started;
      }
      /**
       * Get server name
       */
      getServerName() {
        return this.serverName;
      }
    };
  }
});

// packages/core/dist/src/utils/secure-browser-launcher.js
import { execFile as execFile9 } from "node:child_process";
import { promisify as promisify8 } 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 execFileAsync6(command2, args, options2);
  } catch (error2) {
    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 execFileAsync6(fallbackCommand, [url2], options2);
          return;
        } catch {
          continue;
        }
      }
    }
    throw new Error(`Failed to open browser: ${error2 instanceof Error ? error2.message : "Unknown error"}`);
  }
}
var execFileAsync6;
var init_secure_browser_launcher = __esm({
  "packages/core/dist/src/utils/secure-browser-launcher.js"() {
    "use strict";
    init_esbuild_shims();
    execFileAsync6 = promisify8(execFile9);
    __name(validateUrl, "validateUrl");
    __name(openBrowserSecurely, "openBrowserSecurely");
  }
});

// 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 fs39 } from "node:fs";
import * as path41 from "node:path";
import * as os16 from "node:os";
import * as crypto8 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 = path41.join(os16.homedir(), ".qwen");
        this.tokenFilePath = path41.join(configDir, "mcp-oauth-tokens-v2.json");
        this.encryptionKey = this.deriveEncryptionKey();
      }
      deriveEncryptionKey() {
        const salt = `${os16.hostname()}-${os16.userInfo().username}-qwen-code`;
        return crypto8.scryptSync("qwen-code-oauth", salt, 32);
      }
      encrypt(text) {
        const iv = crypto8.randomBytes(16);
        const cipher = crypto8.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 = crypto8.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 = path41.dirname(this.tokenFilePath);
        await fs39.mkdir(dir, { recursive: true, mode: 448 });
      }
      async loadTokens() {
        try {
          const data = await fs39.readFile(this.tokenFilePath, "utf-8");
          const decrypted = this.decrypt(data);
          const tokens = JSON.parse(decrypted);
          return new Map(Object.entries(tokens));
        } catch (error2) {
          const err = error2;
          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 error2;
        }
      }
      async saveTokens(tokens) {
        await this.ensureDirectoryExists();
        const data = Object.fromEntries(tokens);
        const json2 = JSON.stringify(data, null, 2);
        const encrypted = this.encrypt(json2);
        await fs39.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 fs39.unlink(this.tokenFilePath);
          } catch (error2) {
            const err = error2;
            if (err.code !== "ENOENT") {
              throw error2;
            }
          }
        } 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 fs39.unlink(this.tokenFilePath);
        } catch (error2) {
          const err = error2;
          if (err.code !== "ENOENT") {
            throw error2;
          }
        }
      }
    };
  }
});

// packages/core/dist/src/mcp/token-storage/types.js
var TokenStorageType;
var init_types9 = __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 crypto9 from "node:crypto";
var debugLogger47, KEYCHAIN_TEST_PREFIX, SECRET_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();
    init_debugLogger();
    debugLogger47 = createDebugLogger("MCP_KEYCHAIN");
    KEYCHAIN_TEST_PREFIX = "__keychain_test__";
    SECRET_PREFIX = "__secret__";
    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 (error2) {
          debugLogger47.error(`Failed to load keytar module: ${error2}`);
        }
        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 (error2) {
          if (error2 instanceof SyntaxError) {
            throw new Error(`Failed to parse stored credentials for ${serverName}`);
          }
          throw error2;
        }
      }
      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)).filter((cred) => !cred.account.startsWith(SECRET_PREFIX)).map((cred) => cred.account);
        } catch (error2) {
          debugLogger47.error(`Failed to list servers from keychain: ${error2}`);
          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((c4) => !c4.account.startsWith(KEYCHAIN_TEST_PREFIX)).filter((c4) => !c4.account.startsWith(SECRET_PREFIX));
          for (const cred of credentials) {
            try {
              const data = JSON.parse(cred.password);
              if (!this.isTokenExpired(data)) {
                result.set(cred.account, data);
              }
            } catch (error2) {
              debugLogger47.error(`Failed to parse credentials for ${cred.account}: ${error2}`);
            }
          }
        } catch (error2) {
          debugLogger47.error(`Failed to get all credentials from keychain: ${error2}`);
        }
        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((c4) => c4.account)).catch((error2) => {
          throw new Error(`Failed to list servers for clearing: ${error2.message}`);
        }) : [];
        const errors = [];
        for (const server of servers) {
          try {
            await this.deleteCredentials(server);
          } catch (error2) {
            errors.push(error2);
          }
        }
        if (errors.length > 0) {
          throw new Error(`Failed to clear some credentials: ${errors.map((e4) => e4.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}${crypto9.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();
      }
      async setSecret(key, value) {
        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");
        }
        await keytar.setPassword(this.serviceName, `${SECRET_PREFIX}${key}`, value);
      }
      async getSecret(key) {
        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");
        }
        return keytar.getPassword(this.serviceName, `${SECRET_PREFIX}${key}`);
      }
      async deleteSecret(key) {
        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 deleted = await keytar.deletePassword(this.serviceName, `${SECRET_PREFIX}${key}`);
        if (!deleted) {
          throw new Error(`No secret found for key: ${key}`);
        }
      }
      async listSecrets() {
        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(SECRET_PREFIX)).map((cred) => cred.account.substring(SECRET_PREFIX.length));
        } catch (error2) {
          debugLogger47.error(`Failed to list secrets from keychain: ${error2}`);
          return [];
        }
      }
    };
  }
});

// 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_types9();
    FORCE_FILE_STORAGE_ENV_VAR = "QWEN_CODE_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 (_e2) {
          }
        }
        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/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_types9();
    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/mcp/oauth-token-storage.js
import { promises as fs40 } from "node:fs";
import * as path42 from "node:path";
var debugLogger48, 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_debugLogger();
    init_hybrid_token_storage();
    init_token_storage();
    debugLogger48 = createDebugLogger("MCP_OAUTH");
    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 = path42.dirname(this.getTokenFilePath());
        await fs40.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 fs40.readFile(tokenFile, "utf-8");
          const tokens = JSON.parse(data);
          for (const credential of tokens) {
            tokenMap.set(credential.serverName, credential);
          }
        } catch (error2) {
          if (error2.code !== "ENOENT") {
            debugLogger48.error(`Failed to load MCP OAuth tokens: ${getErrorMessage(error2)}`);
          }
        }
        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 fs40.writeFile(tokenFile, JSON.stringify(tokenArray, null, 2), { mode: 384 });
        } catch (error2) {
          debugLogger48.error(`Failed to save MCP OAuth token: ${getErrorMessage(error2)}`);
          throw error2;
        }
      }
      /**
       * 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 fs40.unlink(tokenFile);
            } else {
              await fs40.writeFile(tokenFile, JSON.stringify(tokenArray, null, 2), {
                mode: 384
              });
            }
          } catch (error2) {
            debugLogger48.error(`Failed to remove MCP OAuth token: ${getErrorMessage(error2)}`);
          }
        }
      }
      /**
       * 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 fs40.unlink(tokenFile);
        } catch (error2) {
          if (error2.code !== "ENOENT") {
            debugLogger48.error(`Failed to clear MCP OAuth tokens: ${getErrorMessage(error2)}`);
          }
        }
      }
    };
  }
});

// packages/core/dist/src/mcp/oauth-utils.js
var debugLogger49, OAuthUtils;
var init_oauth_utils = __esm({
  "packages/core/dist/src/mcp/oauth-utils.js"() {
    "use strict";
    init_esbuild_shims();
    init_errors();
    init_debugLogger();
    debugLogger49 = createDebugLogger("MCP_OAUTH");
    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 (error2) {
          debugLogger49.debug(`Failed to fetch protected resource metadata from ${resourceMetadataUrl}: ${getErrorMessage(error2)}`);
          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 (error2) {
          debugLogger49.debug(`Failed to fetch authorization server metadata from ${authServerMetadataUrl}: ${getErrorMessage(error2)}`);
          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;
          }
        }
        debugLogger49.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 config2 = this.metadataToOAuthConfig(authServerMetadata2);
              if (authServerMetadata2.registration_endpoint) {
                debugLogger49.debug(`Dynamic client registration is supported at: ${authServerMetadata2.registration_endpoint}`);
              }
              return config2;
            }
          }
          debugLogger49.debug(`Trying OAuth discovery fallback at ${serverUrl}`);
          const authServerMetadata = await this.discoverAuthorizationServerMetadata(serverUrl);
          if (authServerMetadata) {
            const config2 = this.metadataToOAuthConfig(authServerMetadata);
            if (authServerMetadata.registration_endpoint) {
              debugLogger49.debug(`Dynamic client registration is supported at: ${authServerMetadata.registration_endpoint}`);
            }
            return config2;
          }
          return null;
        } catch (error2) {
          debugLogger49.debug(`Failed to discover OAuth configuration: ${getErrorMessage(error2)}`);
          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.
       *
       * Per MCP spec and RFC 8707, the resource parameter MUST be the
       * canonical URI of the MCP server. Clients SHOULD provide the most
       * specific URI they can. The URI MUST NOT include a fragment and
       * SHOULD NOT include a query component.
       *
       * @param endpointUrl The MCP server endpoint URL
       * @returns The canonical resource URI
       */
      static buildResourceParameter(endpointUrl) {
        const url2 = new URL(endpointUrl);
        const path125 = url2.pathname === "/" ? "" : url2.pathname;
        let canonical = `${url2.protocol}//${url2.host}${path125}`;
        if (canonical.endsWith("/") && path125 !== "") {
          canonical = canonical.slice(0, -1);
        }
        return canonical;
      }
    };
  }
});

// packages/core/dist/src/mcp/oauth-provider.js
import * as http4 from "node:http";
import * as crypto10 from "node:crypto";
import { URL as URL4 } from "node:url";
var OAUTH_DISPLAY_MESSAGE_EVENT, debugLogger50, 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();
    init_debugLogger();
    init_constants6();
    OAUTH_DISPLAY_MESSAGE_EVENT = "oauth-display-message";
    debugLogger50 = createDebugLogger("MCP_OAUTH");
    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, config2) {
        const redirectUri = config2.redirectUri || `http://localhost:${OAUTH_REDIRECT_PORT}${OAUTH_REDIRECT_PATH}`;
        const registrationRequest = {
          client_name: MCP_OAUTH_CLIENT_NAME,
          redirect_uris: [redirectUri],
          grant_types: ["authorization_code", "refresh_token"],
          response_types: ["code"],
          token_endpoint_auth_method: "none",
          // Public client
          code_challenge_method: ["S256"],
          scope: config2.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 = crypto10.randomBytes(32).toString("base64url");
        const codeChallenge = crypto10.createHash("sha256").update(codeVerifier).digest("base64url");
        const state = crypto10.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((resolve30, reject) => {
          const server = http4.createServer(async (req, res) => {
            try {
              const url2 = new URL4(req.url, `http://localhost:${OAUTH_REDIRECT_PORT}`);
              if (url2.pathname !== OAUTH_REDIRECT_PATH) {
                res.writeHead(404);
                res.end("Not found");
                return;
              }
              const code2 = url2.searchParams.get("code");
              const state = url2.searchParams.get("state");
              const error2 = url2.searchParams.get("error");
              if (error2) {
                res.writeHead(HTTP_OK, { "Content-Type": "text/html" });
                res.end(`
              <html>
                <body>
                  <h1>Authentication Failed</h1>
                  <p>Error: ${error2.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: ${error2}`));
                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 Qwen Code.</p>
                <script>window.close();</script>
              </body>
            </html>
          `);
              server.close();
              resolve30({ code: code2, state });
            } catch (error2) {
              server.close();
              reject(error2);
            }
          });
          server.on("error", reject);
          server.listen(OAUTH_REDIRECT_PORT, () => {
            debugLogger50.debug(`OAuth callback server listening on port ${OAUTH_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(config2, pkceParams, mcpServerUrl) {
        const redirectUri = config2.redirectUri || `http://localhost:${OAUTH_REDIRECT_PORT}${OAUTH_REDIRECT_PATH}`;
        const params = new URLSearchParams({
          client_id: config2.clientId,
          response_type: "code",
          redirect_uri: redirectUri,
          state: pkceParams.state,
          code_challenge: pkceParams.codeChallenge,
          code_challenge_method: "S256"
        });
        if (config2.scopes && config2.scopes.length > 0) {
          params.append("scope", config2.scopes.join(" "));
        }
        if (config2.audiences && config2.audiences.length > 0) {
          params.append("audience", config2.audiences.join(" "));
        }
        if (mcpServerUrl) {
          try {
            params.append("resource", OAuthUtils.buildResourceParameter(mcpServerUrl));
          } catch (error2) {
            debugLogger50.warn(`Could not add resource parameter: ${getErrorMessage(error2)}`);
          }
        }
        const url2 = new URL4(config2.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(config2, code2, codeVerifier, mcpServerUrl) {
        const redirectUri = config2.redirectUri || `http://localhost:${OAUTH_REDIRECT_PORT}${OAUTH_REDIRECT_PATH}`;
        const params = new URLSearchParams({
          grant_type: "authorization_code",
          code: code2,
          redirect_uri: redirectUri,
          code_verifier: codeVerifier,
          client_id: config2.clientId
        });
        if (config2.clientSecret) {
          params.append("client_secret", config2.clientSecret);
        }
        if (config2.audiences && config2.audiences.length > 0) {
          params.append("audience", config2.audiences.join(" "));
        }
        if (mcpServerUrl) {
          const resourceUrl = mcpServerUrl;
          try {
            params.append("resource", OAuthUtils.buildResourceParameter(resourceUrl));
          } catch (error2) {
            debugLogger50.warn(`Could not add resource parameter: ${getErrorMessage(error2)}`);
          }
        }
        const response = await fetch(config2.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 error2 = errorParams.get("error");
            const errorDescription = errorParams.get("error_description");
            if (error2) {
              errorMessage = `Token exchange failed: ${error2} - ${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")) {
          debugLogger50.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 error2 = tokenParams.get("error");
            const errorDescription = tokenParams.get("error_description");
            throw new Error(`Token exchange failed: ${error2 || "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(config2, refreshToken, tokenUrl, mcpServerUrl) {
        const params = new URLSearchParams({
          grant_type: "refresh_token",
          refresh_token: refreshToken,
          client_id: config2.clientId
        });
        if (config2.clientSecret) {
          params.append("client_secret", config2.clientSecret);
        }
        if (config2.scopes && config2.scopes.length > 0) {
          params.append("scope", config2.scopes.join(" "));
        }
        if (config2.audiences && config2.audiences.length > 0) {
          params.append("audience", config2.audiences.join(" "));
        }
        if (mcpServerUrl) {
          try {
            params.append("resource", OAuthUtils.buildResourceParameter(mcpServerUrl));
          } catch (error2) {
            debugLogger50.warn(`Could not add resource parameter: ${getErrorMessage(error2)}`);
          }
        }
        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 error2 = errorParams.get("error");
            const errorDescription = errorParams.get("error_description");
            if (error2) {
              errorMessage = `Token refresh failed: ${error2} - ${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")) {
          debugLogger50.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 error2 = tokenParams.get("error");
            const errorDescription = tokenParams.get("error_description");
            throw new Error(`Token refresh failed: ${error2 || "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, config2, mcpServerUrl, events) {
        const displayMessage = /* @__PURE__ */ __name((message) => {
          if (events) {
            events.emit(OAUTH_DISPLAY_MESSAGE_EVENT, message);
          } else {
            debugLogger50.info(message);
          }
        }, "displayMessage");
        if (!config2.authorizationUrl && mcpServerUrl) {
          debugLogger50.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) {
                  config2 = {
                    ...config2,
                    authorizationUrl: discoveredConfig.authorizationUrl,
                    tokenUrl: discoveredConfig.tokenUrl,
                    scopes: discoveredConfig.scopes || config2.scopes || [],
                    // Preserve existing client credentials
                    clientId: config2.clientId,
                    clientSecret: config2.clientSecret
                  };
                }
              }
            }
          } catch (error2) {
            debugLogger50.debug(`Failed to check endpoint for authentication requirements: ${getErrorMessage(error2)}`);
          }
          if (!config2.authorizationUrl) {
            const discoveredConfig = await this.discoverOAuthFromMCPServer(mcpServerUrl);
            if (discoveredConfig) {
              config2 = {
                ...config2,
                authorizationUrl: discoveredConfig.authorizationUrl,
                tokenUrl: discoveredConfig.tokenUrl,
                scopes: discoveredConfig.scopes || config2.scopes || [],
                registrationUrl: discoveredConfig.registrationUrl,
                // Preserve existing client credentials
                clientId: config2.clientId,
                clientSecret: config2.clientSecret
              };
            } else {
              throw new Error("Failed to discover OAuth configuration from MCP server");
            }
          }
        }
        if (!config2.clientId) {
          let registrationUrl = config2.registrationUrl;
          if (!registrationUrl) {
            if (!config2.authorizationUrl) {
              throw new Error("Cannot perform dynamic registration without authorization URL");
            }
            const authUrl2 = new URL4(config2.authorizationUrl);
            const serverUrl = `${authUrl2.protocol}//${authUrl2.host}`;
            debugLogger50.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, config2);
            config2.clientId = clientRegistration.client_id;
            if (clientRegistration.client_secret) {
              config2.clientSecret = clientRegistration.client_secret;
            }
            debugLogger50.debug("\u2713 Dynamic client registration successful");
          } else {
            throw new Error("No client ID provided and dynamic registration not supported");
          }
        }
        if (!config2.clientId || !config2.authorizationUrl || !config2.tokenUrl) {
          throw new Error("Missing required OAuth configuration after discovery and registration");
        }
        const pkceParams = this.generatePKCEParams();
        const authUrl = this.buildAuthorizationUrl(config2, 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 (error2) {
          debugLogger50.warn(`Failed to open browser automatically: ${getErrorMessage(error2)}`);
        }
        const { code: code2 } = await callbackPromise;
        debugLogger50.debug("\u2713 Authorization code received, exchanging for tokens...");
        const tokenResponse = await this.exchangeCodeForToken(config2, 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, config2.clientId, config2.tokenUrl, mcpServerUrl);
          debugLogger50.debug("\u2713 Authentication successful! Token saved.");
          const savedToken = await this.tokenStorage.getCredentials(serverName);
          if (savedToken && savedToken.token && savedToken.token.accessToken) {
            const tokenFingerprint = crypto10.createHash("sha256").update(savedToken.token.accessToken).digest("hex").slice(0, 8);
            debugLogger50.debug(`\u2713 Token verification successful (fingerprint: ${tokenFingerprint})`);
          } else {
            debugLogger50.error("Token verification failed: token not found or invalid after save");
          }
        } catch (saveError) {
          debugLogger50.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, config2) {
        debugLogger50.debug(`Getting valid token for server: ${serverName}`);
        const credentials = await this.tokenStorage.getCredentials(serverName);
        if (!credentials) {
          debugLogger50.debug(`No credentials found for server: ${serverName}`);
          return null;
        }
        const { token: token2 } = credentials;
        debugLogger50.debug(`Found token for server: ${serverName}, expired: ${this.tokenStorage.isTokenExpired(token2)}`);
        if (!this.tokenStorage.isTokenExpired(token2)) {
          debugLogger50.debug(`Returning valid token for server: ${serverName}`);
          return token2.accessToken;
        }
        if (token2.refreshToken && config2.clientId && credentials.tokenUrl) {
          try {
            debugLogger50.info(`Refreshing expired token for MCP server: ${serverName}`);
            const newTokenResponse = await this.refreshAccessToken(config2, 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, config2.clientId, credentials.tokenUrl, credentials.mcpServerUrl);
            return newToken.accessToken;
          } catch (error2) {
            debugLogger50.error(`Failed to refresh token: ${getErrorMessage(error2)}`);
            await this.tokenStorage.deleteCredentials(serverName);
          }
        }
        return null;
      }
    };
  }
});

// packages/core/dist/src/tools/mcp-client.js
import { basename as basename9 } 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 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 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 annotationsMap = /* @__PURE__ */ new Map();
    try {
      const listToolsResult = await mcpClient.listTools();
      for (const mcpTool of listToolsResult.tools) {
        if (mcpTool.annotations) {
          annotationsMap.set(mcpTool.name, mcpTool.annotations);
        }
      }
    } catch {
      debugLogger51.error(`Failed to fetch tool annotations from MCP server '${mcpServerName}'`);
    }
    const mcpTimeout = mcpServerConfig.timeout ?? MCP_DEFAULT_TIMEOUT_MSEC;
    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,
          mcpClient,
          // raw MCP Client for direct callTool with progress
          mcpTimeout,
          annotationsMap.get(funcDecl.name)
        ));
      } catch (error2) {
        debugLogger51.error(`Error discovering tool: '${funcDecl.name}' from MCP server '${mcpServerName}': ${error2.message}`);
      }
    }
    return discoveredTools;
  } catch (error2) {
    if (error2 instanceof Error && !error2.message?.includes("Method not found")) {
      debugLogger51.error(`Error discovering tools from ${mcpServerName}: ${getErrorMessage(error2)}`);
    }
    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 (error2) {
    if (error2 instanceof Error && !error2.message?.includes("Method not found")) {
      debugLogger51.error(`Error discovering prompts from ${mcpServerName}: ${getErrorMessage(error2)}`);
    }
    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 (error2) {
    if (error2 instanceof Error && !error2.message?.includes("Method not found")) {
      debugLogger51.error(`Error invoking prompt '${promptName}' from ${mcpServerName} ${promptParams}: ${getErrorMessage(error2)}`);
    }
    throw error2;
  }
}
async function createTransport(mcpServerName, mcpServerConfig, debugMode, sendSdkMcpMessage) {
  if (isSdkMcpServerConfig(mcpServerConfig)) {
    if (!sendSdkMcpMessage) {
      throw new Error(`SDK MCP server '${mcpServerName}' requires sendSdkMcpMessage callback`);
    }
    return new SdkControlClientTransport({
      serverName: mcpServerName,
      sendMcpMessage: sendSdkMcpMessage,
      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) {
      debugLogger51.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;
        debugLogger51.debug(`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();
        debugLogger51.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) {
    debugLogger51.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, debugLogger51, MCPServerStatus, MCPDiscoveryState, McpClient, serverStatuses, mcpDiscoveryState, statusChangeListeners;
var init_mcp_client = __esm({
  "packages/core/dist/src/tools/mcp-client.js"() {
    "use strict";
    init_esbuild_shims();
    init_client4();
    init_sse();
    init_stdio2();
    init_streamableHttp();
    init_types8();
    import_shell_quote3 = __toESM(require_shell_quote(), 1);
    init_config3();
    init_google_auth_provider();
    init_sa_impersonation_provider();
    init_mcp_tool();
    init_sdk_control_client_transport();
    init_node();
    init_oauth_provider();
    init_oauth_token_storage();
    init_oauth_utils();
    init_errors();
    init_debugLogger();
    MCP_DEFAULT_TIMEOUT_MSEC = 10 * 60 * 1e3;
    debugLogger51 = createDebugLogger("MCP");
    (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;
      sendSdkMcpMessage;
      client;
      transport;
      status = MCPServerStatus.DISCONNECTED;
      isDisconnecting = false;
      constructor(serverName, serverConfig, toolRegistry, promptRegistry, workspaceContext, debugMode, sendSdkMcpMessage) {
        this.serverName = serverName;
        this.serverConfig = serverConfig;
        this.toolRegistry = toolRegistry;
        this.promptRegistry = promptRegistry;
        this.workspaceContext = workspaceContext;
        this.debugMode = debugMode;
        this.sendSdkMcpMessage = sendSdkMcpMessage;
        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 = (error2) => {
            if (this.isDisconnecting) {
              return;
            }
            debugLogger51.error(`MCP ERROR (${this.serverName}):`, error2.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: basename9(dir)
              });
            }
            return {
              roots
            };
          });
          await this.client.connect(this.transport, {
            timeout: this.serverConfig.timeout
          });
          this.updateStatus(MCPServerStatus.CONNECTED);
        } catch (error2) {
          this.updateStatus(MCPServerStatus.DISCONNECTED);
          throw error2;
        }
      }
      /**
       * Discovers tools and prompts from the MCP server.
       */
      async discover(cliConfig) {
        if (this.status !== MCPServerStatus.CONNECTED) {
          throw new Error("Client is not connected.");
        }
        const prompts3 = await this.discoverPrompts();
        const tools = await this.discoverTools(cliConfig);
        if (prompts3.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;
      }
      async readResource(uri, options2) {
        if (this.status !== MCPServerStatus.CONNECTED) {
          throw new Error("Client is not connected.");
        }
        if (this.client.getServerCapabilities()?.resources == null) {
          throw new Error("MCP server does not support resources.");
        }
        return this.client.request({ method: "resources/read", params: { uri } }, ReadResourceResultSchema, options2);
      }
      updateStatus(status) {
        this.status = status;
        updateMCPServerStatus(this.serverName, status);
      }
      async createTransport() {
        return createTransport(this.serverName, this.serverConfig, this.debugMode, this.sendSdkMcpMessage);
      }
      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;
    statusChangeListeners = [];
    __name(updateMCPServerStatus, "updateMCPServerStatus");
    __name(getMCPServerStatus, "getMCPServerStatus");
    __name(getMCPDiscoveryState, "getMCPDiscoveryState");
    __name(populateMcpServerCommand, "populateMcpServerCommand");
    __name(discoverTools, "discoverTools");
    __name(discoverPrompts, "discoverPrompts");
    __name(invokeMcpPrompt, "invokeMcpPrompt");
    __name(createTransport, "createTransport");
    __name(isEnabled, "isEnabled");
  }
});

// packages/core/dist/src/tools/mcp-client-manager.js
var debugLogger52, McpClientManager;
var init_mcp_client_manager = __esm({
  "packages/core/dist/src/tools/mcp-client-manager.js"() {
    "use strict";
    init_esbuild_shims();
    init_config3();
    init_mcp_client();
    init_errors();
    init_debugLogger();
    debugLogger52 = createDebugLogger("MCP");
    McpClientManager = class {
      static {
        __name(this, "McpClientManager");
      }
      clients = /* @__PURE__ */ new Map();
      toolRegistry;
      cliConfig;
      discoveryState = MCPDiscoveryState.NOT_STARTED;
      eventEmitter;
      sendSdkMcpMessage;
      constructor(config2, toolRegistry, eventEmitter, sendSdkMcpMessage) {
        this.cliConfig = config2;
        this.toolRegistry = toolRegistry;
        this.eventEmitter = eventEmitter;
        this.sendSdkMcpMessage = sendSdkMcpMessage;
      }
      /**
       * 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.cliConfig.getMcpServers() || {}, this.cliConfig.getMcpServerCommand());
        this.discoveryState = MCPDiscoveryState.IN_PROGRESS;
        this.eventEmitter?.emit("mcp-client-update", this.clients);
        const discoveryPromises = Object.entries(servers).map(async ([name3, config2]) => {
          const sdkCallback = isSdkMcpServerConfig(config2) ? this.sendSdkMcpMessage : void 0;
          const client = new McpClient(name3, config2, this.toolRegistry, this.cliConfig.getPromptRegistry(), this.cliConfig.getWorkspaceContext(), this.cliConfig.getDebugMode(), sdkCallback);
          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 (error2) {
            this.eventEmitter?.emit("mcp-client-update", this.clients);
            debugLogger52.error(`Error during discovery for server '${name3}': ${getErrorMessage(error2)}`);
          }
        });
        await Promise.all(discoveryPromises);
        this.discoveryState = MCPDiscoveryState.COMPLETED;
      }
      /**
       * Connects to a single MCP server and discovers its tools/prompts.
       * The connected client is tracked so it can be closed by {@link stop}.
       *
       * This is primarily used for on-demand re-discovery flows (e.g. after OAuth).
       */
      async discoverMcpToolsForServer(serverName, cliConfig) {
        const servers = populateMcpServerCommand(this.cliConfig.getMcpServers() || {}, this.cliConfig.getMcpServerCommand());
        const serverConfig = servers[serverName];
        if (!serverConfig) {
          return;
        }
        const existingClient = this.clients.get(serverName);
        if (existingClient) {
          try {
            await existingClient.disconnect();
          } catch (error2) {
            debugLogger52.error(`Error stopping client '${serverName}': ${getErrorMessage(error2)}`);
          } finally {
            this.clients.delete(serverName);
            this.eventEmitter?.emit("mcp-client-update", this.clients);
          }
        }
        const sdkCallback = isSdkMcpServerConfig(serverConfig) ? this.sendSdkMcpMessage : void 0;
        const client = new McpClient(serverName, serverConfig, this.toolRegistry, this.cliConfig.getPromptRegistry(), this.cliConfig.getWorkspaceContext(), this.cliConfig.getDebugMode(), sdkCallback);
        this.clients.set(serverName, client);
        this.eventEmitter?.emit("mcp-client-update", this.clients);
        try {
          await client.connect();
          await client.discover(cliConfig);
        } catch (error2) {
          debugLogger52.error(`Error during discovery for server '${serverName}': ${getErrorMessage(error2)}`);
        } finally {
          this.eventEmitter?.emit("mcp-client-update", this.clients);
        }
      }
      /**
       * 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 (error2) {
            debugLogger52.error(`Error stopping client '${name3}': ${getErrorMessage(error2)}`);
          }
        });
        await Promise.all(disconnectionPromises);
        this.clients.clear();
      }
      getDiscoveryState() {
        return this.discoveryState;
      }
      async readResource(serverName, uri, options2) {
        let client = this.clients.get(serverName);
        if (!client) {
          const servers = populateMcpServerCommand(this.cliConfig.getMcpServers() || {}, this.cliConfig.getMcpServerCommand());
          const serverConfig = servers[serverName];
          if (!serverConfig) {
            throw new Error(`MCP server '${serverName}' is not configured.`);
          }
          const sdkCallback = isSdkMcpServerConfig(serverConfig) ? this.sendSdkMcpMessage : void 0;
          client = new McpClient(serverName, serverConfig, this.toolRegistry, this.cliConfig.getPromptRegistry(), this.cliConfig.getWorkspaceContext(), this.cliConfig.getDebugMode(), sdkCallback);
          this.clients.set(serverName, client);
          this.eventEmitter?.emit("mcp-client-update", this.clients);
        }
        if (client.getStatus() !== MCPServerStatus.CONNECTED) {
          await client.connect();
        }
        return client.readResource(uri, options2);
      }
    };
  }
});

// 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, debugLogger53, 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_manager();
    init_mcp_tool();
    import_shell_quote4 = __toESM(require_shell_quote(), 1);
    init_tool_error();
    init_safeJsonStringify();
    init_debugLogger();
    debugLogger53 = createDebugLogger("TOOL_REGISTRY");
    DiscoveredToolInvocation = class extends BaseToolInvocation {
      static {
        __name(this, "DiscoveredToolInvocation");
      }
      config;
      toolName;
      constructor(config2, toolName, params) {
        super(params);
        this.config = config2;
        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 error2 = null;
        let code2 = null;
        let signal = null;
        await new Promise((resolve30) => {
          const onStdout = /* @__PURE__ */ __name((data) => {
            stdout += data?.toString();
          }, "onStdout");
          const onStderr = /* @__PURE__ */ __name((data) => {
            stderr += data?.toString();
          }, "onStderr");
          const onError2 = /* @__PURE__ */ __name((err) => {
            error2 = err;
          }, "onError");
          const onClose = /* @__PURE__ */ __name((_code, _signal2) => {
            code2 = _code;
            signal = _signal2;
            cleanup();
            resolve30();
          }, "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 (error2 || code2 !== 0 || signal || stderr) {
          const llmContent = [
            `Stdout: ${stdout || "(empty)"}`,
            `Stderr: ${stderr || "(empty)"}`,
            `Error: ${error2 ?? "(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(config2, name3, description, parameterSchema) {
        const discoveryCmd = config2.getToolDiscoveryCommand();
        const callCommand = config2.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 = config2;
        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(config2, eventEmitter, sendSdkMcpMessage) {
        this.config = config2;
        this.mcpClientManager = new McpClientManager(this.config, this, eventEmitter, sendSdkMcpMessage);
      }
      /**
       * 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 {
            debugLogger53.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);
        await this.mcpClientManager.discoverMcpToolsForServer(serverName, 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((resolve30, 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) {
                debugLogger53.error(`Tool discovery command failed with code ${code2}`);
                debugLogger53.error(stderr);
                return reject(new Error(`Tool discovery command failed with exit code ${code2}`));
              }
              resolve30();
            });
          });
          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) {
              debugLogger53.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 (e4) {
          debugLogger53.error(`Tool discovery command "${discoveryCmd}" failed:`, e4);
          throw e4;
        }
      }
      /**
       * 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((a2, b2) => a2.displayName.localeCompare(b2.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((a2, b2) => a2.name.localeCompare(b2.name));
      }
      /**
       * Get the definition of a specific tool.
       */
      getTool(name3) {
        return this.tools.get(name3);
      }
      async readMcpResource(serverName, uri, options2) {
        if (!this.config.isTrustedFolder()) {
          throw new Error("MCP resources are unavailable in untrusted folders.");
        }
        return this.mcpClientManager.readResource(serverName, uri, options2);
      }
      /**
       * Stops all MCP clients and cleans up resources.
       * This method is idempotent and safe to call multiple times.
       */
      async stop() {
        try {
          await this.mcpClientManager.stop();
        } catch (error2) {
          debugLogger53.error("Error stopping MCP clients:", error2);
        }
      }
    };
  }
});

// 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, Text, Directive, Comment, Script, Style, Tag, CDATA, Doctype;
var init_esm14 = __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;
    Text = 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 Text2(node.data);
  } else if (isComment(node)) {
    result = new Comment2(node.data);
  } else if (isTag2(node)) {
    const children = recursive ? cloneChildren(node.children) : [];
    const clone4 = new Element(node.name, { ...node.attribs }, children);
    children.forEach((child) => child.parent = clone4);
    if (node.namespace != null) {
      clone4.namespace = node.namespace;
    }
    if (node["x-attribsNamespace"]) {
      clone4["x-attribsNamespace"] = { ...node["x-attribsNamespace"] };
    }
    if (node["x-attribsPrefix"]) {
      clone4["x-attribsPrefix"] = { ...node["x-attribsPrefix"] };
    }
    result = clone4;
  } else if (isCDATA(node)) {
    const children = recursive ? cloneChildren(node.children) : [];
    const clone4 = new CDATA2(children);
    children.forEach((child) => child.parent = clone4);
    result = clone4;
  } else if (isDocument(node)) {
    const children = recursive ? cloneChildren(node.children) : [];
    const clone4 = new Document(children);
    children.forEach((child) => child.parent = clone4);
    if (node["x-mode"]) {
      clone4["x-mode"] = node["x-mode"];
    }
    result = clone4;
  } 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 i3 = 1; i3 < children.length; i3++) {
    children[i3].prev = children[i3 - 1];
    children[i3 - 1].next = children[i3];
  }
  return children;
}
var Node2, DataNode, Text2, Comment2, ProcessingInstruction, NodeWithChildren, CDATA2, Document, Element;
var init_node3 = __esm({
  "node_modules/domhandler/lib/esm/node.js"() {
    init_esbuild_shims();
    init_esm14();
    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;
      }
    };
    Text2 = 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 _a7;
        return (_a7 = this.children[0]) !== null && _a7 !== void 0 ? _a7 : 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 _a7, _b2;
          return {
            name: name3,
            value: this.attribs[name3],
            namespace: (_a7 = this["x-attribsNamespace"]) === null || _a7 === void 0 ? void 0 : _a7[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_esm15 = __esm({
  "node_modules/domhandler/lib/esm/index.js"() {
    init_esbuild_shims();
    init_esm14();
    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(error2) {
        this.handleCallback(error2);
      }
      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 Text2(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 Text2("");
        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(error2) {
        if (typeof this.callback === "function") {
          this.callback(error2, this.dom);
        } else if (error2) {
          throw error2;
        }
      }
      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 n2(n3) {
  const o3 = [...n3.matchAll(e3)].map((e4) => e4.index || 0);
  o3.unshift(-1);
  const s5 = t3(o3, 0, o3.length);
  return (e4) => r3(s5, e4);
}
function t3(e4, n3, r5) {
  if (r5 - n3 == 1) return { offset: e4[n3], index: n3 + 1 };
  const o3 = Math.ceil((n3 + r5) / 2), s5 = t3(e4, n3, o3), l3 = t3(e4, o3, r5);
  return { offset: s5.offset, low: s5, high: l3 };
}
function r3(e4, n3) {
  return function(e5) {
    return Object.prototype.hasOwnProperty.call(e5, "index");
  }(e4) ? { line: e4.index, column: n3 - e4.offset } : r3(e4.high.offset < n3 ? e4.high : e4.low, n3);
}
function o2(e4, t5 = "", r5 = {}) {
  const o3 = "string" != typeof t5 ? t5 : r5, l3 = "string" == typeof t5 ? t5 : "", c4 = e4.map(s3), f5 = !!o3.lineNumbers;
  return function(e5, t6 = 0) {
    const r6 = f5 ? n2(e5) : () => ({ line: 0, column: 0 });
    let o4 = t6;
    const s5 = [];
    e: for (; o4 < e5.length; ) {
      let n3 = false;
      for (const t7 of c4) {
        t7.regex.lastIndex = o4;
        const c5 = t7.regex.exec(e5);
        if (c5 && c5[0].length > 0) {
          if (!t7.discard) {
            const e6 = r6(o4), n4 = "string" == typeof t7.replace ? c5[0].replace(new RegExp(t7.regex.source, t7.regex.flags), t7.replace) : c5[0];
            s5.push({ state: l3, name: t7.name, text: n4, offset: o4, len: c5[0].length, line: e6.line, column: e6.column });
          }
          if (o4 = t7.regex.lastIndex, n3 = true, t7.push) {
            const n4 = t7.push(e5, o4);
            s5.push(...n4.tokens), o4 = n4.offset;
          }
          if (t7.pop) break e;
          break;
        }
      }
      if (!n3) break;
    }
    return { tokens: s5, offset: o4, complete: e5.length <= o4 };
  };
}
function s3(e4, n3) {
  return { ...e4, regex: l2(e4, n3) };
}
function l2(e4, n3) {
  if (0 === e4.name.length) throw new Error(`Rule #${n3} has empty name, which is not allowed.`);
  if (function(e5) {
    return Object.prototype.hasOwnProperty.call(e5, "regex");
  }(e4)) return function(e5) {
    if (e5.global) throw new Error(`Regular expression /${e5.source}/${e5.flags} contains the global flag, which is not allowed.`);
    return e5.sticky ? e5 : new RegExp(e5.source, e5.flags + "y");
  }(e4.regex);
  if (function(e5) {
    return Object.prototype.hasOwnProperty.call(e5, "str");
  }(e4)) {
    if (0 === e4.str.length) throw new Error(`Rule #${n3} ("${e4.name}") has empty "str" property, which is not allowed.`);
    return new RegExp(c2(e4.str), "y");
  }
  return new RegExp(c2(e4.name), "y");
}
function c2(e4) {
  return e4.replace(/[-[\]{}()*+!<=:?./\\^$|#\s,]/g, "\\$&");
}
var e3;
var init_leac = __esm({
  "node_modules/leac/lib/leac.mjs"() {
    init_esbuild_shims();
    e3 = /\n/g;
    __name(n2, "n");
    __name(t3, "t");
    __name(r3, "r");
    __name(o2, "o");
    __name(s3, "s");
    __name(l2, "l");
    __name(c2, "c");
  }
});

// node_modules/peberminta/lib/core.mjs
function token(onToken, onEnd) {
  return (data, i3) => {
    let position = i3;
    let value = void 0;
    if (i3 < data.tokens.length) {
      value = onToken(data.tokens[i3], data, i3);
      if (value !== void 0) {
        position++;
      }
    } else {
      onEnd?.(data, i3);
    }
    return value === void 0 ? { matched: false } : {
      matched: true,
      position,
      value
    };
  };
}
function mapInner(r5, f5) {
  return r5.matched ? {
    matched: true,
    position: r5.position,
    value: f5(r5.value, r5.position)
  } : r5;
}
function mapOuter(r5, f5) {
  return r5.matched ? f5(r5) : r5;
}
function map(p2, mapper) {
  return (data, i3) => mapInner(p2(data, i3), (v2, j2) => mapper(v2, data, i3, j2));
}
function option(p2, def2) {
  return (data, i3) => {
    const r5 = p2(data, i3);
    return r5.matched ? r5 : {
      matched: true,
      position: i3,
      value: def2
    };
  };
}
function choice(...ps) {
  return (data, i3) => {
    for (const p2 of ps) {
      const result = p2(data, i3);
      if (result.matched) {
        return result;
      }
    }
    return { matched: false };
  };
}
function otherwise(pa, pb) {
  return (data, i3) => {
    const r1 = pa(data, i3);
    return r1.matched ? r1 : pb(data, i3);
  };
}
function takeWhile(p2, test) {
  return (data, i3) => {
    const values = [];
    let success = true;
    do {
      const r5 = p2(data, i3);
      if (r5.matched && test(r5.value, values.length + 1, data, i3, r5.position)) {
        values.push(r5.value);
        i3 = r5.position;
      } else {
        success = false;
      }
    } while (success);
    return {
      matched: true,
      position: i3,
      value: values
    };
  };
}
function many(p2) {
  return takeWhile(p2, () => true);
}
function many1(p2) {
  return ab(p2, many(p2), (head, tail) => [head, ...tail]);
}
function ab(pa, pb, join45) {
  return (data, i3) => mapOuter(pa(data, i3), (ma) => mapInner(pb(data, ma.position), (vb, j2) => join45(ma.value, vb, data, i3, j2)));
}
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, join45) {
  return (data, i3) => mapOuter(pa(data, i3), (ma) => mapOuter(pb(data, ma.position), (mb) => mapInner(pc(data, mb.position), (vc, j2) => join45(ma.value, mb.value, vc, data, i3, j2))));
}
function middle(pa, pb, pc) {
  return abc(pa, pb, pc, (ra, rb) => rb);
}
function all(...ps) {
  return (data, i3) => {
    const result = [];
    let position = i3;
    for (const p2 of ps) {
      const r1 = p2(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(p2) {
  return map(p2, (vs) => vs.flatMap((v2) => v2));
}
function chainReduce(acc, f5) {
  return (data, i3) => {
    let loop = true;
    let acc1 = acc;
    let pos2 = i3;
    do {
      const r5 = f5(acc1, data, pos2)(data, pos2);
      if (r5.matched) {
        acc1 = r5.value;
        pos2 = r5.position;
      } else {
        loop = false;
      }
    } while (loop);
    return {
      matched: true,
      position: pos2,
      value: acc1
    };
  };
}
function reduceLeft(acc, p2, reducer) {
  return chainReduce(acc, (acc2) => map(p2, (v2, data, i3, j2) => reducer(acc2, v2, data, i3, j2)));
}
function leftAssoc2(pLeft, pOper, pRight) {
  return chain(pLeft, (v0) => reduceLeft(v0, ab(pOper, pRight, (f5, y2) => [f5, y2]), (acc, [f5, y2]) => f5(acc, y2)));
}
function chain(p2, f5) {
  return (data, i3) => mapOuter(p2(data, i3), (m1) => f5(m1.value, data, i3, m1.position)(data, m1.position));
}
var init_core4 = __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 literal2(name3) {
  return token((t5) => t5.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, (m3, t5, r5) => t5 ? "\u2409" : r5 ? "\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,
    (m3, 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,
    (m3, 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((a2, b2) => _compareArrays(_getSelectorPriority(a2), _getSelectorPriority(b2)));
      break;
    }
    case "combinator": {
      normalize4(selector.left);
      break;
    }
    case "list": {
      selector.list.forEach(normalize4);
      selector.list.sort((a2, b2) => serialize(a2) < serialize(b2) ? -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(a2, b2) {
  return _compareArrays(a2, b2);
}
function _compareArrays(a2, b2) {
  if (!Array.isArray(a2) || !Array.isArray(b2)) {
    throw new Error("Arguments must be arrays.");
  }
  const shorter = a2.length < b2.length ? a2.length : b2.length;
  for (let i3 = 0; i3 < shorter; i3++) {
    if (a2[i3] === b2[i3]) {
      continue;
    }
    return a2[i3] < b2[i3] ? -1 : 1;
  }
  return a2.length - b2.length;
}
var ws, nl, nonascii, unicode, escape3, nmstart, nmchar, name, ident, string1, string22, 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_core4();
    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])?)`;
    escape3 = `(?:\\\\[^\\n\\r\\f0-9a-f])`;
    nmstart = `(?:[_a-z]|${nonascii}|${unicode}|${escape3})`;
    nmchar = `(?:[_a-z0-9-]|${nonascii}|${unicode}|${escape3})`;
    name = `(?:${nmchar}+)`;
    ident = `(?:[-]?${nmstart}${nmchar}*)`;
    string1 = `'([^\\n\\r\\f\\\\']|\\\\${nl}|${nonascii}|${unicode}|${escape3})*'`;
    string22 = `"([^\\n\\r\\f\\\\"]|\\\\${nl}|${nonascii}|${unicode}|${escape3})*"`;
    lexSelector = o2([
      { 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(string22, "i") },
      { name: "*" },
      { name: "." },
      { name: "," },
      { name: "[" },
      { name: "]" },
      { name: "=" },
      { name: ">" },
      { name: "|" },
      { name: "+" },
      { name: "~" },
      { name: "^" },
      { name: "$" }
    ]);
    lexEscapedString = o2([
      { name: "unicode", regex: new RegExp(unicode, "i") },
      { name: "escape", regex: new RegExp(escape3, "i") },
      { name: "any", regex: new RegExp("[\\s\\S]", "i") }
    ]);
    __name(sumSpec, "sumSpec");
    __name(sumAllSpec, "sumAllSpec");
    unicodeEscapedSequence_ = token((t5) => t5.name === "unicode" ? String.fromCodePoint(parseInt(t5.text.slice(1), 16)) : void 0);
    escapedSequence_ = token((t5) => t5.name === "escape" ? t5.text.slice(1) : void 0);
    anyChar_ = token((t5) => t5.name === "any" ? t5.text : void 0);
    escapedString_ = map(many(choice(unicodeEscapedSequence_, escapedSequence_, anyChar_)), (cs) => cs.join(""));
    __name(unescape3, "unescape");
    __name(literal2, "literal");
    whitespace_ = token((t5) => t5.name === "ws" ? null : void 0);
    optionalWhitespace_ = option(whitespace_, null);
    __name(optionallySpaced, "optionallySpaced");
    identifier_ = token((t5) => t5.name === "ident" ? unescape3(t5.text) : void 0);
    hashId_ = token((t5) => t5.name === "hash" ? unescape3(t5.text.slice(1)) : void 0);
    string_ = token((t5) => t5.name.startsWith("str") ? unescape3(t5.text.slice(1, -1)) : void 0);
    namespace_ = left(option(identifier_, ""), literal2("|"));
    qualifiedName_ = otherwise(ab(namespace_, identifier_, (ns, name3) => ({ name: name3, namespace: ns })), map(identifier_, (name3) => ({ name: name3, namespace: null })));
    uniSelector_ = otherwise(ab(namespace_, literal2("*"), (ns) => ({ type: "universal", namespace: ns, specificity: [0, 0, 0] })), map(literal2("*"), () => ({ 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(literal2("."), 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((t5) => {
      if (t5.name === "ident") {
        if (t5.text === "i" || t5.text === "I") {
          return "i";
        }
        if (t5.text === "s" || t5.text === "S") {
          return "s";
        }
      }
      return void 0;
    });
    attrValue_ = otherwise(ab(string_, option(right(optionalWhitespace_, attrModifier_), null), (v2, mod2) => ({ value: v2, modifier: mod2 })), ab(identifier_, option(right(whitespace_, attrModifier_), null), (v2, mod2) => ({ value: v2, modifier: mod2 })));
    attrMatcher_ = choice(map(literal2("="), () => "="), ab(literal2("~"), literal2("="), () => "~="), ab(literal2("|"), literal2("="), () => "|="), ab(literal2("^"), literal2("="), () => "^="), ab(literal2("$"), literal2("="), () => "$="), ab(literal2("*"), literal2("="), () => "*="));
    attrPresenceSelector_ = abc(literal2("["), optionallySpaced(qualifiedName_), literal2("]"), (lbr, { name: name3, namespace }) => ({
      type: "attrPresence",
      name: name3,
      namespace,
      specificity: [0, 1, 0]
    }));
    attrValueSelector_ = middle(literal2("["), abc(optionallySpaced(qualifiedName_), attrMatcher_, optionallySpaced(attrValue_), ({ name: name3, namespace }, matcher, { value, modifier }) => ({
      type: "attrValue",
      name: name3,
      namespace,
      matcher,
      value,
      modifier,
      specificity: [0, 1, 0]
    })), literal2("]"));
    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((s5) => s5.specificity))
      };
    });
    combinator_ = choice(map(literal2(">"), () => ">"), map(literal2("+"), () => "+"), map(literal2("~"), () => "~"), ab(literal2("|"), literal2("|"), () => "||"));
    combinatorSeparator_ = otherwise(optionallySpaced(combinator_), map(whitespace_, () => " "));
    complexSelector_ = leftAssoc2(compoundSelector_, map(combinatorSeparator_, (c4) => (left3, right3) => ({
      type: "compound",
      list: [...right3.list, { type: "combinator", combinator: c4, left: left3, specificity: left3.specificity }],
      specificity: sumSpec(left3.specificity, right3.specificity)
    })), compoundSelector_);
    listSelector_ = leftAssoc2(map(complexSelector_, (s5) => ({ type: "list", list: [s5] })), map(optionallySpaced(literal2(",")), () => (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(array2) {
  const len = array2.length;
  const results = new Array(len);
  for (let i3 = 0; i3 < len; i3++) {
    const [selectorString, val] = array2[i3];
    const ast = preprocess2(parse1(selectorString));
    results[i3] = {
      ast,
      terminal: {
        type: "terminal",
        valueContainer: { index: i3, value: val, specificity: ast.specificity }
      }
    };
  }
  return results;
}
function preprocess2(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 } = partition3(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(kind2, items) {
  if (kind2 === "tag") {
    return tagNameBranch(items);
  }
  if (kind2.startsWith("attrValue ")) {
    return attrValueBranch(kind2.substring(10), items);
  }
  if (kind2.startsWith("attrPresence ")) {
    return attrPresenceBranch(kind2.substring(13), items);
  }
  if (kind2 === "combinator >") {
    return combinatorBranch(">", items);
  }
  if (kind2 === "combinator +") {
    return combinatorBranch("+", items);
  }
  throw new Error(`Unsupported selector kind: ${kind2}`);
}
function tagNameBranch(items) {
  const groups = spliceAndGroup(items, (x3) => x3.type === "tag", (x3) => x3.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, (x3) => x3.type === "attrPresence" && x3.name === name3);
  }
  return {
    type: "attrPresence",
    name: name3,
    cont: weave(items)
  };
}
function attrValueBranch(name3, items) {
  const groups = spliceAndGroup(items, (x3) => x3.type === "attrValue" && x3.name === name3, (x3) => `${x3.matcher} ${x3.modifier || ""} ${x3.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 lower3 = actual.toLowerCase();
          return expected === lower3 || lower3.startsWith(expected) && lower3[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, (x3) => x3.type === "combinator" && x3.combinator === combinator, (x3) => serialize(x3.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 i3 = simpsels.length; i3-- > 0; ) {
    if (predicate(simpsels[i3])) {
      matches[i3] = true;
      firstIndex = i3;
    }
  }
  if (firstIndex == -1) {
    throw new Error(`Couldn't find the required simple selector.`);
  }
  const result = simpsels[firstIndex];
  item.ast.list = simpsels.filter((sel, i3) => !matches[i3]);
  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 partition3(src, predicate) {
  const matches = [];
  const rest = [];
  for (const x3 of src) {
    if (predicate(x3)) {
      matches.push(x3);
    } else {
      rest.push(x3);
    }
  }
  return { matches, rest };
}
function partition1(src, predicate) {
  const matches = [];
  const rest = [];
  for (const x3 of src) {
    if (predicate(x3)) {
      matches.push(x3);
    } else {
      rest.push(x3);
    }
  }
  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(preprocess2, "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(partition3, "partition");
    __name(partition1, "partition1");
    Picker = class {
      static {
        __name(this, "Picker");
      }
      constructor(f5) {
        this.f = f5;
      }
      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 i3 = 1; i3 < len; i3++) {
          const next = results[i3];
          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((m3) => m3(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_esm15();
    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((c4) => c4.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((c4) => c4.charCodeAt(0))
    );
  }
});

// node_modules/entities/lib/esm/decode_codepoint.js
function replaceCodePoint(codePoint) {
  var _a7;
  if (codePoint >= 55296 && codePoint <= 57343 || codePoint > 1114111) {
    return 65533;
  }
  return (_a7 = decodeMap.get(codePoint)) !== null && _a7 !== void 0 ? _a7 : codePoint;
}
var _a5, 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
    (_a5 = String.fromCodePoint) !== null && _a5 !== void 0 ? _a5 : 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 _a7;
        if (this.consumed <= expectedLength) {
          (_a7 = this.errors) === null || _a7 === void 0 ? void 0 : _a7.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 _a7;
        const { result, decodeTree } = this;
        const valueLength = (decodeTree[result] & BinTrieFlags.VALUE_LENGTH) >> 14;
        this.emitNamedEntityData(result, valueLength, this.consumed);
        (_a7 = this.errors) === null || _a7 === void 0 ? void 0 : _a7.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 _a7;
        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: {
            (_a7 = this.errors) === null || _a7 === void 0 ? void 0 : _a7.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(c4) {
  return c4 === CharCodes2.Space || c4 === CharCodes2.NewLine || c4 === CharCodes2.Tab || c4 === CharCodes2.FormFeed || c4 === CharCodes2.CarriageReturn;
}
function isEndOfTagSection(c4) {
  return c4 === CharCodes2.Slash || c4 === CharCodes2.Gt || isWhitespace2(c4);
}
function isNumber2(c4) {
  return c4 >= CharCodes2.Zero && c4 <= CharCodes2.Nine;
}
function isASCIIAlpha(c4) {
  return c4 >= CharCodes2.LowerA && c4 <= CharCodes2.LowerZ || c4 >= CharCodes2.UpperA && c4 <= CharCodes2.UpperZ;
}
function isHexDigit(c4) {
  return c4 >= CharCodes2.UpperA && c4 <= CharCodes2.UpperF || c4 >= CharCodes2.LowerA && c4 <= 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(c4) {
        if (c4 === 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 && c4 === CharCodes2.Amp) {
          this.state = State.BeforeEntity;
        }
      }
      stateSpecialStartSequence(c4) {
        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(c4)
        ) : (
          // Otherwise, do a case-insensitive comparison
          (c4 | 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(c4);
      }
      /** Look for an end tag. For <title> tags, also decode entities. */
      stateInSpecialTag(c4) {
        if (this.sequenceIndex === this.currentSequence.length) {
          if (c4 === CharCodes2.Gt || isWhitespace2(c4)) {
            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(c4);
            return;
          }
          this.sequenceIndex = 0;
        }
        if ((c4 | 32) === this.currentSequence[this.sequenceIndex]) {
          this.sequenceIndex += 1;
        } else if (this.sequenceIndex === 0) {
          if (this.currentSequence === Sequences.TitleEnd) {
            if (this.decodeEntities && c4 === CharCodes2.Amp) {
              this.state = State.BeforeEntity;
            }
          } else if (this.fastForwardTo(CharCodes2.Lt)) {
            this.sequenceIndex = 1;
          }
        } else {
          this.sequenceIndex = Number(c4 === CharCodes2.Lt);
        }
      }
      stateCDATASequence(c4) {
        if (c4 === 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(c4);
        }
      }
      /**
       * 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(c4) {
        while (++this.index < this.buffer.length + this.offset) {
          if (this.buffer.charCodeAt(this.index - this.offset) === c4) {
            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(c4) {
        if (c4 === 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 (c4 !== 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(c4) {
        return this.xmlMode ? !isEndOfTagSection(c4) : isASCIIAlpha(c4);
      }
      startSpecial(sequence, offset) {
        this.isSpecial = true;
        this.currentSequence = sequence;
        this.sequenceIndex = offset;
        this.state = State.SpecialStartSequence;
      }
      stateBeforeTagName(c4) {
        if (c4 === CharCodes2.ExclamationMark) {
          this.state = State.BeforeDeclaration;
          this.sectionStart = this.index + 1;
        } else if (c4 === CharCodes2.Questionmark) {
          this.state = State.InProcessingInstruction;
          this.sectionStart = this.index + 1;
        } else if (this.isTagStartChar(c4)) {
          const lower3 = c4 | 32;
          this.sectionStart = this.index;
          if (!this.xmlMode && lower3 === Sequences.TitleEnd[2]) {
            this.startSpecial(Sequences.TitleEnd, 3);
          } else {
            this.state = !this.xmlMode && lower3 === Sequences.ScriptEnd[2] ? State.BeforeSpecialS : State.InTagName;
          }
        } else if (c4 === CharCodes2.Slash) {
          this.state = State.BeforeClosingTagName;
        } else {
          this.state = State.Text;
          this.stateText(c4);
        }
      }
      stateInTagName(c4) {
        if (isEndOfTagSection(c4)) {
          this.cbs.onopentagname(this.sectionStart, this.index);
          this.sectionStart = -1;
          this.state = State.BeforeAttributeName;
          this.stateBeforeAttributeName(c4);
        }
      }
      stateBeforeClosingTagName(c4) {
        if (isWhitespace2(c4)) {
        } else if (c4 === CharCodes2.Gt) {
          this.state = State.Text;
        } else {
          this.state = this.isTagStartChar(c4) ? State.InClosingTagName : State.InSpecialComment;
          this.sectionStart = this.index;
        }
      }
      stateInClosingTagName(c4) {
        if (c4 === CharCodes2.Gt || isWhitespace2(c4)) {
          this.cbs.onclosetag(this.sectionStart, this.index);
          this.sectionStart = -1;
          this.state = State.AfterClosingTagName;
          this.stateAfterClosingTagName(c4);
        }
      }
      stateAfterClosingTagName(c4) {
        if (c4 === CharCodes2.Gt || this.fastForwardTo(CharCodes2.Gt)) {
          this.state = State.Text;
          this.baseState = State.Text;
          this.sectionStart = this.index + 1;
        }
      }
      stateBeforeAttributeName(c4) {
        if (c4 === 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 (c4 === CharCodes2.Slash) {
          this.state = State.InSelfClosingTag;
        } else if (!isWhitespace2(c4)) {
          this.state = State.InAttributeName;
          this.sectionStart = this.index;
        }
      }
      stateInSelfClosingTag(c4) {
        if (c4 === 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(c4)) {
          this.state = State.BeforeAttributeName;
          this.stateBeforeAttributeName(c4);
        }
      }
      stateInAttributeName(c4) {
        if (c4 === CharCodes2.Eq || isEndOfTagSection(c4)) {
          this.cbs.onattribname(this.sectionStart, this.index);
          this.sectionStart = -1;
          this.state = State.AfterAttributeName;
          this.stateAfterAttributeName(c4);
        }
      }
      stateAfterAttributeName(c4) {
        if (c4 === CharCodes2.Eq) {
          this.state = State.BeforeAttributeValue;
        } else if (c4 === CharCodes2.Slash || c4 === CharCodes2.Gt) {
          this.cbs.onattribend(QuoteType.NoValue, this.index);
          this.state = State.BeforeAttributeName;
          this.stateBeforeAttributeName(c4);
        } else if (!isWhitespace2(c4)) {
          this.cbs.onattribend(QuoteType.NoValue, this.index);
          this.state = State.InAttributeName;
          this.sectionStart = this.index;
        }
      }
      stateBeforeAttributeValue(c4) {
        if (c4 === CharCodes2.DoubleQuote) {
          this.state = State.InAttributeValueDq;
          this.sectionStart = this.index + 1;
        } else if (c4 === CharCodes2.SingleQuote) {
          this.state = State.InAttributeValueSq;
          this.sectionStart = this.index + 1;
        } else if (!isWhitespace2(c4)) {
          this.sectionStart = this.index;
          this.state = State.InAttributeValueNq;
          this.stateInAttributeValueNoQuotes(c4);
        }
      }
      handleInAttributeValue(c4, quote3) {
        if (c4 === 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 && c4 === CharCodes2.Amp) {
          this.baseState = this.state;
          this.state = State.BeforeEntity;
        }
      }
      stateInAttributeValueDoubleQuotes(c4) {
        this.handleInAttributeValue(c4, CharCodes2.DoubleQuote);
      }
      stateInAttributeValueSingleQuotes(c4) {
        this.handleInAttributeValue(c4, CharCodes2.SingleQuote);
      }
      stateInAttributeValueNoQuotes(c4) {
        if (isWhitespace2(c4) || c4 === 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(c4);
        } else if (this.decodeEntities && c4 === CharCodes2.Amp) {
          this.baseState = this.state;
          this.state = State.BeforeEntity;
        }
      }
      stateBeforeDeclaration(c4) {
        if (c4 === CharCodes2.OpeningSquareBracket) {
          this.state = State.CDATASequence;
          this.sequenceIndex = 0;
        } else {
          this.state = c4 === CharCodes2.Dash ? State.BeforeComment : State.InDeclaration;
        }
      }
      stateInDeclaration(c4) {
        if (c4 === CharCodes2.Gt || this.fastForwardTo(CharCodes2.Gt)) {
          this.cbs.ondeclaration(this.sectionStart, this.index);
          this.state = State.Text;
          this.sectionStart = this.index + 1;
        }
      }
      stateInProcessingInstruction(c4) {
        if (c4 === CharCodes2.Gt || this.fastForwardTo(CharCodes2.Gt)) {
          this.cbs.onprocessinginstruction(this.sectionStart, this.index);
          this.state = State.Text;
          this.sectionStart = this.index + 1;
        }
      }
      stateBeforeComment(c4) {
        if (c4 === CharCodes2.Dash) {
          this.state = State.InCommentLike;
          this.currentSequence = Sequences.CommentEnd;
          this.sequenceIndex = 2;
          this.sectionStart = this.index + 1;
        } else {
          this.state = State.InDeclaration;
        }
      }
      stateInSpecialComment(c4) {
        if (c4 === CharCodes2.Gt || this.fastForwardTo(CharCodes2.Gt)) {
          this.cbs.oncomment(this.sectionStart, this.index, 0);
          this.state = State.Text;
          this.sectionStart = this.index + 1;
        }
      }
      stateBeforeSpecialS(c4) {
        const lower3 = c4 | 32;
        if (lower3 === Sequences.ScriptEnd[3]) {
          this.startSpecial(Sequences.ScriptEnd, 4);
        } else if (lower3 === Sequences.StyleEnd[3]) {
          this.startSpecial(Sequences.StyleEnd, 4);
        } else {
          this.state = State.InTagName;
          this.stateInTagName(c4);
        }
      }
      stateBeforeEntity(c4) {
        this.entityExcess = 1;
        this.entityResult = 0;
        if (c4 === CharCodes2.Number) {
          this.state = State.BeforeNumericEntity;
        } else if (c4 === CharCodes2.Amp) {
        } else {
          this.trieIndex = 0;
          this.trieCurrent = this.entityTrie[0];
          this.state = State.InNamedEntity;
          this.stateInNamedEntity(c4);
        }
      }
      stateInNamedEntity(c4) {
        this.entityExcess += 1;
        this.trieIndex = determineBranch(this.entityTrie, this.trieCurrent, this.trieIndex + 1, c4);
        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() && c4 !== 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(c4) {
        if ((c4 | 32) === CharCodes2.LowerX) {
          this.entityExcess++;
          this.state = State.InHexEntity;
        } else {
          this.state = State.InNumericEntity;
          this.stateInNumericEntity(c4);
        }
      }
      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(c4) {
        if (c4 === CharCodes2.Semi) {
          this.emitNumericEntity(true);
        } else if (isNumber2(c4)) {
          this.entityResult = this.entityResult * 10 + (c4 - CharCodes2.Zero);
          this.entityExcess++;
        } else {
          if (this.allowLegacyEntity()) {
            this.emitNumericEntity(false);
          } else {
            this.state = this.baseState;
          }
          this.index--;
        }
      }
      stateInHexEntity(c4) {
        if (c4 === CharCodes2.Semi) {
          this.emitNumericEntity(true);
        } else if (isNumber2(c4)) {
          this.entityResult = this.entityResult * 16 + (c4 - CharCodes2.Zero);
          this.entityExcess++;
        } else if (isHexDigit(c4)) {
          this.entityResult = this.entityResult * 16 + ((c4 | 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 c4 = this.buffer.charCodeAt(this.index - this.offset);
          switch (this.state) {
            case State.Text: {
              this.stateText(c4);
              break;
            }
            case State.SpecialStartSequence: {
              this.stateSpecialStartSequence(c4);
              break;
            }
            case State.InSpecialTag: {
              this.stateInSpecialTag(c4);
              break;
            }
            case State.CDATASequence: {
              this.stateCDATASequence(c4);
              break;
            }
            case State.InAttributeValueDq: {
              this.stateInAttributeValueDoubleQuotes(c4);
              break;
            }
            case State.InAttributeName: {
              this.stateInAttributeName(c4);
              break;
            }
            case State.InCommentLike: {
              this.stateInCommentLike(c4);
              break;
            }
            case State.InSpecialComment: {
              this.stateInSpecialComment(c4);
              break;
            }
            case State.BeforeAttributeName: {
              this.stateBeforeAttributeName(c4);
              break;
            }
            case State.InTagName: {
              this.stateInTagName(c4);
              break;
            }
            case State.InClosingTagName: {
              this.stateInClosingTagName(c4);
              break;
            }
            case State.BeforeTagName: {
              this.stateBeforeTagName(c4);
              break;
            }
            case State.AfterAttributeName: {
              this.stateAfterAttributeName(c4);
              break;
            }
            case State.InAttributeValueSq: {
              this.stateInAttributeValueSingleQuotes(c4);
              break;
            }
            case State.BeforeAttributeValue: {
              this.stateBeforeAttributeValue(c4);
              break;
            }
            case State.BeforeClosingTagName: {
              this.stateBeforeClosingTagName(c4);
              break;
            }
            case State.AfterClosingTagName: {
              this.stateAfterClosingTagName(c4);
              break;
            }
            case State.BeforeSpecialS: {
              this.stateBeforeSpecialS(c4);
              break;
            }
            case State.InAttributeValueNq: {
              this.stateInAttributeValueNoQuotes(c4);
              break;
            }
            case State.InSelfClosingTag: {
              this.stateInSelfClosingTag(c4);
              break;
            }
            case State.InDeclaration: {
              this.stateInDeclaration(c4);
              break;
            }
            case State.BeforeDeclaration: {
              this.stateBeforeDeclaration(c4);
              break;
            }
            case State.BeforeComment: {
              this.stateBeforeComment(c4);
              break;
            }
            case State.InProcessingInstruction: {
              this.stateInProcessingInstruction(c4);
              break;
            }
            case State.InNamedEntity: {
              this.stateInNamedEntity(c4);
              break;
            }
            case State.BeforeEntity: {
              this.stateBeforeEntity(c4);
              break;
            }
            case State.InHexEntity: {
              this.stateInHexEntity(c4);
              break;
            }
            case State.InNumericEntity: {
              this.stateInNumericEntity(c4);
              break;
            }
            default: {
              this.stateBeforeNumericEntity(c4);
            }
          }
          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(cp3) {
        if (this.baseState !== State.Text && this.baseState !== State.InSpecialTag) {
          this.cbs.onattribentity(cp3);
        } else {
          this.cbs.ontextentity(cp3);
        }
      }
    };
  }
});

// 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 _a7, _b2, _c2, _d, _e2;
        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 = (_a7 = options2.lowerCaseTags) !== null && _a7 !== void 0 ? _a7 : !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);
        (_e2 = (_d = this.cbs).onparserinit) === null || _e2 === void 0 ? void 0 : _e2.call(_d, this);
      }
      // Tokenizer event handlers
      /** @internal */
      ontext(start, endIndex) {
        var _a7, _b2;
        const data = this.getSlice(start, endIndex);
        this.endIndex = endIndex - 1;
        (_b2 = (_a7 = this.cbs).ontext) === null || _b2 === void 0 ? void 0 : _b2.call(_a7, data);
        this.startIndex = endIndex;
      }
      /** @internal */
      ontextentity(cp3) {
        var _a7, _b2;
        const index = this.tokenizer.getSectionStart();
        this.endIndex = index - 1;
        (_b2 = (_a7 = this.cbs).ontext) === null || _b2 === void 0 ? void 0 : _b2.call(_a7, fromCodePoint(cp3));
        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 _a7, _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 = (_a7 = this.cbs).onclosetag) === null || _b2 === void 0 ? void 0 : _b2.call(_a7, 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 _a7, _b2;
        this.startIndex = this.openTagStart;
        if (this.attribs) {
          (_b2 = (_a7 = this.cbs).onopentag) === null || _b2 === void 0 ? void 0 : _b2.call(_a7, 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 _a7, _b2, _c2, _d, _e2, _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 = (_a7 = this.cbs).onopentagname) === null || _b2 === void 0 ? void 0 : _b2.call(_a7, "br");
          (_d = (_c2 = this.cbs).onopentag) === null || _d === void 0 ? void 0 : _d.call(_c2, "br", {}, true);
          (_f = (_e2 = this.cbs).onclosetag) === null || _f === void 0 ? void 0 : _f.call(_e2, "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 _a7, _b2;
        const name3 = this.tagname;
        this.endOpenTag(isOpenImplied);
        if (this.stack[this.stack.length - 1] === name3) {
          (_b2 = (_a7 = this.cbs).onclosetag) === null || _b2 === void 0 ? void 0 : _b2.call(_a7, 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(cp3) {
        this.attribvalue += fromCodePoint(cp3);
      }
      /** @internal */
      onattribend(quote3, endIndex) {
        var _a7, _b2;
        this.endIndex = endIndex;
        (_b2 = (_a7 = this.cbs).onattribute) === null || _b2 === void 0 ? void 0 : _b2.call(_a7, 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 _a7, _b2, _c2, _d;
        this.endIndex = endIndex;
        (_b2 = (_a7 = this.cbs).oncomment) === null || _b2 === void 0 ? void 0 : _b2.call(_a7, 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 _a7, _b2, _c2, _d, _e2, _f, _g, _h, _j, _k;
        this.endIndex = endIndex;
        const value = this.getSlice(start, endIndex - offset);
        if (this.options.xmlMode || this.options.recognizeCDATA) {
          (_b2 = (_a7 = this.cbs).oncdatastart) === null || _b2 === void 0 ? void 0 : _b2.call(_a7);
          (_d = (_c2 = this.cbs).ontext) === null || _d === void 0 ? void 0 : _d.call(_c2, value);
          (_f = (_e2 = this.cbs).oncdataend) === null || _f === void 0 ? void 0 : _f.call(_e2);
        } 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 _a7, _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 = (_a7 = this.cbs).onend) === null || _b2 === void 0 ? void 0 : _b2.call(_a7);
      }
      /**
       * Resets the parser to a blank state, ready to parse a new HTML document
       */
      reset() {
        var _a7, _b2, _c2, _d;
        (_b2 = (_a7 = this.cbs).onreset) === null || _b2 === void 0 ? void 0 : _b2.call(_a7);
        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 _a7, _b2;
        if (this.ended) {
          (_b2 = (_a7 = this.cbs).onerror) === null || _b2 === void 0 ? void 0 : _b2.call(_a7, 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 _a7, _b2;
        if (this.ended) {
          (_b2 = (_a7 = this.cbs).onerror) === null || _b2 === void 0 ? void 0 : _b2.call(_a7, 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 i3 = 1; i3 < arr.length; i3++) {
    arr[i3][0] += arr[i3 - 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 i3 = match2.index;
    const char = str2.charCodeAt(i3);
    const next = xmlCodeMap.get(char);
    if (next !== void 0) {
      ret += str2.substring(lastIdx, i3) + next;
      lastIdx = i3 + 1;
    } else {
      ret += `${str2.substring(lastIdx, i3)}&#x${getCodePoint(str2, i3).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
      (c4, index) => (c4.charCodeAt(index) & 64512) === 55296 ? (c4.charCodeAt(index) - 55296) * 1024 + c4.charCodeAt(index + 1) - 56320 + 65536 : c4.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_esm16 = __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 _a7;
  if (!attributes)
    return;
  const encode4 = ((_a7 = opts.encodeEntities) !== null && _a7 !== void 0 ? _a7 : opts.decodeEntities) === false ? replaceQuotes : opts.xmlMode || opts.encodeEntities !== "utf8" ? encodeXML : escapeAttribute;
  return Object.keys(attributes).map((key) => {
    var _a8, _b2;
    const value = (_a8 = attributes[key]) !== null && _a8 !== void 0 ? _a8 : "";
    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 render(node, options2 = {}) {
  const nodes = "length" in node ? node : [node];
  let output = "";
  for (let i3 = 0; i3 < nodes.length; i3++) {
    output += renderNode(nodes[i3], options2);
  }
  return output;
}
function renderNode(node, options2) {
  switch (node.type) {
    case Root:
      return render(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 Text:
      return renderText(node, options2);
  }
}
function renderTag(elem, opts) {
  var _a7;
  if (opts.xmlMode === "foreign") {
    elem.name = (_a7 = elementNames.get(elem.name)) !== null && _a7 !== void 0 ? _a7 : 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 += render(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 _a7;
  let data = elem.data || "";
  if (((_a7 = opts.encodeEntities) !== null && _a7 !== void 0 ? _a7 : 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_esm17 = __esm({
  "node_modules/dom-serializer/lib/esm/index.js"() {
    init_esbuild_shims();
    init_esm14();
    init_esm16();
    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(render, "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_esm15();
    init_esm17();
    init_esm14();
  }
});

// node_modules/domutils/lib/esm/traversal.js
var init_traversal = __esm({
  "node_modules/domutils/lib/esm/traversal.js"() {
    init_esbuild_shims();
    init_esm15();
  }
});

// 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_esm15();
  }
});

// node_modules/domutils/lib/esm/legacy.js
var init_legacy = __esm({
  "node_modules/domutils/lib/esm/legacy.js"() {
    init_esbuild_shims();
    init_esm15();
    init_querying();
  }
});

// node_modules/domutils/lib/esm/helpers.js
var DocumentPosition;
var init_helpers2 = __esm({
  "node_modules/domutils/lib/esm/helpers.js"() {
    init_esbuild_shims();
    init_esm15();
    (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_esm18 = __esm({
  "node_modules/domutils/lib/esm/index.js"() {
    init_esbuild_shims();
    init_stringify3();
    init_traversal();
    init_manipulation();
    init_querying();
    init_legacy();
    init_helpers2();
    init_feeds();
    init_esm15();
  }
});

// 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_esm19 = __esm({
  "node_modules/htmlparser2/lib/esm/index.js"() {
    init_esbuild_shims();
    init_Parser();
    init_Parser();
    init_esm15();
    init_esm15();
    init_Tokenizer();
    init_esm14();
    init_esm18();
    init_esm18();
    init_esm18();
    __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(object3, property) {
      try {
        return property in object3;
      } catch (_2) {
        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(array2, options2) {
      if (!Array.isArray(array2)) {
        throw new Error("first argument should be an array");
      }
      return array2.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(n3, f5, g2 = () => void 0) {
  if (n3 === void 0) {
    const f1 = /* @__PURE__ */ __name(function(...args) {
      return f5(f1, ...args);
    }, "f1");
    return f1;
  }
  if (n3 >= 0) {
    return function(...args) {
      return f5(limitedDepthRecursive(n3 - 1, f5, g2), ...args);
    };
  }
  return g2;
}
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, (c4) => "\\u" + c4.charCodeAt().toString(16).padStart(4, "0"));
}
function mergeDuplicatesPreferLast(items, getKey) {
  const map2 = /* @__PURE__ */ new Map();
  for (let i3 = items.length; i3-- > 0; ) {
    const item = items[i3];
    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, path125) {
  for (const key of path125) {
    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((n3) => String.fromCharCode(baseCode + n3)).join("");
}
function numberToRoman(num) {
  return [...num + ""].map((n3) => +n3).reverse().map((v2, i3) => v2 % 5 < 4 ? (v2 < 5 ? "" : V2[i3]) + I2[i3].repeat(v2 % 5) : I2[i3] + (v2 < 5 ? V2[i3] : I2[i3 + 1])).reverse().join("");
}
function charactersToCodes(str2) {
  return [...str2].map((c4) => "\\u" + c4.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((s5) => !s5.format);
  if (selectorsWithoutFormat.length) {
    throw new Error(
      "Following selectors have no specified format: " + selectorsWithoutFormat.map((s5) => `\`${s5.selector}\``).join(", ")
    );
  }
  const picker = new DecisionTree(
    options2.selectors.map((s5) => [s5.selector, s5])
  ).build(hp2Builder);
  if (typeof options2.encodeCharacters !== "function") {
    options2.encodeCharacters = makeReplacerFromDict(options2.encodeCharacters);
  }
  const baseSelectorsPicker = new DecisionTree(
    options2.baseElements.selectors.map((s5, i3) => [s5, i3 + 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 process12(html2, metadata, options2, picker, findBaseElements, limitedWalk);
  };
}
function process12(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((a2, b2) => a2.selectorIndex - b2.selectorIndex);
  }
  return options2.baseElements.returnDomByDefault && results.length === 0 ? dom : results.map((x3) => x3.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(([, v2]) => v2 !== false);
  const regex3 = new RegExp(
    entries.map(([c4]) => `(${unicodeEscape([...c4][0])})`).join("|"),
    "g"
  );
  const values = entries.map(([, v2]) => v2);
  const replacer = /* @__PURE__ */ __name((m3, ...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(([k2, v2]) => v2 === "" ? k2 : `${k2}=${v2.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(
    render(elem, { decodeEntities: builder.options.decodeEntities })
  );
  builder.stopNoWrap();
}
function formatBlockHtml(elem, walk, builder, formatOptions) {
  builder.openBlock({ leadingLineBreaks: formatOptions.leadingLineBreaks || 2 });
  builder.startNoWrap();
  builder.addLiteral(
    render(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, j2) {
  if (!matrix[j2]) {
    matrix[j2] = [];
  }
  return matrix[j2];
}
function findFirstVacantIndex(row, x3 = 0) {
  while (row[x3]) {
    x3++;
  }
  return x3;
}
function transposeInPlace(matrix, maxSize) {
  for (let i3 = 0; i3 < maxSize; i3++) {
    const rowI = getRow(matrix, i3);
    for (let j2 = 0; j2 < i3; j2++) {
      const rowJ = getRow(matrix, j2);
      if (rowI[j2] || rowJ[i3]) {
        const temp = rowI[j2];
        rowI[j2] = rowJ[i3];
        rowJ[i3] = temp;
      }
    }
  }
}
function putCellIntoLayout(cell, layout, baseRow, baseCol) {
  for (let r5 = 0; r5 < cell.rowspan; r5++) {
    const layoutRow = getRow(layout, baseRow + r5);
    for (let c4 = 0; c4 < cell.colspan; c4++) {
      layoutRow[baseCol + c4] = 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 j2 = 0; j2 < rowNumber; j2++) {
    const layoutRow = getRow(layout, j2);
    const cells = tableRows[j2];
    let x3 = 0;
    for (let i3 = 0; i3 < cells.length; i3++) {
      const cell = cells[i3];
      x3 = findFirstVacantIndex(layoutRow, x3);
      putCellIntoLayout(cell, layout, j2, x3);
      x3 += cell.colspan;
      cell.lines = cell.text.split("\n");
      const cellHeight = cell.lines.length;
      updateOffset(rowOffsets, j2, cell.rowspan, cellHeight + rowSpacing);
    }
    colNumber = layoutRow.length > colNumber ? layoutRow.length : colNumber;
  }
  transposeInPlace(layout, rowNumber > colNumber ? rowNumber : colNumber);
  const outputLines = [];
  const colOffsets = [0];
  for (let x3 = 0; x3 < colNumber; x3++) {
    let y2 = 0;
    let cell;
    const rowsInThisColumn = Math.min(rowNumber, layout[x3].length);
    while (y2 < rowsInThisColumn) {
      cell = layout[x3][y2];
      if (cell) {
        if (!cell.rendered) {
          let cellWidth = 0;
          for (let j2 = 0; j2 < cell.lines.length; j2++) {
            const line = cell.lines[j2];
            const lineOffset = rowOffsets[y2] + j2;
            outputLines[lineOffset] = (outputLines[lineOffset] || "").padEnd(colOffsets[x3]) + line;
            cellWidth = line.length > cellWidth ? line.length : cellWidth;
          }
          updateOffset(colOffsets, x3, cell.colspan, cellWidth + colSpacing);
          cell.rendered = true;
        }
        y2 += cell.rowspan;
      } else {
        const lineOffset = rowOffsets[y2];
        outputLines[lineOffset] = outputLines[lineOffset] || "";
        y2++;
      }
    }
  }
  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(path125, rewriter, baseUrl, metadata, elem) {
  const modifiedPath = typeof rewriter === "function" ? rewriter(path125, metadata, elem) : path125;
  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 (i3) => numberToLetterSequence(i3, "a");
    case "A":
      return (i3) => numberToLetterSequence(i3, "A");
    case "i":
      return (i3) => numberToRoman(i3).toLowerCase();
    case "I":
      return (i3) => numberToRoman(i3);
    case "1":
    default:
      return (i3) => i3.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((x3) => classes.includes(x3)) || attrIds.some((x3) => ids.includes(x3));
}
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, (s5) => s5.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, (s5) => s5.selector);
  }
  function set(obj, path125, value) {
    const valueKey = path125.pop();
    for (const key of path125) {
      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, I2, V2, 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_esm19();
    init_selderee();
    import_deepmerge = __toESM(require_cjs2(), 1);
    init_esm17();
    __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");
    I2 = ["I", "X", "C", "M"];
    V2 = ["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(n3 = 1) {
        this.lines.push(this.nextLineWords);
        if (n3 > 1) {
          this.lines.push(...Array.from({ length: n3 - 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, transform2) {
        super(next);
        this.transform = transform2;
      }
    };
    __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, transform2 = (str2) => str2, noWrap = false) {
            if (!text) {
              return;
            }
            const previouslyStashedSpace = inlineTextBuilder.stashedSpace;
            let anyMatch = false;
            let m3 = wordOrNewlineRe.exec(text);
            if (m3) {
              anyMatch = true;
              if (m3[0] === "\n") {
                inlineTextBuilder.startNewLine();
              } else if (previouslyStashedSpace || this.testLeadingWhitespace(text)) {
                inlineTextBuilder.pushWord(transform2(m3[0]), noWrap);
              } else {
                inlineTextBuilder.concatWord(transform2(m3[0]), noWrap);
              }
              while ((m3 = wordOrNewlineRe.exec(text)) !== null) {
                if (m3[0] === "\n") {
                  inlineTextBuilder.startNewLine();
                } else {
                  inlineTextBuilder.pushWord(transform2(m3[0]), noWrap);
                }
              }
            }
            inlineTextBuilder.stashedSpace = previouslyStashedSpace && !anyMatch || this.testTrailingWhitespace(text);
          };
        } else {
          const wordRe = new RegExp(`[^${whitespaceCodes}]+`, "g");
          this.shrinkWrapAdd = function(text, inlineTextBuilder, transform2 = (str2) => str2, noWrap = false) {
            if (!text) {
              return;
            }
            const previouslyStashedSpace = inlineTextBuilder.stashedSpace;
            let anyMatch = false;
            let m3 = wordRe.exec(text);
            if (m3) {
              anyMatch = true;
              if (previouslyStashedSpace || this.testLeadingWhitespace(text)) {
                inlineTextBuilder.pushWord(transform2(m3[0]), noWrap);
              } else {
                inlineTextBuilder.concatWord(transform2(m3[0]), noWrap);
              }
              while ((m3 = wordRe.exec(text)) !== null) {
                inlineTextBuilder.pushWord(transform2(m3[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 m3 = this.newlineOrNonNewlineStringRe.exec(text);
        if (m3) {
          anyMatch = true;
          if (m3[0] === "\n") {
            inlineTextBuilder.startNewLine();
          } else if (previouslyStashedSpace) {
            inlineTextBuilder.pushWord(m3[0], noWrap);
          } else {
            inlineTextBuilder.concatWord(m3[0], noWrap);
          }
          while ((m3 = this.newlineOrNonNewlineStringRe.exec(text)) !== null) {
            if (m3[0] === "\n") {
              inlineTextBuilder.startNewLine();
            } else {
              inlineTextBuilder.pushWord(m3[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 transform2 = this._wordTransformer.transform;
        this._wordTransformer = this._wordTransformer.next;
        return transform2;
      }
      /**
       * 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 wt2 = this._wordTransformer ? (str2) => applyTransformer(str2, this._wordTransformer) : void 0;
        const ce2 = this.options.encodeCharacters;
        return wt2 ? ce2 ? (str2) => ce2(wt2(str2)) : wt2 : ce2;
      }
      _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(process12, "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((s5) => typeof s5 === "object") ? concatMerge(acc, src) : overwriteMerge(acc, src), "selectorsMerge");
    __name(compile, "compile");
    __name(convert, "convert");
    __name(handleDeprecatedOptions, "handleDeprecatedOptions");
  }
});

// packages/core/dist/src/tools/web-fetch.js
var import_undici3, 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_undici3 = __toESM(require_undici(), 1);
    init_config3();
    init_fetch();
    init_partUtils();
    init_tool_error();
    init_tools();
    init_models();
    init_tool_names();
    init_debugLogger();
    URL_FETCH_TIMEOUT_MS = 1e4;
    MAX_CONTENT_LENGTH = 1e5;
    WebFetchToolInvocation = class extends BaseToolInvocation {
      static {
        __name(this, "WebFetchToolInvocation");
      }
      config;
      debugLogger;
      constructor(config2, params) {
        super(params);
        this.config = config2;
        this.debugLogger = createDebugLogger("WEB_FETCH");
      }
      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/", "/");
          this.debugLogger.debug(`[WebFetchTool] Converted GitHub blob URL to raw URL: ${url2}`);
        }
        try {
          this.debugLogger.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}`;
            this.debugLogger.error(`[WebFetchTool] ${errorMessage}`);
            throw new Error(errorMessage);
          }
          this.debugLogger.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);
          this.debugLogger.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}
---`;
          this.debugLogger.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) || "";
          this.debugLogger.debug(`[WebFetchTool] Successfully processed content from ${this.params.url}`);
          return {
            llmContent: resultText,
            returnDisplay: `Content from ${this.params.url} processed successfully.`
          };
        } catch (e4) {
          const error2 = e4;
          const errorMessage = `Error during fetch for ${url2}: ${error2.message}`;
          this.debugLogger.error(`[WebFetchTool] ${errorMessage}`, error2);
          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 || this.config.getApprovalMode() === ApprovalMode.PLAN) {
          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) {
          this.debugLogger.debug(`[WebFetchTool] Private IP detected for ${this.params.url}, using direct fetch`);
        } else {
          this.debugLogger.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(config2) {
        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 = config2;
        const proxy = config2.getProxy();
        if (proxy) {
          (0, import_undici3.setGlobalDispatcher)(new import_undici3.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((s5, i3) => `[${i3 + 1}] ${s5.title || "Untitled"} (${s5.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 (error2) {
          if (error2 instanceof Error && error2.message.startsWith(`[${this.name}]`)) {
            throw error2;
          }
          const message = error2 instanceof Error ? error2.message : String(error2);
          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(config2) {
        super();
        this.config = config2;
      }
      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((r5) => ({
          title: r5.title,
          url: r5.url,
          content: r5.content,
          score: r5.score,
          publishedDate: r5.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(config2) {
        super();
        this.config = config2;
      }
      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 fs41 } from "node:fs";
import * as os17 from "os";
import * as path43 from "path";
function getQwenCachedCredentialPath2() {
  return path43.join(os17.homedir(), QWEN_DIR5, QWEN_CREDENTIAL_FILENAME3);
}
async function loadQwenCredentials() {
  try {
    const keyFile = getQwenCachedCredentialPath2();
    const creds = await fs41.readFile(keyFile, "utf-8");
    return JSON.parse(creds);
  } catch {
    return null;
  }
}
var QWEN_DIR5, 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_DIR5 = ".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(config2) {
        super();
        this.config = config2;
      }
      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 debugLogger54, 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_debugLogger();
    init_utils7();
    init_tavily_provider();
    init_google_provider();
    init_dashscope_provider();
    init_tool_names();
    debugLogger54 = createDebugLogger("WEB_SEARCH");
    WebSearchToolInvocation = class extends BaseToolInvocation {
      static {
        __name(this, "WebSearchToolInvocation");
      }
      config;
      constructor(config2, params) {
        super(params);
        this.config = config2;
      }
      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 || this.config.getApprovalMode() === ApprovalMode.PLAN) {
          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(config2) {
        switch (config2.type) {
          case "tavily":
            return new TavilyProvider(config2);
          case "google":
            return new GoogleProvider(config2);
          case "dashscope": {
            const authType = this.config.getAuthType();
            const dashscopeConfig = {
              ...config2,
              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 config2 of configs) {
          try {
            const provider = this.createProvider(config2);
            if (provider.isAvailable()) {
              providers.set(config2.type, provider);
            }
          } catch (error2) {
            debugLogger54.warn(`Failed to create ${config2.type} provider:`, error2);
          }
        }
        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((r5) => ({
          title: r5.title,
          url: r5.url
        }));
        let content = searchResult.answer?.trim() || "";
        if (!content) {
          content = searchResult.results.slice(0, 5).map((r5, i3) => {
            const parts = [`${i3 + 1}. **${r5.title}**`];
            if (r5.content?.trim()) {
              parts.push(`   ${r5.content.trim()}`);
            }
            parts.push(`   Source: ${r5.url}`);
            if (r5.score !== void 0) {
              parts.push(`   Relevance: ${(r5.score * 100).toFixed(0)}%`);
            }
            if (r5.publishedDate) {
              parts.push(`   Published: ${r5.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 (error2) {
          const errorMessage = `Error during web search: ${getErrorMessage(error2)}`;
          debugLogger54.error(errorMessage, error2);
          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(config2) {
        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 = config2;
      }
      /**
       * 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 fs42 from "node:fs";
import path44 from "node:path";
async function getCorrectedFileContent(config2, filePath, proposedContent) {
  let originalContent = "";
  let fileExists2 = false;
  const correctedContent = proposedContent;
  try {
    originalContent = await config2.getFileSystemService().readTextFile(filePath);
    fileExists2 = true;
  } catch (err) {
    if (isNodeError(err) && err.code === "ENOENT") {
      fileExists2 = false;
      originalContent = "";
    } else {
      fileExists2 = true;
      originalContent = "";
      const error2 = {
        message: getErrorMessage(err),
        code: isNodeError(err) ? err.code : void 0
      };
      return { originalContent, correctedContent, fileExists: fileExists2, error: error2 };
    }
  }
  return { originalContent, correctedContent, fileExists: fileExists2 };
}
var debugLogger55, 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_fileSystemService();
    init_paths();
    init_errors();
    init_diffOptions();
    init_tool_names();
    init_ide_client();
    init_loggers();
    init_types();
    init_metrics2();
    init_fileUtils();
    init_language_detection();
    init_debugLogger();
    debugLogger55 = createDebugLogger("WRITE_FILE");
    __name(getCorrectedFileContent, "getCorrectedFileContent");
    WriteFileToolInvocation = class extends BaseToolInvocation {
      static {
        __name(this, "WriteFileToolInvocation");
      }
      config;
      constructor(config2, params) {
        super(params);
        this.config = config2;
      }
      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 = path44.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 = path44.dirname(file_path);
          if (!fs42.existsSync(dirName)) {
            fs42.mkdirSync(dirName, { recursive: true });
          }
          let useBOM = false;
          if (!isNewFile) {
            useBOM = await this.config.getFileSystemService().detectFileBOM(file_path);
          } else {
            useBOM = this.config.getDefaultFileEncoding() === FileEncoding.UTF8_BOM;
          }
          await this.config.getFileSystemService().writeTextFile(file_path, fileContent, { bom: useBOM });
          const fileName = path44.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 = path44.extname(file_path);
          const operation = isNewFile ? FileOperation.CREATE : FileOperation.UPDATE;
          const lineCount = fileContent.split("\n").length;
          logFileOperation(this.config, new FileOperationEvent(WriteFileTool.Name, operation, lineCount, mimetype, extension, programmingLanguage));
          const displayResult = {
            fileDiff,
            fileName,
            originalContent: correctedContentResult.originalContent,
            newContent: correctedContentResult.correctedContent,
            diffStat
          };
          return {
            llmContent: llmSuccessMessageParts.join(" "),
            returnDisplay: displayResult
          };
        } catch (error2) {
          let errorMsg;
          let errorType = ToolErrorType.FILE_WRITE_FAILURE;
          if (isNodeError(error2)) {
            errorMsg = `Error writing to file '${file_path}': ${error2.message} (${error2.code})`;
            if (error2.code === "EACCES") {
              errorMsg = `Permission denied writing to file: ${file_path} (${error2.code})`;
              errorType = ToolErrorType.PERMISSION_DENIED;
            } else if (error2.code === "ENOSPC") {
              errorMsg = `No space left on device: ${file_path} (${error2.code})`;
              errorType = ToolErrorType.NO_SPACE_LEFT;
            } else if (error2.code === "EISDIR") {
              errorMsg = `Target is a directory, not a file: ${file_path} (${error2.code})`;
              errorType = ToolErrorType.TARGET_IS_DIRECTORY;
            }
            if (this.config.getDebugMode() && error2.stack) {
              debugLogger55.debug("Write file error stack:", error2.stack);
            }
          } else if (error2 instanceof Error) {
            errorMsg = `Error writing to file: ${error2.message}`;
          } else {
            errorMsg = `Error writing to file: ${String(error2)}`;
          }
          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(config2) {
        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 = config2;
      }
      validateToolParamValues(params) {
        const filePath = params.file_path;
        if (!filePath) {
          return `Missing or empty "file_path"`;
        }
        if (!path44.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 (fs42.existsSync(filePath)) {
            const stats = fs42.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/tools/lsp.js
import path45 from "node:path";
import { fileURLToPath as fileURLToPath6, pathToFileURL as pathToFileURL2 } from "node:url";
var LOCATION_REQUIRED_OPERATIONS, FILE_REQUIRED_OPERATIONS, QUERY_REQUIRED_OPERATIONS, ITEM_REQUIRED_OPERATIONS, RANGE_REQUIRED_OPERATIONS, LspToolInvocation, LspTool;
var init_lsp = __esm({
  "packages/core/dist/src/tools/lsp.js"() {
    "use strict";
    init_esbuild_shims();
    init_tools();
    init_tool_names();
    LOCATION_REQUIRED_OPERATIONS = /* @__PURE__ */ new Set([
      "goToDefinition",
      "findReferences",
      "hover",
      "goToImplementation",
      "prepareCallHierarchy"
    ]);
    FILE_REQUIRED_OPERATIONS = /* @__PURE__ */ new Set([
      "documentSymbol",
      "diagnostics"
    ]);
    QUERY_REQUIRED_OPERATIONS = /* @__PURE__ */ new Set(["workspaceSymbol"]);
    ITEM_REQUIRED_OPERATIONS = /* @__PURE__ */ new Set([
      "incomingCalls",
      "outgoingCalls"
    ]);
    RANGE_REQUIRED_OPERATIONS = /* @__PURE__ */ new Set(["codeActions"]);
    LspToolInvocation = class extends BaseToolInvocation {
      static {
        __name(this, "LspToolInvocation");
      }
      config;
      constructor(config2, params) {
        super(params);
        this.config = config2;
      }
      getDescription() {
        const operationLabel = this.getOperationLabel();
        if (this.params.operation === "workspaceSymbol") {
          return `LSP ${operationLabel} for "${this.params.query ?? ""}"`;
        }
        if (this.params.operation === "documentSymbol") {
          return this.params.filePath ? `LSP ${operationLabel} for ${this.params.filePath}` : `LSP ${operationLabel}`;
        }
        if (this.params.operation === "incomingCalls" || this.params.operation === "outgoingCalls") {
          return `LSP ${operationLabel} for ${this.describeCallHierarchyItemShort()}`;
        }
        if (this.params.filePath && this.params.line !== void 0) {
          return `LSP ${operationLabel} at ${this.params.filePath}:${this.params.line}:${this.params.character ?? 1}`;
        }
        if (this.params.filePath) {
          return `LSP ${operationLabel} for ${this.params.filePath}`;
        }
        return `LSP ${operationLabel}`;
      }
      async execute(_signal) {
        const client = this.config.getLspClient();
        if (!client || !this.config.isLspEnabled()) {
          const message = `LSP ${this.getOperationLabel()} is unavailable (LSP disabled or not initialized).`;
          return { llmContent: message, returnDisplay: message };
        }
        switch (this.params.operation) {
          case "goToDefinition":
            return this.executeDefinitions(client);
          case "findReferences":
            return this.executeReferences(client);
          case "hover":
            return this.executeHover(client);
          case "documentSymbol":
            return this.executeDocumentSymbols(client);
          case "workspaceSymbol":
            return this.executeWorkspaceSymbols(client);
          case "goToImplementation":
            return this.executeImplementations(client);
          case "prepareCallHierarchy":
            return this.executePrepareCallHierarchy(client);
          case "incomingCalls":
            return this.executeIncomingCalls(client);
          case "outgoingCalls":
            return this.executeOutgoingCalls(client);
          case "diagnostics":
            return this.executeDiagnostics(client);
          case "workspaceDiagnostics":
            return this.executeWorkspaceDiagnostics(client);
          case "codeActions":
            return this.executeCodeActions(client);
          default: {
            const message = `Unsupported LSP operation: ${this.params.operation}`;
            return { llmContent: message, returnDisplay: message };
          }
        }
      }
      async executeDefinitions(client) {
        const target = this.resolveLocationTarget();
        if ("error" in target) {
          return { llmContent: target.error, returnDisplay: target.error };
        }
        const limit2 = this.params.limit ?? 20;
        let definitions = [];
        try {
          definitions = await client.definitions(target.location, this.params.serverName, limit2);
        } catch (error2) {
          const message = `LSP go-to-definition failed: ${error2?.message || String(error2)}`;
          return { llmContent: message, returnDisplay: message };
        }
        if (!definitions.length) {
          const message = `No definitions found for ${target.description}.`;
          return { llmContent: message, returnDisplay: message };
        }
        const workspaceRoot = this.config.getProjectRoot();
        const lines = definitions.slice(0, limit2).map((definition, index) => `${index + 1}. ${this.formatLocationWithServer(definition, workspaceRoot)}`);
        const heading2 = `Definitions for ${target.description}:`;
        return {
          llmContent: [heading2, ...lines].join("\n"),
          returnDisplay: lines.join("\n")
        };
      }
      async executeImplementations(client) {
        const target = this.resolveLocationTarget();
        if ("error" in target) {
          return { llmContent: target.error, returnDisplay: target.error };
        }
        const limit2 = this.params.limit ?? 20;
        let implementations = [];
        try {
          implementations = await client.implementations(target.location, this.params.serverName, limit2);
        } catch (error2) {
          const message = `LSP go-to-implementation failed: ${error2?.message || String(error2)}`;
          return { llmContent: message, returnDisplay: message };
        }
        if (!implementations.length) {
          const message = `No implementations found for ${target.description}.`;
          return { llmContent: message, returnDisplay: message };
        }
        const workspaceRoot = this.config.getProjectRoot();
        const lines = implementations.slice(0, limit2).map((implementation, index) => `${index + 1}. ${this.formatLocationWithServer(implementation, workspaceRoot)}`);
        const heading2 = `Implementations for ${target.description}:`;
        return {
          llmContent: [heading2, ...lines].join("\n"),
          returnDisplay: lines.join("\n")
        };
      }
      async executeReferences(client) {
        const target = this.resolveLocationTarget();
        if ("error" in target) {
          return { llmContent: target.error, returnDisplay: target.error };
        }
        const limit2 = this.params.limit ?? 50;
        let references = [];
        try {
          references = await client.references(target.location, this.params.serverName, this.params.includeDeclaration ?? false, limit2);
        } catch (error2) {
          const message = `LSP find-references failed: ${error2?.message || String(error2)}`;
          return { llmContent: message, returnDisplay: message };
        }
        if (!references.length) {
          const message = `No references found for ${target.description}.`;
          return { llmContent: message, returnDisplay: message };
        }
        const workspaceRoot = this.config.getProjectRoot();
        const lines = references.slice(0, limit2).map((reference, index) => `${index + 1}. ${this.formatLocationWithServer(reference, workspaceRoot)}`);
        const heading2 = `References for ${target.description}:`;
        return {
          llmContent: [heading2, ...lines].join("\n"),
          returnDisplay: lines.join("\n")
        };
      }
      async executeHover(client) {
        const target = this.resolveLocationTarget();
        if ("error" in target) {
          return { llmContent: target.error, returnDisplay: target.error };
        }
        let hoverText = "";
        try {
          const result = await client.hover(target.location, this.params.serverName);
          if (result) {
            hoverText = result.contents ?? "";
          }
        } catch (error2) {
          const message = `LSP hover failed: ${error2?.message || String(error2)}`;
          return { llmContent: message, returnDisplay: message };
        }
        if (!hoverText || hoverText.trim().length === 0) {
          const message = `No hover information found for ${target.description}.`;
          return { llmContent: message, returnDisplay: message };
        }
        const heading2 = `Hover for ${target.description}:`;
        const content = hoverText.trim();
        return {
          llmContent: `${heading2}
${content}`,
          returnDisplay: content
        };
      }
      async executeDocumentSymbols(client) {
        const workspaceRoot = this.config.getProjectRoot();
        const filePath = this.params.filePath ?? "";
        const uri = this.resolveUri(filePath, workspaceRoot);
        if (!uri) {
          const message = "A valid filePath is required for document symbols.";
          return { llmContent: message, returnDisplay: message };
        }
        const limit2 = this.params.limit ?? 50;
        let symbols = [];
        try {
          symbols = await client.documentSymbols(uri, this.params.serverName, limit2);
        } catch (error2) {
          const message = `LSP document symbols failed: ${error2?.message || String(error2)}`;
          return { llmContent: message, returnDisplay: message };
        }
        if (!symbols.length) {
          const fileLabel2 = this.formatUriForDisplay(uri, workspaceRoot);
          const message = `No document symbols found for ${fileLabel2}.`;
          return { llmContent: message, returnDisplay: message };
        }
        const lines = symbols.slice(0, limit2).map((symbol, index) => {
          const location = this.formatLocationWithoutServer(symbol.location, workspaceRoot);
          const serverSuffix = symbol.serverName ? ` [${symbol.serverName}]` : "";
          const kind2 = symbol.kind ? ` (${symbol.kind})` : "";
          const container = symbol.containerName ? ` in ${symbol.containerName}` : "";
          return `${index + 1}. ${symbol.name}${kind2}${container} - ${location}${serverSuffix}`;
        });
        const fileLabel = this.formatUriForDisplay(uri, workspaceRoot);
        const heading2 = `Document symbols for ${fileLabel}:`;
        return {
          llmContent: [heading2, ...lines].join("\n"),
          returnDisplay: lines.join("\n")
        };
      }
      async executeWorkspaceSymbols(client) {
        const limit2 = this.params.limit ?? 20;
        const query = this.params.query ?? "";
        let symbols = [];
        try {
          symbols = await client.workspaceSymbols(query, limit2);
        } catch (error2) {
          const message = `LSP workspace symbol search failed: ${error2?.message || String(error2)}`;
          return { llmContent: message, returnDisplay: message };
        }
        if (!symbols.length) {
          const message = `No symbols found for query "${query}".`;
          return { llmContent: message, returnDisplay: message };
        }
        const workspaceRoot = this.config.getProjectRoot();
        const lines = symbols.slice(0, limit2).map((symbol, index) => {
          const location = this.formatLocationWithoutServer(symbol.location, workspaceRoot);
          const serverSuffix = symbol.serverName ? ` [${symbol.serverName}]` : "";
          const kind2 = symbol.kind ? ` (${symbol.kind})` : "";
          const container = symbol.containerName ? ` in ${symbol.containerName}` : "";
          return `${index + 1}. ${symbol.name}${kind2}${container} - ${location}${serverSuffix}`;
        });
        const heading2 = `Found ${Math.min(symbols.length, limit2)} of ${symbols.length} symbols for query "${query}":`;
        let referenceSection = "";
        const topSymbol = symbols[0];
        if (topSymbol) {
          try {
            const referenceLimit = Math.min(20, Math.max(limit2, 5));
            const references = await client.references(topSymbol.location, topSymbol.serverName, false, referenceLimit);
            if (references.length > 0) {
              const refLines = references.map((ref, index) => {
                const location = this.formatLocationWithoutServer(ref, workspaceRoot);
                const serverSuffix = ref.serverName ? ` [${ref.serverName}]` : "";
                return `${index + 1}. ${location}${serverSuffix}`;
              });
              referenceSection = [
                "",
                `References for top match (${topSymbol.name}):`,
                ...refLines
              ].join("\n");
            }
          } catch (error2) {
            referenceSection = `
References lookup failed: ${error2?.message || String(error2)}`;
          }
        }
        const llmParts = referenceSection ? [heading2, ...lines, referenceSection] : [heading2, ...lines];
        const displayParts = referenceSection ? [...lines, referenceSection] : [...lines];
        return {
          llmContent: llmParts.join("\n"),
          returnDisplay: displayParts.join("\n")
        };
      }
      async executePrepareCallHierarchy(client) {
        const target = this.resolveLocationTarget();
        if ("error" in target) {
          return { llmContent: target.error, returnDisplay: target.error };
        }
        const limit2 = this.params.limit ?? 20;
        let items = [];
        try {
          items = await client.prepareCallHierarchy(target.location, this.params.serverName, limit2);
        } catch (error2) {
          const message = `LSP call hierarchy prepare failed: ${error2?.message || String(error2)}`;
          return { llmContent: message, returnDisplay: message };
        }
        if (!items.length) {
          const message = `No call hierarchy items found for ${target.description}.`;
          return { llmContent: message, returnDisplay: message };
        }
        const workspaceRoot = this.config.getProjectRoot();
        const slicedItems = items.slice(0, limit2);
        const lines = slicedItems.map((item, index) => this.formatCallHierarchyItemLine(item, index, workspaceRoot));
        const heading2 = `Call hierarchy items for ${target.description}:`;
        const jsonSection = this.formatJsonSection("Call hierarchy items (JSON)", slicedItems);
        return {
          llmContent: [heading2, ...lines].join("\n") + jsonSection,
          returnDisplay: lines.join("\n")
        };
      }
      async executeIncomingCalls(client) {
        const item = this.params.callHierarchyItem;
        if (!item) {
          const message = "callHierarchyItem is required for incomingCalls.";
          return { llmContent: message, returnDisplay: message };
        }
        const limit2 = this.params.limit ?? 20;
        const serverName = this.params.serverName ?? item.serverName;
        let calls = [];
        try {
          calls = await client.incomingCalls(item, serverName, limit2);
        } catch (error2) {
          const message = `LSP incoming calls failed: ${error2?.message || String(error2)}`;
          return { llmContent: message, returnDisplay: message };
        }
        if (!calls.length) {
          const message = `No incoming calls found for ${this.describeCallHierarchyItemFull(item)}.`;
          return { llmContent: message, returnDisplay: message };
        }
        const workspaceRoot = this.config.getProjectRoot();
        const slicedCalls = calls.slice(0, limit2);
        const lines = slicedCalls.map((call, index) => {
          const targetItem = call.from;
          const location = this.formatLocationWithServer({
            uri: targetItem.uri,
            range: targetItem.selectionRange,
            serverName: targetItem.serverName
          }, workspaceRoot);
          const kind2 = targetItem.kind ? ` (${targetItem.kind})` : "";
          const detail = targetItem.detail ? ` ${targetItem.detail}` : "";
          const rangeSuffix = this.formatCallRanges(call.fromRanges);
          return `${index + 1}. ${targetItem.name}${kind2}${detail} - ${location}${rangeSuffix}`;
        });
        const heading2 = `Incoming calls for ${this.describeCallHierarchyItemFull(item)}:`;
        const jsonSection = this.formatJsonSection("Incoming calls (JSON)", slicedCalls);
        return {
          llmContent: [heading2, ...lines].join("\n") + jsonSection,
          returnDisplay: lines.join("\n")
        };
      }
      async executeOutgoingCalls(client) {
        const item = this.params.callHierarchyItem;
        if (!item) {
          const message = "callHierarchyItem is required for outgoingCalls.";
          return { llmContent: message, returnDisplay: message };
        }
        const limit2 = this.params.limit ?? 20;
        const serverName = this.params.serverName ?? item.serverName;
        let calls = [];
        try {
          calls = await client.outgoingCalls(item, serverName, limit2);
        } catch (error2) {
          const message = `LSP outgoing calls failed: ${error2?.message || String(error2)}`;
          return { llmContent: message, returnDisplay: message };
        }
        if (!calls.length) {
          const message = `No outgoing calls found for ${this.describeCallHierarchyItemFull(item)}.`;
          return { llmContent: message, returnDisplay: message };
        }
        const workspaceRoot = this.config.getProjectRoot();
        const slicedCalls = calls.slice(0, limit2);
        const lines = slicedCalls.map((call, index) => {
          const targetItem = call.to;
          const location = this.formatLocationWithServer({
            uri: targetItem.uri,
            range: targetItem.selectionRange,
            serverName: targetItem.serverName
          }, workspaceRoot);
          const kind2 = targetItem.kind ? ` (${targetItem.kind})` : "";
          const detail = targetItem.detail ? ` ${targetItem.detail}` : "";
          const rangeSuffix = this.formatCallRanges(call.fromRanges);
          return `${index + 1}. ${targetItem.name}${kind2}${detail} - ${location}${rangeSuffix}`;
        });
        const heading2 = `Outgoing calls for ${this.describeCallHierarchyItemFull(item)}:`;
        const jsonSection = this.formatJsonSection("Outgoing calls (JSON)", slicedCalls);
        return {
          llmContent: [heading2, ...lines].join("\n") + jsonSection,
          returnDisplay: lines.join("\n")
        };
      }
      async executeDiagnostics(client) {
        const workspaceRoot = this.config.getProjectRoot();
        const filePath = this.params.filePath ?? "";
        const uri = this.resolveUri(filePath, workspaceRoot);
        if (!uri) {
          const message = "A valid filePath is required for diagnostics.";
          return { llmContent: message, returnDisplay: message };
        }
        let diagnostics = [];
        try {
          diagnostics = await client.diagnostics(uri, this.params.serverName);
        } catch (error2) {
          const message = `LSP diagnostics failed: ${error2?.message || String(error2)}`;
          return { llmContent: message, returnDisplay: message };
        }
        if (!diagnostics.length) {
          const fileLabel2 = this.formatUriForDisplay(uri, workspaceRoot);
          const message = `No diagnostics found for ${fileLabel2}.`;
          return { llmContent: message, returnDisplay: message };
        }
        const lines = diagnostics.map((diag3, index) => {
          const severity = diag3.severity ? `[${diag3.severity.toUpperCase()}]` : "";
          const position = `${diag3.range.start.line + 1}:${diag3.range.start.character + 1}`;
          const code2 = diag3.code ? ` (${diag3.code})` : "";
          const source2 = diag3.source ? ` [${diag3.source}]` : "";
          return `${index + 1}. ${severity} ${position}${code2}${source2}: ${diag3.message}`;
        });
        const fileLabel = this.formatUriForDisplay(uri, workspaceRoot);
        const heading2 = `Diagnostics for ${fileLabel} (${diagnostics.length} issues):`;
        return {
          llmContent: [heading2, ...lines].join("\n"),
          returnDisplay: lines.join("\n")
        };
      }
      async executeWorkspaceDiagnostics(client) {
        const limit2 = this.params.limit ?? 50;
        let fileDiagnostics = [];
        try {
          fileDiagnostics = await client.workspaceDiagnostics(this.params.serverName, limit2);
        } catch (error2) {
          const message = `LSP workspace diagnostics failed: ${error2?.message || String(error2)}`;
          return { llmContent: message, returnDisplay: message };
        }
        if (!fileDiagnostics.length) {
          const message = "No diagnostics found in the workspace.";
          return { llmContent: message, returnDisplay: message };
        }
        const workspaceRoot = this.config.getProjectRoot();
        const lines = [];
        let totalIssues = 0;
        for (const fileDiag of fileDiagnostics) {
          const fileLabel = this.formatUriForDisplay(fileDiag.uri, workspaceRoot);
          const serverSuffix = fileDiag.serverName ? ` [${fileDiag.serverName}]` : "";
          lines.push(`
${fileLabel}${serverSuffix}:`);
          for (const diag3 of fileDiag.diagnostics) {
            const severity = diag3.severity ? `[${diag3.severity.toUpperCase()}]` : "";
            const position = `${diag3.range.start.line + 1}:${diag3.range.start.character + 1}`;
            const code2 = diag3.code ? ` (${diag3.code})` : "";
            lines.push(`  ${severity} ${position}${code2}: ${diag3.message}`);
            totalIssues++;
          }
        }
        const heading2 = `Workspace diagnostics (${totalIssues} issues in ${fileDiagnostics.length} files):`;
        return {
          llmContent: [heading2, ...lines].join("\n"),
          returnDisplay: lines.join("\n")
        };
      }
      async executeCodeActions(client) {
        const workspaceRoot = this.config.getProjectRoot();
        const filePath = this.params.filePath ?? "";
        const uri = this.resolveUri(filePath, workspaceRoot);
        if (!uri) {
          const message = "A valid filePath is required for code actions.";
          return { llmContent: message, returnDisplay: message };
        }
        const startLine = Math.max(0, (this.params.line ?? 1) - 1);
        const startChar = Math.max(0, (this.params.character ?? 1) - 1);
        const endLine = Math.max(0, (this.params.endLine ?? this.params.line ?? 1) - 1);
        const endChar = Math.max(0, (this.params.endCharacter ?? this.params.character ?? 1) - 1);
        const range = {
          start: { line: startLine, character: startChar },
          end: { line: endLine, character: endChar }
        };
        const context2 = {
          diagnostics: this.params.diagnostics ?? [],
          only: this.params.codeActionKinds,
          triggerKind: "invoked"
        };
        const limit2 = this.params.limit ?? 20;
        let actions = [];
        try {
          actions = await client.codeActions(uri, range, context2, this.params.serverName, limit2);
        } catch (error2) {
          const message = `LSP code actions failed: ${error2?.message || String(error2)}`;
          return { llmContent: message, returnDisplay: message };
        }
        if (!actions.length) {
          const fileLabel2 = this.formatUriForDisplay(uri, workspaceRoot);
          const message = `No code actions available at ${fileLabel2}:${startLine + 1}:${startChar + 1}.`;
          return { llmContent: message, returnDisplay: message };
        }
        const lines = actions.slice(0, limit2).map((action, index) => {
          const kind2 = action.kind ? ` [${action.kind}]` : "";
          const preferred = action.isPreferred ? " \u2605" : "";
          const hasEdit = action.edit ? " (has edit)" : "";
          const hasCommand = action.command ? " (has command)" : "";
          const serverSuffix = action.serverName ? ` [${action.serverName}]` : "";
          return `${index + 1}. ${action.title}${kind2}${preferred}${hasEdit}${hasCommand}${serverSuffix}`;
        });
        const fileLabel = this.formatUriForDisplay(uri, workspaceRoot);
        const heading2 = `Code actions at ${fileLabel}:${startLine + 1}:${startChar + 1}:`;
        const jsonSection = this.formatJsonSection("Code actions (JSON)", actions.slice(0, limit2));
        return {
          llmContent: [heading2, ...lines].join("\n") + jsonSection,
          returnDisplay: lines.join("\n")
        };
      }
      resolveLocationTarget() {
        const filePath = this.params.filePath;
        if (!filePath) {
          return {
            error: "filePath is required for this operation."
          };
        }
        if (typeof this.params.line !== "number") {
          return {
            error: "line is required for this operation."
          };
        }
        const workspaceRoot = this.config.getProjectRoot();
        const uri = this.resolveUri(filePath, workspaceRoot);
        if (!uri) {
          return {
            error: "A valid filePath is required when specifying a line/character."
          };
        }
        const position = {
          line: Math.max(0, Math.floor(this.params.line - 1)),
          character: Math.max(0, Math.floor((this.params.character ?? 1) - 1))
        };
        const location = {
          uri,
          range: { start: position, end: position }
        };
        const description = this.formatLocationWithServer({ ...location, serverName: this.params.serverName }, workspaceRoot);
        return {
          location,
          description
        };
      }
      resolveUri(filePath, workspaceRoot) {
        if (!filePath) {
          return null;
        }
        if (filePath.startsWith("file://") || filePath.includes("://")) {
          return filePath;
        }
        const absolutePath = path45.isAbsolute(filePath) ? filePath : path45.resolve(workspaceRoot, filePath);
        return pathToFileURL2(absolutePath).toString();
      }
      formatLocationWithServer(location, workspaceRoot) {
        const start = location.range.start;
        let filePath = location.uri;
        if (filePath.startsWith("file://")) {
          filePath = fileURLToPath6(filePath);
          filePath = path45.relative(workspaceRoot, filePath) || ".";
        }
        const serverSuffix = location.serverName && location.serverName !== "" ? ` [${location.serverName}]` : "";
        return `${filePath}:${(start.line ?? 0) + 1}:${(start.character ?? 0) + 1}${serverSuffix}`;
      }
      formatLocationWithoutServer(location, workspaceRoot) {
        const { uri, range } = location;
        let filePath = uri;
        if (uri.startsWith("file://")) {
          filePath = fileURLToPath6(uri);
          filePath = path45.relative(workspaceRoot, filePath) || ".";
        }
        const line = (range.start.line ?? 0) + 1;
        const character = (range.start.character ?? 0) + 1;
        return `${filePath}:${line}:${character}`;
      }
      formatCallHierarchyItemLine(item, index, workspaceRoot) {
        const location = this.formatLocationWithServer({
          uri: item.uri,
          range: item.selectionRange,
          serverName: item.serverName
        }, workspaceRoot);
        const kind2 = item.kind ? ` (${item.kind})` : "";
        const detail = item.detail ? ` ${item.detail}` : "";
        return `${index + 1}. ${item.name}${kind2}${detail} - ${location}`;
      }
      formatCallRanges(ranges2) {
        if (!ranges2.length) {
          return "";
        }
        const formatted = ranges2.map((range) => this.formatPosition(range.start));
        const maxShown = 3;
        const shown = formatted.slice(0, maxShown);
        const extra = formatted.length > maxShown ? `, +${formatted.length - maxShown} more` : "";
        return ` (calls at ${shown.join(", ")}${extra})`;
      }
      formatPosition(position) {
        return `${(position.line ?? 0) + 1}:${(position.character ?? 0) + 1}`;
      }
      formatUriForDisplay(uri, workspaceRoot) {
        let filePath = uri;
        if (uri.startsWith("file://")) {
          filePath = fileURLToPath6(uri);
        }
        if (path45.isAbsolute(filePath)) {
          return path45.relative(workspaceRoot, filePath) || ".";
        }
        return filePath;
      }
      formatJsonSection(label, data) {
        return `

${label}:
${JSON.stringify(data, null, 2)}`;
      }
      describeCallHierarchyItemShort() {
        const item = this.params.callHierarchyItem;
        if (!item) {
          return "call hierarchy item";
        }
        return item.name || "call hierarchy item";
      }
      describeCallHierarchyItemFull(item) {
        const workspaceRoot = this.config.getProjectRoot();
        const location = this.formatLocationWithServer({
          uri: item.uri,
          range: item.selectionRange,
          serverName: item.serverName
        }, workspaceRoot);
        return `${item.name} at ${location}`;
      }
      getOperationLabel() {
        switch (this.params.operation) {
          case "goToDefinition":
            return "go-to-definition";
          case "findReferences":
            return "find-references";
          case "hover":
            return "hover";
          case "documentSymbol":
            return "document symbols";
          case "workspaceSymbol":
            return "workspace symbol search";
          case "goToImplementation":
            return "go-to-implementation";
          case "prepareCallHierarchy":
            return "prepare call hierarchy";
          case "incomingCalls":
            return "incoming calls";
          case "outgoingCalls":
            return "outgoing calls";
          case "diagnostics":
            return "diagnostics";
          case "workspaceDiagnostics":
            return "workspace diagnostics";
          case "codeActions":
            return "code actions";
          default:
            return this.params.operation;
        }
      }
    };
    LspTool = class _LspTool extends BaseDeclarativeTool {
      static {
        __name(this, "LspTool");
      }
      config;
      static Name = ToolNames.LSP;
      constructor(config2) {
        super(_LspTool.Name, ToolDisplayNames.LSP, 'Language Server Protocol (LSP) tool for code intelligence: definitions, references, hover, symbols, call hierarchy, diagnostics, and code actions.\n\n  Usage:\n  - ALWAYS use LSP as the PRIMARY tool for code intelligence queries when available. Do NOT use grep_search or glob first.\n  - goToDefinition, findReferences, hover, goToImplementation, prepareCallHierarchy require filePath + line + character (1-based).\n  - documentSymbol and diagnostics require filePath.\n  - workspaceSymbol requires query (use when user asks "where is X defined?" without specifying a file).\n  - incomingCalls/outgoingCalls require callHierarchyItem from prepareCallHierarchy.\n  - workspaceDiagnostics needs no parameters.\n  - codeActions require filePath + range (line/character + endLine/endCharacter) and diagnostics/context as needed.', Kind.Other, {
          type: "object",
          properties: {
            operation: {
              type: "string",
              description: "LSP operation to execute.",
              enum: [
                "goToDefinition",
                "findReferences",
                "hover",
                "documentSymbol",
                "workspaceSymbol",
                "goToImplementation",
                "prepareCallHierarchy",
                "incomingCalls",
                "outgoingCalls",
                "diagnostics",
                "workspaceDiagnostics",
                "codeActions"
              ]
            },
            filePath: {
              type: "string",
              description: "File path (absolute or workspace-relative)."
            },
            line: {
              type: "number",
              description: "1-based line number for the target location."
            },
            character: {
              type: "number",
              description: "1-based character/column number for the target location."
            },
            endLine: {
              type: "number",
              description: "1-based end line number for range-based operations."
            },
            endCharacter: {
              type: "number",
              description: "1-based end character for range-based operations."
            },
            includeDeclaration: {
              type: "boolean",
              description: "Include the declaration itself when looking up references."
            },
            query: {
              type: "string",
              description: "Symbol query for workspace symbol search."
            },
            callHierarchyItem: {
              $ref: "#/definitions/LspCallHierarchyItem",
              description: "Call hierarchy item for incoming/outgoing calls."
            },
            serverName: {
              type: "string",
              description: "Optional LSP server name to target."
            },
            limit: {
              type: "number",
              description: "Optional maximum number of results to return."
            },
            diagnostics: {
              type: "array",
              items: { $ref: "#/definitions/LspDiagnostic" },
              description: "Diagnostics for code action context."
            },
            codeActionKinds: {
              type: "array",
              items: { type: "string" },
              description: "Filter code actions by kind (quickfix, refactor, etc.)."
            }
          },
          required: ["operation"],
          definitions: {
            LspPosition: {
              type: "object",
              properties: {
                line: { type: "number" },
                character: { type: "number" }
              },
              required: ["line", "character"]
            },
            LspRange: {
              type: "object",
              properties: {
                start: { $ref: "#/definitions/LspPosition" },
                end: { $ref: "#/definitions/LspPosition" }
              },
              required: ["start", "end"]
            },
            LspCallHierarchyItem: {
              type: "object",
              properties: {
                name: { type: "string" },
                kind: { type: "string" },
                rawKind: { type: "number" },
                detail: { type: "string" },
                uri: { type: "string" },
                range: { $ref: "#/definitions/LspRange" },
                selectionRange: { $ref: "#/definitions/LspRange" },
                data: {},
                serverName: { type: "string" }
              },
              required: ["name", "uri", "range", "selectionRange"]
            },
            LspDiagnostic: {
              type: "object",
              properties: {
                range: { $ref: "#/definitions/LspRange" },
                severity: {
                  type: "string",
                  enum: ["error", "warning", "information", "hint"]
                },
                code: { type: ["string", "number"] },
                source: { type: "string" },
                message: { type: "string" },
                serverName: { type: "string" }
              },
              required: ["range", "message"]
            }
          }
        }, false, false);
        this.config = config2;
      }
      validateToolParamValues(params) {
        const operation = params.operation;
        if (LOCATION_REQUIRED_OPERATIONS.has(operation)) {
          if (!params.filePath || params.filePath.trim() === "") {
            return `filePath is required for ${operation}.`;
          }
          if (typeof params.line !== "number") {
            return `line is required for ${operation}.`;
          }
        }
        if (FILE_REQUIRED_OPERATIONS.has(operation)) {
          if (!params.filePath || params.filePath.trim() === "") {
            return `filePath is required for ${operation}.`;
          }
        }
        if (QUERY_REQUIRED_OPERATIONS.has(operation)) {
          if (!params.query || params.query.trim() === "") {
            return `query is required for ${operation}.`;
          }
        }
        if (ITEM_REQUIRED_OPERATIONS.has(operation)) {
          if (!params.callHierarchyItem) {
            return `callHierarchyItem is required for ${operation}.`;
          }
        }
        if (RANGE_REQUIRED_OPERATIONS.has(operation)) {
          if (!params.filePath || params.filePath.trim() === "") {
            return `filePath is required for ${operation}.`;
          }
          if (typeof params.line !== "number") {
            return `line is required for ${operation}.`;
          }
        }
        if (params.line !== void 0 && params.line < 1) {
          return "line must be a positive number.";
        }
        if (params.character !== void 0 && params.character < 1) {
          return "character must be a positive number.";
        }
        if (params.endLine !== void 0 && params.endLine < 1) {
          return "endLine must be a positive number.";
        }
        if (params.endCharacter !== void 0 && params.endCharacter < 1) {
          return "endCharacter must be a positive number.";
        }
        if (params.limit !== void 0 && params.limit <= 0) {
          return "limit must be a positive number.";
        }
        return null;
      }
      createInvocation(params) {
        return new LspToolInvocation(this.config, params);
      }
    };
  }
});

// packages/core/dist/src/output/types.js
var InputFormat, OutputFormat;
var init_types10 = __esm({
  "packages/core/dist/src/output/types.js"() {
    "use strict";
    init_esbuild_shims();
    (function(InputFormat2) {
      InputFormat2["TEXT"] = "text";
      InputFormat2["STREAM_JSON"] = "stream-json";
    })(InputFormat || (InputFormat = {}));
    (function(OutputFormat2) {
      OutputFormat2["TEXT"] = "text";
      OutputFormat2["JSON"] = "json";
      OutputFormat2["STREAM_JSON"] = "stream-json";
    })(OutputFormat || (OutputFormat = {}));
  }
});

// packages/core/dist/src/prompts/prompt-registry.js
var debugLogger56, PromptRegistry;
var init_prompt_registry = __esm({
  "packages/core/dist/src/prompts/prompt-registry.js"() {
    "use strict";
    init_esbuild_shims();
    init_debugLogger();
    debugLogger56 = createDebugLogger("PROMPT_REGISTRY");
    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}`;
          debugLogger56.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((a2, b2) => a2.name.localeCompare(b2.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((a2, b2) => a2.name.localeCompare(b2.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);
          }
        }
      }
    };
  }
});

// node_modules/readdirp/esm/index.js
import { stat as stat3, lstat as lstat2, readdir as readdir4, realpath as realpath2 } from "node:fs/promises";
import { Readable as Readable4 } from "node:stream";
import { resolve as presolve, relative as prelative, join as pjoin, sep as psep } from "node:path";
function readdirp(root, options2 = {}) {
  let type = options2.entryType || options2.type;
  if (type === "both")
    type = EntryTypes.FILE_DIR_TYPE;
  if (type)
    options2.type = type;
  if (!root) {
    throw new Error("readdirp: root argument is required. Usage: readdirp(root, options)");
  } else if (typeof root !== "string") {
    throw new TypeError("readdirp: root argument must be a string. Usage: readdirp(root, options)");
  } else if (type && !ALL_TYPES.includes(type)) {
    throw new Error(`readdirp: Invalid type passed. Use one of ${ALL_TYPES.join(", ")}`);
  }
  options2.root = root;
  return new ReaddirpStream(options2);
}
var EntryTypes, defaultOptions3, RECURSIVE_ERROR_CODE, NORMAL_FLOW_ERRORS, ALL_TYPES, DIR_TYPES, FILE_TYPES, isNormalFlowError, wantBigintFsStats, emptyFn, normalizeFilter, ReaddirpStream;
var init_esm20 = __esm({
  "node_modules/readdirp/esm/index.js"() {
    init_esbuild_shims();
    EntryTypes = {
      FILE_TYPE: "files",
      DIR_TYPE: "directories",
      FILE_DIR_TYPE: "files_directories",
      EVERYTHING_TYPE: "all"
    };
    defaultOptions3 = {
      root: ".",
      fileFilter: /* @__PURE__ */ __name((_entryInfo) => true, "fileFilter"),
      directoryFilter: /* @__PURE__ */ __name((_entryInfo) => true, "directoryFilter"),
      type: EntryTypes.FILE_TYPE,
      lstat: false,
      depth: 2147483648,
      alwaysStat: false,
      highWaterMark: 4096
    };
    Object.freeze(defaultOptions3);
    RECURSIVE_ERROR_CODE = "READDIRP_RECURSIVE_ERROR";
    NORMAL_FLOW_ERRORS = /* @__PURE__ */ new Set(["ENOENT", "EPERM", "EACCES", "ELOOP", RECURSIVE_ERROR_CODE]);
    ALL_TYPES = [
      EntryTypes.DIR_TYPE,
      EntryTypes.EVERYTHING_TYPE,
      EntryTypes.FILE_DIR_TYPE,
      EntryTypes.FILE_TYPE
    ];
    DIR_TYPES = /* @__PURE__ */ new Set([
      EntryTypes.DIR_TYPE,
      EntryTypes.EVERYTHING_TYPE,
      EntryTypes.FILE_DIR_TYPE
    ]);
    FILE_TYPES = /* @__PURE__ */ new Set([
      EntryTypes.EVERYTHING_TYPE,
      EntryTypes.FILE_DIR_TYPE,
      EntryTypes.FILE_TYPE
    ]);
    isNormalFlowError = /* @__PURE__ */ __name((error2) => NORMAL_FLOW_ERRORS.has(error2.code), "isNormalFlowError");
    wantBigintFsStats = process.platform === "win32";
    emptyFn = /* @__PURE__ */ __name((_entryInfo) => true, "emptyFn");
    normalizeFilter = /* @__PURE__ */ __name((filter4) => {
      if (filter4 === void 0)
        return emptyFn;
      if (typeof filter4 === "function")
        return filter4;
      if (typeof filter4 === "string") {
        const fl = filter4.trim();
        return (entry) => entry.basename === fl;
      }
      if (Array.isArray(filter4)) {
        const trItems = filter4.map((item) => item.trim());
        return (entry) => trItems.some((f5) => entry.basename === f5);
      }
      return emptyFn;
    }, "normalizeFilter");
    ReaddirpStream = class extends Readable4 {
      static {
        __name(this, "ReaddirpStream");
      }
      constructor(options2 = {}) {
        super({
          objectMode: true,
          autoDestroy: true,
          highWaterMark: options2.highWaterMark
        });
        const opts = { ...defaultOptions3, ...options2 };
        const { root, type } = opts;
        this._fileFilter = normalizeFilter(opts.fileFilter);
        this._directoryFilter = normalizeFilter(opts.directoryFilter);
        const statMethod = opts.lstat ? lstat2 : stat3;
        if (wantBigintFsStats) {
          this._stat = (path125) => statMethod(path125, { bigint: true });
        } else {
          this._stat = statMethod;
        }
        this._maxDepth = opts.depth ?? defaultOptions3.depth;
        this._wantsDir = type ? DIR_TYPES.has(type) : false;
        this._wantsFile = type ? FILE_TYPES.has(type) : false;
        this._wantsEverything = type === EntryTypes.EVERYTHING_TYPE;
        this._root = presolve(root);
        this._isDirent = !opts.alwaysStat;
        this._statsProp = this._isDirent ? "dirent" : "stats";
        this._rdOptions = { encoding: "utf8", withFileTypes: this._isDirent };
        this.parents = [this._exploreDir(root, 1)];
        this.reading = false;
        this.parent = void 0;
      }
      async _read(batch) {
        if (this.reading)
          return;
        this.reading = true;
        try {
          while (!this.destroyed && batch > 0) {
            const par = this.parent;
            const fil = par && par.files;
            if (fil && fil.length > 0) {
              const { path: path125, depth } = par;
              const slice = fil.splice(0, batch).map((dirent) => this._formatEntry(dirent, path125));
              const awaited = await Promise.all(slice);
              for (const entry of awaited) {
                if (!entry)
                  continue;
                if (this.destroyed)
                  return;
                const entryType = await this._getEntryType(entry);
                if (entryType === "directory" && this._directoryFilter(entry)) {
                  if (depth <= this._maxDepth) {
                    this.parents.push(this._exploreDir(entry.fullPath, depth + 1));
                  }
                  if (this._wantsDir) {
                    this.push(entry);
                    batch--;
                  }
                } else if ((entryType === "file" || this._includeAsFile(entry)) && this._fileFilter(entry)) {
                  if (this._wantsFile) {
                    this.push(entry);
                    batch--;
                  }
                }
              }
            } else {
              const parent = this.parents.pop();
              if (!parent) {
                this.push(null);
                break;
              }
              this.parent = await parent;
              if (this.destroyed)
                return;
            }
          }
        } catch (error2) {
          this.destroy(error2);
        } finally {
          this.reading = false;
        }
      }
      async _exploreDir(path125, depth) {
        let files;
        try {
          files = await readdir4(path125, this._rdOptions);
        } catch (error2) {
          this._onError(error2);
        }
        return { files, depth, path: path125 };
      }
      async _formatEntry(dirent, path125) {
        let entry;
        const basename26 = this._isDirent ? dirent.name : dirent;
        try {
          const fullPath = presolve(pjoin(path125, basename26));
          entry = { path: prelative(this._root, fullPath), fullPath, basename: basename26 };
          entry[this._statsProp] = this._isDirent ? dirent : await this._stat(fullPath);
        } catch (err) {
          this._onError(err);
          return;
        }
        return entry;
      }
      _onError(err) {
        if (isNormalFlowError(err) && !this.destroyed) {
          this.emit("warn", err);
        } else {
          this.destroy(err);
        }
      }
      async _getEntryType(entry) {
        if (!entry && this._statsProp in entry) {
          return "";
        }
        const stats = entry[this._statsProp];
        if (stats.isFile())
          return "file";
        if (stats.isDirectory())
          return "directory";
        if (stats && stats.isSymbolicLink()) {
          const full = entry.fullPath;
          try {
            const entryRealPath = await realpath2(full);
            const entryRealPathStats = await lstat2(entryRealPath);
            if (entryRealPathStats.isFile()) {
              return "file";
            }
            if (entryRealPathStats.isDirectory()) {
              const len = entryRealPath.length;
              if (full.startsWith(entryRealPath) && full.substr(len, 1) === psep) {
                const recursiveError = new Error(`Circular symlink detected: "${full}" points to "${entryRealPath}"`);
                recursiveError.code = RECURSIVE_ERROR_CODE;
                return this._onError(recursiveError);
              }
              return "directory";
            }
          } catch (error2) {
            this._onError(error2);
            return "";
          }
        }
      }
      _includeAsFile(entry) {
        const stats = entry && entry[this._statsProp];
        return stats && this._wantsEverything && !stats.isDirectory();
      }
    };
    __name(readdirp, "readdirp");
  }
});

// node_modules/chokidar/esm/handler.js
import { watchFile, unwatchFile, watch as fs_watch } from "fs";
import { open as open3, stat as stat4, lstat as lstat3, realpath as fsrealpath } from "fs/promises";
import * as sysPath from "path";
import { type as osType } from "os";
function createFsWatchInstance(path125, options2, listener, errHandler, emitRaw) {
  const handleEvent = /* @__PURE__ */ __name((rawEvent, evPath) => {
    listener(path125);
    emitRaw(rawEvent, evPath, { watchedPath: path125 });
    if (evPath && path125 !== evPath) {
      fsWatchBroadcast(sysPath.resolve(path125, evPath), KEY_LISTENERS, sysPath.join(path125, evPath));
    }
  }, "handleEvent");
  try {
    return fs_watch(path125, {
      persistent: options2.persistent
    }, handleEvent);
  } catch (error2) {
    errHandler(error2);
    return void 0;
  }
}
var STR_DATA, STR_END, STR_CLOSE, EMPTY_FN, pl, isWindows2, isMacos, isLinux, isFreeBSD, isIBMi, EVENTS, EV, THROTTLE_MODE_WATCH, statMethods, KEY_LISTENERS, KEY_ERR, KEY_RAW, HANDLER_KEYS, binaryExtensions, isBinaryPath, foreach, addAndConvert, clearItem, delFromSet, isEmptySet, FsWatchInstances, fsWatchBroadcast, setFsWatchListener, FsWatchFileInstances, setFsWatchFileListener, NodeFsHandler;
var init_handler = __esm({
  "node_modules/chokidar/esm/handler.js"() {
    init_esbuild_shims();
    STR_DATA = "data";
    STR_END = "end";
    STR_CLOSE = "close";
    EMPTY_FN = /* @__PURE__ */ __name(() => {
    }, "EMPTY_FN");
    pl = process.platform;
    isWindows2 = pl === "win32";
    isMacos = pl === "darwin";
    isLinux = pl === "linux";
    isFreeBSD = pl === "freebsd";
    isIBMi = osType() === "OS400";
    EVENTS = {
      ALL: "all",
      READY: "ready",
      ADD: "add",
      CHANGE: "change",
      ADD_DIR: "addDir",
      UNLINK: "unlink",
      UNLINK_DIR: "unlinkDir",
      RAW: "raw",
      ERROR: "error"
    };
    EV = EVENTS;
    THROTTLE_MODE_WATCH = "watch";
    statMethods = { lstat: lstat3, stat: stat4 };
    KEY_LISTENERS = "listeners";
    KEY_ERR = "errHandlers";
    KEY_RAW = "rawEmitters";
    HANDLER_KEYS = [KEY_LISTENERS, KEY_ERR, KEY_RAW];
    binaryExtensions = /* @__PURE__ */ new Set([
      "3dm",
      "3ds",
      "3g2",
      "3gp",
      "7z",
      "a",
      "aac",
      "adp",
      "afdesign",
      "afphoto",
      "afpub",
      "ai",
      "aif",
      "aiff",
      "alz",
      "ape",
      "apk",
      "appimage",
      "ar",
      "arj",
      "asf",
      "au",
      "avi",
      "bak",
      "baml",
      "bh",
      "bin",
      "bk",
      "bmp",
      "btif",
      "bz2",
      "bzip2",
      "cab",
      "caf",
      "cgm",
      "class",
      "cmx",
      "cpio",
      "cr2",
      "cur",
      "dat",
      "dcm",
      "deb",
      "dex",
      "djvu",
      "dll",
      "dmg",
      "dng",
      "doc",
      "docm",
      "docx",
      "dot",
      "dotm",
      "dra",
      "DS_Store",
      "dsk",
      "dts",
      "dtshd",
      "dvb",
      "dwg",
      "dxf",
      "ecelp4800",
      "ecelp7470",
      "ecelp9600",
      "egg",
      "eol",
      "eot",
      "epub",
      "exe",
      "f4v",
      "fbs",
      "fh",
      "fla",
      "flac",
      "flatpak",
      "fli",
      "flv",
      "fpx",
      "fst",
      "fvt",
      "g3",
      "gh",
      "gif",
      "graffle",
      "gz",
      "gzip",
      "h261",
      "h263",
      "h264",
      "icns",
      "ico",
      "ief",
      "img",
      "ipa",
      "iso",
      "jar",
      "jpeg",
      "jpg",
      "jpgv",
      "jpm",
      "jxr",
      "key",
      "ktx",
      "lha",
      "lib",
      "lvp",
      "lz",
      "lzh",
      "lzma",
      "lzo",
      "m3u",
      "m4a",
      "m4v",
      "mar",
      "mdi",
      "mht",
      "mid",
      "midi",
      "mj2",
      "mka",
      "mkv",
      "mmr",
      "mng",
      "mobi",
      "mov",
      "movie",
      "mp3",
      "mp4",
      "mp4a",
      "mpeg",
      "mpg",
      "mpga",
      "mxu",
      "nef",
      "npx",
      "numbers",
      "nupkg",
      "o",
      "odp",
      "ods",
      "odt",
      "oga",
      "ogg",
      "ogv",
      "otf",
      "ott",
      "pages",
      "pbm",
      "pcx",
      "pdb",
      "pdf",
      "pea",
      "pgm",
      "pic",
      "png",
      "pnm",
      "pot",
      "potm",
      "potx",
      "ppa",
      "ppam",
      "ppm",
      "pps",
      "ppsm",
      "ppsx",
      "ppt",
      "pptm",
      "pptx",
      "psd",
      "pya",
      "pyc",
      "pyo",
      "pyv",
      "qt",
      "rar",
      "ras",
      "raw",
      "resources",
      "rgb",
      "rip",
      "rlc",
      "rmf",
      "rmvb",
      "rpm",
      "rtf",
      "rz",
      "s3m",
      "s7z",
      "scpt",
      "sgi",
      "shar",
      "snap",
      "sil",
      "sketch",
      "slk",
      "smv",
      "snk",
      "so",
      "stl",
      "suo",
      "sub",
      "swf",
      "tar",
      "tbz",
      "tbz2",
      "tga",
      "tgz",
      "thmx",
      "tif",
      "tiff",
      "tlz",
      "ttc",
      "ttf",
      "txz",
      "udf",
      "uvh",
      "uvi",
      "uvm",
      "uvp",
      "uvs",
      "uvu",
      "viv",
      "vob",
      "war",
      "wav",
      "wax",
      "wbmp",
      "wdp",
      "weba",
      "webm",
      "webp",
      "whl",
      "wim",
      "wm",
      "wma",
      "wmv",
      "wmx",
      "woff",
      "woff2",
      "wrm",
      "wvx",
      "xbm",
      "xif",
      "xla",
      "xlam",
      "xls",
      "xlsb",
      "xlsm",
      "xlsx",
      "xlt",
      "xltm",
      "xltx",
      "xm",
      "xmind",
      "xpi",
      "xpm",
      "xwd",
      "xz",
      "z",
      "zip",
      "zipx"
    ]);
    isBinaryPath = /* @__PURE__ */ __name((filePath) => binaryExtensions.has(sysPath.extname(filePath).slice(1).toLowerCase()), "isBinaryPath");
    foreach = /* @__PURE__ */ __name((val, fn) => {
      if (val instanceof Set) {
        val.forEach(fn);
      } else {
        fn(val);
      }
    }, "foreach");
    addAndConvert = /* @__PURE__ */ __name((main2, prop, item) => {
      let container = main2[prop];
      if (!(container instanceof Set)) {
        main2[prop] = container = /* @__PURE__ */ new Set([container]);
      }
      container.add(item);
    }, "addAndConvert");
    clearItem = /* @__PURE__ */ __name((cont) => (key) => {
      const set = cont[key];
      if (set instanceof Set) {
        set.clear();
      } else {
        delete cont[key];
      }
    }, "clearItem");
    delFromSet = /* @__PURE__ */ __name((main2, prop, item) => {
      const container = main2[prop];
      if (container instanceof Set) {
        container.delete(item);
      } else if (container === item) {
        delete main2[prop];
      }
    }, "delFromSet");
    isEmptySet = /* @__PURE__ */ __name((val) => val instanceof Set ? val.size === 0 : !val, "isEmptySet");
    FsWatchInstances = /* @__PURE__ */ new Map();
    __name(createFsWatchInstance, "createFsWatchInstance");
    fsWatchBroadcast = /* @__PURE__ */ __name((fullPath, listenerType, val1, val2, val3) => {
      const cont = FsWatchInstances.get(fullPath);
      if (!cont)
        return;
      foreach(cont[listenerType], (listener) => {
        listener(val1, val2, val3);
      });
    }, "fsWatchBroadcast");
    setFsWatchListener = /* @__PURE__ */ __name((path125, fullPath, options2, handlers) => {
      const { listener, errHandler, rawEmitter } = handlers;
      let cont = FsWatchInstances.get(fullPath);
      let watcher;
      if (!options2.persistent) {
        watcher = createFsWatchInstance(path125, options2, listener, errHandler, rawEmitter);
        if (!watcher)
          return;
        return watcher.close.bind(watcher);
      }
      if (cont) {
        addAndConvert(cont, KEY_LISTENERS, listener);
        addAndConvert(cont, KEY_ERR, errHandler);
        addAndConvert(cont, KEY_RAW, rawEmitter);
      } else {
        watcher = createFsWatchInstance(
          path125,
          options2,
          fsWatchBroadcast.bind(null, fullPath, KEY_LISTENERS),
          errHandler,
          // no need to use broadcast here
          fsWatchBroadcast.bind(null, fullPath, KEY_RAW)
        );
        if (!watcher)
          return;
        watcher.on(EV.ERROR, async (error2) => {
          const broadcastErr = fsWatchBroadcast.bind(null, fullPath, KEY_ERR);
          if (cont)
            cont.watcherUnusable = true;
          if (isWindows2 && error2.code === "EPERM") {
            try {
              const fd = await open3(path125, "r");
              await fd.close();
              broadcastErr(error2);
            } catch (err) {
            }
          } else {
            broadcastErr(error2);
          }
        });
        cont = {
          listeners: listener,
          errHandlers: errHandler,
          rawEmitters: rawEmitter,
          watcher
        };
        FsWatchInstances.set(fullPath, cont);
      }
      return () => {
        delFromSet(cont, KEY_LISTENERS, listener);
        delFromSet(cont, KEY_ERR, errHandler);
        delFromSet(cont, KEY_RAW, rawEmitter);
        if (isEmptySet(cont.listeners)) {
          cont.watcher.close();
          FsWatchInstances.delete(fullPath);
          HANDLER_KEYS.forEach(clearItem(cont));
          cont.watcher = void 0;
          Object.freeze(cont);
        }
      };
    }, "setFsWatchListener");
    FsWatchFileInstances = /* @__PURE__ */ new Map();
    setFsWatchFileListener = /* @__PURE__ */ __name((path125, fullPath, options2, handlers) => {
      const { listener, rawEmitter } = handlers;
      let cont = FsWatchFileInstances.get(fullPath);
      const copts = cont && cont.options;
      if (copts && (copts.persistent < options2.persistent || copts.interval > options2.interval)) {
        unwatchFile(fullPath);
        cont = void 0;
      }
      if (cont) {
        addAndConvert(cont, KEY_LISTENERS, listener);
        addAndConvert(cont, KEY_RAW, rawEmitter);
      } else {
        cont = {
          listeners: listener,
          rawEmitters: rawEmitter,
          options: options2,
          watcher: watchFile(fullPath, options2, (curr, prev) => {
            foreach(cont.rawEmitters, (rawEmitter2) => {
              rawEmitter2(EV.CHANGE, fullPath, { curr, prev });
            });
            const currmtime = curr.mtimeMs;
            if (curr.size !== prev.size || currmtime > prev.mtimeMs || currmtime === 0) {
              foreach(cont.listeners, (listener2) => listener2(path125, curr));
            }
          })
        };
        FsWatchFileInstances.set(fullPath, cont);
      }
      return () => {
        delFromSet(cont, KEY_LISTENERS, listener);
        delFromSet(cont, KEY_RAW, rawEmitter);
        if (isEmptySet(cont.listeners)) {
          FsWatchFileInstances.delete(fullPath);
          unwatchFile(fullPath);
          cont.options = cont.watcher = void 0;
          Object.freeze(cont);
        }
      };
    }, "setFsWatchFileListener");
    NodeFsHandler = class {
      static {
        __name(this, "NodeFsHandler");
      }
      constructor(fsW) {
        this.fsw = fsW;
        this._boundHandleError = (error2) => fsW._handleError(error2);
      }
      /**
       * Watch file for changes with fs_watchFile or fs_watch.
       * @param path to file or dir
       * @param listener on fs change
       * @returns closer for the watcher instance
       */
      _watchWithNodeFs(path125, listener) {
        const opts = this.fsw.options;
        const directory = sysPath.dirname(path125);
        const basename26 = sysPath.basename(path125);
        const parent = this.fsw._getWatchedDir(directory);
        parent.add(basename26);
        const absolutePath = sysPath.resolve(path125);
        const options2 = {
          persistent: opts.persistent
        };
        if (!listener)
          listener = EMPTY_FN;
        let closer;
        if (opts.usePolling) {
          const enableBin = opts.interval !== opts.binaryInterval;
          options2.interval = enableBin && isBinaryPath(basename26) ? opts.binaryInterval : opts.interval;
          closer = setFsWatchFileListener(path125, absolutePath, options2, {
            listener,
            rawEmitter: this.fsw._emitRaw
          });
        } else {
          closer = setFsWatchListener(path125, absolutePath, options2, {
            listener,
            errHandler: this._boundHandleError,
            rawEmitter: this.fsw._emitRaw
          });
        }
        return closer;
      }
      /**
       * Watch a file and emit add event if warranted.
       * @returns closer for the watcher instance
       */
      _handleFile(file, stats, initialAdd) {
        if (this.fsw.closed) {
          return;
        }
        const dirname26 = sysPath.dirname(file);
        const basename26 = sysPath.basename(file);
        const parent = this.fsw._getWatchedDir(dirname26);
        let prevStats = stats;
        if (parent.has(basename26))
          return;
        const listener = /* @__PURE__ */ __name(async (path125, newStats) => {
          if (!this.fsw._throttle(THROTTLE_MODE_WATCH, file, 5))
            return;
          if (!newStats || newStats.mtimeMs === 0) {
            try {
              const newStats2 = await stat4(file);
              if (this.fsw.closed)
                return;
              const at2 = newStats2.atimeMs;
              const mt2 = newStats2.mtimeMs;
              if (!at2 || at2 <= mt2 || mt2 !== prevStats.mtimeMs) {
                this.fsw._emit(EV.CHANGE, file, newStats2);
              }
              if ((isMacos || isLinux || isFreeBSD) && prevStats.ino !== newStats2.ino) {
                this.fsw._closeFile(path125);
                prevStats = newStats2;
                const closer2 = this._watchWithNodeFs(file, listener);
                if (closer2)
                  this.fsw._addPathCloser(path125, closer2);
              } else {
                prevStats = newStats2;
              }
            } catch (error2) {
              this.fsw._remove(dirname26, basename26);
            }
          } else if (parent.has(basename26)) {
            const at2 = newStats.atimeMs;
            const mt2 = newStats.mtimeMs;
            if (!at2 || at2 <= mt2 || mt2 !== prevStats.mtimeMs) {
              this.fsw._emit(EV.CHANGE, file, newStats);
            }
            prevStats = newStats;
          }
        }, "listener");
        const closer = this._watchWithNodeFs(file, listener);
        if (!(initialAdd && this.fsw.options.ignoreInitial) && this.fsw._isntIgnored(file)) {
          if (!this.fsw._throttle(EV.ADD, file, 0))
            return;
          this.fsw._emit(EV.ADD, file, stats);
        }
        return closer;
      }
      /**
       * Handle symlinks encountered while reading a dir.
       * @param entry returned by readdirp
       * @param directory path of dir being read
       * @param path of this item
       * @param item basename of this item
       * @returns true if no more processing is needed for this entry.
       */
      async _handleSymlink(entry, directory, path125, item) {
        if (this.fsw.closed) {
          return;
        }
        const full = entry.fullPath;
        const dir = this.fsw._getWatchedDir(directory);
        if (!this.fsw.options.followSymlinks) {
          this.fsw._incrReadyCount();
          let linkPath;
          try {
            linkPath = await fsrealpath(path125);
          } catch (e4) {
            this.fsw._emitReady();
            return true;
          }
          if (this.fsw.closed)
            return;
          if (dir.has(item)) {
            if (this.fsw._symlinkPaths.get(full) !== linkPath) {
              this.fsw._symlinkPaths.set(full, linkPath);
              this.fsw._emit(EV.CHANGE, path125, entry.stats);
            }
          } else {
            dir.add(item);
            this.fsw._symlinkPaths.set(full, linkPath);
            this.fsw._emit(EV.ADD, path125, entry.stats);
          }
          this.fsw._emitReady();
          return true;
        }
        if (this.fsw._symlinkPaths.has(full)) {
          return true;
        }
        this.fsw._symlinkPaths.set(full, true);
      }
      _handleRead(directory, initialAdd, wh, target, dir, depth, throttler) {
        directory = sysPath.join(directory, "");
        throttler = this.fsw._throttle("readdir", directory, 1e3);
        if (!throttler)
          return;
        const previous = this.fsw._getWatchedDir(wh.path);
        const current = /* @__PURE__ */ new Set();
        let stream2 = this.fsw._readdirp(directory, {
          fileFilter: /* @__PURE__ */ __name((entry) => wh.filterPath(entry), "fileFilter"),
          directoryFilter: /* @__PURE__ */ __name((entry) => wh.filterDir(entry), "directoryFilter")
        });
        if (!stream2)
          return;
        stream2.on(STR_DATA, async (entry) => {
          if (this.fsw.closed) {
            stream2 = void 0;
            return;
          }
          const item = entry.path;
          let path125 = sysPath.join(directory, item);
          current.add(item);
          if (entry.stats.isSymbolicLink() && await this._handleSymlink(entry, directory, path125, item)) {
            return;
          }
          if (this.fsw.closed) {
            stream2 = void 0;
            return;
          }
          if (item === target || !target && !previous.has(item)) {
            this.fsw._incrReadyCount();
            path125 = sysPath.join(dir, sysPath.relative(dir, path125));
            this._addToNodeFs(path125, initialAdd, wh, depth + 1);
          }
        }).on(EV.ERROR, this._boundHandleError);
        return new Promise((resolve30, reject) => {
          if (!stream2)
            return reject();
          stream2.once(STR_END, () => {
            if (this.fsw.closed) {
              stream2 = void 0;
              return;
            }
            const wasThrottled = throttler ? throttler.clear() : false;
            resolve30(void 0);
            previous.getChildren().filter((item) => {
              return item !== directory && !current.has(item);
            }).forEach((item) => {
              this.fsw._remove(directory, item);
            });
            stream2 = void 0;
            if (wasThrottled)
              this._handleRead(directory, false, wh, target, dir, depth, throttler);
          });
        });
      }
      /**
       * Read directory to add / remove files from `@watched` list and re-read it on change.
       * @param dir fs path
       * @param stats
       * @param initialAdd
       * @param depth relative to user-supplied path
       * @param target child path targeted for watch
       * @param wh Common watch helpers for this path
       * @param realpath
       * @returns closer for the watcher instance.
       */
      async _handleDir(dir, stats, initialAdd, depth, target, wh, realpath3) {
        const parentDir = this.fsw._getWatchedDir(sysPath.dirname(dir));
        const tracked = parentDir.has(sysPath.basename(dir));
        if (!(initialAdd && this.fsw.options.ignoreInitial) && !target && !tracked) {
          this.fsw._emit(EV.ADD_DIR, dir, stats);
        }
        parentDir.add(sysPath.basename(dir));
        this.fsw._getWatchedDir(dir);
        let throttler;
        let closer;
        const oDepth = this.fsw.options.depth;
        if ((oDepth == null || depth <= oDepth) && !this.fsw._symlinkPaths.has(realpath3)) {
          if (!target) {
            await this._handleRead(dir, initialAdd, wh, target, dir, depth, throttler);
            if (this.fsw.closed)
              return;
          }
          closer = this._watchWithNodeFs(dir, (dirPath, stats2) => {
            if (stats2 && stats2.mtimeMs === 0)
              return;
            this._handleRead(dirPath, false, wh, target, dir, depth, throttler);
          });
        }
        return closer;
      }
      /**
       * Handle added file, directory, or glob pattern.
       * Delegates call to _handleFile / _handleDir after checks.
       * @param path to file or ir
       * @param initialAdd was the file added at watch instantiation?
       * @param priorWh depth relative to user-supplied path
       * @param depth Child path actually targeted for watch
       * @param target Child path actually targeted for watch
       */
      async _addToNodeFs(path125, initialAdd, priorWh, depth, target) {
        const ready = this.fsw._emitReady;
        if (this.fsw._isIgnored(path125) || this.fsw.closed) {
          ready();
          return false;
        }
        const wh = this.fsw._getWatchHelpers(path125);
        if (priorWh) {
          wh.filterPath = (entry) => priorWh.filterPath(entry);
          wh.filterDir = (entry) => priorWh.filterDir(entry);
        }
        try {
          const stats = await statMethods[wh.statMethod](wh.watchPath);
          if (this.fsw.closed)
            return;
          if (this.fsw._isIgnored(wh.watchPath, stats)) {
            ready();
            return false;
          }
          const follow = this.fsw.options.followSymlinks;
          let closer;
          if (stats.isDirectory()) {
            const absPath = sysPath.resolve(path125);
            const targetPath = follow ? await fsrealpath(path125) : path125;
            if (this.fsw.closed)
              return;
            closer = await this._handleDir(wh.watchPath, stats, initialAdd, depth, target, wh, targetPath);
            if (this.fsw.closed)
              return;
            if (absPath !== targetPath && targetPath !== void 0) {
              this.fsw._symlinkPaths.set(absPath, targetPath);
            }
          } else if (stats.isSymbolicLink()) {
            const targetPath = follow ? await fsrealpath(path125) : path125;
            if (this.fsw.closed)
              return;
            const parent = sysPath.dirname(wh.watchPath);
            this.fsw._getWatchedDir(parent).add(wh.watchPath);
            this.fsw._emit(EV.ADD, wh.watchPath, stats);
            closer = await this._handleDir(parent, stats, initialAdd, depth, path125, wh, targetPath);
            if (this.fsw.closed)
              return;
            if (targetPath !== void 0) {
              this.fsw._symlinkPaths.set(sysPath.resolve(path125), targetPath);
            }
          } else {
            closer = this._handleFile(wh.watchPath, stats, initialAdd);
          }
          ready();
          if (closer)
            this.fsw._addPathCloser(path125, closer);
          return false;
        } catch (error2) {
          if (this.fsw._handleError(error2)) {
            ready();
            return path125;
          }
        }
      }
    };
  }
});

// node_modules/chokidar/esm/index.js
import { stat as statcb } from "fs";
import { stat as stat5, readdir as readdir5 } from "fs/promises";
import { EventEmitter as EventEmitter6 } from "events";
import * as sysPath2 from "path";
function arrify(item) {
  return Array.isArray(item) ? item : [item];
}
function createPattern(matcher) {
  if (typeof matcher === "function")
    return matcher;
  if (typeof matcher === "string")
    return (string4) => matcher === string4;
  if (matcher instanceof RegExp)
    return (string4) => matcher.test(string4);
  if (typeof matcher === "object" && matcher !== null) {
    return (string4) => {
      if (matcher.path === string4)
        return true;
      if (matcher.recursive) {
        const relative11 = sysPath2.relative(matcher.path, string4);
        if (!relative11) {
          return false;
        }
        return !relative11.startsWith("..") && !sysPath2.isAbsolute(relative11);
      }
      return false;
    };
  }
  return () => false;
}
function normalizePath(path125) {
  if (typeof path125 !== "string")
    throw new Error("string expected");
  path125 = sysPath2.normalize(path125);
  path125 = path125.replace(/\\/g, "/");
  let prepend = false;
  if (path125.startsWith("//"))
    prepend = true;
  const DOUBLE_SLASH_RE2 = /\/\//;
  while (path125.match(DOUBLE_SLASH_RE2))
    path125 = path125.replace(DOUBLE_SLASH_RE2, "/");
  if (prepend)
    path125 = "/" + path125;
  return path125;
}
function matchPatterns(patterns, testString, stats) {
  const path125 = normalizePath(testString);
  for (let index = 0; index < patterns.length; index++) {
    const pattern = patterns[index];
    if (pattern(path125, stats)) {
      return true;
    }
  }
  return false;
}
function anymatch(matchers, testString) {
  if (matchers == null) {
    throw new TypeError("anymatch: specify first argument");
  }
  const matchersArray = arrify(matchers);
  const patterns = matchersArray.map((matcher) => createPattern(matcher));
  if (testString == null) {
    return (testString2, stats) => {
      return matchPatterns(patterns, testString2, stats);
    };
  }
  return matchPatterns(patterns, testString);
}
function watch(paths, options2 = {}) {
  const watcher = new FSWatcher(options2);
  watcher.add(paths);
  return watcher;
}
var SLASH, SLASH_SLASH, ONE_DOT, TWO_DOTS, STRING_TYPE, BACK_SLASH_RE, DOUBLE_SLASH_RE, DOT_RE, REPLACER_RE, isMatcherObject, unifyPaths, toUnix, normalizePathToUnix, normalizeIgnored, getAbsolutePath, EMPTY_SET, DirEntry, STAT_METHOD_F, STAT_METHOD_L, WatchHelper, FSWatcher;
var init_esm21 = __esm({
  "node_modules/chokidar/esm/index.js"() {
    init_esbuild_shims();
    init_esm20();
    init_handler();
    SLASH = "/";
    SLASH_SLASH = "//";
    ONE_DOT = ".";
    TWO_DOTS = "..";
    STRING_TYPE = "string";
    BACK_SLASH_RE = /\\/g;
    DOUBLE_SLASH_RE = /\/\//;
    DOT_RE = /\..*\.(sw[px])$|~$|\.subl.*\.tmp/;
    REPLACER_RE = /^\.[/\\]/;
    __name(arrify, "arrify");
    isMatcherObject = /* @__PURE__ */ __name((matcher) => typeof matcher === "object" && matcher !== null && !(matcher instanceof RegExp), "isMatcherObject");
    __name(createPattern, "createPattern");
    __name(normalizePath, "normalizePath");
    __name(matchPatterns, "matchPatterns");
    __name(anymatch, "anymatch");
    unifyPaths = /* @__PURE__ */ __name((paths_) => {
      const paths = arrify(paths_).flat();
      if (!paths.every((p2) => typeof p2 === STRING_TYPE)) {
        throw new TypeError(`Non-string provided as watch path: ${paths}`);
      }
      return paths.map(normalizePathToUnix);
    }, "unifyPaths");
    toUnix = /* @__PURE__ */ __name((string4) => {
      let str2 = string4.replace(BACK_SLASH_RE, SLASH);
      let prepend = false;
      if (str2.startsWith(SLASH_SLASH)) {
        prepend = true;
      }
      while (str2.match(DOUBLE_SLASH_RE)) {
        str2 = str2.replace(DOUBLE_SLASH_RE, SLASH);
      }
      if (prepend) {
        str2 = SLASH + str2;
      }
      return str2;
    }, "toUnix");
    normalizePathToUnix = /* @__PURE__ */ __name((path125) => toUnix(sysPath2.normalize(toUnix(path125))), "normalizePathToUnix");
    normalizeIgnored = /* @__PURE__ */ __name((cwd7 = "") => (path125) => {
      if (typeof path125 === "string") {
        return normalizePathToUnix(sysPath2.isAbsolute(path125) ? path125 : sysPath2.join(cwd7, path125));
      } else {
        return path125;
      }
    }, "normalizeIgnored");
    getAbsolutePath = /* @__PURE__ */ __name((path125, cwd7) => {
      if (sysPath2.isAbsolute(path125)) {
        return path125;
      }
      return sysPath2.join(cwd7, path125);
    }, "getAbsolutePath");
    EMPTY_SET = Object.freeze(/* @__PURE__ */ new Set());
    DirEntry = class {
      static {
        __name(this, "DirEntry");
      }
      constructor(dir, removeWatcher) {
        this.path = dir;
        this._removeWatcher = removeWatcher;
        this.items = /* @__PURE__ */ new Set();
      }
      add(item) {
        const { items } = this;
        if (!items)
          return;
        if (item !== ONE_DOT && item !== TWO_DOTS)
          items.add(item);
      }
      async remove(item) {
        const { items } = this;
        if (!items)
          return;
        items.delete(item);
        if (items.size > 0)
          return;
        const dir = this.path;
        try {
          await readdir5(dir);
        } catch (err) {
          if (this._removeWatcher) {
            this._removeWatcher(sysPath2.dirname(dir), sysPath2.basename(dir));
          }
        }
      }
      has(item) {
        const { items } = this;
        if (!items)
          return;
        return items.has(item);
      }
      getChildren() {
        const { items } = this;
        if (!items)
          return [];
        return [...items.values()];
      }
      dispose() {
        this.items.clear();
        this.path = "";
        this._removeWatcher = EMPTY_FN;
        this.items = EMPTY_SET;
        Object.freeze(this);
      }
    };
    STAT_METHOD_F = "stat";
    STAT_METHOD_L = "lstat";
    WatchHelper = class {
      static {
        __name(this, "WatchHelper");
      }
      constructor(path125, follow, fsw) {
        this.fsw = fsw;
        const watchPath = path125;
        this.path = path125 = path125.replace(REPLACER_RE, "");
        this.watchPath = watchPath;
        this.fullWatchPath = sysPath2.resolve(watchPath);
        this.dirParts = [];
        this.dirParts.forEach((parts) => {
          if (parts.length > 1)
            parts.pop();
        });
        this.followSymlinks = follow;
        this.statMethod = follow ? STAT_METHOD_F : STAT_METHOD_L;
      }
      entryPath(entry) {
        return sysPath2.join(this.watchPath, sysPath2.relative(this.watchPath, entry.fullPath));
      }
      filterPath(entry) {
        const { stats } = entry;
        if (stats && stats.isSymbolicLink())
          return this.filterDir(entry);
        const resolvedPath = this.entryPath(entry);
        return this.fsw._isntIgnored(resolvedPath, stats) && this.fsw._hasReadPermissions(stats);
      }
      filterDir(entry) {
        return this.fsw._isntIgnored(this.entryPath(entry), entry.stats);
      }
    };
    FSWatcher = class extends EventEmitter6 {
      static {
        __name(this, "FSWatcher");
      }
      // Not indenting methods for history sake; for now.
      constructor(_opts = {}) {
        super();
        this.closed = false;
        this._closers = /* @__PURE__ */ new Map();
        this._ignoredPaths = /* @__PURE__ */ new Set();
        this._throttled = /* @__PURE__ */ new Map();
        this._streams = /* @__PURE__ */ new Set();
        this._symlinkPaths = /* @__PURE__ */ new Map();
        this._watched = /* @__PURE__ */ new Map();
        this._pendingWrites = /* @__PURE__ */ new Map();
        this._pendingUnlinks = /* @__PURE__ */ new Map();
        this._readyCount = 0;
        this._readyEmitted = false;
        const awf = _opts.awaitWriteFinish;
        const DEF_AWF = { stabilityThreshold: 2e3, pollInterval: 100 };
        const opts = {
          // Defaults
          persistent: true,
          ignoreInitial: false,
          ignorePermissionErrors: false,
          interval: 100,
          binaryInterval: 300,
          followSymlinks: true,
          usePolling: false,
          // useAsync: false,
          atomic: true,
          // NOTE: overwritten later (depends on usePolling)
          ..._opts,
          // Change format
          ignored: _opts.ignored ? arrify(_opts.ignored) : arrify([]),
          awaitWriteFinish: awf === true ? DEF_AWF : typeof awf === "object" ? { ...DEF_AWF, ...awf } : false
        };
        if (isIBMi)
          opts.usePolling = true;
        if (opts.atomic === void 0)
          opts.atomic = !opts.usePolling;
        const envPoll = process.env.CHOKIDAR_USEPOLLING;
        if (envPoll !== void 0) {
          const envLower = envPoll.toLowerCase();
          if (envLower === "false" || envLower === "0")
            opts.usePolling = false;
          else if (envLower === "true" || envLower === "1")
            opts.usePolling = true;
          else
            opts.usePolling = !!envLower;
        }
        const envInterval = process.env.CHOKIDAR_INTERVAL;
        if (envInterval)
          opts.interval = Number.parseInt(envInterval, 10);
        let readyCalls = 0;
        this._emitReady = () => {
          readyCalls++;
          if (readyCalls >= this._readyCount) {
            this._emitReady = EMPTY_FN;
            this._readyEmitted = true;
            process.nextTick(() => this.emit(EVENTS.READY));
          }
        };
        this._emitRaw = (...args) => this.emit(EVENTS.RAW, ...args);
        this._boundRemove = this._remove.bind(this);
        this.options = opts;
        this._nodeFsHandler = new NodeFsHandler(this);
        Object.freeze(opts);
      }
      _addIgnoredPath(matcher) {
        if (isMatcherObject(matcher)) {
          for (const ignored of this._ignoredPaths) {
            if (isMatcherObject(ignored) && ignored.path === matcher.path && ignored.recursive === matcher.recursive) {
              return;
            }
          }
        }
        this._ignoredPaths.add(matcher);
      }
      _removeIgnoredPath(matcher) {
        this._ignoredPaths.delete(matcher);
        if (typeof matcher === "string") {
          for (const ignored of this._ignoredPaths) {
            if (isMatcherObject(ignored) && ignored.path === matcher) {
              this._ignoredPaths.delete(ignored);
            }
          }
        }
      }
      // Public methods
      /**
       * Adds paths to be watched on an existing FSWatcher instance.
       * @param paths_ file or file list. Other arguments are unused
       */
      add(paths_, _origAdd, _internal) {
        const { cwd: cwd7 } = this.options;
        this.closed = false;
        this._closePromise = void 0;
        let paths = unifyPaths(paths_);
        if (cwd7) {
          paths = paths.map((path125) => {
            const absPath = getAbsolutePath(path125, cwd7);
            return absPath;
          });
        }
        paths.forEach((path125) => {
          this._removeIgnoredPath(path125);
        });
        this._userIgnored = void 0;
        if (!this._readyCount)
          this._readyCount = 0;
        this._readyCount += paths.length;
        Promise.all(paths.map(async (path125) => {
          const res = await this._nodeFsHandler._addToNodeFs(path125, !_internal, void 0, 0, _origAdd);
          if (res)
            this._emitReady();
          return res;
        })).then((results) => {
          if (this.closed)
            return;
          results.forEach((item) => {
            if (item)
              this.add(sysPath2.dirname(item), sysPath2.basename(_origAdd || item));
          });
        });
        return this;
      }
      /**
       * Close watchers or start ignoring events from specified paths.
       */
      unwatch(paths_) {
        if (this.closed)
          return this;
        const paths = unifyPaths(paths_);
        const { cwd: cwd7 } = this.options;
        paths.forEach((path125) => {
          if (!sysPath2.isAbsolute(path125) && !this._closers.has(path125)) {
            if (cwd7)
              path125 = sysPath2.join(cwd7, path125);
            path125 = sysPath2.resolve(path125);
          }
          this._closePath(path125);
          this._addIgnoredPath(path125);
          if (this._watched.has(path125)) {
            this._addIgnoredPath({
              path: path125,
              recursive: true
            });
          }
          this._userIgnored = void 0;
        });
        return this;
      }
      /**
       * Close watchers and remove all listeners from watched paths.
       */
      close() {
        if (this._closePromise) {
          return this._closePromise;
        }
        this.closed = true;
        this.removeAllListeners();
        const closers = [];
        this._closers.forEach((closerList) => closerList.forEach((closer) => {
          const promise = closer();
          if (promise instanceof Promise)
            closers.push(promise);
        }));
        this._streams.forEach((stream2) => stream2.destroy());
        this._userIgnored = void 0;
        this._readyCount = 0;
        this._readyEmitted = false;
        this._watched.forEach((dirent) => dirent.dispose());
        this._closers.clear();
        this._watched.clear();
        this._streams.clear();
        this._symlinkPaths.clear();
        this._throttled.clear();
        this._closePromise = closers.length ? Promise.all(closers).then(() => void 0) : Promise.resolve();
        return this._closePromise;
      }
      /**
       * Expose list of watched paths
       * @returns for chaining
       */
      getWatched() {
        const watchList = {};
        this._watched.forEach((entry, dir) => {
          const key = this.options.cwd ? sysPath2.relative(this.options.cwd, dir) : dir;
          const index = key || ONE_DOT;
          watchList[index] = entry.getChildren().sort();
        });
        return watchList;
      }
      emitWithAll(event, args) {
        this.emit(event, ...args);
        if (event !== EVENTS.ERROR)
          this.emit(EVENTS.ALL, event, ...args);
      }
      // Common helpers
      // --------------
      /**
       * Normalize and emit events.
       * Calling _emit DOES NOT MEAN emit() would be called!
       * @param event Type of event
       * @param path File or directory path
       * @param stats arguments to be passed with event
       * @returns the error if defined, otherwise the value of the FSWatcher instance's `closed` flag
       */
      async _emit(event, path125, stats) {
        if (this.closed)
          return;
        const opts = this.options;
        if (isWindows2)
          path125 = sysPath2.normalize(path125);
        if (opts.cwd)
          path125 = sysPath2.relative(opts.cwd, path125);
        const args = [path125];
        if (stats != null)
          args.push(stats);
        const awf = opts.awaitWriteFinish;
        let pw;
        if (awf && (pw = this._pendingWrites.get(path125))) {
          pw.lastChange = /* @__PURE__ */ new Date();
          return this;
        }
        if (opts.atomic) {
          if (event === EVENTS.UNLINK) {
            this._pendingUnlinks.set(path125, [event, ...args]);
            setTimeout(() => {
              this._pendingUnlinks.forEach((entry, path126) => {
                this.emit(...entry);
                this.emit(EVENTS.ALL, ...entry);
                this._pendingUnlinks.delete(path126);
              });
            }, typeof opts.atomic === "number" ? opts.atomic : 100);
            return this;
          }
          if (event === EVENTS.ADD && this._pendingUnlinks.has(path125)) {
            event = EVENTS.CHANGE;
            this._pendingUnlinks.delete(path125);
          }
        }
        if (awf && (event === EVENTS.ADD || event === EVENTS.CHANGE) && this._readyEmitted) {
          const awfEmit = /* @__PURE__ */ __name((err, stats2) => {
            if (err) {
              event = EVENTS.ERROR;
              args[0] = err;
              this.emitWithAll(event, args);
            } else if (stats2) {
              if (args.length > 1) {
                args[1] = stats2;
              } else {
                args.push(stats2);
              }
              this.emitWithAll(event, args);
            }
          }, "awfEmit");
          this._awaitWriteFinish(path125, awf.stabilityThreshold, event, awfEmit);
          return this;
        }
        if (event === EVENTS.CHANGE) {
          const isThrottled = !this._throttle(EVENTS.CHANGE, path125, 50);
          if (isThrottled)
            return this;
        }
        if (opts.alwaysStat && stats === void 0 && (event === EVENTS.ADD || event === EVENTS.ADD_DIR || event === EVENTS.CHANGE)) {
          const fullPath = opts.cwd ? sysPath2.join(opts.cwd, path125) : path125;
          let stats2;
          try {
            stats2 = await stat5(fullPath);
          } catch (err) {
          }
          if (!stats2 || this.closed)
            return;
          args.push(stats2);
        }
        this.emitWithAll(event, args);
        return this;
      }
      /**
       * Common handler for errors
       * @returns The error if defined, otherwise the value of the FSWatcher instance's `closed` flag
       */
      _handleError(error2) {
        const code2 = error2 && error2.code;
        if (error2 && code2 !== "ENOENT" && code2 !== "ENOTDIR" && (!this.options.ignorePermissionErrors || code2 !== "EPERM" && code2 !== "EACCES")) {
          this.emit(EVENTS.ERROR, error2);
        }
        return error2 || this.closed;
      }
      /**
       * Helper utility for throttling
       * @param actionType type being throttled
       * @param path being acted upon
       * @param timeout duration of time to suppress duplicate actions
       * @returns tracking object or false if action should be suppressed
       */
      _throttle(actionType, path125, timeout2) {
        if (!this._throttled.has(actionType)) {
          this._throttled.set(actionType, /* @__PURE__ */ new Map());
        }
        const action = this._throttled.get(actionType);
        if (!action)
          throw new Error("invalid throttle");
        const actionPath = action.get(path125);
        if (actionPath) {
          actionPath.count++;
          return false;
        }
        let timeoutObject;
        const clear = /* @__PURE__ */ __name(() => {
          const item = action.get(path125);
          const count = item ? item.count : 0;
          action.delete(path125);
          clearTimeout(timeoutObject);
          if (item)
            clearTimeout(item.timeoutObject);
          return count;
        }, "clear");
        timeoutObject = setTimeout(clear, timeout2);
        const thr = { timeoutObject, clear, count: 0 };
        action.set(path125, thr);
        return thr;
      }
      _incrReadyCount() {
        return this._readyCount++;
      }
      /**
       * Awaits write operation to finish.
       * Polls a newly created file for size variations. When files size does not change for 'threshold' milliseconds calls callback.
       * @param path being acted upon
       * @param threshold Time in milliseconds a file size must be fixed before acknowledging write OP is finished
       * @param event
       * @param awfEmit Callback to be called when ready for event to be emitted.
       */
      _awaitWriteFinish(path125, threshold, event, awfEmit) {
        const awf = this.options.awaitWriteFinish;
        if (typeof awf !== "object")
          return;
        const pollInterval = awf.pollInterval;
        let timeoutHandler;
        let fullPath = path125;
        if (this.options.cwd && !sysPath2.isAbsolute(path125)) {
          fullPath = sysPath2.join(this.options.cwd, path125);
        }
        const now = /* @__PURE__ */ new Date();
        const writes = this._pendingWrites;
        function awaitWriteFinishFn(prevStat) {
          statcb(fullPath, (err, curStat) => {
            if (err || !writes.has(path125)) {
              if (err && err.code !== "ENOENT")
                awfEmit(err);
              return;
            }
            const now2 = Number(/* @__PURE__ */ new Date());
            if (prevStat && curStat.size !== prevStat.size) {
              writes.get(path125).lastChange = now2;
            }
            const pw = writes.get(path125);
            const df = now2 - pw.lastChange;
            if (df >= threshold) {
              writes.delete(path125);
              awfEmit(void 0, curStat);
            } else {
              timeoutHandler = setTimeout(awaitWriteFinishFn, pollInterval, curStat);
            }
          });
        }
        __name(awaitWriteFinishFn, "awaitWriteFinishFn");
        if (!writes.has(path125)) {
          writes.set(path125, {
            lastChange: now,
            cancelWait: /* @__PURE__ */ __name(() => {
              writes.delete(path125);
              clearTimeout(timeoutHandler);
              return event;
            }, "cancelWait")
          });
          timeoutHandler = setTimeout(awaitWriteFinishFn, pollInterval);
        }
      }
      /**
       * Determines whether user has asked to ignore this path.
       */
      _isIgnored(path125, stats) {
        if (this.options.atomic && DOT_RE.test(path125))
          return true;
        if (!this._userIgnored) {
          const { cwd: cwd7 } = this.options;
          const ign = this.options.ignored;
          const ignored = (ign || []).map(normalizeIgnored(cwd7));
          const ignoredPaths = [...this._ignoredPaths];
          const list3 = [...ignoredPaths.map(normalizeIgnored(cwd7)), ...ignored];
          this._userIgnored = anymatch(list3, void 0);
        }
        return this._userIgnored(path125, stats);
      }
      _isntIgnored(path125, stat10) {
        return !this._isIgnored(path125, stat10);
      }
      /**
       * Provides a set of common helpers and properties relating to symlink handling.
       * @param path file or directory pattern being watched
       */
      _getWatchHelpers(path125) {
        return new WatchHelper(path125, this.options.followSymlinks, this);
      }
      // Directory helpers
      // -----------------
      /**
       * Provides directory tracking objects
       * @param directory path of the directory
       */
      _getWatchedDir(directory) {
        const dir = sysPath2.resolve(directory);
        if (!this._watched.has(dir))
          this._watched.set(dir, new DirEntry(dir, this._boundRemove));
        return this._watched.get(dir);
      }
      // File helpers
      // ------------
      /**
       * Check for read permissions: https://stackoverflow.com/a/11781404/1358405
       */
      _hasReadPermissions(stats) {
        if (this.options.ignorePermissionErrors)
          return true;
        return Boolean(Number(stats.mode) & 256);
      }
      /**
       * Handles emitting unlink events for
       * files and directories, and via recursion, for
       * files and directories within directories that are unlinked
       * @param directory within which the following item is located
       * @param item      base path of item/directory
       */
      _remove(directory, item, isDirectory) {
        const path125 = sysPath2.join(directory, item);
        const fullPath = sysPath2.resolve(path125);
        isDirectory = isDirectory != null ? isDirectory : this._watched.has(path125) || this._watched.has(fullPath);
        if (!this._throttle("remove", path125, 100))
          return;
        if (!isDirectory && this._watched.size === 1) {
          this.add(directory, item, true);
        }
        const wp = this._getWatchedDir(path125);
        const nestedDirectoryChildren = wp.getChildren();
        nestedDirectoryChildren.forEach((nested) => this._remove(path125, nested));
        const parent = this._getWatchedDir(directory);
        const wasTracked = parent.has(item);
        parent.remove(item);
        if (this._symlinkPaths.has(fullPath)) {
          this._symlinkPaths.delete(fullPath);
        }
        let relPath = path125;
        if (this.options.cwd)
          relPath = sysPath2.relative(this.options.cwd, path125);
        if (this.options.awaitWriteFinish && this._pendingWrites.has(relPath)) {
          const event = this._pendingWrites.get(relPath).cancelWait();
          if (event === EVENTS.ADD)
            return;
        }
        this._watched.delete(path125);
        this._watched.delete(fullPath);
        const eventName = isDirectory ? EVENTS.UNLINK_DIR : EVENTS.UNLINK;
        if (wasTracked && !this._isIgnored(path125))
          this._emit(eventName, path125);
        this._closePath(path125);
      }
      /**
       * Closes all watchers for a path
       */
      _closePath(path125) {
        this._closeFile(path125);
        const dir = sysPath2.dirname(path125);
        this._getWatchedDir(dir).remove(sysPath2.basename(path125));
      }
      /**
       * Closes only file-specific watchers
       */
      _closeFile(path125) {
        const closers = this._closers.get(path125);
        if (!closers)
          return;
        closers.forEach((closer) => closer());
        this._closers.delete(path125);
      }
      _addPathCloser(path125, closer) {
        if (!closer)
          return;
        let list3 = this._closers.get(path125);
        if (!list3) {
          list3 = [];
          this._closers.set(path125, list3);
        }
        list3.push(closer);
      }
      _readdirp(root, opts) {
        if (this.closed)
          return;
        const options2 = { type: EVENTS.ALL, alwaysStat: true, lstat: true, ...opts, depth: 0 };
        let stream2 = readdirp(root, options2);
        this._streams.add(stream2);
        stream2.once(STR_CLOSE, () => {
          stream2 = void 0;
        });
        stream2.once(STR_END, () => {
          if (stream2) {
            this._streams.delete(stream2);
            stream2 = void 0;
          }
        });
        return stream2;
      }
    };
    __name(watch, "watch");
  }
});

// packages/core/dist/src/utils/yaml-parser.js
function parse6(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 i3 = 0; i3 < lines.length; i3++) {
    const line = lines[i3];
    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 (i3 + 1 < lines.length) {
          const nextLine = lines[i3 + 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 stringify2(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(parse6, "parse");
    __name(stringify2, "stringify");
    __name(parseValue, "parseValue");
    __name(formatValue, "formatValue");
  }
});

// packages/core/dist/src/skills/types.js
var SkillError, SkillErrorCode;
var init_types11 = __esm({
  "packages/core/dist/src/skills/types.js"() {
    "use strict";
    init_esbuild_shims();
    SkillError = class extends Error {
      static {
        __name(this, "SkillError");
      }
      code;
      skillName;
      constructor(message, code2, skillName) {
        super(message);
        this.code = code2;
        this.skillName = skillName;
        this.name = "SkillError";
      }
    };
    SkillErrorCode = {
      NOT_FOUND: "NOT_FOUND",
      INVALID_CONFIG: "INVALID_CONFIG",
      INVALID_NAME: "INVALID_NAME",
      FILE_ERROR: "FILE_ERROR",
      PARSE_ERROR: "PARSE_ERROR"
    };
  }
});

// packages/core/dist/src/skills/skill-load.js
import * as fs43 from "fs/promises";
import * as path46 from "path";
async function loadSkillsFromDir(baseDir) {
  debugLogger57.debug(`Loading skills from directory (skill-load): ${baseDir}`);
  try {
    const entries = await fs43.readdir(baseDir, { withFileTypes: true });
    const skills = [];
    debugLogger57.debug(`Found ${entries.length} entries in ${baseDir}`);
    for (const entry of entries) {
      if (!entry.isDirectory()) {
        debugLogger57.warn(`Skipping non-directory entry: ${entry.name}`);
        continue;
      }
      const skillDir = path46.join(baseDir, entry.name);
      const skillManifest = path46.join(skillDir, SKILL_MANIFEST_FILE);
      try {
        await fs43.access(skillManifest);
        const content = await fs43.readFile(skillManifest, "utf8");
        const config2 = parseSkillContent(content, skillManifest);
        skills.push(config2);
      } catch (error2) {
        const errorMessage = error2 instanceof Error ? error2.message : "Unknown error";
        debugLogger57.error(`Failed to parse skill at ${skillDir}: ${errorMessage}`);
        continue;
      }
    }
    return skills;
  } catch (error2) {
    const errorMessage = error2 instanceof Error ? error2.message : "Unknown error";
    debugLogger57.debug(`Cannot read skills directory ${baseDir}: ${errorMessage}`);
    return [];
  }
}
function normalizeSkillFileContent(content) {
  let normalized2 = content.replace(/^\uFEFF/, "");
  normalized2 = normalized2.replace(/\r\n/g, "\n").replace(/\r/g, "\n");
  return normalized2;
}
function parseSkillContent(content, filePath) {
  debugLogger57.debug(`Parsing skill content from: ${filePath}`);
  const normalizedContent = normalizeSkillFileContent(content);
  const frontmatterRegex = /^---\n([\s\S]*?)\n---(?:\n|$)([\s\S]*)$/;
  const match2 = normalizedContent.match(frontmatterRegex);
  if (!match2) {
    throw new Error("Invalid format: missing YAML frontmatter");
  }
  const [, frontmatterYaml, body] = match2;
  const frontmatter = parse6(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 allowedToolsRaw = frontmatter["allowedTools"];
  let allowedTools;
  if (allowedToolsRaw !== void 0) {
    if (Array.isArray(allowedToolsRaw)) {
      allowedTools = allowedToolsRaw.map(String);
    } else {
      throw new Error('"allowedTools" must be an array');
    }
  }
  const config2 = {
    name: name3,
    description,
    allowedTools,
    filePath,
    body: body.trim(),
    level: "extension"
  };
  const validation2 = validateConfig(config2);
  if (!validation2.isValid) {
    throw new Error(`Validation failed: ${validation2.errors.join(", ")}`);
  }
  debugLogger57.debug(`Successfully parsed skill: ${name3} from ${filePath}`);
  return config2;
}
function validateConfig(config2) {
  const errors = [];
  const warnings = [];
  if (typeof config2.name !== "string") {
    errors.push('Missing or invalid "name" field');
  } else if (config2.name.trim() === "") {
    errors.push('"name" cannot be empty');
  }
  if (typeof config2.description !== "string") {
    errors.push('Missing or invalid "description" field');
  } else if (config2.description.trim() === "") {
    errors.push('"description" cannot be empty');
  }
  if (config2.allowedTools !== void 0) {
    if (!Array.isArray(config2.allowedTools)) {
      errors.push('"allowedTools" must be an array');
    } else {
      for (const tool of config2.allowedTools) {
        if (typeof tool !== "string") {
          errors.push('"allowedTools" must contain only strings');
          break;
        }
      }
    }
  }
  if (!config2.body || config2.body.trim() === "") {
    warnings.push("Skill body is empty");
  }
  return {
    isValid: errors.length === 0,
    errors,
    warnings
  };
}
var debugLogger57, SKILL_MANIFEST_FILE;
var init_skill_load = __esm({
  "packages/core/dist/src/skills/skill-load.js"() {
    "use strict";
    init_esbuild_shims();
    init_yaml_parser();
    init_debugLogger();
    debugLogger57 = createDebugLogger("SKILL_LOAD");
    SKILL_MANIFEST_FILE = "SKILL.md";
    __name(loadSkillsFromDir, "loadSkillsFromDir");
    __name(normalizeSkillFileContent, "normalizeSkillFileContent");
    __name(parseSkillContent, "parseSkillContent");
    __name(validateConfig, "validateConfig");
  }
});

// packages/core/dist/src/skills/skill-manager.js
import * as fs44 from "fs/promises";
import * as fsSync2 from "fs";
import * as path47 from "path";
import * as os18 from "os";
function normalizeSkillFileContent2(content) {
  let normalized2 = content.replace(/^\uFEFF/, "");
  normalized2 = normalized2.replace(/\r\n/g, "\n").replace(/\r/g, "\n");
  return normalized2;
}
var debugLogger58, QWEN_CONFIG_DIR2, SKILLS_CONFIG_DIR, SKILL_MANIFEST_FILE2, SkillManager;
var init_skill_manager = __esm({
  "packages/core/dist/src/skills/skill-manager.js"() {
    "use strict";
    init_esbuild_shims();
    init_esm21();
    init_yaml_parser();
    init_types11();
    init_skill_load();
    init_debugLogger();
    debugLogger58 = createDebugLogger("SKILL_MANAGER");
    QWEN_CONFIG_DIR2 = ".qwen";
    SKILLS_CONFIG_DIR = "skills";
    SKILL_MANIFEST_FILE2 = "SKILL.md";
    SkillManager = class {
      static {
        __name(this, "SkillManager");
      }
      config;
      skillsCache = null;
      changeListeners = /* @__PURE__ */ new Set();
      parseErrors = /* @__PURE__ */ new Map();
      watchers = /* @__PURE__ */ new Map();
      watchStarted = false;
      refreshTimer = null;
      constructor(config2) {
        this.config = config2;
      }
      /**
       * Adds a listener that will be called when skills change.
       * @returns A function to remove the listener.
       */
      addChangeListener(listener) {
        this.changeListeners.add(listener);
        return () => {
          this.changeListeners.delete(listener);
        };
      }
      /**
       * Notifies all registered change listeners.
       */
      notifyChangeListeners() {
        for (const listener of this.changeListeners) {
          try {
            listener();
          } catch (error2) {
            debugLogger58.warn("Skill change listener threw an error:", error2);
          }
        }
      }
      /**
       * Gets any parse errors that occurred during skill loading.
       * @returns Map of skill paths to their parse errors.
       */
      getParseErrors() {
        return new Map(this.parseErrors);
      }
      /**
       * Lists all available skills.
       *
       * @param options - Filtering options
       * @returns Array of skill configurations
       */
      async listSkills(options2 = {}) {
        debugLogger58.debug(`Listing skills${options2.level ? ` at level: ${options2.level}` : ""}${options2.force ? " (forced refresh)" : ""}`);
        const skills = [];
        const seenNames = /* @__PURE__ */ new Set();
        const levelsToCheck = options2.level ? [options2.level] : ["project", "user", "extension"];
        const shouldUseCache = !options2.force && this.skillsCache !== null;
        if (!shouldUseCache) {
          debugLogger58.debug("Cache miss or force refresh, reloading skills");
          await this.refreshCache();
        } else {
          debugLogger58.debug("Using cached skills");
        }
        for (const level of levelsToCheck) {
          const levelSkills = this.skillsCache?.get(level) || [];
          debugLogger58.debug(`Processing ${levelSkills.length} ${level} level skills`);
          for (const skill of levelSkills) {
            if (seenNames.has(skill.name)) {
              debugLogger58.debug(`Skipping duplicate skill: ${skill.name} (${level})`);
              continue;
            }
            skills.push(skill);
            seenNames.add(skill.name);
          }
        }
        skills.sort((a2, b2) => a2.name.localeCompare(b2.name));
        debugLogger58.info(`Listed ${skills.length} unique skills`);
        return skills;
      }
      /**
       * Loads a skill configuration by name.
       * If level is specified, only searches that level.
       * If level is omitted, searches project-level first, then user-level.
       *
       * @param name - Name of the skill to load
       * @param level - Optional level to limit search to
       * @returns SkillConfig or null if not found
       */
      async loadSkill(name3, level) {
        debugLogger58.debug(`Loading skill: ${name3}${level ? ` at level: ${level}` : ""}`);
        if (level) {
          const skill = await this.findSkillByNameAtLevel(name3, level);
          if (skill) {
            debugLogger58.debug(`Found skill ${name3} at ${level} level`);
          } else {
            debugLogger58.debug(`Skill ${name3} not found at ${level} level`);
          }
          return skill;
        }
        const projectSkill = await this.findSkillByNameAtLevel(name3, "project");
        if (projectSkill) {
          debugLogger58.debug(`Found skill ${name3} at project level`);
          return projectSkill;
        }
        const userSkill = await this.findSkillByNameAtLevel(name3, "user");
        if (userSkill) {
          debugLogger58.debug(`Found skill ${name3} at user level`);
          return userSkill;
        }
        const extensionSkill = await this.findSkillByNameAtLevel(name3, "extension");
        if (extensionSkill) {
          debugLogger58.debug(`Found skill ${name3} at extension level`);
        } else {
          debugLogger58.debug(`Skill ${name3} not found at any level`);
        }
        return extensionSkill;
      }
      /**
       * Loads a skill with its full content, ready for runtime use.
       * This includes loading additional files from the skill directory.
       *
       * @param name - Name of the skill to load
       * @param level - Optional level to limit search to
       * @returns SkillConfig or null if not found
       */
      async loadSkillForRuntime(name3, level) {
        debugLogger58.debug(`Loading skill for runtime: ${name3}${level ? ` at level: ${level}` : ""}`);
        const skill = await this.loadSkill(name3, level);
        if (!skill) {
          debugLogger58.debug(`Skill not found for runtime: ${name3}`);
          return null;
        }
        debugLogger58.info(`Skill loaded for runtime: ${name3} from ${skill.filePath}`);
        return skill;
      }
      /**
       * Validates a skill configuration.
       *
       * @param config - Configuration to validate
       * @returns Validation result
       */
      validateConfig(config2) {
        return validateConfig(config2);
      }
      /**
       * Refreshes the skills cache by loading all skills from disk.
       */
      async refreshCache() {
        debugLogger58.info("Refreshing skills cache...");
        const skillsCache = /* @__PURE__ */ new Map();
        this.parseErrors.clear();
        const levels = ["project", "user", "extension"];
        let totalSkills = 0;
        for (const level of levels) {
          const levelSkills = await this.listSkillsAtLevel(level);
          skillsCache.set(level, levelSkills);
          totalSkills += levelSkills.length;
          debugLogger58.debug(`Loaded ${levelSkills.length} ${level} level skills`);
        }
        this.skillsCache = skillsCache;
        debugLogger58.info(`Skills cache refreshed: ${totalSkills} total skills loaded`);
        this.notifyChangeListeners();
      }
      /**
       * Starts watching skill directories for changes.
       */
      async startWatching() {
        if (this.watchStarted) {
          debugLogger58.debug("Skill watching already started, skipping");
          return;
        }
        debugLogger58.info("Starting skill directory watchers...");
        this.watchStarted = true;
        await this.ensureUserSkillsDir();
        await this.refreshCache();
        this.updateWatchersFromCache();
        debugLogger58.info("Skill directory watchers started");
      }
      /**
       * Stops watching skill directories for changes.
       */
      stopWatching() {
        debugLogger58.info("Stopping skill directory watchers...");
        for (const watcher of this.watchers.values()) {
          void watcher.close().catch((error2) => {
            debugLogger58.warn("Failed to close skills watcher:", error2);
          });
        }
        this.watchers.clear();
        this.watchStarted = false;
        if (this.refreshTimer) {
          clearTimeout(this.refreshTimer);
          this.refreshTimer = null;
        }
        debugLogger58.info("Skill directory watchers stopped");
      }
      /**
       * Parses a SKILL.md file and returns the configuration.
       *
       * @param filePath - Path to the SKILL.md file
       * @param level - Storage level
       * @returns SkillConfig
       * @throws SkillError if parsing fails
       */
      parseSkillFile(filePath, level) {
        return this.parseSkillFileInternal(filePath, level);
      }
      /**
       * Internal implementation of skill file parsing.
       */
      async parseSkillFileInternal(filePath, level) {
        let content;
        try {
          content = await fs44.readFile(filePath, "utf8");
        } catch (error2) {
          const errorMessage = error2 instanceof Error ? error2.message : "Unknown error";
          debugLogger58.error(`Failed to read skill file ${filePath}: ${errorMessage}`);
          const skillError = new SkillError(`Failed to read skill file: ${errorMessage}`, SkillErrorCode.FILE_ERROR);
          this.parseErrors.set(filePath, skillError);
          throw skillError;
        }
        return this.parseSkillContent(content, filePath, level);
      }
      /**
       * Parses skill content from a string.
       *
       * @param content - File content
       * @param filePath - File path for error reporting
       * @param level - Storage level
       * @returns SkillConfig
       * @throws SkillError if parsing fails
       */
      parseSkillContent(content, filePath, level) {
        try {
          const normalizedContent = normalizeSkillFileContent2(content);
          const frontmatterRegex = /^---\n([\s\S]*?)\n---(?:\n|$)([\s\S]*)$/;
          const match2 = normalizedContent.match(frontmatterRegex);
          if (!match2) {
            throw new Error("Invalid format: missing YAML frontmatter");
          }
          const [, frontmatterYaml, body] = match2;
          const frontmatter = parse6(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 allowedToolsRaw = frontmatter["allowedTools"];
          let allowedTools;
          if (allowedToolsRaw !== void 0) {
            if (Array.isArray(allowedToolsRaw)) {
              allowedTools = allowedToolsRaw.map(String);
            } else {
              throw new Error('"allowedTools" must be an array');
            }
          }
          const config2 = {
            name: name3,
            description,
            allowedTools,
            level,
            filePath,
            body: body.trim()
          };
          const validation2 = this.validateConfig(config2);
          if (!validation2.isValid) {
            throw new Error(`Validation failed: ${validation2.errors.join(", ")}`);
          }
          debugLogger58.debug(`Successfully parsed skill: ${name3} (${level}) from ${filePath}`);
          return config2;
        } catch (error2) {
          const skillError = new SkillError(`Failed to parse skill file: ${error2 instanceof Error ? error2.message : "Unknown error"}`, SkillErrorCode.PARSE_ERROR);
          this.parseErrors.set(filePath, skillError);
          throw skillError;
        }
      }
      /**
       * Gets the base directory for skills at a specific level.
       *
       * @param level - Storage level
       * @returns Absolute directory path
       */
      getSkillsBaseDir(level) {
        const baseDir = level === "project" ? path47.join(this.config.getProjectRoot(), QWEN_CONFIG_DIR2, SKILLS_CONFIG_DIR) : path47.join(os18.homedir(), QWEN_CONFIG_DIR2, SKILLS_CONFIG_DIR);
        return baseDir;
      }
      /**
       * Lists skills at a specific level.
       *
       * @param level - Storage level to scan
       * @returns Array of skill configurations
       */
      async listSkillsAtLevel(level) {
        const projectRoot = this.config.getProjectRoot();
        const homeDir = os18.homedir();
        const isHomeDirectory = path47.resolve(projectRoot) === path47.resolve(homeDir);
        if (level === "project" && isHomeDirectory) {
          debugLogger58.debug("Skipping project-level skills: project root is home directory");
          return [];
        }
        if (level === "extension") {
          const extensions = this.config.getActiveExtensions();
          const skills2 = [];
          for (const extension of extensions) {
            extension.skills?.forEach((skill) => {
              skills2.push(skill);
            });
          }
          debugLogger58.debug(`Loaded ${skills2.length} extension-level skills from ${extensions.length} extensions`);
          return skills2;
        }
        const baseDir = this.getSkillsBaseDir(level);
        debugLogger58.debug(`Loading ${level} level skills from: ${baseDir}`);
        const skills = await this.loadSkillsFromDir(baseDir, level);
        debugLogger58.debug(`Loaded ${skills.length} ${level} level skills`);
        return skills;
      }
      async loadSkillsFromDir(baseDir, level) {
        debugLogger58.debug(`Loading skills from directory: ${baseDir}`);
        try {
          const entries = await fs44.readdir(baseDir, { withFileTypes: true });
          const skills = [];
          debugLogger58.debug(`Found ${entries.length} entries in ${baseDir}`);
          for (const entry of entries) {
            const isDirectory = entry.isDirectory();
            const isSymlink = entry.isSymbolicLink();
            if (!isDirectory && !isSymlink) {
              debugLogger58.warn(`Skipping non-directory entry: ${entry.name}`);
              continue;
            }
            const skillDir = path47.join(baseDir, entry.name);
            if (isSymlink) {
              try {
                const targetStat = await fs44.stat(skillDir);
                if (!targetStat.isDirectory()) {
                  debugLogger58.warn(`Skipping symlink ${entry.name} that does not point to a directory`);
                  continue;
                }
              } catch (error2) {
                debugLogger58.warn(`Skipping invalid symlink ${entry.name}: ${error2 instanceof Error ? error2.message : "Unknown error"}`);
                continue;
              }
            }
            const skillManifest = path47.join(skillDir, SKILL_MANIFEST_FILE2);
            try {
              await fs44.access(skillManifest);
              const config2 = await this.parseSkillFileInternal(skillManifest, level);
              skills.push(config2);
            } catch (error2) {
              if (error2 instanceof SkillError) {
                debugLogger58.error(`Failed to parse skill at ${skillDir}: ${error2.message}`);
              } else {
                debugLogger58.debug(`No valid SKILL.md found in ${skillDir}, skipping`);
              }
              continue;
            }
          }
          return skills;
        } catch (error2) {
          const errorMessage = error2 instanceof Error ? error2.message : "Unknown error";
          debugLogger58.debug(`Cannot read skills directory ${baseDir}: ${errorMessage}`);
          return [];
        }
      }
      /**
       * Finds a skill by name at a specific level.
       *
       * @param name - Name of the skill to find
       * @param level - Storage level to search
       * @returns SkillConfig or null if not found
       */
      async findSkillByNameAtLevel(name3, level) {
        await this.ensureLevelCache(level);
        const levelSkills = this.skillsCache?.get(level) || [];
        return levelSkills.find((skill) => skill.name === name3) || null;
      }
      /**
       * Ensures the cache is populated for a specific level without loading other levels.
       */
      async ensureLevelCache(level) {
        if (!this.skillsCache) {
          this.skillsCache = /* @__PURE__ */ new Map();
        }
        if (!this.skillsCache.has(level)) {
          const levelSkills = await this.listSkillsAtLevel(level);
          this.skillsCache.set(level, levelSkills);
        }
      }
      updateWatchersFromCache() {
        const watchTargets = new Set(["project", "user"].map((level) => this.getSkillsBaseDir(level)).filter((baseDir) => fsSync2.existsSync(baseDir)));
        for (const existingPath of this.watchers.keys()) {
          if (!watchTargets.has(existingPath)) {
            void this.watchers.get(existingPath)?.close().catch((error2) => {
              debugLogger58.warn(`Failed to close skills watcher for ${existingPath}:`, error2);
            });
            this.watchers.delete(existingPath);
          }
        }
        for (const watchPath of watchTargets) {
          if (this.watchers.has(watchPath)) {
            continue;
          }
          try {
            const watcher = watch(watchPath, {
              ignoreInitial: true
            }).on("all", () => {
              this.scheduleRefresh();
            }).on("error", (error2) => {
              debugLogger58.warn(`Skills watcher error for ${watchPath}:`, error2);
            });
            this.watchers.set(watchPath, watcher);
          } catch (error2) {
            debugLogger58.warn(`Failed to watch skills directory at ${watchPath}:`, error2);
          }
        }
      }
      scheduleRefresh() {
        if (this.refreshTimer) {
          clearTimeout(this.refreshTimer);
        }
        this.refreshTimer = setTimeout(() => {
          this.refreshTimer = null;
          void this.refreshCache().then(() => this.updateWatchersFromCache());
        }, 150);
      }
      async ensureUserSkillsDir() {
        const baseDir = this.getSkillsBaseDir("user");
        try {
          await fs44.mkdir(baseDir, { recursive: true });
        } catch (error2) {
          debugLogger58.warn(`Failed to create user skills directory at ${baseDir}:`, error2);
        }
      }
    };
    __name(normalizeSkillFileContent2, "normalizeSkillFileContent");
  }
});

// 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_types5();
    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(config2) {
        const errors = [];
        const warnings = [];
        const nameValidation = this.validateName(config2.name);
        if (!nameValidation.isValid) {
          errors.push(...nameValidation.errors);
        }
        if (!config2.description || config2.description.trim().length === 0) {
          errors.push("Description is required and cannot be empty");
        } else if (config2.description.length > 500) {
          warnings.push("Description is quite long (>500 chars), consider shortening for better readability");
        }
        const promptValidation = this.validateSystemPrompt(config2.systemPrompt);
        if (!promptValidation.isValid) {
          errors.push(...promptValidation.errors);
        }
        warnings.push(...promptValidation.warnings);
        if (config2.tools) {
          const toolsValidation = this.validateTools(config2.tools);
          if (!toolsValidation.isValid) {
            errors.push(...toolsValidation.errors);
          }
          warnings.push(...toolsValidation.warnings);
        }
        if (config2.modelConfig) {
          const modelValidation = this.validateModelConfig(config2.modelConfig);
          if (!modelValidation.isValid) {
            errors.push(...modelValidation.errors);
          }
          warnings.push(...modelValidation.warnings);
        }
        if (config2.runConfig) {
          const runValidation = this.validateRunConfig(config2.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(config2, subagentName) {
        const result = this.validateConfig(config2);
        if (!result.isValid) {
          throw new SubagentError(`Validation failed: ${result.errors.join(", ")}`, SubagentErrorCode.VALIDATION_ERROR, subagentName || config2.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((a2) => a2.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 fs45 from "fs/promises";
import * as path48 from "path";
import * as os19 from "os";
async function loadSubagentFromDir(baseDir) {
  try {
    const files = await fs45.readdir(baseDir);
    const subagents = [];
    for (const file of files) {
      if (!file.endsWith(".md"))
        continue;
      const filePath = path48.join(baseDir, file);
      try {
        const content = await fs45.readFile(filePath, "utf8");
        const config2 = parseSubagentContent(content, filePath, "extension", new SubagentValidator());
        subagents.push(config2);
      } catch (_error) {
        continue;
      }
    }
    return subagents;
  } catch (_error) {
    return [];
  }
}
function parseSubagentContent(content, filePath, level, validator) {
  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 = parse6(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 config2 = {
      name: name3,
      description,
      tools,
      systemPrompt: systemPrompt.trim(),
      filePath,
      modelConfig,
      runConfig,
      color,
      level
    };
    const validation2 = validator.validateConfig(config2);
    if (!validation2.isValid) {
      throw new Error(`Validation failed: ${validation2.errors.join(", ")}`);
    }
    return config2;
  } catch (error2) {
    throw new SubagentError(`Failed to parse subagent file: ${error2 instanceof Error ? error2.message : "Unknown error"}`, SubagentErrorCode.INVALID_CONFIG);
  }
}
var debugLogger59, QWEN_CONFIG_DIR3, 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_types5();
    init_validation();
    init_subagent();
    init_debugLogger();
    init_builtin_agents();
    init_tool_names();
    debugLogger59 = createDebugLogger("SUBAGENT_MANAGER");
    QWEN_CONFIG_DIR3 = ".qwen";
    AGENT_CONFIG_DIR = "agents";
    SubagentManager = class {
      static {
        __name(this, "SubagentManager");
      }
      config;
      validator;
      subagentsCache = null;
      changeListeners = /* @__PURE__ */ new Set();
      constructor(config2) {
        this.config = config2;
        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 (error2) {
            debugLogger59.warn("Subagent change listener threw an error:", error2);
          }
        }
      }
      /**
       * Creates a new subagent configuration.
       *
       * @param config - Subagent configuration to create
       * @param options - Creation options
       * @throws SubagentError if creation fails
       */
      async createSubagent(config2, options2) {
        this.validator.validateOrThrow(config2);
        if (options2.level === "session") {
          throw new SubagentError(`Cannot create session-level subagent "${config2.name}". Session agents are read-only and provided at runtime.`, SubagentErrorCode.INVALID_CONFIG, config2.name);
        }
        const filePath = options2.customPath || this.getSubagentPath(config2.name, options2.level);
        if (!options2.overwrite) {
          try {
            await fs45.access(filePath);
            throw new SubagentError(`Subagent "${config2.name}" already exists at ${filePath}`, SubagentErrorCode.ALREADY_EXISTS, config2.name);
          } catch (error2) {
            if (error2 instanceof SubagentError)
              throw error2;
          }
        }
        const dir = path48.dirname(filePath);
        await fs45.mkdir(dir, { recursive: true });
        const finalConfig = {
          ...config2,
          level: options2.level,
          filePath
        };
        const content = this.serializeSubagent(finalConfig);
        try {
          await fs45.writeFile(filePath, content, "utf8");
          await this.refreshCache();
        } catch (error2) {
          throw new SubagentError(`Failed to write subagent file: ${error2 instanceof Error ? error2.message : "Unknown error"}`, SubagentErrorCode.FILE_ERROR, config2.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);
          }
          if (level === "session") {
            const sessionSubagents2 = this.subagentsCache?.get("session") || [];
            return sessionSubagents2.find((agent) => agent.name === name3) || null;
          }
          return this.findSubagentByNameAtLevel(name3, level);
        }
        const sessionSubagents = this.subagentsCache?.get("session") || [];
        const sessionConfig = sessionSubagents.find((agent) => agent.name === name3);
        if (sessionConfig) {
          return sessionConfig;
        }
        const projectConfig = await this.findSubagentByNameAtLevel(name3, "project");
        if (projectConfig) {
          return projectConfig;
        }
        const userConfig = await this.findSubagentByNameAtLevel(name3, "user");
        if (userConfig) {
          return userConfig;
        }
        const extensionConfig = await this.findSubagentByNameAtLevel(name3, "extension");
        if (extensionConfig) {
          return extensionConfig;
        }
        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);
        }
        if (existing.level === "session") {
          throw new SubagentError(`Cannot update session-level subagent "${name3}"`, SubagentErrorCode.INVALID_CONFIG, name3);
        }
        const updatedConfig = this.mergeConfigurations(existing, updates);
        this.validator.validateOrThrow(updatedConfig);
        if (!existing.filePath) {
          throw new SubagentError(`Cannot update subagent "${name3}": no file path available`, SubagentErrorCode.FILE_ERROR, name3);
        }
        const content = this.serializeSubagent(updatedConfig);
        try {
          await fs45.writeFile(existing.filePath, content, "utf8");
          await this.refreshCache();
        } catch (error2) {
          throw new SubagentError(`Failed to update subagent file: ${error2 instanceof Error ? error2.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, extensionName) {
        if (BuiltinAgentRegistry.isBuiltinAgent(name3)) {
          throw new SubagentError(`Cannot delete built-in subagent "${name3}"`, SubagentErrorCode.INVALID_CONFIG, name3);
        }
        if (level === "extension") {
          throw new SubagentError(`Cannot delete subagent "${name3}" in extension "${extensionName}", If needed, you can directly uninstall extension.`, SubagentErrorCode.INVALID_CONFIG, name3);
        }
        const levelsToCheck = level ? [level] : ["project", "user"];
        let deleted = false;
        for (const currentLevel of levelsToCheck) {
          if (currentLevel === "builtin" || currentLevel === "session") {
            continue;
          }
          const config2 = await this.findSubagentByNameAtLevel(name3, currentLevel);
          if (config2 && config2.filePath) {
            try {
              await fs45.unlink(config2.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();
        if (this.config.getSdkMode()) {
          const levelsToCheck2 = options2.level ? [options2.level] : ["session"];
          for (const level of levelsToCheck2) {
            const levelSubagents = this.subagentsCache?.get(level) || [];
            for (const subagent of levelSubagents) {
              if (options2.hasTool && (!subagent.tools || !subagent.tools.includes(options2.hasTool))) {
                continue;
              }
              subagents.push(subagent);
              seenNames.add(subagent.name);
            }
          }
          return subagents;
        }
        const levelsToCheck = options2.level ? [options2.level] : ["project", "user", "builtin", "extension"];
        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((a2, b2) => {
            let comparison = 0;
            switch (options2.sortBy) {
              case "name":
                comparison = a2.name.localeCompare(b2.name);
                break;
              case "level": {
                const levelOrder = {
                  project: 0,
                  user: 1,
                  builtin: 2,
                  session: 3,
                  extension: 4
                };
                comparison = levelOrder[a2.level] - levelOrder[b2.level];
                break;
              }
              default:
                comparison = 0;
                break;
            }
            return options2.sortOrder === "desc" ? -comparison : comparison;
          });
        }
        return subagents;
      }
      /**
       * Loads session-level subagents into the cache.
       * Session subagents are provided directly via config and are read-only.
       *
       * @param subagents - Array of session subagent configurations
       */
      loadSessionSubagents(subagents) {
        if (!this.subagentsCache) {
          this.subagentsCache = /* @__PURE__ */ new Map();
        }
        const sessionSubagents = subagents.map((config2) => ({
          ...config2,
          level: "session",
          filePath: `<session:${config2.name}>`
        }));
        this.subagentsCache.set("session", sessionSubagents);
        this.notifyChangeListeners();
      }
      /**
       * 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", "extension"];
        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 config2 = await this.loadSubagent(name3, level);
        if (!config2) {
          return null;
        }
        return config2;
      }
      /**
       * 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 fs45.readFile(filePath, "utf8");
        } catch (error2) {
          throw new SubagentError(`Failed to read subagent file: ${error2 instanceof Error ? error2.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) {
        return parseSubagentContent(content, filePath, level, this.validator);
      }
      /**
       * Serializes a subagent configuration to Markdown format.
       *
       * @param config - Configuration to serialize
       * @returns Markdown content with YAML frontmatter
       */
      serializeSubagent(config2) {
        const frontmatter = {
          name: config2.name,
          description: config2.description
        };
        if (config2.tools && config2.tools.length > 0) {
          frontmatter["tools"] = config2.tools;
        }
        if (config2.modelConfig) {
          frontmatter["modelConfig"] = config2.modelConfig;
        }
        if (config2.runConfig) {
          frontmatter["runConfig"] = config2.runConfig;
        }
        if (config2.color && config2.color !== "auto") {
          frontmatter["color"] = config2.color;
        }
        const yamlContent = stringify2(frontmatter, {
          lineWidth: 0,
          // Disable line wrapping
          minContentWidth: 0
        }).trim();
        return `---
${yamlContent}
---

${config2.systemPrompt}
`;
      }
      /**
       * Creates a SubAgentScope from a subagent configuration.
       *
       * @param config - Subagent configuration
       * @param runtimeContext - Runtime context
       * @returns Promise resolving to SubAgentScope
       */
      async createSubagentScope(config2, runtimeContext, options2) {
        try {
          const runtimeConfig = this.convertToRuntimeConfig(config2);
          return await SubAgentScope.create(config2.name, runtimeContext, runtimeConfig.promptConfig, runtimeConfig.modelConfig, runtimeConfig.runConfig, runtimeConfig.toolConfig, options2?.eventEmitter, options2?.hooks);
        } catch (error2) {
          if (error2 instanceof Error) {
            throw new SubagentError(`Failed to create SubAgentScope: ${error2.message}`, SubagentErrorCode.INVALID_CONFIG, config2.name);
          }
          throw error2;
        }
      }
      /**
       * Converts a file-based SubagentConfig to runtime configuration
       * compatible with SubAgentScope.create().
       *
       * @param config - File-based subagent configuration
       * @returns Runtime configuration for SubAgentScope
       */
      convertToRuntimeConfig(config2) {
        const promptConfig = {
          systemPrompt: config2.systemPrompt
        };
        const modelConfig = {
          ...config2.modelConfig
        };
        const runConfig = {
          ...config2.runConfig
        };
        let toolConfig;
        if (config2.tools && config2.tools.length > 0) {
          const toolNames = this.transformToToolNames(config2.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);
          debugLogger59.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}>`;
        }
        if (level === "session") {
          return `<session:${name3}>`;
        }
        const baseDir = level === "project" ? path48.join(this.config.getProjectRoot(), QWEN_CONFIG_DIR3, AGENT_CONFIG_DIR) : path48.join(os19.homedir(), QWEN_CONFIG_DIR3, AGENT_CONFIG_DIR);
        return path48.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();
        }
        if (level === "extension") {
          const extensions = this.config.getActiveExtensions();
          return extensions.flatMap((extension) => extension.agents || []);
        }
        const projectRoot = this.config.getProjectRoot();
        const homeDir = os19.homedir();
        const isHomeDirectory = path48.resolve(projectRoot) === path48.resolve(homeDir);
        if (level === "project" && isHomeDirectory) {
          return [];
        }
        let baseDir = level === "project" ? projectRoot : homeDir;
        baseDir = path48.join(baseDir, QWEN_CONFIG_DIR3, AGENT_CONFIG_DIR);
        try {
          const files = await fs45.readdir(baseDir);
          const subagents = [];
          for (const file of files) {
            if (!file.endsWith(".md"))
              continue;
            const filePath = path48.join(baseDir, file);
            try {
              const config2 = await this.parseSubagentFile(filePath, level);
              subagents.push(config2);
            } 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;
      }
    };
    __name(loadSubagentFromDir, "loadSubagentFromDir");
    __name(parseSubagentContent, "parseSubagentContent");
  }
});

// packages/core/dist/src/extension/variableSchema.js
var PATH_SEPARATOR_DEFINITION, VARIABLE_SCHEMA;
var init_variableSchema = __esm({
  "packages/core/dist/src/extension/variableSchema.js"() {
    "use strict";
    init_esbuild_shims();
    PATH_SEPARATOR_DEFINITION = {
      type: "string",
      description: "The path separator."
    };
    VARIABLE_SCHEMA = {
      extensionPath: {
        type: "string",
        description: "The path of the extension in the filesystem."
      },
      CLAUDE_PLUGIN_ROOT: {
        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/core/dist/src/extension/variables.js
import path49 from "node:path";
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}`);
    }
  }
}
function hydrateString(str2, context2) {
  validateVariables(context2, VARIABLE_SCHEMA);
  const regex3 = /\${(.*?)}/g;
  return str2.replace(regex3, (match2, key) => context2[key] == null ? match2 : context2[key]);
}
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;
}
var EXTENSIONS_DIRECTORY_NAME, EXTENSIONS_CONFIG_FILENAME, INSTALL_METADATA_FILENAME, EXTENSION_SETTINGS_FILENAME;
var init_variables = __esm({
  "packages/core/dist/src/extension/variables.js"() {
    "use strict";
    init_esbuild_shims();
    init_variableSchema();
    init_storage();
    EXTENSIONS_DIRECTORY_NAME = path49.join(QWEN_DIR2, "extensions");
    EXTENSIONS_CONFIG_FILENAME = "qwen-extension.json";
    INSTALL_METADATA_FILENAME = ".qwen-extension-install.json";
    EXTENSION_SETTINGS_FILENAME = ".env";
    __name(validateVariables, "validateVariables");
    __name(hydrateString, "hydrateString");
    __name(recursivelyHydrateStrings, "recursivelyHydrateStrings");
  }
});

// packages/core/dist/src/utils/envVarResolver.js
function resolveEnvVarsInString(value, customEnv) {
  const envVarRegex = /\$(?:(\w+)|{([^}]+)})/g;
  return value.replace(envVarRegex, (match2, varName1, varName2) => {
    const varName = varName1 || varName2;
    if (customEnv && typeof customEnv[varName] === "string") {
      return customEnv[varName];
    }
    if (process && process.env && typeof process.env[varName] === "string") {
      return process.env[varName];
    }
    return match2;
  });
}
function resolveEnvVarsInObject(obj, customEnv) {
  return resolveEnvVarsInObjectInternal(obj, /* @__PURE__ */ new WeakSet(), customEnv);
}
function resolveEnvVarsInObjectInternal(obj, visited, customEnv) {
  if (obj === null || obj === void 0 || typeof obj === "boolean" || typeof obj === "number") {
    return obj;
  }
  if (typeof obj === "string") {
    return resolveEnvVarsInString(obj, customEnv);
  }
  if (Array.isArray(obj)) {
    if (visited.has(obj)) {
      return [...obj];
    }
    visited.add(obj);
    const result = obj.map((item) => resolveEnvVarsInObjectInternal(item, visited, customEnv));
    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, customEnv);
      }
    }
    visited.delete(obj);
    return newObj;
  }
  return obj;
}
var init_envVarResolver = __esm({
  "packages/core/dist/src/utils/envVarResolver.js"() {
    "use strict";
    init_esbuild_shims();
    __name(resolveEnvVarsInString, "resolveEnvVarsInString");
    __name(resolveEnvVarsInObject, "resolveEnvVarsInObject");
    __name(resolveEnvVarsInObjectInternal, "resolveEnvVarsInObjectInternal");
  }
});

// node_modules/@isaacs/fs-minipass/dist/esm/index.js
import EE from "events";
import fs46 from "fs";
var writev, _autoClose, _close, _ended, _fd, _finished, _flags, _flush, _handleChunk, _makeBuf, _mode, _needDrain, _onerror, _onopen, _onread, _onwrite, _open, _path, _pos, _queue, _read, _readSize, _reading, _remain, _size2, _write, _writing, _defaultFlag, _errored, ReadStream, ReadStreamSync, WriteStream, WriteStreamSync;
var init_esm22 = __esm({
  "node_modules/@isaacs/fs-minipass/dist/esm/index.js"() {
    init_esbuild_shims();
    init_esm9();
    writev = fs46.writev;
    _autoClose = Symbol("_autoClose");
    _close = Symbol("_close");
    _ended = Symbol("_ended");
    _fd = Symbol("_fd");
    _finished = Symbol("_finished");
    _flags = Symbol("_flags");
    _flush = Symbol("_flush");
    _handleChunk = Symbol("_handleChunk");
    _makeBuf = Symbol("_makeBuf");
    _mode = Symbol("_mode");
    _needDrain = Symbol("_needDrain");
    _onerror = Symbol("_onerror");
    _onopen = Symbol("_onopen");
    _onread = Symbol("_onread");
    _onwrite = Symbol("_onwrite");
    _open = Symbol("_open");
    _path = Symbol("_path");
    _pos = Symbol("_pos");
    _queue = Symbol("_queue");
    _read = Symbol("_read");
    _readSize = Symbol("_readSize");
    _reading = Symbol("_reading");
    _remain = Symbol("_remain");
    _size2 = Symbol("_size");
    _write = Symbol("_write");
    _writing = Symbol("_writing");
    _defaultFlag = Symbol("_defaultFlag");
    _errored = Symbol("_errored");
    ReadStream = class extends Minipass {
      static {
        __name(this, "ReadStream");
      }
      [_errored] = false;
      [_fd];
      [_path];
      [_readSize];
      [_reading] = false;
      [_size2];
      [_remain];
      [_autoClose];
      constructor(path125, opt) {
        opt = opt || {};
        super(opt);
        this.readable = true;
        this.writable = false;
        if (typeof path125 !== "string") {
          throw new TypeError("path must be a string");
        }
        this[_errored] = false;
        this[_fd] = typeof opt.fd === "number" ? opt.fd : void 0;
        this[_path] = path125;
        this[_readSize] = opt.readSize || 16 * 1024 * 1024;
        this[_reading] = false;
        this[_size2] = typeof opt.size === "number" ? opt.size : Infinity;
        this[_remain] = this[_size2];
        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]() {
        fs46.open(this[_path], "r", (er2, fd) => this[_onopen](er2, fd));
      }
      [_onopen](er2, fd) {
        if (er2) {
          this[_onerror](er2);
        } 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));
          }
          fs46.read(this[_fd], buf, 0, buf.length, null, (er2, br3, b2) => this[_onread](er2, br3, b2));
        }
      }
      [_onread](er2, br3, buf) {
        this[_reading] = false;
        if (er2) {
          this[_onerror](er2);
        } else if (this[_handleChunk](br3, buf)) {
          this[_read]();
        }
      }
      [_close]() {
        if (this[_autoClose] && typeof this[_fd] === "number") {
          const fd = this[_fd];
          this[_fd] = void 0;
          fs46.close(fd, (er2) => er2 ? this.emit("error", er2) : this.emit("close"));
        }
      }
      [_onerror](er2) {
        this[_reading] = true;
        this[_close]();
        this.emit("error", er2);
      }
      [_handleChunk](br3, buf) {
        let ret = false;
        this[_remain] -= br3;
        if (br3 > 0) {
          ret = super.write(br3 < buf.length ? buf.subarray(0, br3) : buf);
        }
        if (br3 === 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);
        }
      }
    };
    ReadStreamSync = class extends ReadStream {
      static {
        __name(this, "ReadStreamSync");
      }
      [_open]() {
        let threw = true;
        try {
          this[_onopen](null, fs46.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 br3 = buf.length === 0 ? 0 : fs46.readSync(this[_fd], buf, 0, buf.length, null);
              if (!this[_handleChunk](br3, 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;
          fs46.closeSync(fd);
          this.emit("close");
        }
      }
    };
    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(path125, opt) {
        opt = opt || {};
        super(opt);
        this[_path] = path125;
        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](er2) {
        this[_close]();
        this[_writing] = true;
        this.emit("error", er2);
      }
      [_open]() {
        fs46.open(this[_path], this[_flags], this[_mode], (er2, fd) => this[_onopen](er2, fd));
      }
      [_onopen](er2, fd) {
        if (this[_defaultFlag] && this[_flags] === "r+" && er2 && er2.code === "ENOENT") {
          this[_flags] = "w";
          this[_open]();
        } else if (er2) {
          this[_onerror](er2);
        } 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) {
        fs46.write(this[_fd], buf, 0, buf.length, this[_pos], (er2, bw) => this[_onwrite](er2, bw));
      }
      [_onwrite](er2, bw) {
        if (er2) {
          this[_onerror](er2);
        } 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], (er2, bw) => this[_onwrite](er2, bw));
        }
      }
      [_close]() {
        if (this[_autoClose] && typeof this[_fd] === "number") {
          const fd = this[_fd];
          this[_fd] = void 0;
          fs46.close(fd, (er2) => er2 ? this.emit("error", er2) : this.emit("close"));
        }
      }
    };
    WriteStreamSync = class extends WriteStream {
      static {
        __name(this, "WriteStreamSync");
      }
      [_open]() {
        let fd;
        if (this[_defaultFlag] && this[_flags] === "r+") {
          try {
            fd = fs46.openSync(this[_path], this[_flags], this[_mode]);
          } catch (er2) {
            if (er2?.code === "ENOENT") {
              this[_flags] = "w";
              return this[_open]();
            } else {
              throw er2;
            }
          }
        } else {
          fd = fs46.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;
          fs46.closeSync(fd);
          this.emit("close");
        }
      }
      [_write](buf) {
        let threw = true;
        try {
          this[_onwrite](null, fs46.writeSync(this[_fd], buf, 0, buf.length, this[_pos]));
          threw = false;
        } finally {
          if (threw) {
            try {
              this[_close]();
            } catch {
            }
          }
        }
      }
    };
  }
});

// node_modules/tar/dist/esm/options.js
var argmap, isSyncFile, isAsyncFile, isSyncNoFile, isAsyncNoFile, isFile2, dealiasKey, dealias;
var init_options = __esm({
  "node_modules/tar/dist/esm/options.js"() {
    init_esbuild_shims();
    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"]
    ]);
    isSyncFile = /* @__PURE__ */ __name((o3) => !!o3.sync && !!o3.file, "isSyncFile");
    isAsyncFile = /* @__PURE__ */ __name((o3) => !o3.sync && !!o3.file, "isAsyncFile");
    isSyncNoFile = /* @__PURE__ */ __name((o3) => !!o3.sync && !o3.file, "isSyncNoFile");
    isAsyncNoFile = /* @__PURE__ */ __name((o3) => !o3.sync && !o3.file, "isAsyncNoFile");
    isFile2 = /* @__PURE__ */ __name((o3) => !!o3.file, "isFile");
    dealiasKey = /* @__PURE__ */ __name((k2) => {
      const d2 = argmap.get(k2);
      if (d2)
        return d2;
      return k2;
    }, "dealiasKey");
    dealias = /* @__PURE__ */ __name((opt = {}) => {
      if (!opt)
        return {};
      const result = {};
      for (const [key, v2] of Object.entries(opt)) {
        const k2 = dealiasKey(key);
        result[k2] = v2;
      }
      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;
var init_make_command = __esm({
  "node_modules/tar/dist/esm/make-command.js"() {
    init_esbuild_shims();
    init_options();
    makeCommand = /* @__PURE__ */ __name((syncFile, asyncFile, syncNoFile, asyncNoFile, validate3) => {
      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_);
        validate3?.(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 p2 = asyncFile(opt, entries);
          const c4 = cb ? cb : void 0;
          return c4 ? p2.then(() => c4(), c4) : p2;
        } 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: validate3
      });
    }, "makeCommand");
  }
});

// node_modules/minizlib/dist/esm/constants.js
import realZlib from "zlib";
var realZlibConstants, constants;
var init_constants7 = __esm({
  "node_modules/minizlib/dist/esm/constants.js"() {
    init_esbuild_shims();
    realZlibConstants = realZlib.constants || { ZLIB_VERNUM: 4736 };
    constants = 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
import assert2 from "assert";
import { Buffer as Buffer6 } from "buffer";
import * as realZlib2 from "zlib";
var OriginalBufferConcat, desc, noop4, passthroughBufferConcat, _superWrite, ZlibError, _flushFlag, ZlibBase, Zlib, Gzip, Unzip, Brotli, BrotliCompress, BrotliDecompress, Zstd, ZstdCompress, ZstdDecompress;
var init_esm23 = __esm({
  "node_modules/minizlib/dist/esm/index.js"() {
    init_esbuild_shims();
    init_esm9();
    init_constants7();
    init_constants7();
    OriginalBufferConcat = Buffer6.concat;
    desc = Object.getOwnPropertyDescriptor(Buffer6, "concat");
    noop4 = /* @__PURE__ */ __name((args) => args, "noop");
    passthroughBufferConcat = desc?.writable === true || desc?.set !== void 0 ? (makeNoOp) => {
      Buffer6.concat = makeNoOp ? noop4 : OriginalBufferConcat;
    } : (_2) => {
    };
    _superWrite = Symbol("_superWrite");
    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";
      }
    };
    _flushFlag = Symbol("flushFlag");
    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 (er2) {
          throw new ZlibError(er2, this.constructor);
        }
        this.#onError = (err) => {
          if (this.#sawError)
            return;
          this.#sawError = true;
          this.close();
          this.emit("error", err);
        };
        this.#handle?.on("error", (er2) => this.#onError(new ZlibError(er2)));
        this.once("end", () => this.close);
      }
      close() {
        if (this.#handle) {
          this.#handle.close();
          this.#handle = void 0;
          this.emit("close");
        }
      }
      reset() {
        if (!this.#sawError) {
          assert2(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(Buffer6.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 = Buffer6.from(chunk, encoding);
        if (this.#sawError)
          return;
        assert2(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", (er2) => this.#onError(new ZlibError(er2, this.write)));
        let writeReturn;
        if (result) {
          if (Array.isArray(result) && result.length > 0) {
            const r5 = result[0];
            writeReturn = this[_superWrite](Buffer6.from(r5));
            for (let i3 = 1; i3 < result.length; i3++) {
              writeReturn = this[_superWrite](result[i3]);
            }
          } else {
            writeReturn = this[_superWrite](Buffer6.from(result));
          }
        }
        if (cb)
          cb();
        return writeReturn;
      }
    };
    Zlib = class extends ZlibBase {
      static {
        __name(this, "Zlib");
      }
      #level;
      #strategy;
      constructor(opts, mode) {
        opts = opts || {};
        opts.flush = opts.flush || constants.Z_NO_FLUSH;
        opts.finishFlush = opts.finishFlush || constants.Z_FINISH;
        opts.fullFlushFlag = constants.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(constants.Z_SYNC_FLUSH);
          assert2(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;
          }
        }
      }
    };
    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);
      }
    };
    Unzip = class extends Zlib {
      static {
        __name(this, "Unzip");
      }
      constructor(opts) {
        super(opts, "Unzip");
      }
    };
    Brotli = class extends ZlibBase {
      static {
        __name(this, "Brotli");
      }
      constructor(opts, mode) {
        opts = opts || {};
        opts.flush = opts.flush || constants.BROTLI_OPERATION_PROCESS;
        opts.finishFlush = opts.finishFlush || constants.BROTLI_OPERATION_FINISH;
        opts.fullFlushFlag = constants.BROTLI_OPERATION_FLUSH;
        super(opts, mode);
      }
    };
    BrotliCompress = class extends Brotli {
      static {
        __name(this, "BrotliCompress");
      }
      constructor(opts) {
        super(opts, "BrotliCompress");
      }
    };
    BrotliDecompress = class extends Brotli {
      static {
        __name(this, "BrotliDecompress");
      }
      constructor(opts) {
        super(opts, "BrotliDecompress");
      }
    };
    Zstd = class extends ZlibBase {
      static {
        __name(this, "Zstd");
      }
      constructor(opts, mode) {
        opts = opts || {};
        opts.flush = opts.flush || constants.ZSTD_e_continue;
        opts.finishFlush = opts.finishFlush || constants.ZSTD_e_end;
        opts.fullFlushFlag = constants.ZSTD_e_flush;
        super(opts, mode);
      }
    };
    ZstdCompress = class extends Zstd {
      static {
        __name(this, "ZstdCompress");
      }
      constructor(opts) {
        super(opts, "ZstdCompress");
      }
    };
    ZstdDecompress = class extends Zstd {
      static {
        __name(this, "ZstdDecompress");
      }
      constructor(opts) {
        super(opts, "ZstdDecompress");
      }
    };
  }
});

// node_modules/tar/dist/esm/large-numbers.js
var encode2, encodePositive, encodeNegative, parse7, twos, pos, onesComp, twosComp;
var init_large_numbers = __esm({
  "node_modules/tar/dist/esm/large-numbers.js"() {
    init_esbuild_shims();
    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");
    encodePositive = /* @__PURE__ */ __name((num, buf) => {
      buf[0] = 128;
      for (var i3 = buf.length; i3 > 1; i3--) {
        buf[i3 - 1] = num & 255;
        num = Math.floor(num / 256);
      }
    }, "encodePositive");
    encodeNegative = /* @__PURE__ */ __name((num, buf) => {
      buf[0] = 255;
      var flipped = false;
      num = num * -1;
      for (var i3 = buf.length; i3 > 1; i3--) {
        var byte = num & 255;
        num = Math.floor(num / 256);
        if (flipped) {
          buf[i3 - 1] = onesComp(byte);
        } else if (byte === 0) {
          buf[i3 - 1] = 0;
        } else {
          flipped = true;
          buf[i3 - 1] = twosComp(byte);
        }
      }
    }, "encodeNegative");
    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");
    twos = /* @__PURE__ */ __name((buf) => {
      var len = buf.length;
      var sum = 0;
      var flipped = false;
      for (var i3 = len - 1; i3 > -1; i3--) {
        var byte = Number(buf[i3]);
        var f5;
        if (flipped) {
          f5 = onesComp(byte);
        } else if (byte === 0) {
          f5 = byte;
        } else {
          flipped = true;
          f5 = twosComp(byte);
        }
        if (f5 !== 0) {
          sum -= f5 * Math.pow(256, len - i3 - 1);
        }
      }
      return sum;
    }, "twos");
    pos = /* @__PURE__ */ __name((buf) => {
      var len = buf.length;
      var sum = 0;
      for (var i3 = len - 1; i3 > -1; i3--) {
        var byte = Number(buf[i3]);
        if (byte !== 0) {
          sum += byte * Math.pow(256, len - i3 - 1);
        }
      }
      return sum;
    }, "pos");
    onesComp = /* @__PURE__ */ __name((byte) => (255 ^ byte) & 255, "onesComp");
    twosComp = /* @__PURE__ */ __name((byte) => (255 ^ byte) + 1 & 255, "twosComp");
  }
});

// node_modules/tar/dist/esm/types.js
var isCode, name2, code;
var init_types12 = __esm({
  "node_modules/tar/dist/esm/types.js"() {
    init_esbuild_shims();
    isCode = /* @__PURE__ */ __name((c4) => name2.has(c4), "isCode");
    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"]
    ]);
    code = new Map(Array.from(name2).map((kv) => [kv[1], kv[0]]));
  }
});

// node_modules/tar/dist/esm/header.js
import { posix as pathModule } from "node:path";
var Header, splitPrefix, decString, decDate, numToDate, decNumber, nanUndef, decSmallNumber, MAXNUM, encNumber, encSmallNumber, octalString, padOctal, encDate, NULLS, encString;
var init_header = __esm({
  "node_modules/tar/dist/esm/header.js"() {
    init_esbuild_shims();
    init_large_numbers();
    init_types12();
    Header = 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 = ex?.path ?? decString(buf, off, 100);
        this.mode = ex?.mode ?? gex?.mode ?? decNumber(buf, off + 100, 8);
        this.uid = ex?.uid ?? gex?.uid ?? decNumber(buf, off + 108, 8);
        this.gid = ex?.gid ?? gex?.gid ?? decNumber(buf, off + 116, 8);
        this.size = ex?.size ?? gex?.size ?? decNumber(buf, off + 124, 12);
        this.mtime = ex?.mtime ?? gex?.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 t5 = decString(buf, off + 156, 1);
        if (isCode(t5)) {
          this.#type = t5 || "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 = ex?.uname ?? gex?.uname ?? decString(buf, off + 265, 32);
          this.gname = ex?.gname ?? gex?.gname ?? decString(buf, off + 297, 32);
          this.devmaj = ex?.devmaj ?? gex?.devmaj ?? decNumber(buf, off + 329, 8) ?? 0;
          this.devmin = ex?.devmin ?? gex?.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 = ex?.atime ?? gex?.atime ?? decDate(buf, off + 476, 12);
            this.ctime = ex?.ctime ?? gex?.ctime ?? decDate(buf, off + 488, 12);
          }
        }
        let sum = 8 * 32;
        for (let i3 = off; i3 < off + 148; i3++) {
          sum += buf[i3];
        }
        for (let i3 = off + 156; i3 < off + 512; i3++) {
          sum += buf[i3];
        }
        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(([k2, v2]) => {
          return !(v2 === null || v2 === void 0 || k2 === "path" && gex || k2 === "linkpath" && gex || k2 === "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 path125 = split[0];
        const prefix = split[1];
        this.needPax = !!split[2];
        this.needPax = encString(buf, off, 100, path125) || 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 i3 = off; i3 < off + 148; i3++) {
          sum += buf[i3];
        }
        for (let i3 = off + 156; i3 < off + 512; i3++) {
          sum += buf[i3];
        }
        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 c4 = String(code.get(type));
        if (isCode(c4) || c4 === "Unsupported") {
          this.#type = c4;
        } else if (isCode(type)) {
          this.#type = type;
        } else {
          throw new TypeError("invalid entry type: " + type);
        }
      }
    };
    splitPrefix = /* @__PURE__ */ __name((p2, prefixSize) => {
      const pathSize = 100;
      let pp = p2;
      let prefix = "";
      let ret = void 0;
      const root = pathModule.parse(p2).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 = [p2.slice(0, pathSize - 1), "", true];
        }
      }
      return ret;
    }, "splitPrefix");
    decString = /* @__PURE__ */ __name((buf, off, size) => buf.subarray(off, off + size).toString("utf8").replace(/\0.*/, ""), "decString");
    decDate = /* @__PURE__ */ __name((buf, off, size) => numToDate(decNumber(buf, off, size)), "decDate");
    numToDate = /* @__PURE__ */ __name((num) => num === void 0 ? void 0 : new Date(num * 1e3), "numToDate");
    decNumber = /* @__PURE__ */ __name((buf, off, size) => Number(buf[off]) & 128 ? parse7(buf.subarray(off, off + size)) : decSmallNumber(buf, off, size), "decNumber");
    nanUndef = /* @__PURE__ */ __name((value) => isNaN(value) ? void 0 : value, "nanUndef");
    decSmallNumber = /* @__PURE__ */ __name((buf, off, size) => nanUndef(parseInt(buf.subarray(off, off + size).toString("utf8").replace(/\0.*$/, "").trim(), 8)), "decSmallNumber");
    MAXNUM = {
      12: 8589934591,
      8: 2097151
    };
    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");
    encSmallNumber = /* @__PURE__ */ __name((buf, off, size, num) => buf.write(octalString(num, size), off, size, "ascii"), "encSmallNumber");
    octalString = /* @__PURE__ */ __name((num, size) => padOctal(Math.floor(num).toString(8), size), "octalString");
    padOctal = /* @__PURE__ */ __name((str2, size) => (str2.length === size - 1 ? str2 : new Array(size - str2.length - 1).join("0") + str2 + " ") + "\0", "padOctal");
    encDate = /* @__PURE__ */ __name((buf, off, size, date4) => date4 === void 0 ? false : encNumber(buf, off, size, date4.getTime() / 1e3), "encDate");
    NULLS = new Array(156).join("\0");
    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
import { basename as basename12 } from "node:path";
var Pax, merge3, parseKV, parseKVLine;
var init_pax = __esm({
  "node_modules/tar/dist/esm/pax.js"() {
    init_esbuild_shims();
    init_header();
    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 i3 = 0; i3 < 512; i3++) {
          buf[i3] = 0;
        }
        new Header({
          // XXX split the path
          // then the path should be PaxHeader + basename, but less than 99,
          // prepend with the dirname
          /* c8 ignore start */
          path: ("PaxHeader/" + basename12(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 i3 = bodyLen + 512; i3 < buf.length; i3++) {
          buf[i3] = 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 r5 = this[field];
        const v2 = r5 instanceof Date ? r5.getTime() / 1e3 : r5;
        const s5 = " " + (field === "dev" || field === "ino" || field === "nlink" ? "SCHILY." : "") + field + "=" + v2 + "\n";
        const byteLen = Buffer.byteLength(s5);
        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 + s5;
      }
      static parse(str2, ex, g2 = false) {
        return new _Pax(merge3(parseKV(str2), ex), g2);
      }
    };
    merge3 = /* @__PURE__ */ __name((a2, b2) => b2 ? Object.assign({}, b2, a2) : a2, "merge");
    parseKV = /* @__PURE__ */ __name((str2) => str2.replace(/\n$/, "").split("\n").reduce(parseKVLine, /* @__PURE__ */ Object.create(null)), "parseKV");
    parseKVLine = /* @__PURE__ */ __name((set, line) => {
      const n3 = parseInt(line, 10);
      if (n3 !== Buffer.byteLength(line) + 1) {
        return set;
      }
      line = line.slice((n3 + " ").length);
      const kv = line.split("=");
      const r5 = kv.shift();
      if (!r5) {
        return set;
      }
      const k2 = r5.replace(/^SCHILY\.(dev|ino|nlink)/, "$1");
      const v2 = kv.join("=");
      set[k2] = /^([A-Z]+\.)?([mac]|birth|creation)time$/.test(k2) ? new Date(Number(v2) * 1e3) : /^[0-9]+$/.test(v2) ? +v2 : v2;
      return set;
    }, "parseKVLine");
  }
});

// node_modules/tar/dist/esm/normalize-windows-path.js
var platform6, normalizeWindowsPath;
var init_normalize_windows_path = __esm({
  "node_modules/tar/dist/esm/normalize-windows-path.js"() {
    init_esbuild_shims();
    platform6 = process.env.TESTING_TAR_FAKE_PLATFORM || process.platform;
    normalizeWindowsPath = platform6 !== "win32" ? (p2) => p2 : (p2) => p2 && p2.replace(/\\/g, "/");
  }
});

// node_modules/tar/dist/esm/read-entry.js
var ReadEntry;
var init_read_entry = __esm({
  "node_modules/tar/dist/esm/read-entry.js"() {
    init_esbuild_shims();
    init_esm9();
    init_normalize_windows_path();
    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 r5 = this.remain;
        const br3 = this.blockRemain;
        this.remain = Math.max(0, r5 - writeLen);
        this.blockRemain = Math.max(0, br3 - writeLen);
        if (this.ignore) {
          return true;
        }
        if (r5 >= writeLen) {
          return super.write(data);
        }
        return super.write(data.subarray(0, r5));
      }
      #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(([k2, v2]) => {
          return !(v2 === null || v2 === void 0 || k2 === "path" && gex);
        })));
      }
    };
  }
});

// node_modules/tar/dist/esm/warn-method.js
var warnMethod;
var init_warn_method = __esm({
  "node_modules/tar/dist/esm/warn-method.js"() {
    init_esbuild_shims();
    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
import { EventEmitter as EE2 } from "events";
var maxMetaEntrySize, gzipHeader, zstdHeader, ZIP_HEADER_LEN, STATE, WRITEENTRY, READENTRY, NEXTENTRY, PROCESSENTRY, EX, GEX, META, EMITMETA, BUFFER2, QUEUE, ENDED, EMITTEDEND, EMIT, UNZIP, CONSUMECHUNK, CONSUMECHUNKSUB, CONSUMEBODY, CONSUMEMETA, CONSUMEHEADER, CONSUMING, BUFFERCONCAT, MAYBEEND, WRITING, ABORTED2, DONE, SAW_VALID_ENTRY, SAW_NULL_BLOCK, SAW_EOF, CLOSESTREAM, noop5, Parser2;
var init_parse5 = __esm({
  "node_modules/tar/dist/esm/parse.js"() {
    init_esbuild_shims();
    init_esm23();
    init_header();
    init_pax();
    init_read_entry();
    init_warn_method();
    maxMetaEntrySize = 1024 * 1024;
    gzipHeader = Buffer.from([31, 139]);
    zstdHeader = Buffer.from([40, 181, 47, 253]);
    ZIP_HEADER_LEN = Math.max(gzipHeader.length, zstdHeader.length);
    STATE = Symbol("state");
    WRITEENTRY = Symbol("writeEntry");
    READENTRY = Symbol("readEntry");
    NEXTENTRY = Symbol("nextEntry");
    PROCESSENTRY = Symbol("processEntry");
    EX = Symbol("extendedHeader");
    GEX = Symbol("globalExtendedHeader");
    META = Symbol("meta");
    EMITMETA = Symbol("emitMeta");
    BUFFER2 = Symbol("buffer");
    QUEUE = Symbol("queue");
    ENDED = Symbol("ended");
    EMITTEDEND = Symbol("emittedEnd");
    EMIT = Symbol("emit");
    UNZIP = Symbol("unzip");
    CONSUMECHUNK = Symbol("consumeChunk");
    CONSUMECHUNKSUB = Symbol("consumeChunkSub");
    CONSUMEBODY = Symbol("consumeBody");
    CONSUMEMETA = Symbol("consumeMeta");
    CONSUMEHEADER = Symbol("consumeHeader");
    CONSUMING = Symbol("consuming");
    BUFFERCONCAT = Symbol("bufferConcat");
    MAYBEEND = Symbol("maybeEnd");
    WRITING = Symbol("writing");
    ABORTED2 = Symbol("aborted");
    DONE = Symbol("onDone");
    SAW_VALID_ENTRY = Symbol("sawValidEntry");
    SAW_NULL_BLOCK = Symbol("sawNullBlock");
    SAW_EOF = Symbol("sawEOF");
    CLOSESTREAM = Symbol("closeStream");
    noop5 = /* @__PURE__ */ __name(() => true, "noop");
    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 Header(chunk, position, this[EX], this[GEX]);
        } catch (er2) {
          return this.warn("TAR_ENTRY_INVALID", er2);
        }
        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", (c4) => this[META] += c4);
                  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 re3 = this[READENTRY];
          const drainNow = !re3 || re3.flowing || re3.size === re3.remain;
          if (drainNow) {
            if (!this[WRITING]) {
              this.emit("drain");
            }
          } else {
            re3.once("drain", () => this.emit("drain"));
          }
        }
      }
      [CONSUMEBODY](chunk, position) {
        const entry = this[WRITEENTRY];
        if (!entry) {
          throw new Error("attempt to consume body without entry??");
        }
        const br3 = entry.blockRemain ?? 0;
        const c4 = br3 >= chunk.length && position === 0 ? chunk : chunk.subarray(position, position + br3);
        entry.write(c4);
        if (!entry.blockRemain) {
          this[STATE] = "header";
          this[WRITEENTRY] = void 0;
          entry.end();
        }
        return c4.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(error2) {
        this[ABORTED2] = true;
        this.emit("abort", error2);
        this.warn("TAR_ABORT", error2, { 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 i3 = 0; this[UNZIP] === void 0 && i3 < gzipHeader.length; i3++) {
            if (chunk[i3] !== gzipHeader[i3]) {
              this[UNZIP] = false;
            }
          }
          let isZstd = false;
          if (this[UNZIP] === false && this.zstd !== false) {
            isZstd = true;
            for (let i3 = 0; i3 < zstdHeader.length; i3++) {
              if (chunk[i3] !== zstdHeader[i3]) {
                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 Header(chunk.subarray(0, 512));
                this.brotli = false;
              } catch (_2) {
                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", (er2) => this.abort(er2));
            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](c4) {
        if (c4 && !this[ABORTED2]) {
          this[BUFFER2] = this[BUFFER2] ? Buffer.concat([this[BUFFER2], c4]) : c4;
        }
      }
      [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 c4 = this[BUFFER2];
            this[BUFFER2] = void 0;
            this[CONSUMECHUNKSUB](c4);
          } else {
            this[CONSUMECHUNKSUB](chunk);
          }
          while (this[BUFFER2] && this[BUFFER2]?.length >= 512 && !this[ABORTED2] && !this[SAW_EOF]) {
            const c4 = this[BUFFER2];
            this[BUFFER2] = void 0;
            this[CONSUMECHUNKSUB](c4);
          }
          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
var stripTrailingSlashes;
var init_strip_trailing_slashes = __esm({
  "node_modules/tar/dist/esm/strip-trailing-slashes.js"() {
    init_esbuild_shims();
    stripTrailingSlashes = /* @__PURE__ */ __name((str2) => {
      let i3 = str2.length - 1;
      let slashesStart = -1;
      while (i3 > -1 && str2.charAt(i3) === "/") {
        slashesStart = i3;
        i3--;
      }
      return slashesStart === -1 ? str2 : str2.slice(0, slashesStart);
    }, "stripTrailingSlashes");
  }
});

// node_modules/tar/dist/esm/list.js
import fs47 from "node:fs";
import { dirname as dirname13, parse as parse8 } from "path";
var onReadEntryFunction, filesFilter, listFileSync, listFile, list;
var init_list = __esm({
  "node_modules/tar/dist/esm/list.js"() {
    init_esbuild_shims();
    init_esm22();
    init_make_command();
    init_parse5();
    init_strip_trailing_slashes();
    onReadEntryFunction = /* @__PURE__ */ __name((opt) => {
      const onReadEntry = opt.onReadEntry;
      opt.onReadEntry = onReadEntry ? (e4) => {
        onReadEntry(e4);
        e4.resume();
      } : (e4) => e4.resume();
    }, "onReadEntryFunction");
    filesFilter = /* @__PURE__ */ __name((opt, files) => {
      const map2 = new Map(files.map((f5) => [stripTrailingSlashes(f5), true]));
      const filter4 = opt.filter;
      const mapHas = /* @__PURE__ */ __name((file, r5 = "") => {
        const root = r5 || parse8(file).root || ".";
        let ret;
        if (file === root)
          ret = false;
        else {
          const m3 = map2.get(file);
          if (m3 !== void 0) {
            ret = m3;
          } else {
            ret = mapHas(dirname13(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");
    listFileSync = /* @__PURE__ */ __name((opt) => {
      const p2 = new Parser2(opt);
      const file = opt.file;
      let fd;
      try {
        fd = fs47.openSync(file, "r");
        const stat10 = fs47.fstatSync(fd);
        const readSize = opt.maxReadSize || 16 * 1024 * 1024;
        if (stat10.size < readSize) {
          const buf = Buffer.allocUnsafe(stat10.size);
          const read3 = fs47.readSync(fd, buf, 0, stat10.size, 0);
          p2.end(read3 === buf.byteLength ? buf : buf.subarray(0, read3));
        } else {
          let pos2 = 0;
          const buf = Buffer.allocUnsafe(readSize);
          while (pos2 < stat10.size) {
            const bytesRead = fs47.readSync(fd, buf, 0, readSize, pos2);
            if (bytesRead === 0)
              break;
            pos2 += bytesRead;
            p2.write(buf.subarray(0, bytesRead));
          }
          p2.end();
        }
      } finally {
        if (typeof fd === "number") {
          try {
            fs47.closeSync(fd);
          } catch (er2) {
          }
        }
      }
    }, "listFileSync");
    listFile = /* @__PURE__ */ __name((opt, _files) => {
      const parse14 = new Parser2(opt);
      const readSize = opt.maxReadSize || 16 * 1024 * 1024;
      const file = opt.file;
      const p2 = new Promise((resolve30, reject) => {
        parse14.on("error", reject);
        parse14.on("end", resolve30);
        fs47.stat(file, (er2, stat10) => {
          if (er2) {
            reject(er2);
          } else {
            const stream2 = new ReadStream(file, {
              readSize,
              size: stat10.size
            });
            stream2.on("error", reject);
            stream2.pipe(parse14);
          }
        });
      });
      return p2;
    }, "listFile");
    list = 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/mode-fix.js
var modeFix;
var init_mode_fix = __esm({
  "node_modules/tar/dist/esm/mode-fix.js"() {
    init_esbuild_shims();
    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
import { win32 as win322 } from "node:path";
var isAbsolute4, parse9, stripAbsolutePath;
var init_strip_absolute_path = __esm({
  "node_modules/tar/dist/esm/strip-absolute-path.js"() {
    init_esbuild_shims();
    ({ isAbsolute: isAbsolute4, parse: parse9 } = win322);
    stripAbsolutePath = /* @__PURE__ */ __name((path125) => {
      let r5 = "";
      let parsed = parse9(path125);
      while (isAbsolute4(path125) || parsed.root) {
        const root = path125.charAt(0) === "/" && path125.slice(0, 4) !== "//?/" ? "/" : parsed.root;
        path125 = path125.slice(root.length);
        r5 += root;
        parsed = parse9(path125);
      }
      return [r5, path125];
    }, "stripAbsolutePath");
  }
});

// node_modules/tar/dist/esm/winchars.js
var raw, win, toWin, toRaw, encode3, decode;
var init_winchars = __esm({
  "node_modules/tar/dist/esm/winchars.js"() {
    init_esbuild_shims();
    raw = ["|", "<", ">", "?", ":"];
    win = raw.map((char) => String.fromCharCode(61440 + char.charCodeAt(0)));
    toWin = new Map(raw.map((char, i3) => [char, win[i3]]));
    toRaw = new Map(win.map((char, i3) => [char, raw[i3]]));
    encode3 = /* @__PURE__ */ __name((s5) => raw.reduce((s6, c4) => s6.split(c4).join(toWin.get(c4)), s5), "encode");
    decode = /* @__PURE__ */ __name((s5) => win.reduce((s6, c4) => s6.split(c4).join(toRaw.get(c4)), s5), "decode");
  }
});

// node_modules/tar/dist/esm/write-entry.js
import fs48 from "fs";
import path50 from "path";
var prefixPath, maxReadSize, PROCESS2, FILE, DIRECTORY, SYMLINK, HARDLINK, HEADER, READ2, LSTAT, ONLSTAT, ONREAD, ONREADLINK, OPENFILE, ONOPENFILE, CLOSE, MODE, AWAITDRAIN, ONDRAIN, PREFIX, WriteEntry, WriteEntrySync, WriteEntryTar, getType3;
var init_write_entry = __esm({
  "node_modules/tar/dist/esm/write-entry.js"() {
    init_esbuild_shims();
    init_esm9();
    init_header();
    init_mode_fix();
    init_normalize_windows_path();
    init_options();
    init_pax();
    init_strip_absolute_path();
    init_strip_trailing_slashes();
    init_warn_method();
    init_winchars();
    prefixPath = /* @__PURE__ */ __name((path125, prefix) => {
      if (!prefix) {
        return normalizeWindowsPath(path125);
      }
      path125 = normalizeWindowsPath(path125).replace(/^\.(\/|$)/, "");
      return stripTrailingSlashes(prefix) + "/" + path125;
    }, "prefixPath");
    maxReadSize = 16 * 1024 * 1024;
    PROCESS2 = Symbol("process");
    FILE = Symbol("file");
    DIRECTORY = Symbol("directory");
    SYMLINK = Symbol("symlink");
    HARDLINK = Symbol("hardlink");
    HEADER = Symbol("header");
    READ2 = Symbol("read");
    LSTAT = Symbol("lstat");
    ONLSTAT = Symbol("onlstat");
    ONREAD = Symbol("onread");
    ONREADLINK = Symbol("onreadlink");
    OPENFILE = Symbol("openfile");
    ONOPENFILE = Symbol("onopenfile");
    CLOSE = Symbol("close");
    MODE = Symbol("mode");
    AWAITDRAIN = Symbol("awaitDrain");
    ONDRAIN = Symbol("ondrain");
    PREFIX = Symbol("prefix");
    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(p2, opt_ = {}) {
        const opt = dealias(opt_);
        super();
        this.path = normalizeWindowsPath(p2);
        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, "/"));
          p2 = p2.replace(/\\/g, "/");
        }
        this.absolute = normalizeWindowsPath(opt.absolute || path50.resolve(this.cwd, p2));
        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]() {
        fs48.lstat(this.absolute, (er2, stat10) => {
          if (er2) {
            return this.emit("error", er2);
          }
          this[ONLSTAT](stat10);
        });
      }
      [ONLSTAT](stat10) {
        this.statCache.set(this.absolute, stat10);
        this.stat = stat10;
        if (!stat10.isFile()) {
          stat10.size = 0;
        }
        this.type = getType3(stat10);
        this.emit("stat", stat10);
        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](path125) {
        return prefixPath(path125, 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 Header({
          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]() {
        fs48.readlink(this.absolute, (er2, linkpath) => {
          if (er2) {
            return this.emit("error", er2);
          }
          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(path50.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]() {
        fs48.open(this.absolute, "r", (er2, fd) => {
          if (er2) {
            return this.emit("error", er2);
          }
          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");
        }
        fs48.read(fd, buf, offset, length, pos2, (er2, bytesRead) => {
          if (er2) {
            return this[CLOSE](() => this.emit("error", er2));
          }
          this[ONREAD](bytesRead);
        });
      }
      /* c8 ignore start */
      [CLOSE](cb = () => {
      }) {
        if (this.fd !== void 0)
          fs48.close(this.fd, cb);
      }
      [ONREAD](bytesRead) {
        if (bytesRead <= 0 && this.remain > 0) {
          const er2 = Object.assign(new Error("encountered unexpected EOF"), {
            path: this.absolute,
            syscall: "read",
            code: "EOF"
          });
          return this[CLOSE](() => this.emit("error", er2));
        }
        if (bytesRead > this.remain) {
          const er2 = Object.assign(new Error("did not encounter expected EOF"), {
            path: this.absolute,
            syscall: "read",
            code: "EOF"
          });
          return this[CLOSE](() => this.emit("error", er2));
        }
        if (!this.buf) {
          throw new Error("should have created buffer prior to reading");
        }
        if (bytesRead === this.remain) {
          for (let i3 = bytesRead; i3 < this.length && bytesRead < this.blockRemain; i3++) {
            this.buf[i3 + 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 er2 = Object.assign(new Error("writing more data than expected"), {
            path: this.absolute
          });
          return this.emit("error", er2);
        }
        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]((er2) => er2 ? this.emit("error", er2) : 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]();
      }
    };
    WriteEntrySync = class extends WriteEntry {
      static {
        __name(this, "WriteEntrySync");
      }
      sync = true;
      [LSTAT]() {
        this[ONLSTAT](fs48.lstatSync(this.absolute));
      }
      [SYMLINK]() {
        this[ONREADLINK](fs48.readlinkSync(this.absolute));
      }
      [OPENFILE]() {
        this[ONOPENFILE](fs48.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 = fs48.readSync(fd, buf, offset, length, pos2);
          this[ONREAD](bytesRead);
          threw = false;
        } finally {
          if (threw) {
            try {
              this[CLOSE](() => {
              });
            } catch (er2) {
            }
          }
        }
      }
      [AWAITDRAIN](cb) {
        cb();
      }
      /* c8 ignore start */
      [CLOSE](cb = () => {
      }) {
        if (this.fd !== void 0)
          fs48.closeSync(this.fd);
        cb();
      }
    };
    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 Header({
          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 b2 = this.header?.block;
        if (!b2)
          throw new Error("failed to encode header");
        super.write(b2);
        readEntry.pipe(this);
      }
      [PREFIX](path125) {
        return prefixPath(path125, 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;
      }
    };
    getType3 = /* @__PURE__ */ __name((stat10) => stat10.isFile() ? "File" : stat10.isDirectory() ? "Directory" : stat10.isSymbolicLink() ? "SymbolicLink" : "Unsupported", "getType");
  }
});

// node_modules/yallist/dist/esm/index.js
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;
}
function push(self2, item) {
  self2.tail = new Node3(item, self2.tail, void 0, self2);
  if (!self2.head) {
    self2.head = self2.tail;
  }
  self2.length++;
}
function unshift(self2, item) {
  self2.head = new Node3(item, void 0, self2.head, self2);
  if (!self2.tail) {
    self2.tail = self2.head;
  }
  self2.length++;
}
var Yallist, Node3;
var init_esm24 = __esm({
  "node_modules/yallist/dist/esm/index.js"() {
    init_esbuild_shims();
    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 i3 = 0, l3 = args.length; i3 < l3; i3++) {
          push(this, args[i3]);
        }
        return this.length;
      }
      unshift(...args) {
        for (var i3 = 0, l3 = args.length; i3 < l3; i3++) {
          unshift(this, args[i3]);
        }
        return this.length;
      }
      pop() {
        if (!this.tail) {
          return void 0;
        }
        const res = this.tail.value;
        const t5 = this.tail;
        this.tail = this.tail.prev;
        if (this.tail) {
          this.tail.next = void 0;
        } else {
          this.head = void 0;
        }
        t5.list = void 0;
        this.length--;
        return res;
      }
      shift() {
        if (!this.head) {
          return void 0;
        }
        const res = this.head.value;
        const h3 = this.head;
        this.head = this.head.next;
        if (this.head) {
          this.head.prev = void 0;
        } else {
          this.tail = void 0;
        }
        h3.list = void 0;
        this.length--;
        return res;
      }
      forEach(fn, thisp) {
        thisp = thisp || this;
        for (let walker = this.head, i3 = 0; !!walker; i3++) {
          fn.call(thisp, walker.value, i3, this);
          walker = walker.next;
        }
      }
      forEachReverse(fn, thisp) {
        thisp = thisp || this;
        for (let walker = this.tail, i3 = this.length - 1; !!walker; i3--) {
          fn.call(thisp, walker.value, i3, this);
          walker = walker.prev;
        }
      }
      get(n3) {
        let i3 = 0;
        let walker = this.head;
        for (; !!walker && i3 < n3; i3++) {
          walker = walker.next;
        }
        if (i3 === n3 && !!walker) {
          return walker.value;
        }
      }
      getReverse(n3) {
        let i3 = 0;
        let walker = this.tail;
        for (; !!walker && i3 < n3; i3++) {
          walker = walker.prev;
        }
        if (i3 === n3 && !!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 i3 = 0; !!walker; i3++) {
          acc = fn(acc, walker.value, i3);
          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 i3 = this.length - 1; !!walker; i3--) {
          acc = fn(acc, walker.value, i3);
          walker = walker.prev;
        }
        return acc;
      }
      toArray() {
        const arr = new Array(this.length);
        for (let i3 = 0, walker = this.head; !!walker; i3++) {
          arr[i3] = walker.value;
          walker = walker.next;
        }
        return arr;
      }
      toArrayReverse() {
        const arr = new Array(this.length);
        for (let i3 = 0, walker = this.tail; !!walker; i3++) {
          arr[i3] = 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 i3 = 0;
        for (i3 = 0; !!walker && i3 < from; i3++) {
          walker = walker.next;
        }
        for (; !!walker && i3 < to; i3++, 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 i3 = this.length;
        let walker = this.tail;
        for (; !!walker && i3 > to; i3--) {
          walker = walker.prev;
        }
        for (; !!walker && i3 > from; i3--, 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 i3 = 0; !!walker && i3 < start; i3++) {
          walker = walker.next;
        }
        const ret = [];
        for (let i3 = 0; !!walker && i3 < deleteCount; i3++) {
          ret.push(walker.value);
          walker = this.removeNode(walker);
        }
        if (!walker) {
          walker = this.tail;
        } else if (walker !== this.tail) {
          walker = walker.prev;
        }
        for (const v2 of nodes) {
          walker = insertAfter(this, walker, v2);
        }
        return ret;
      }
      reverse() {
        const head = this.head;
        const tail = this.tail;
        for (let walker = head; !!walker; walker = walker.prev) {
          const p2 = walker.prev;
          walker.prev = walker.next;
          walker.next = p2;
        }
        this.head = tail;
        this.tail = head;
        return this;
      }
    };
    __name(insertAfter, "insertAfter");
    __name(push, "push");
    __name(unshift, "unshift");
    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 fs49 from "fs";
import path51 from "path";
var PackJob, EOF2, ONSTAT, ENDED2, QUEUE2, CURRENT, PROCESS3, PROCESSING, PROCESSJOB, JOBS, JOBDONE, ADDFSENTRY, ADDTARENTRY, STAT, READDIR, ONREADDIR, PIPE, ENTRY, ENTRYOPT, WRITEENTRYCLASS, WRITE, ONDRAIN2, Pack, PackSync;
var init_pack = __esm({
  "node_modules/tar/dist/esm/pack.js"() {
    init_esbuild_shims();
    init_write_entry();
    init_esm9();
    init_esm23();
    init_esm24();
    init_read_entry();
    init_warn_method();
    init_normalize_windows_path();
    PackJob = class {
      static {
        __name(this, "PackJob");
      }
      path;
      absolute;
      entry;
      stat;
      readdir;
      pending = false;
      ignore = false;
      piped = false;
      constructor(path125, absolute) {
        this.path = path125 || "./";
        this.absolute = absolute;
      }
    };
    EOF2 = Buffer.alloc(1024);
    ONSTAT = Symbol("onStat");
    ENDED2 = Symbol("ended");
    QUEUE2 = Symbol("queue");
    CURRENT = Symbol("current");
    PROCESS3 = Symbol("process");
    PROCESSING = Symbol("processing");
    PROCESSJOB = Symbol("processJob");
    JOBS = Symbol("jobs");
    JOBDONE = Symbol("jobDone");
    ADDFSENTRY = Symbol("addFSEntry");
    ADDTARENTRY = Symbol("addTarEntry");
    STAT = Symbol("stat");
    READDIR = Symbol("readdir");
    ONREADDIR = Symbol("onreaddir");
    PIPE = Symbol("pipe");
    ENTRY = Symbol("entry");
    ENTRYOPT = Symbol("entryOpt");
    WRITEENTRYCLASS = Symbol("writeEntryClass");
    WRITE = Symbol("write");
    ONDRAIN2 = Symbol("ondrain");
    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(path125) {
        this.write(path125);
        return this;
      }
      end(path125, encoding, cb) {
        if (typeof path125 === "function") {
          cb = path125;
          path125 = void 0;
        }
        if (typeof encoding === "function") {
          cb = encoding;
          encoding = void 0;
        }
        if (path125) {
          this.add(path125);
        }
        this[ENDED2] = true;
        this[PROCESS3]();
        if (cb)
          cb();
        return this;
      }
      write(path125) {
        if (this[ENDED2]) {
          throw new Error("write after end");
        }
        if (path125 instanceof ReadEntry) {
          this[ADDTARENTRY](path125);
        } else {
          this[ADDFSENTRY](path125);
        }
        return this.flowing;
      }
      [ADDTARENTRY](p2) {
        const absolute = normalizeWindowsPath(path51.resolve(this.cwd, p2.path));
        if (!this.filter(p2.path, p2)) {
          p2.resume();
        } else {
          const job = new PackJob(p2.path, absolute);
          job.entry = new WriteEntryTar(p2, this[ENTRYOPT](job));
          job.entry.on("end", () => this[JOBDONE](job));
          this[JOBS] += 1;
          this[QUEUE2].push(job);
        }
        this[PROCESS3]();
      }
      [ADDFSENTRY](p2) {
        const absolute = normalizeWindowsPath(path51.resolve(this.cwd, p2));
        this[QUEUE2].push(new PackJob(p2, absolute));
        this[PROCESS3]();
      }
      [STAT](job) {
        job.pending = true;
        this[JOBS] += 1;
        const stat10 = this.follow ? "stat" : "lstat";
        fs49[stat10](job.absolute, (er2, stat11) => {
          job.pending = false;
          this[JOBS] -= 1;
          if (er2) {
            this.emit("error", er2);
          } else {
            this[ONSTAT](job, stat11);
          }
        });
      }
      [ONSTAT](job, stat10) {
        this.statCache.set(job.absolute, stat10);
        job.stat = stat10;
        if (!this.filter(job.path, stat10)) {
          job.ignore = true;
        }
        this[PROCESS3]();
      }
      [READDIR](job) {
        job.pending = true;
        this[JOBS] += 1;
        fs49.readdir(job.absolute, (er2, entries) => {
          job.pending = false;
          this[JOBS] -= 1;
          if (er2) {
            return this.emit("error", er2);
          }
          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 w2 = this[QUEUE2].head; !!w2 && this[JOBS] < this.jobs; w2 = w2.next) {
          this[PROCESSJOB](w2.value);
          if (w2.value.ignore) {
            const p2 = w2.next;
            this[QUEUE2].removeNode(w2);
            w2.next = p2;
          }
        }
        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 e4 = new this[WRITEENTRYCLASS](job.path, this[ENTRYOPT](job));
          return e4.on("end", () => this[JOBDONE](job)).on("error", (er2) => this.emit("error", er2));
        } catch (er2) {
          this.emit("error", er2);
        }
      }
      [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 p2 = job.path;
            const base = p2 === "./" ? "" : p2.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);
      }
    };
    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 stat10 = this.follow ? "statSync" : "lstatSync";
        this[ONSTAT](job, fs49[stat10](job.absolute));
      }
      [READDIR](job) {
        this[ONREADDIR](job, fs49.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 p2 = job.path;
            const base = p2 === "./" ? "" : p2.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
import path52 from "node:path";
var createFileSync, createFile, addFilesSync, addFilesAsync, createSync, createAsync, create;
var init_create = __esm({
  "node_modules/tar/dist/esm/create.js"() {
    init_esbuild_shims();
    init_esm22();
    init_list();
    init_make_command();
    init_pack();
    createFileSync = /* @__PURE__ */ __name((opt, files) => {
      const p2 = new PackSync(opt);
      const stream2 = new WriteStreamSync(opt.file, {
        mode: opt.mode || 438
      });
      p2.pipe(stream2);
      addFilesSync(p2, files);
    }, "createFileSync");
    createFile = /* @__PURE__ */ __name((opt, files) => {
      const p2 = new Pack(opt);
      const stream2 = new WriteStream(opt.file, {
        mode: opt.mode || 438
      });
      p2.pipe(stream2);
      const promise = new Promise((res, rej) => {
        stream2.on("error", rej);
        stream2.on("close", res);
        p2.on("error", rej);
      });
      addFilesAsync(p2, files);
      return promise;
    }, "createFile");
    addFilesSync = /* @__PURE__ */ __name((p2, files) => {
      files.forEach((file) => {
        if (file.charAt(0) === "@") {
          list({
            file: path52.resolve(p2.cwd, file.slice(1)),
            sync: true,
            noResume: true,
            onReadEntry: /* @__PURE__ */ __name((entry) => p2.add(entry), "onReadEntry")
          });
        } else {
          p2.add(file);
        }
      });
      p2.end();
    }, "addFilesSync");
    addFilesAsync = /* @__PURE__ */ __name(async (p2, files) => {
      for (let i3 = 0; i3 < files.length; i3++) {
        const file = String(files[i3]);
        if (file.charAt(0) === "@") {
          await list({
            file: path52.resolve(String(p2.cwd), file.slice(1)),
            noResume: true,
            onReadEntry: /* @__PURE__ */ __name((entry) => {
              p2.add(entry);
            }, "onReadEntry")
          });
        } else {
          p2.add(file);
        }
      }
      p2.end();
    }, "addFilesAsync");
    createSync = /* @__PURE__ */ __name((opt, files) => {
      const p2 = new PackSync(opt);
      addFilesSync(p2, files);
      return p2;
    }, "createSync");
    createAsync = /* @__PURE__ */ __name((opt, files) => {
      const p2 = new Pack(opt);
      addFilesAsync(p2, files);
      return p2;
    }, "createAsync");
    create = 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/get-write-flag.js
import fs50 from "fs";
var platform7, isWindows3, O_CREAT, O_TRUNC, O_WRONLY, UV_FS_O_FILEMAP, fMapEnabled, fMapLimit, fMapFlag, getWriteFlag;
var init_get_write_flag = __esm({
  "node_modules/tar/dist/esm/get-write-flag.js"() {
    init_esbuild_shims();
    platform7 = process.env.__FAKE_PLATFORM__ || process.platform;
    isWindows3 = platform7 === "win32";
    ({ O_CREAT, O_TRUNC, O_WRONLY } = fs50.constants);
    UV_FS_O_FILEMAP = Number(process.env.__FAKE_FS_O_FILENAME__) || fs50.constants.UV_FS_O_FILEMAP || 0;
    fMapEnabled = isWindows3 && !!UV_FS_O_FILEMAP;
    fMapLimit = 512 * 1024;
    fMapFlag = UV_FS_O_FILEMAP | O_TRUNC | O_CREAT | O_WRONLY;
    getWriteFlag = !fMapEnabled ? () => "w" : (size) => size < fMapLimit ? fMapFlag : "w";
  }
});

// node_modules/chownr/dist/esm/index.js
import fs51 from "node:fs";
import path53 from "node:path";
var lchownSync, chown, chownrKid, chownr, chownrKidSync, chownrSync;
var init_esm25 = __esm({
  "node_modules/chownr/dist/esm/index.js"() {
    init_esbuild_shims();
    lchownSync = /* @__PURE__ */ __name((path125, uid, gid) => {
      try {
        return fs51.lchownSync(path125, uid, gid);
      } catch (er2) {
        if (er2?.code !== "ENOENT")
          throw er2;
      }
    }, "lchownSync");
    chown = /* @__PURE__ */ __name((cpath, uid, gid, cb) => {
      fs51.lchown(cpath, uid, gid, (er2) => {
        cb(er2 && er2?.code !== "ENOENT" ? er2 : null);
      });
    }, "chown");
    chownrKid = /* @__PURE__ */ __name((p2, child, uid, gid, cb) => {
      if (child.isDirectory()) {
        chownr(path53.resolve(p2, child.name), uid, gid, (er2) => {
          if (er2)
            return cb(er2);
          const cpath = path53.resolve(p2, child.name);
          chown(cpath, uid, gid, cb);
        });
      } else {
        const cpath = path53.resolve(p2, child.name);
        chown(cpath, uid, gid, cb);
      }
    }, "chownrKid");
    chownr = /* @__PURE__ */ __name((p2, uid, gid, cb) => {
      fs51.readdir(p2, { withFileTypes: true }, (er2, children) => {
        if (er2) {
          if (er2.code === "ENOENT")
            return cb();
          else if (er2.code !== "ENOTDIR" && er2.code !== "ENOTSUP")
            return cb(er2);
        }
        if (er2 || !children.length)
          return chown(p2, uid, gid, cb);
        let len = children.length;
        let errState = null;
        const then = /* @__PURE__ */ __name((er3) => {
          if (errState)
            return;
          if (er3)
            return cb(errState = er3);
          if (--len === 0)
            return chown(p2, uid, gid, cb);
        }, "then");
        for (const child of children) {
          chownrKid(p2, child, uid, gid, then);
        }
      });
    }, "chownr");
    chownrKidSync = /* @__PURE__ */ __name((p2, child, uid, gid) => {
      if (child.isDirectory())
        chownrSync(path53.resolve(p2, child.name), uid, gid);
      lchownSync(path53.resolve(p2, child.name), uid, gid);
    }, "chownrKidSync");
    chownrSync = /* @__PURE__ */ __name((p2, uid, gid) => {
      let children;
      try {
        children = fs51.readdirSync(p2, { withFileTypes: true });
      } catch (er2) {
        const e4 = er2;
        if (e4?.code === "ENOENT")
          return;
        else if (e4?.code === "ENOTDIR" || e4?.code === "ENOTSUP")
          return lchownSync(p2, uid, gid);
        else
          throw e4;
      }
      for (const child of children) {
        chownrKidSync(p2, child, uid, gid);
      }
      return lchownSync(p2, uid, gid);
    }, "chownrSync");
  }
});

// node_modules/tar/dist/esm/cwd-error.js
var CwdError;
var init_cwd_error = __esm({
  "node_modules/tar/dist/esm/cwd-error.js"() {
    init_esbuild_shims();
    CwdError = class extends Error {
      static {
        __name(this, "CwdError");
      }
      path;
      code;
      syscall = "chdir";
      constructor(path125, code2) {
        super(`${code2}: Cannot cd into '${path125}'`);
        this.path = path125;
        this.code = code2;
      }
      get name() {
        return "CwdError";
      }
    };
  }
});

// node_modules/tar/dist/esm/symlink-error.js
var SymlinkError;
var init_symlink_error = __esm({
  "node_modules/tar/dist/esm/symlink-error.js"() {
    init_esbuild_shims();
    SymlinkError = class extends Error {
      static {
        __name(this, "SymlinkError");
      }
      path;
      symlink;
      syscall = "symlink";
      code = "TAR_SYMLINK_ERROR";
      constructor(symlink, path125) {
        super("TAR_SYMLINK_ERROR: Cannot extract through symbolic link");
        this.symlink = symlink;
        this.path = path125;
      }
      get name() {
        return "SymlinkError";
      }
    };
  }
});

// node_modules/tar/dist/esm/mkdir.js
import fs52 from "node:fs";
import fsp from "node:fs/promises";
import path54 from "node:path";
var checkCwd, mkdir6, mkdir_, onmkdir, checkCwdSync, mkdirSync4;
var init_mkdir = __esm({
  "node_modules/tar/dist/esm/mkdir.js"() {
    init_esbuild_shims();
    init_esm25();
    init_cwd_error();
    init_normalize_windows_path();
    init_symlink_error();
    checkCwd = /* @__PURE__ */ __name((dir, cb) => {
      fs52.stat(dir, (er2, st2) => {
        if (er2 || !st2.isDirectory()) {
          er2 = new CwdError(dir, er2?.code || "ENOTDIR");
        }
        cb(er2);
      });
    }, "checkCwd");
    mkdir6 = /* @__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((er2, created) => {
        if (er2) {
          cb(er2);
        } else {
          if (created && doChown) {
            chownr(created, uid, gid, (er3) => done(er3));
          } else if (needChmod) {
            fs52.chmod(dir, mode, cb);
          } else {
            cb();
          }
        }
      }, "done");
      if (dir === cwd7) {
        return checkCwd(dir, done);
      }
      if (preserve) {
        return fsp.mkdir(dir, { mode, recursive: true }).then(
          (made) => done(null, made ?? void 0),
          // oh, ts
          done
        );
      }
      const sub = normalizeWindowsPath(path54.relative(cwd7, dir));
      const parts = sub.split("/");
      mkdir_(cwd7, parts, mode, unlink3, cwd7, void 0, done);
    }, "mkdir");
    mkdir_ = /* @__PURE__ */ __name((base, parts, mode, unlink3, cwd7, created, cb) => {
      if (!parts.length) {
        return cb(null, created);
      }
      const p2 = parts.shift();
      const part = normalizeWindowsPath(path54.resolve(base + "/" + p2));
      fs52.mkdir(part, mode, onmkdir(part, parts, mode, unlink3, cwd7, created, cb));
    }, "mkdir_");
    onmkdir = /* @__PURE__ */ __name((part, parts, mode, unlink3, cwd7, created, cb) => (er2) => {
      if (er2) {
        fs52.lstat(part, (statEr, st2) => {
          if (statEr) {
            statEr.path = statEr.path && normalizeWindowsPath(statEr.path);
            cb(statEr);
          } else if (st2.isDirectory()) {
            mkdir_(part, parts, mode, unlink3, cwd7, created, cb);
          } else if (unlink3) {
            fs52.unlink(part, (er3) => {
              if (er3) {
                return cb(er3);
              }
              fs52.mkdir(part, mode, onmkdir(part, parts, mode, unlink3, cwd7, created, cb));
            });
          } else if (st2.isSymbolicLink()) {
            return cb(new SymlinkError(part, part + "/" + parts.join("/")));
          } else {
            cb(er2);
          }
        });
      } else {
        created = created || part;
        mkdir_(part, parts, mode, unlink3, cwd7, created, cb);
      }
    }, "onmkdir");
    checkCwdSync = /* @__PURE__ */ __name((dir) => {
      let ok2 = false;
      let code2 = void 0;
      try {
        ok2 = fs52.statSync(dir).isDirectory();
      } catch (er2) {
        code2 = er2?.code;
      } finally {
        if (!ok2) {
          throw new CwdError(dir, code2 ?? "ENOTDIR");
        }
      }
    }, "checkCwdSync");
    mkdirSync4 = /* @__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) {
          fs52.chmodSync(dir, mode);
        }
      }, "done");
      if (dir === cwd7) {
        checkCwdSync(cwd7);
        return done();
      }
      if (preserve) {
        return done(fs52.mkdirSync(dir, { mode, recursive: true }) ?? void 0);
      }
      const sub = normalizeWindowsPath(path54.relative(cwd7, dir));
      const parts = sub.split("/");
      let created = void 0;
      for (let p2 = parts.shift(), part = cwd7; p2 && (part += "/" + p2); p2 = parts.shift()) {
        part = normalizeWindowsPath(path54.resolve(part));
        try {
          fs52.mkdirSync(part, mode);
          created = created || part;
        } catch (er2) {
          const st2 = fs52.lstatSync(part);
          if (st2.isDirectory()) {
            continue;
          } else if (unlink3) {
            fs52.unlinkSync(part);
            fs52.mkdirSync(part, mode);
            created = created || part;
            continue;
          } else if (st2.isSymbolicLink()) {
            return new SymlinkError(part, part + "/" + parts.join("/"));
          }
        }
      }
      return done(created);
    }, "mkdirSync");
  }
});

// node_modules/tar/dist/esm/normalize-unicode.js
var normalizeCache2, MAX, cache2, normalizeUnicode;
var init_normalize_unicode = __esm({
  "node_modules/tar/dist/esm/normalize-unicode.js"() {
    init_esbuild_shims();
    normalizeCache2 = /* @__PURE__ */ Object.create(null);
    MAX = 1e4;
    cache2 = /* @__PURE__ */ new Set();
    normalizeUnicode = /* @__PURE__ */ __name((s5) => {
      if (!cache2.has(s5)) {
        normalizeCache2[s5] = s5.normalize("NFD");
      } else {
        cache2.delete(s5);
      }
      cache2.add(s5);
      const ret = normalizeCache2[s5];
      let i3 = cache2.size - MAX;
      if (i3 > MAX / 10) {
        for (const s6 of cache2) {
          cache2.delete(s6);
          delete normalizeCache2[s6];
          if (--i3 <= 0)
            break;
        }
      }
      return ret;
    }, "normalizeUnicode");
  }
});

// node_modules/tar/dist/esm/path-reservations.js
import { join as join20 } from "node:path";
var platform8, isWindows4, getDirs, PathReservations;
var init_path_reservations = __esm({
  "node_modules/tar/dist/esm/path-reservations.js"() {
    init_esbuild_shims();
    init_normalize_unicode();
    init_strip_trailing_slashes();
    platform8 = process.env.TESTING_TAR_FAKE_PLATFORM || process.platform;
    isWindows4 = platform8 === "win32";
    getDirs = /* @__PURE__ */ __name((path125) => {
      const dirs = path125.split("/").slice(0, -1).reduce((set, path126) => {
        const s5 = set[set.length - 1];
        if (s5 !== void 0) {
          path126 = join20(s5, path126);
        }
        set.push(path126 || "/");
        return set;
      }, []);
      return dirs;
    }, "getDirs");
    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 = isWindows4 ? ["win32 parallelization disabled"] : paths.map((p2) => {
          return stripTrailingSlashes(join20(normalizeUnicode(p2))).toLowerCase();
        });
        const dirs = new Set(paths.map((path125) => getDirs(path125)).reduce((a2, b2) => a2.concat(b2)));
        this.#reservations.set(fn, { dirs, paths });
        for (const p2 of paths) {
          const q2 = this.#queues.get(p2);
          if (!q2) {
            this.#queues.set(p2, [fn]);
          } else {
            q2.push(fn);
          }
        }
        for (const dir of dirs) {
          const q2 = this.#queues.get(dir);
          if (!q2) {
            this.#queues.set(dir, [/* @__PURE__ */ new Set([fn])]);
          } else {
            const l3 = q2[q2.length - 1];
            if (l3 instanceof Set) {
              l3.add(fn);
            } else {
              q2.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((path125) => this.#queues.get(path125)),
          dirs: [...res.dirs].map((path125) => this.#queues.get(path125))
        };
      }
      // 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((q2) => q2 && q2[0] === fn) && dirs.every((q2) => q2 && q2[0] instanceof Set && q2[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 path125 of paths) {
          const q2 = this.#queues.get(path125);
          if (!q2 || q2?.[0] !== fn) {
            continue;
          }
          const q0 = q2[1];
          if (!q0) {
            this.#queues.delete(path125);
            continue;
          }
          q2.shift();
          if (typeof q0 === "function") {
            next.add(q0);
          } else {
            for (const f5 of q0) {
              next.add(f5);
            }
          }
        }
        for (const dir of dirs) {
          const q2 = this.#queues.get(dir);
          const q0 = q2?.[0];
          if (!q2 || !(q0 instanceof Set))
            continue;
          if (q0.size === 1 && q2.length === 1) {
            this.#queues.delete(dir);
            continue;
          } else if (q0.size === 1) {
            q2.shift();
            const n3 = q2[0];
            if (typeof n3 === "function") {
              next.add(n3);
            }
          } else {
            q0.delete(fn);
          }
        }
        this.#running.delete(fn);
        next.forEach((fn2) => this.#run(fn2));
        return true;
      }
    };
  }
});

// node_modules/tar/dist/esm/unpack.js
import assert3 from "node:assert";
import { randomBytes as randomBytes4 } from "node:crypto";
import fs53 from "node:fs";
import path55 from "node:path";
var ONENTRY, CHECKFS, CHECKFS2, ISREUSABLE, MAKEFS, FILE2, DIRECTORY2, LINK, SYMLINK2, HARDLINK2, UNSUPPORTED, CHECKPATH, MKDIR, ONERROR, PENDING, PEND, UNPEND, ENDED3, MAYBECLOSE, SKIP, DOCHOWN, UID, GID, CHECKED_CWD, platform9, isWindows5, DEFAULT_MAX_DEPTH, unlinkFile, unlinkFileSync, uint32, Unpack, callSync, UnpackSync;
var init_unpack = __esm({
  "node_modules/tar/dist/esm/unpack.js"() {
    init_esbuild_shims();
    init_esm22();
    init_get_write_flag();
    init_mkdir();
    init_normalize_windows_path();
    init_parse5();
    init_strip_absolute_path();
    init_winchars();
    init_path_reservations();
    ONENTRY = Symbol("onEntry");
    CHECKFS = Symbol("checkFs");
    CHECKFS2 = Symbol("checkFs2");
    ISREUSABLE = Symbol("isReusable");
    MAKEFS = Symbol("makeFs");
    FILE2 = Symbol("file");
    DIRECTORY2 = Symbol("directory");
    LINK = Symbol("link");
    SYMLINK2 = Symbol("symlink");
    HARDLINK2 = Symbol("hardlink");
    UNSUPPORTED = Symbol("unsupported");
    CHECKPATH = Symbol("checkPath");
    MKDIR = Symbol("mkdir");
    ONERROR = Symbol("onError");
    PENDING = Symbol("pending");
    PEND = Symbol("pend");
    UNPEND = Symbol("unpend");
    ENDED3 = Symbol("ended");
    MAYBECLOSE = Symbol("maybeClose");
    SKIP = Symbol("skip");
    DOCHOWN = Symbol("doChown");
    UID = Symbol("uid");
    GID = Symbol("gid");
    CHECKED_CWD = Symbol("checkedCwd");
    platform9 = process.env.TESTING_TAR_FAKE_PLATFORM || process.platform;
    isWindows5 = platform9 === "win32";
    DEFAULT_MAX_DEPTH = 1024;
    unlinkFile = /* @__PURE__ */ __name((path125, cb) => {
      if (!isWindows5) {
        return fs53.unlink(path125, cb);
      }
      const name3 = path125 + ".DELETE." + randomBytes4(16).toString("hex");
      fs53.rename(path125, name3, (er2) => {
        if (er2) {
          return cb(er2);
        }
        fs53.unlink(name3, cb);
      });
    }, "unlinkFile");
    unlinkFileSync = /* @__PURE__ */ __name((path125) => {
      if (!isWindows5) {
        return fs53.unlinkSync(path125);
      }
      const name3 = path125 + ".DELETE." + randomBytes4(16).toString("hex");
      fs53.renameSync(path125, name3);
      fs53.unlinkSync(name3);
    }, "unlinkFileSync");
    uint32 = /* @__PURE__ */ __name((a2, b2, c4) => a2 !== void 0 && a2 === a2 >>> 0 ? a2 : b2 !== void 0 && b2 === b2 >>> 0 ? b2 : c4, "uint32");
    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 || isWindows5;
        this.newer = !!opt.newer;
        this.keep = !!opt.keep;
        this.noMtime = !!opt.noMtime;
        this.preservePaths = !!opt.preservePaths;
        this.unlink = !!opt.unlink;
        this.cwd = normalizeWindowsPath(path55.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 p2 = normalizeWindowsPath(entry.path);
        const parts = p2.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: p2,
            depth: parts.length,
            maxDepth: this.maxDepth
          });
          return false;
        }
        if (!this.preservePaths) {
          if (parts.includes("..") || /* c8 ignore next */
          isWindows5 && /^[a-z]:\.\.$/i.test(parts[0] ?? "")) {
            this.warn("TAR_ENTRY_ERROR", `path contains '..'`, {
              entry,
              path: p2
            });
            return false;
          }
          const [root, stripped] = stripAbsolutePath(p2);
          if (root) {
            entry.path = String(stripped);
            this.warn("TAR_ENTRY_INFO", `stripping ${root} from absolute path`, {
              entry,
              path: p2
            });
          }
        }
        if (path55.isAbsolute(entry.path)) {
          entry.absolute = normalizeWindowsPath(path55.resolve(entry.path));
        } else {
          entry.absolute = normalizeWindowsPath(path55.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 } = path55.win32.parse(String(entry.absolute));
          entry.absolute = aRoot + encode3(String(entry.absolute).slice(aRoot.length));
          const { root: pRoot } = path55.win32.parse(entry.path);
          entry.path = pRoot + encode3(entry.path.slice(pRoot.length));
        }
        return true;
      }
      [ONENTRY](entry) {
        if (!this[CHECKPATH](entry)) {
          return entry.resume();
        }
        assert3.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](er2, entry) {
        if (er2.name === "CwdError") {
          this.emit("error", er2);
        } else {
          this.warn("TAR_ENTRY_ERROR", er2, { entry });
          this[UNPEND]();
          entry.resume();
        }
      }
      [MKDIR](dir, mode, cb) {
        mkdir6(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", (er2) => {
          if (stream2.fd) {
            fs53.close(stream2.fd, () => {
            });
          }
          stream2.write = () => true;
          this[ONERROR](er2, entry);
          fullyDone();
        });
        let actions = 1;
        const done = /* @__PURE__ */ __name((er2) => {
          if (er2) {
            if (stream2.fd) {
              fs53.close(stream2.fd, () => {
              });
            }
            this[ONERROR](er2, entry);
            fullyDone();
            return;
          }
          if (--actions === 0) {
            if (stream2.fd !== void 0) {
              fs53.close(stream2.fd, (er3) => {
                if (er3) {
                  this[ONERROR](er3, 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;
            fs53.futimes(fd, atime, mtime, (er2) => er2 ? fs53.utimes(abs, atime, mtime, (er22) => done(er22 && er2)) : 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") {
              fs53.fchown(fd, uid, gid, (er2) => er2 ? fs53.chown(abs, uid, gid, (er22) => done(er22 && er2)) : done());
            }
          }
          done();
        });
        const tx = this.transform ? this.transform(entry) || entry : entry;
        if (tx !== entry) {
          tx.on("error", (er2) => {
            this[ONERROR](er2, 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, (er2) => {
          if (er2) {
            this[ONERROR](er2, 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++;
            fs53.utimes(String(entry.absolute), entry.atime || /* @__PURE__ */ new Date(), entry.mtime, done);
          }
          if (this[DOCHOWN](entry)) {
            actions++;
            fs53.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(path55.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, st2) {
        return entry.type === "File" && !this.unlink && st2.isFile() && st2.nlink <= 1 && !isWindows5;
      }
      // 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((er2) => {
          fullyDone(er2);
        }, "done");
        const checkCwd2 = /* @__PURE__ */ __name(() => {
          this[MKDIR](this.cwd, this.dmode, (er2) => {
            if (er2) {
              this[ONERROR](er2, entry);
              done();
              return;
            }
            this[CHECKED_CWD] = true;
            start();
          });
        }, "checkCwd");
        const start = /* @__PURE__ */ __name(() => {
          if (entry.absolute !== this.cwd) {
            const parent = normalizeWindowsPath(path55.dirname(String(entry.absolute)));
            if (parent !== this.cwd) {
              return this[MKDIR](parent, this.dmode, (er2) => {
                if (er2) {
                  this[ONERROR](er2, entry);
                  done();
                  return;
                }
                afterMakeParent();
              });
            }
          }
          afterMakeParent();
        }, "start");
        const afterMakeParent = /* @__PURE__ */ __name(() => {
          fs53.lstat(String(entry.absolute), (lstatEr, st2) => {
            if (st2 && (this.keep || /* c8 ignore next */
            this.newer && st2.mtime > (entry.mtime ?? st2.mtime))) {
              this[SKIP](entry);
              done();
              return;
            }
            if (lstatEr || this[ISREUSABLE](entry, st2)) {
              return this[MAKEFS](null, entry, done);
            }
            if (st2.isDirectory()) {
              if (entry.type === "Directory") {
                const needChmod = this.chmod && entry.mode && (st2.mode & 4095) !== entry.mode;
                const afterChmod = /* @__PURE__ */ __name((er2) => this[MAKEFS](er2 ?? null, entry, done), "afterChmod");
                if (!needChmod) {
                  return afterChmod();
                }
                return fs53.chmod(String(entry.absolute), Number(entry.mode), afterChmod);
              }
              if (entry.absolute !== this.cwd) {
                return fs53.rmdir(String(entry.absolute), (er2) => this[MAKEFS](er2 ?? null, entry, done));
              }
            }
            if (entry.absolute === this.cwd) {
              return this[MAKEFS](null, entry, done);
            }
            unlinkFile(String(entry.absolute), (er2) => this[MAKEFS](er2 ?? null, entry, done));
          });
        }, "afterMakeParent");
        if (this[CHECKED_CWD]) {
          start();
        } else {
          checkCwd2();
        }
      }
      [MAKEFS](er2, entry, done) {
        if (er2) {
          this[ONERROR](er2, 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) {
        fs53[link3](linkpath, String(entry.absolute), (er2) => {
          if (er2) {
            this[ONERROR](er2, entry);
          } else {
            this[UNPEND]();
            entry.resume();
          }
          done();
        });
      }
    };
    callSync = /* @__PURE__ */ __name((fn) => {
      try {
        return [null, fn()];
      } catch (er2) {
        return [er2, null];
      }
    }, "callSync");
    UnpackSync = class extends Unpack {
      static {
        __name(this, "UnpackSync");
      }
      sync = true;
      [MAKEFS](er2, entry) {
        return super[MAKEFS](er2, entry, () => {
        });
      }
      [CHECKFS](entry) {
        if (!this[CHECKED_CWD]) {
          const er3 = this[MKDIR](this.cwd, this.dmode);
          if (er3) {
            return this[ONERROR](er3, entry);
          }
          this[CHECKED_CWD] = true;
        }
        if (entry.absolute !== this.cwd) {
          const parent = normalizeWindowsPath(path55.dirname(String(entry.absolute)));
          if (parent !== this.cwd) {
            const mkParent = this[MKDIR](parent, this.dmode);
            if (mkParent) {
              return this[ONERROR](mkParent, entry);
            }
          }
        }
        const [lstatEr, st2] = callSync(() => fs53.lstatSync(String(entry.absolute)));
        if (st2 && (this.keep || /* c8 ignore next */
        this.newer && st2.mtime > (entry.mtime ?? st2.mtime))) {
          return this[SKIP](entry);
        }
        if (lstatEr || this[ISREUSABLE](entry, st2)) {
          return this[MAKEFS](null, entry);
        }
        if (st2.isDirectory()) {
          if (entry.type === "Directory") {
            const needChmod = this.chmod && entry.mode && (st2.mode & 4095) !== entry.mode;
            const [er4] = needChmod ? callSync(() => {
              fs53.chmodSync(String(entry.absolute), Number(entry.mode));
            }) : [];
            return this[MAKEFS](er4, entry);
          }
          const [er3] = callSync(() => fs53.rmdirSync(String(entry.absolute)));
          this[MAKEFS](er3, entry);
        }
        const [er2] = entry.absolute === this.cwd ? [] : callSync(() => unlinkFileSync(String(entry.absolute)));
        this[MAKEFS](er2, entry);
      }
      [FILE2](entry, done) {
        const mode = typeof entry.mode === "number" ? entry.mode & 4095 : this.fmode;
        const oner = /* @__PURE__ */ __name((er2) => {
          let closeError;
          try {
            fs53.closeSync(fd);
          } catch (e4) {
            closeError = e4;
          }
          if (er2 || closeError) {
            this[ONERROR](er2 || closeError, entry);
          }
          done();
        }, "oner");
        let fd;
        try {
          fd = fs53.openSync(String(entry.absolute), getWriteFlag(entry.size), mode);
        } catch (er2) {
          return oner(er2);
        }
        const tx = this.transform ? this.transform(entry) || entry : entry;
        if (tx !== entry) {
          tx.on("error", (er2) => this[ONERROR](er2, entry));
          entry.pipe(tx);
        }
        tx.on("data", (chunk) => {
          try {
            fs53.writeSync(fd, chunk, 0, chunk.length);
          } catch (er2) {
            oner(er2);
          }
        });
        tx.on("end", () => {
          let er2 = null;
          if (entry.mtime && !this.noMtime) {
            const atime = entry.atime || /* @__PURE__ */ new Date();
            const mtime = entry.mtime;
            try {
              fs53.futimesSync(fd, atime, mtime);
            } catch (futimeser) {
              try {
                fs53.utimesSync(String(entry.absolute), atime, mtime);
              } catch (utimeser) {
                er2 = futimeser;
              }
            }
          }
          if (this[DOCHOWN](entry)) {
            const uid = this[UID](entry);
            const gid = this[GID](entry);
            try {
              fs53.fchownSync(fd, Number(uid), Number(gid));
            } catch (fchowner) {
              try {
                fs53.chownSync(String(entry.absolute), Number(uid), Number(gid));
              } catch (chowner) {
                er2 = er2 || fchowner;
              }
            }
          }
          oner(er2);
        });
      }
      [DIRECTORY2](entry, done) {
        const mode = typeof entry.mode === "number" ? entry.mode & 4095 : this.dmode;
        const er2 = this[MKDIR](String(entry.absolute), mode);
        if (er2) {
          this[ONERROR](er2, entry);
          done();
          return;
        }
        if (entry.mtime && !this.noMtime) {
          try {
            fs53.utimesSync(String(entry.absolute), entry.atime || /* @__PURE__ */ new Date(), entry.mtime);
          } catch (er3) {
          }
        }
        if (this[DOCHOWN](entry)) {
          try {
            fs53.chownSync(String(entry.absolute), Number(this[UID](entry)), Number(this[GID](entry)));
          } catch (er3) {
          }
        }
        done();
        entry.resume();
      }
      [MKDIR](dir, mode) {
        try {
          return mkdirSync4(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 (er2) {
          return er2;
        }
      }
      [LINK](entry, linkpath, link3, done) {
        const ls = `${link3}Sync`;
        try {
          fs53[ls](linkpath, String(entry.absolute));
          done();
          entry.resume();
        } catch (er2) {
          return this[ONERROR](er2, entry);
        }
      }
    };
  }
});

// node_modules/tar/dist/esm/extract.js
import fs54 from "node:fs";
var extractFileSync, extractFile, extract;
var init_extract = __esm({
  "node_modules/tar/dist/esm/extract.js"() {
    init_esbuild_shims();
    init_esm22();
    init_list();
    init_make_command();
    init_unpack();
    extractFileSync = /* @__PURE__ */ __name((opt) => {
      const u2 = new UnpackSync(opt);
      const file = opt.file;
      const stat10 = fs54.statSync(file);
      const readSize = opt.maxReadSize || 16 * 1024 * 1024;
      const stream2 = new ReadStreamSync(file, {
        readSize,
        size: stat10.size
      });
      stream2.pipe(u2);
    }, "extractFileSync");
    extractFile = /* @__PURE__ */ __name((opt, _2) => {
      const u2 = new Unpack(opt);
      const readSize = opt.maxReadSize || 16 * 1024 * 1024;
      const file = opt.file;
      const p2 = new Promise((resolve30, reject) => {
        u2.on("error", reject);
        u2.on("close", resolve30);
        fs54.stat(file, (er2, stat10) => {
          if (er2) {
            reject(er2);
          } else {
            const stream2 = new ReadStream(file, {
              readSize,
              size: stat10.size
            });
            stream2.on("error", reject);
            stream2.pipe(u2);
          }
        });
      });
      return p2;
    }, "extractFile");
    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
import fs55 from "node:fs";
import path56 from "node:path";
var replaceSync, streamSync2, replaceAsync, addFilesSync2, addFilesAsync2, replace;
var init_replace = __esm({
  "node_modules/tar/dist/esm/replace.js"() {
    init_esbuild_shims();
    init_esm22();
    init_header();
    init_list();
    init_make_command();
    init_options();
    init_pack();
    replaceSync = /* @__PURE__ */ __name((opt, files) => {
      const p2 = new PackSync(opt);
      let threw = true;
      let fd;
      let position;
      try {
        try {
          fd = fs55.openSync(opt.file, "r+");
        } catch (er2) {
          if (er2?.code === "ENOENT") {
            fd = fs55.openSync(opt.file, "w+");
          } else {
            throw er2;
          }
        }
        const st2 = fs55.fstatSync(fd);
        const headBuf = Buffer.alloc(512);
        POSITION: for (position = 0; position < st2.size; position += 512) {
          for (let bufPos = 0, bytes = 0; bufPos < 512; bufPos += bytes) {
            bytes = fs55.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 h3 = new Header(headBuf);
          if (!h3.cksumValid) {
            break;
          }
          const entryBlockSize = 512 * Math.ceil((h3.size || 0) / 512);
          if (position + entryBlockSize + 512 > st2.size) {
            break;
          }
          position += entryBlockSize;
          if (opt.mtimeCache && h3.mtime) {
            opt.mtimeCache.set(String(h3.path), h3.mtime);
          }
        }
        threw = false;
        streamSync2(opt, p2, position, fd, files);
      } finally {
        if (threw) {
          try {
            fs55.closeSync(fd);
          } catch (er2) {
          }
        }
      }
    }, "replaceSync");
    streamSync2 = /* @__PURE__ */ __name((opt, p2, position, fd, files) => {
      const stream2 = new WriteStreamSync(opt.file, {
        fd,
        start: position
      });
      p2.pipe(stream2);
      addFilesSync2(p2, files);
    }, "streamSync");
    replaceAsync = /* @__PURE__ */ __name((opt, files) => {
      files = Array.from(files);
      const p2 = new Pack(opt);
      const getPos = /* @__PURE__ */ __name((fd, size, cb_) => {
        const cb = /* @__PURE__ */ __name((er2, pos2) => {
          if (er2) {
            fs55.close(fd, (_2) => cb_(er2));
          } 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((er2, bytes) => {
          if (er2 || typeof bytes === "undefined") {
            return cb(er2);
          }
          bufPos += bytes;
          if (bufPos < 512 && bytes) {
            return fs55.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 h3 = new Header(headBuf);
          if (!h3.cksumValid) {
            return cb(null, position);
          }
          const entryBlockSize = 512 * Math.ceil((h3.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 && h3.mtime) {
            opt.mtimeCache.set(String(h3.path), h3.mtime);
          }
          bufPos = 0;
          fs55.read(fd, headBuf, 0, 512, position, onread);
        }, "onread");
        fs55.read(fd, headBuf, 0, 512, position, onread);
      }, "getPos");
      const promise = new Promise((resolve30, reject) => {
        p2.on("error", reject);
        let flag = "r+";
        const onopen = /* @__PURE__ */ __name((er2, fd) => {
          if (er2 && er2.code === "ENOENT" && flag === "r+") {
            flag = "w+";
            return fs55.open(opt.file, flag, onopen);
          }
          if (er2 || !fd) {
            return reject(er2);
          }
          fs55.fstat(fd, (er3, st2) => {
            if (er3) {
              return fs55.close(fd, () => reject(er3));
            }
            getPos(fd, st2.size, (er4, position) => {
              if (er4) {
                return reject(er4);
              }
              const stream2 = new WriteStream(opt.file, {
                fd,
                start: position
              });
              p2.pipe(stream2);
              stream2.on("error", reject);
              stream2.on("close", resolve30);
              addFilesAsync2(p2, files);
            });
          });
        }, "onopen");
        fs55.open(opt.file, flag, onopen);
      });
      return promise;
    }, "replaceAsync");
    addFilesSync2 = /* @__PURE__ */ __name((p2, files) => {
      files.forEach((file) => {
        if (file.charAt(0) === "@") {
          list({
            file: path56.resolve(p2.cwd, file.slice(1)),
            sync: true,
            noResume: true,
            onReadEntry: /* @__PURE__ */ __name((entry) => p2.add(entry), "onReadEntry")
          });
        } else {
          p2.add(file);
        }
      });
      p2.end();
    }, "addFilesSync");
    addFilesAsync2 = /* @__PURE__ */ __name(async (p2, files) => {
      for (let i3 = 0; i3 < files.length; i3++) {
        const file = String(files[i3]);
        if (file.charAt(0) === "@") {
          await list({
            file: path56.resolve(String(p2.cwd), file.slice(1)),
            noResume: true,
            onReadEntry: /* @__PURE__ */ __name((entry) => p2.add(entry), "onReadEntry")
          });
        } else {
          p2.add(file);
        }
      }
      p2.end();
    }, "addFilesAsync");
    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 (!isFile2(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
var update, mtimeFilter;
var init_update = __esm({
  "node_modules/tar/dist/esm/update.js"() {
    init_esbuild_shims();
    init_make_command();
    init_replace();
    update = makeCommand(replace.syncFile, replace.asyncFile, replace.syncNoFile, replace.asyncNoFile, (opt, entries = []) => {
      replace.validate?.(opt, entries);
      mtimeFilter(opt);
    });
    mtimeFilter = /* @__PURE__ */ __name((opt) => {
      const filter4 = opt.filter;
      if (!opt.mtimeCache) {
        opt.mtimeCache = /* @__PURE__ */ new Map();
      }
      opt.filter = filter4 ? (path125, stat10) => filter4(path125, stat10) && !/* c8 ignore start */
      ((opt.mtimeCache?.get(path125) ?? stat10.mtime ?? 0) > (stat10.mtime ?? 0)) : (path125, stat10) => !/* c8 ignore start */
      ((opt.mtimeCache?.get(path125) ?? stat10.mtime ?? 0) > (stat10.mtime ?? 0));
    }, "mtimeFilter");
  }
});

// node_modules/tar/dist/esm/index.js
var init_esm26 = __esm({
  "node_modules/tar/dist/esm/index.js"() {
    init_esbuild_shims();
    init_create();
    init_create();
    init_extract();
    init_extract();
    init_header();
    init_list();
    init_list();
    init_pack();
    init_parse5();
    init_pax();
    init_read_entry();
    init_replace();
    init_replace();
    init_types12();
    init_unpack();
    init_update();
    init_update();
    init_write_entry();
  }
});

// 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(k2) {
        wrapper[k2] = fn[k2];
      });
      return wrapper;
      function wrapper() {
        var args = new Array(arguments.length);
        for (var i3 = 0; i3 < args.length; i3++) {
          args[i3] = arguments[i3];
        }
        var ret = fn.apply(this, args);
        var cb2 = args[args.length - 1];
        if (typeof ret === "function" && ret !== cb2) {
          Object.keys(cb2).forEach(function(k2) {
            ret[k2] = cb2[k2];
          });
        }
        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 f5 = /* @__PURE__ */ __name(function() {
        if (f5.called) return f5.value;
        f5.called = true;
        return f5.value = fn.apply(this, arguments);
      }, "f");
      f5.called = false;
      return f5;
    }
    __name(once, "once");
    function onceStrict(fn) {
      var f5 = /* @__PURE__ */ __name(function() {
        if (f5.called)
          throw new Error(f5.onceError);
        f5.called = true;
        return f5.value = fn.apply(this, arguments);
      }, "f");
      var name3 = fn.name || "Function wrapped with `once`";
      f5.onceError = name3 + " shouldn't be called more than once";
      f5.called = false;
      return f5;
    }
    __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 noop8 = /* @__PURE__ */ __name(function() {
    }, "noop");
    var qnt = globalThis.Bare ? queueMicrotask : process.nextTick.bind(process);
    var isRequest3 = /* @__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 || noop8);
      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 (isRequest3(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 fs113;
    try {
      fs113 = __require("fs");
    } catch (e4) {
    }
    var noop8 = /* @__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 (!fs113) return false;
      return (stream2 instanceof (fs113.ReadStream || noop8) || stream2 instanceof (fs113.WriteStream || noop8)) && isFn(stream2.close);
    }, "isFS");
    var isRequest3 = /* @__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(noop8);
        if (isRequest3(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 pipe2 = /* @__PURE__ */ __name(function(from, to) {
      return from.pipe(to);
    }, "pipe");
    var pump3 = /* @__PURE__ */ __name(function() {
      var streams = Array.prototype.slice.call(arguments);
      var callback = isFn(streams[streams.length - 1] || noop8) && streams.pop() || noop8;
      if (Array.isArray(streams[0])) streams = streams[0];
      if (streams.length < 2) throw new Error("pump requires two streams per minimum");
      var error2;
      var destroys = streams.map(function(stream2, i3) {
        var reading = i3 < streams.length - 1;
        var writing = i3 > 0;
        return destroyer(stream2, reading, writing, function(err) {
          if (!error2) error2 = err;
          if (err) destroys.forEach(call);
          if (reading) return;
          destroys.forEach(call);
          callback(error2);
        });
      });
      return streams.reduce(pipe2);
    }, "pump");
    module2.exports = pump3;
  }
});

// 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: array2 } = options2;
      let { encoding } = options2;
      const isBuffer = encoding === "buffer";
      let objectMode = false;
      if (array2) {
        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 (array2) {
          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 pump3 = 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((resolve30, reject) => {
        const rejectPromise = /* @__PURE__ */ __name((error2) => {
          if (error2 && stream2.getBufferedLength() <= BufferConstants.MAX_LENGTH) {
            error2.bufferedData = stream2.getBufferedValue();
          }
          reject(error2);
        }, "rejectPromise");
        stream2 = pump3(inputStream, bufferStream(options2), (error2) => {
          if (error2) {
            rejectPromise(error2);
            return;
          }
          resolve30();
        });
        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 fs113 = __require("fs");
    var util3 = __require("util");
    var stream2 = __require("stream");
    var Readable6 = stream2.Readable;
    var Writable3 = stream2.Writable;
    var PassThrough8 = stream2.PassThrough;
    var Pend = require_pend();
    var EventEmitter11 = __require("events").EventEmitter;
    exports2.createFromBuffer = createFromBuffer;
    exports2.createFromFd = createFromFd;
    exports2.BufferSlicer = BufferSlicer;
    exports2.FdSlicer = FdSlicer;
    util3.inherits(FdSlicer, EventEmitter11);
    function FdSlicer(fd, options2) {
      options2 = options2 || {};
      EventEmitter11.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) {
        fs113.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) {
        fs113.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) {
        fs113.close(self2.fd, onCloseDone);
      }
      function onCloseDone(err) {
        if (err) {
          self2.emit("error", err);
        } else {
          self2.emit("close");
        }
      }
      __name(onCloseDone, "onCloseDone");
    };
    util3.inherits(ReadStream2, Readable6);
    function ReadStream2(context2, options2) {
      options2 = options2 || {};
      Readable6.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(n3) {
      var self2 = this;
      if (self2.destroyed) return;
      var toRead = Math.min(self2._readableState.highWaterMark, n3);
      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);
        fs113.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();
    };
    util3.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();
        fs113.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();
    };
    util3.inherits(BufferSlicer, EventEmitter11);
    function BufferSlicer(buffer, options2) {
      EventEmitter11.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 PassThrough8(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 Buffer9 = __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 (Buffer9.isBuffer(input)) {
        return input;
      }
      var hasNewBufferAPI = typeof Buffer9.alloc === "function" && typeof Buffer9.from === "function";
      if (typeof input === "number") {
        return hasNewBufferAPI ? Buffer9.alloc(input) : new Buffer9(input);
      } else if (typeof input === "string") {
        return hasNewBufferAPI ? Buffer9.from(input) : new Buffer9(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 (Buffer9.isBuffer(previous)) {
        previous = previous.readUInt32BE(0);
      }
      var crc = ~~previous ^ -1;
      for (var n3 = 0; n3 < buf.length; n3++) {
        crc = CRC_TABLE[(crc ^ buf[n3]) & 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 fs113 = __require("fs");
    var zlib4 = __require("zlib");
    var fd_slicer = require_fd_slicer();
    var crc32 = require_buffer_crc32();
    var util3 = __require("util");
    var EventEmitter11 = __require("events").EventEmitter;
    var Transform2 = __require("stream").Transform;
    var PassThrough8 = __require("stream").PassThrough;
    var Writable3 = __require("stream").Writable;
    exports2.open = open4;
    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 open4(path125, 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;
      fs113.open(path125, "r", function(err, fd) {
        if (err) return callback(err);
        fromFd(fd, options2, function(err2, zipfile) {
          if (err2) fs113.close(fd, defaultCallback);
          callback(err2, zipfile);
        });
      });
    }
    __name(open4, "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;
      fs113.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 i3 = bufferSize - eocdrWithoutCommentSize; i3 >= 0; i3 -= 1) {
          if (buffer.readUInt32LE(i3) !== 101010256) continue;
          var eocdrBuffer = buffer.slice(i3);
          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 + i3 - 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");
    util3.inherits(ZipFile, EventEmitter11);
    function ZipFile(reader, centralDirectoryOffset, fileSize, entryCount, comment, autoClose, lazyEntries, decodeStrings, validateEntrySizes, strictFileNames) {
      var self2 = this;
      EventEmitter11.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 i3 = 0;
          while (i3 < extraFieldBuffer.length - 3) {
            var headerId = extraFieldBuffer.readUInt16LE(i3 + 0);
            var dataSize = extraFieldBuffer.readUInt16LE(i3 + 2);
            var dataStart = i3 + 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
            });
            i3 = 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 i3 = 0; i3 < entry.extraFields.length; i3++) {
              var extraField = entry.extraFields[i3];
              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 i3 = 0; i3 < entry.extraFields.length; i3++) {
              var extraField = entry.extraFields[i3];
              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 = zlib4.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(date4, time3) {
      var day = date4 & 31;
      var month = (date4 >> 5 & 15) - 1;
      var year = (date4 >> 9 & 127) + 1980;
      var millisecond = 0;
      var second = (time3 & 31) * 2;
      var minute = time3 >> 5 & 63;
      var hour = time3 >> 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");
    util3.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();
    };
    util3.inherits(RandomAccessReader, EventEmitter11);
    function RandomAccessReader() {
      EventEmitter11.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 PassThrough8();
        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(error2) {
        callback(error2);
      });
      readStream.pipe(writeStream);
    };
    RandomAccessReader.prototype.close = function(callback) {
      setImmediate(callback);
    };
    util3.inherits(RefUnrefFilter, PassThrough8);
    function RefUnrefFilter(context2) {
      PassThrough8.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 i3 = start; i3 < end; i3++) {
          result += cp437[buffer[i3]];
        }
        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 debug3 = require_src()("extract-zip");
    var { createWriteStream: createWriteStream5, promises: fs113 } = __require("fs");
    var getStream = require_get_stream();
    var path125 = __require("path");
    var { promisify: promisify13 } = __require("util");
    var stream2 = __require("stream");
    var yauzl = require_yauzl();
    var openZip = promisify13(yauzl.open);
    var pipeline3 = promisify13(stream2.pipeline);
    var Extractor = class {
      static {
        __name(this, "Extractor");
      }
      constructor(zipPath, opts) {
        this.zipPath = zipPath;
        this.opts = opts;
      }
      async extract() {
        debug3("opening", this.zipPath, "with opts", this.opts);
        this.zipfile = await openZip(this.zipPath, { lazyEntries: true });
        this.canceled = false;
        return new Promise((resolve30, reject) => {
          this.zipfile.on("error", (err) => {
            this.canceled = true;
            reject(err);
          });
          this.zipfile.readEntry();
          this.zipfile.on("close", () => {
            if (!this.canceled) {
              debug3("zip extraction complete");
              resolve30();
            }
          });
          this.zipfile.on("entry", async (entry) => {
            if (this.canceled) {
              debug3("skipping entry", entry.fileName, { cancelled: this.canceled });
              return;
            }
            debug3("zipfile entry", entry.fileName);
            if (entry.fileName.startsWith("__MACOSX/")) {
              this.zipfile.readEntry();
              return;
            }
            const destDir = path125.dirname(path125.join(this.opts.dir, entry.fileName));
            try {
              await fs113.mkdir(destDir, { recursive: true });
              const canonicalDestDir = await fs113.realpath(destDir);
              const relativeDestDir = path125.relative(this.opts.dir, canonicalDestDir);
              if (relativeDestDir.split(path125.sep).includes("..")) {
                throw new Error(`Out of bound path "${canonicalDestDir}" found while processing file ${entry.fileName}`);
              }
              await this.extractEntry(entry);
              debug3("finished processing", entry.fileName);
              this.zipfile.readEntry();
            } catch (err) {
              this.canceled = true;
              this.zipfile.close();
              reject(err);
            }
          });
        });
      }
      async extractEntry(entry) {
        if (this.canceled) {
          debug3("skipping entry extraction", entry.fileName, { cancelled: this.canceled });
          return;
        }
        if (this.opts.onEntry) {
          this.opts.onEntry(entry, this.zipfile);
        }
        const dest = path125.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;
        debug3("extracting entry", { filename: entry.fileName, isDir, isSymlink: symlink });
        const procMode = this.getExtractedMode(mode, isDir) & 511;
        const destDir = isDir ? dest : path125.dirname(dest);
        const mkdirOptions2 = { recursive: true };
        if (isDir) {
          mkdirOptions2.mode = procMode;
        }
        debug3("mkdir", { dir: destDir, ...mkdirOptions2 });
        await fs113.mkdir(destDir, mkdirOptions2);
        if (isDir) return;
        debug3("opening read stream", dest);
        const readStream = await promisify13(this.zipfile.openReadStream.bind(this.zipfile))(entry);
        if (symlink) {
          const link3 = await getStream(readStream);
          debug3("creating symlink", link3, dest);
          await fs113.symlink(link3, dest);
        } else {
          await pipeline3(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) {
      debug3("creating target directory", opts.dir);
      if (!path125.isAbsolute(opts.dir)) {
        throw new Error("Target directory is expected to be absolute");
      }
      await fs113.mkdir(opts.dir, { recursive: true });
      opts.dir = await fs113.realpath(opts.dir);
      return new Extractor(zipPath, opts).extract();
    };
  }
});

// packages/core/dist/src/extension/github.js
import * as os20 from "node:os";
import * as https4 from "node:https";
import * as fs56 from "node:fs";
import * as path57 from "node:path";
function getGitHubToken() {
  return process.env["GITHUB_TOKEN"];
}
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 (error2) {
    throw new Error(`Failed to clone Git repository from ${installMetadata.source} ${getErrorMessage(error2)}`, {
      cause: error2
    });
  }
}
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 };
}
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);
}
async function checkForExtensionUpdate(extension, extensionManager) {
  const installMetadata = extension.installMetadata;
  if (installMetadata?.type === "local") {
    let latestConfig;
    try {
      latestConfig = extensionManager.loadExtensionConfig({
        extensionDir: installMetadata.source
      });
    } catch (e4) {
      debugLogger60.error(`Failed to check for update for local extension "${extension.name}". Could not load extension from source path: ${installMetadata.source}. Error: ${getErrorMessage(e4)}`);
      return ExtensionUpdateState.NOT_UPDATABLE;
    }
    if (!latestConfig) {
      debugLogger60.error(`Failed to check for update for local extension "${extension.name}". Could not load extension from source path: ${installMetadata.source}`);
      return ExtensionUpdateState.NOT_UPDATABLE;
    }
    if (latestConfig.version !== extension.version) {
      return ExtensionUpdateState.UPDATE_AVAILABLE;
    }
    return ExtensionUpdateState.UP_TO_DATE;
  }
  if (!installMetadata || installMetadata.type !== "git" && installMetadata.type !== "github-release") {
    return ExtensionUpdateState.NOT_UPDATABLE;
  }
  try {
    if (installMetadata.type === "git") {
      const git = simpleGit(extension.path);
      const remotes = await git.getRemotes(true);
      if (remotes.length === 0) {
        debugLogger60.error("No git remotes found.");
        return ExtensionUpdateState.ERROR;
      }
      const remoteUrl = remotes[0].refs.fetch;
      if (!remoteUrl) {
        debugLogger60.error(`No fetch URL found for git remote ${remotes[0].name}.`);
        return ExtensionUpdateState.ERROR;
      }
      const refToCheck = installMetadata.ref || "HEAD";
      const lsRemoteOutput = await git.listRemote([remoteUrl, refToCheck]);
      if (typeof lsRemoteOutput !== "string" || lsRemoteOutput.trim() === "") {
        debugLogger60.error(`Git ref ${refToCheck} not found.`);
        return ExtensionUpdateState.ERROR;
      }
      const remoteHash = lsRemoteOutput.split("	")[0];
      const localHash = await git.revparse(["HEAD"]);
      if (!remoteHash) {
        debugLogger60.error(`Unable to parse hash from git ls-remote output "${lsRemoteOutput}"`);
        return ExtensionUpdateState.ERROR;
      }
      if (remoteHash === localHash) {
        return ExtensionUpdateState.UP_TO_DATE;
      }
      return ExtensionUpdateState.UPDATE_AVAILABLE;
    } else {
      const { source: source2, releaseTag } = installMetadata;
      if (!source2) {
        debugLogger60.error('No "source" provided for extension.');
        return ExtensionUpdateState.ERROR;
      }
      const { owner, repo } = parseGitHubRepoForReleases(source2);
      const releaseData = await fetchReleaseFromGithub(owner, repo, installMetadata.ref);
      if (releaseData.tag_name !== releaseTag) {
        return ExtensionUpdateState.UPDATE_AVAILABLE;
      }
      return ExtensionUpdateState.UP_TO_DATE;
    }
  } catch (error2) {
    debugLogger60.error(`Failed to check for updates for extension "${installMetadata.source}": ${getErrorMessage(error2)}`);
    return ExtensionUpdateState.ERROR;
  }
}
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 = path57.join(destination, path57.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 fs56.promises.readdir(destination, {
      withFileTypes: true
    });
    if (entries.length === 2) {
      const lonelyDir = entries.find((entry) => entry.isDirectory());
      if (lonelyDir) {
        const hasQwenConfig = fs56.existsSync(path57.join(destination, lonelyDir.name, EXTENSIONS_CONFIG_FILENAME));
        const hasGeminiConfig = fs56.existsSync(path57.join(destination, lonelyDir.name, "gemini-extension.json"));
        const hasMarketplaceConfig = fs56.existsSync(path57.join(destination, lonelyDir.name, ".claude-plugin/marketplace.json"));
        const hasClaudePluginConfig = fs56.existsSync(path57.join(destination, lonelyDir.name, ".claude-plugin/plugin.json"));
        if (hasQwenConfig || hasGeminiConfig || hasMarketplaceConfig || hasClaudePluginConfig) {
          const dirPathToExtract = path57.join(destination, lonelyDir.name);
          const extractedDirFiles = await fs56.promises.readdir(dirPathToExtract);
          for (const file of extractedDirFiles) {
            await fs56.promises.rename(path57.join(dirPathToExtract, file), path57.join(destination, file));
          }
          await fs56.promises.rmdir(dirPathToExtract);
        }
      }
    }
    await fs56.promises.unlink(downloadedAssetPath);
    return {
      tagName: releaseData.tag_name,
      type: "github-release"
    };
  } catch (error2) {
    throw new Error(`Failed to download release from ${installMetadata.source}: ${getErrorMessage(error2)}`);
  }
}
function findReleaseAsset(assets) {
  const platform16 = os20.platform();
  const arch3 = os20.arch();
  const platformArchPrefix = `${platform16}.${arch3}.`;
  const platformPrefix = `${platform16}.`;
  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;
}
async function fetchJson(url2) {
  const headers = {
    "User-Agent": "gemini-cli"
  };
  const token2 = getGitHubToken();
  if (token2) {
    headers.Authorization = `token ${token2}`;
  }
  return new Promise((resolve30, reject) => {
    https4.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();
        resolve30(JSON.parse(data));
      });
    }).on("error", reject);
  });
}
async function downloadFile2(url2, dest) {
  const headers = {
    "User-agent": "gemini-cli"
  };
  const token2 = getGitHubToken();
  if (token2) {
    headers.Authorization = `token ${token2}`;
  }
  return new Promise((resolve30, reject) => {
    https4.get(url2, { headers }, (res) => {
      if (res.statusCode === 302 || res.statusCode === 301) {
        downloadFile2(res.headers.location, dest).then(resolve30).catch(reject);
        return;
      }
      if (res.statusCode !== 200) {
        return reject(new Error(`Request failed with status code ${res.statusCode}`));
      }
      const file = fs56.createWriteStream(dest);
      res.pipe(file);
      file.on("finish", () => file.close(resolve30));
    }).on("error", reject);
  });
}
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}`);
  }
}
var import_extract_zip, debugLogger60;
var init_github = __esm({
  "packages/core/dist/src/extension/github.js"() {
    "use strict";
    init_esbuild_shims();
    init_esm12();
    init_errors();
    init_variables();
    init_esm26();
    import_extract_zip = __toESM(require_extract_zip(), 1);
    init_debugLogger();
    init_extensionManager();
    debugLogger60 = createDebugLogger("EXT_GITHUB");
    __name(getGitHubToken, "getGitHubToken");
    __name(cloneFromGit, "cloneFromGit");
    __name(parseGitHubRepoForReleases, "parseGitHubRepoForReleases");
    __name(fetchReleaseFromGithub, "fetchReleaseFromGithub");
    __name(checkForExtensionUpdate, "checkForExtensionUpdate");
    __name(downloadFromGitHubRelease, "downloadFromGitHubRelease");
    __name(findReleaseAsset, "findReleaseAsset");
    __name(fetchJson, "fetchJson");
    __name(downloadFile2, "downloadFile");
    __name(extractFile2, "extractFile");
  }
});

// packages/core/dist/src/extension/override.js
function globToRegex(glob2) {
  const regexString = glob2.replace(/[.+?^${}()|[\]\\]/g, "\\$&").replace(/(\/?)\*/g, "($1.*)?");
  return new RegExp(`^${regexString}$`);
}
var Override, ensureLeadingAndTrailingSlash;
var init_override = __esm({
  "packages/core/dist/src/extension/override.js"() {
    "use strict";
    init_esbuild_shims();
    Override = class _Override {
      static {
        __name(this, "Override");
      }
      baseRule;
      isDisable;
      includeSubdirs;
      constructor(baseRule, isDisable, includeSubdirs) {
        this.baseRule = baseRule;
        this.isDisable = isDisable;
        this.includeSubdirs = includeSubdirs;
      }
      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(path125) {
        return this.asRegex().test(path125);
      }
    };
    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");
    __name(globToRegex, "globToRegex");
  }
});

// packages/core/dist/src/extension/storage.js
import path58 from "node:path";
import * as os21 from "node:os";
import * as fs57 from "node:fs";
var ExtensionStorage;
var init_storage2 = __esm({
  "packages/core/dist/src/extension/storage.js"() {
    "use strict";
    init_esbuild_shims();
    init_storage();
    init_variables();
    ExtensionStorage = class _ExtensionStorage {
      static {
        __name(this, "ExtensionStorage");
      }
      extensionName;
      constructor(extensionName) {
        this.extensionName = extensionName;
      }
      getExtensionDir() {
        return path58.join(_ExtensionStorage.getUserExtensionsDir(), this.extensionName);
      }
      getConfigPath() {
        return path58.join(this.getExtensionDir(), EXTENSIONS_CONFIG_FILENAME);
      }
      getEnvFilePath() {
        return path58.join(this.getExtensionDir(), EXTENSION_SETTINGS_FILENAME);
      }
      static getUserExtensionsDir() {
        const homeDir = os21.homedir();
        if (!homeDir) {
          const tmpDir = os21.tmpdir();
          if (!tmpDir) {
            return "/tmp/.qwen/extensions";
          }
          return path58.join(tmpDir, ".qwen", "extensions");
        }
        const storage = new Storage(homeDir);
        return storage.getExtensionsDir();
      }
      static async createTmpDir() {
        return await fs57.promises.mkdtemp(path58.join(os21.tmpdir(), "qwen-extension"));
      }
    };
  }
});

// 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 date4 = new Date(value);
      if (isNaN(date4)) {
        throw new TypeError("Invalid Datetime");
      } else {
        return date4;
      }
    };
  }
});

// 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 = (d2, num) => {
      num = String(num);
      while (num.length < d2) 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 f5 = require_format_num();
    var FloatingDateTime = class extends Date {
      static {
        __name(this, "FloatingDateTime");
      }
      constructor(value) {
        super(value + "Z");
        this.isFloating = true;
      }
      toISOString() {
        const date4 = `${this.getUTCFullYear()}-${f5(2, this.getUTCMonth() + 1)}-${f5(2, this.getUTCDate())}`;
        const time3 = `${f5(2, this.getUTCHours())}:${f5(2, this.getUTCMinutes())}:${f5(2, this.getUTCSeconds())}.${f5(3, this.getUTCMilliseconds())}`;
        return `${date4}T${time3}`;
      }
    };
    module2.exports = (value) => {
      const date4 = new FloatingDateTime(value);
      if (isNaN(date4)) {
        throw new TypeError("Invalid Datetime");
      } else {
        return date4;
      }
    };
  }
});

// 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 f5 = 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()}-${f5(2, this.getUTCMonth() + 1)}-${f5(2, this.getUTCDate())}`;
      }
    };
    module2.exports = (value) => {
      const date4 = new Date2(value);
      if (isNaN(date4)) {
        throw new TypeError("Invalid Datetime");
      } else {
        return date4;
      }
    };
  }
});

// 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 f5 = 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 `${f5(2, this.getUTCHours())}:${f5(2, this.getUTCMinutes())}:${f5(2, this.getUTCSeconds())}.${f5(3, this.getUTCMilliseconds())}`;
      }
    };
    module2.exports = (value) => {
      const date4 = new Time(value);
      if (isNaN(date4)) {
        throw new TypeError("Invalid Datetime");
      } else {
        return date4;
      }
    };
  }
});

// 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(cp3) {
      return cp3 >= CHAR_0 && cp3 <= CHAR_9;
    }
    __name(isDigit, "isDigit");
    function isHexit(cp3) {
      return cp3 >= CHAR_A && cp3 <= CHAR_F || cp3 >= CHAR_a && cp3 <= CHAR_f || cp3 >= CHAR_0 && cp3 <= CHAR_9;
    }
    __name(isHexit, "isHexit");
    function isBit(cp3) {
      return cp3 === CHAR_1 || cp3 === CHAR_0;
    }
    __name(isBit, "isBit");
    function isOctit(cp3) {
      return cp3 >= CHAR_0 && cp3 <= CHAR_7;
    }
    __name(isOctit, "isOctit");
    function isAlphaNumQuoteHyphen(cp3) {
      return cp3 >= CHAR_A && cp3 <= CHAR_Z || cp3 >= CHAR_a && cp3 <= CHAR_z || cp3 >= CHAR_0 && cp3 <= CHAR_9 || cp3 === CHAR_APOS || cp3 === CHAR_QUOT || cp3 === CHAR_LOWBAR || cp3 === CHAR_HYPHEN;
    }
    __name(isAlphaNumQuoteHyphen, "isAlphaNumQuoteHyphen");
    function isAlphaNumHyphen(cp3) {
      return cp3 >= CHAR_A && cp3 <= CHAR_Z || cp3 >= CHAR_a && cp3 <= CHAR_z || cp3 >= CHAR_0 && cp3 <= CHAR_9 || cp3 === CHAR_LOWBAR || cp3 === 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 (_2) {
    }
    var _inspect = _custom || "inspect";
    var BoxedBigInt = class {
      static {
        __name(this, "BoxedBigInt");
      }
      constructor(value) {
        try {
          this.value = globalThis.BigInt.asIntN(64, value);
        } catch (_2) {
          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 = parseAsync3;
    var TOMLParser = require_toml_parser();
    var prettyError = require_parse_pretty_error();
    function parseAsync3(str2, opts) {
      if (!opts) opts = {};
      const index = 0;
      const blocksize = opts.blocksize || 40960;
      const parser6 = new TOMLParser();
      return new Promise((resolve30, reject) => {
        setImmediate(parseAsyncNext, index, blocksize, resolve30, reject);
      });
      function parseAsyncNext(index2, blocksize2, resolve30, reject) {
        if (index2 >= str2.length) {
          try {
            return resolve30(parser6.finish());
          } catch (err) {
            return reject(prettyError(err, str2));
          }
        }
        try {
          parser6.parse(str2.slice(index2, index2 + blocksize2));
          setImmediate(parseAsyncNext, index2 + blocksize2, blocksize2, resolve30, reject);
        } catch (err) {
          reject(prettyError(err, str2));
        }
      }
      __name(parseAsyncNext, "parseAsyncNext");
    }
    __name(parseAsync3, "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((resolve30, reject) => {
        let readable;
        let ended = false;
        let errored = false;
        function finish() {
          ended = true;
          if (readable) return;
          try {
            resolve30(parser6.finish());
          } catch (err) {
            reject(err);
          }
        }
        __name(finish, "finish");
        function error2(err) {
          errored = true;
          reject(err);
        }
        __name(error2, "error");
        stm.once("end", finish);
        stm.once("error", error2);
        readNext();
        function readNext() {
          readable = true;
          let data;
          while ((data = stm.read()) !== null) {
            try {
              parser6.parse(data);
            } catch (err) {
              return error2(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_parse6 = __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_stringify2 = __commonJS({
  "node_modules/@iarna/toml/stringify.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    module2.exports = stringify4;
    module2.exports.value = stringifyInline;
    function stringify4(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(stringify4, "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])/, (c4) => "\\u" + numpad(4, c4.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((_2) => tomlType2(_2) !== "null" && tomlType2(_2) !== "undefined" && tomlType2(_2) !== "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 int2 = chunks[0];
      var dec = chunks[1] || 0;
      return stringifyInteger(int2) + "." + 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((_2) => tomlType2(_2) === contentType)) return contentType;
      if (values.every((_2) => isNumber3(tomlType2(_2)))) 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((_2) => stringifyInline(_2, 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_parse6();
    exports2.stringify = require_stringify2();
  }
});

// packages/core/dist/src/utils/toml-to-markdown-converter.js
function convertTomlToMarkdown(tomlContent) {
  let parsed;
  try {
    parsed = import_toml.default.parse(tomlContent);
  } catch (error2) {
    throw new Error(`Failed to parse TOML: ${error2 instanceof Error ? error2.message : String(error2)}`);
  }
  if (typeof parsed !== "object" || parsed === null) {
    throw new Error("TOML content must be an object");
  }
  const obj = parsed;
  if (typeof obj["prompt"] !== "string") {
    throw new Error('TOML must contain a "prompt" field');
  }
  const prompt = obj["prompt"];
  const description = typeof obj["description"] === "string" ? obj["description"] : void 0;
  if (description) {
    return `---
description: ${description}
---

${prompt}
`;
  } else {
    return `${prompt}
`;
  }
}
var import_toml;
var init_toml_to_markdown_converter = __esm({
  "packages/core/dist/src/utils/toml-to-markdown-converter.js"() {
    "use strict";
    init_esbuild_shims();
    import_toml = __toESM(require_toml(), 1);
    __name(convertTomlToMarkdown, "convertTomlToMarkdown");
  }
});

// packages/core/dist/src/extension/gemini-converter.js
import * as fs58 from "node:fs";
import * as path59 from "node:path";
function convertGeminiToQwenConfig(extensionDir) {
  const configFilePath2 = path59.join(extensionDir, "gemini-extension.json");
  const configContent = fs58.readFileSync(configFilePath2, "utf-8");
  const geminiConfig = JSON.parse(configContent);
  if (!geminiConfig.name || !geminiConfig.version) {
    throw new Error("Gemini extension config must have name and version fields");
  }
  const settings = geminiConfig.settings;
  return {
    name: geminiConfig.name,
    version: geminiConfig.version,
    mcpServers: geminiConfig.mcpServers,
    contextFileName: geminiConfig.contextFileName,
    settings
  };
}
async function convertGeminiExtensionPackage(extensionDir) {
  const geminiConfig = convertGeminiToQwenConfig(extensionDir);
  const tmpDir = await ExtensionStorage.createTmpDir();
  try {
    await copyDirectory(extensionDir, tmpDir);
    const commandsDir = path59.join(tmpDir, "commands");
    if (fs58.existsSync(commandsDir)) {
      await convertCommandsDirectory(commandsDir);
    }
    const qwenConfigPath = path59.join(tmpDir, "qwen-extension.json");
    fs58.writeFileSync(qwenConfigPath, JSON.stringify(geminiConfig, null, 2), "utf-8");
    return {
      config: geminiConfig,
      convertedDir: tmpDir
    };
  } catch (error2) {
    try {
      fs58.rmSync(tmpDir, { recursive: true, force: true });
    } catch {
    }
    throw error2;
  }
}
async function copyDirectory(source2, destination) {
  if (!fs58.existsSync(destination)) {
    fs58.mkdirSync(destination, { recursive: true });
  }
  const entries = fs58.readdirSync(source2, { withFileTypes: true });
  for (const entry of entries) {
    const sourcePath = path59.join(source2, entry.name);
    const destPath = path59.join(destination, entry.name);
    if (entry.isDirectory()) {
      await copyDirectory(sourcePath, destPath);
    } else {
      fs58.copyFileSync(sourcePath, destPath);
    }
  }
}
async function convertCommandsDirectory(commandsDir) {
  const tomlFiles = await glob("**/*.toml", {
    cwd: commandsDir,
    nodir: true,
    dot: false
  });
  for (const relativeFile of tomlFiles) {
    const tomlPath = path59.join(commandsDir, relativeFile);
    try {
      const tomlContent = fs58.readFileSync(tomlPath, "utf-8");
      const markdownContent = convertTomlToMarkdown(tomlContent);
      const markdownPath = tomlPath.replace(/\.toml$/, ".md");
      fs58.writeFileSync(markdownPath, markdownContent, "utf-8");
      fs58.unlinkSync(tomlPath);
    } catch (error2) {
      debugLogger61.warn(`Warning: Failed to convert command file ${relativeFile}: ${error2 instanceof Error ? error2.message : String(error2)}`);
    }
  }
}
function isGeminiExtensionConfig(extensionDir) {
  const configFilePath2 = path59.join(extensionDir, "gemini-extension.json");
  if (!fs58.existsSync(configFilePath2)) {
    return false;
  }
  const configContent = fs58.readFileSync(configFilePath2, "utf-8");
  const parsedConfig = JSON.parse(configContent);
  if (typeof parsedConfig !== "object" || parsedConfig === null) {
    return false;
  }
  const obj = parsedConfig;
  if (typeof obj["name"] !== "string" || typeof obj["version"] !== "string") {
    return false;
  }
  if (obj["settings"] && Array.isArray(obj["settings"])) {
    const firstSetting = obj["settings"][0];
    if (firstSetting && typeof firstSetting === "object" && "envVar" in firstSetting) {
      return true;
    }
  }
  return true;
}
var debugLogger61;
var init_gemini_converter = __esm({
  "packages/core/dist/src/extension/gemini-converter.js"() {
    "use strict";
    init_esbuild_shims();
    init_esm11();
    init_storage2();
    init_toml_to_markdown_converter();
    init_debugLogger();
    debugLogger61 = createDebugLogger("GEMINI_CONVERTER");
    __name(convertGeminiToQwenConfig, "convertGeminiToQwenConfig");
    __name(convertGeminiExtensionPackage, "convertGeminiExtensionPackage");
    __name(copyDirectory, "copyDirectory");
    __name(convertCommandsDirectory, "convertCommandsDirectory");
    __name(isGeminiExtensionConfig, "isGeminiExtensionConfig");
  }
});

// packages/core/dist/src/extension/claude-converter.js
import * as fs59 from "node:fs";
import * as path60 from "node:path";
import { createHash as createHash4 } from "node:crypto";
function parseStringOrArray(value) {
  if (value === void 0 || value === null) {
    return void 0;
  }
  if (Array.isArray(value)) {
    return value.map(String);
  }
  if (typeof value === "string") {
    return value.split(",").map((s5) => s5.trim()).filter((s5) => s5.length > 0);
  }
  return void 0;
}
function convertClaudeAgentConfig(claudeAgent) {
  const qwenAgent = {
    name: claudeAgent.name,
    description: claudeAgent.description
  };
  if (claudeAgent.color) {
    qwenAgent["color"] = claudeAgent.color;
  }
  if (claudeAgent.systemPrompt) {
    qwenAgent["systemPrompt"] = claudeAgent.systemPrompt;
  }
  if (claudeAgent.tools && claudeAgent.tools.length > 0) {
    qwenAgent["tools"] = claudeBuildInToolsTransform(claudeAgent.tools);
  }
  if (claudeAgent.model) {
    qwenAgent["modelConfig"] = {
      model: claudeAgent.model === "inherit" ? void 0 : claudeAgent.model
    };
  }
  if (claudeAgent.permissionMode) {
    qwenAgent["permissionMode"] = claudeAgent.permissionMode;
  }
  if (claudeAgent.hooks) {
    qwenAgent["hooks"] = claudeAgent.hooks;
  }
  if (claudeAgent.skills && claudeAgent.skills.length > 0) {
    qwenAgent["skills"] = claudeAgent.skills;
  }
  if (claudeAgent.disallowedTools && claudeAgent.disallowedTools.length > 0) {
    qwenAgent["disallowedTools"] = claudeAgent.disallowedTools;
  }
  return qwenAgent;
}
async function convertAgentFiles(agentsDir) {
  if (!fs59.existsSync(agentsDir)) {
    return;
  }
  const files = await fs59.promises.readdir(agentsDir);
  for (const file of files) {
    if (!file.endsWith(".md"))
      continue;
    const filePath = path60.join(agentsDir, file);
    try {
      const content = await fs59.promises.readFile(filePath, "utf-8");
      const frontmatterRegex = /^---\n([\s\S]*?)\n---\n([\s\S]*)$/;
      const match2 = content.match(frontmatterRegex);
      if (!match2) {
        continue;
      }
      const [, frontmatterYaml, body] = match2;
      const frontmatter = parse6(frontmatterYaml);
      const claudeAgent = {
        name: String(frontmatter["name"] || ""),
        description: String(frontmatter["description"] || ""),
        tools: parseStringOrArray(frontmatter["tools"]),
        disallowedTools: parseStringOrArray(frontmatter["disallowedTools"]),
        model: frontmatter["model"],
        permissionMode: frontmatter["permissionMode"],
        skills: parseStringOrArray(frontmatter["skills"]),
        hooks: frontmatter["hooks"],
        color: frontmatter["color"],
        systemPrompt: body.trim()
      };
      const qwenAgent = convertClaudeAgentConfig(claudeAgent);
      const newFrontmatter = {};
      for (const [key, value] of Object.entries(qwenAgent)) {
        if (key !== "systemPrompt" && value !== void 0) {
          newFrontmatter[key] = value;
        }
      }
      const newYaml = stringify2(newFrontmatter);
      const systemPrompt = qwenAgent["systemPrompt"] || body.trim();
      const newContent = `---
${newYaml}
---

${systemPrompt}
`;
      await fs59.promises.writeFile(filePath, newContent, "utf-8");
    } catch (error2) {
      debugLogger62.warn(`[Claude Converter] Failed to convert agent file ${filePath}: ${error2 instanceof Error ? error2.message : String(error2)}`);
    }
  }
}
function convertClaudeToQwenConfig(claudeConfig) {
  if (!claudeConfig.name) {
    throw new Error("Claude plugin config must have name field");
  }
  let mcpServers;
  if (claudeConfig.mcpServers) {
    if (typeof claudeConfig.mcpServers === "string") {
      debugLogger62.warn(`[Claude Converter] MCP servers path not yet supported: ${claudeConfig.mcpServers}`);
    } else {
      mcpServers = claudeConfig.mcpServers;
    }
  }
  if (claudeConfig.hooks) {
    debugLogger62.warn(`[Claude Converter] Hooks are not yet supported in ${claudeConfig.name}`);
  }
  if (claudeConfig.outputStyles) {
    debugLogger62.warn(`[Claude Converter] Output styles are not yet supported in ${claudeConfig.name}`);
  }
  return {
    name: claudeConfig.name,
    version: claudeConfig.version,
    mcpServers,
    lspServers: claudeConfig.lspServers
  };
}
async function convertClaudePluginPackage(extensionDir, pluginName) {
  const marketplaceJsonPath = path60.join(extensionDir, ".claude-plugin", "marketplace.json");
  if (!fs59.existsSync(marketplaceJsonPath)) {
    throw new Error(`Marketplace configuration not found at ${marketplaceJsonPath}`);
  }
  const marketplaceContent = fs59.readFileSync(marketplaceJsonPath, "utf-8");
  const marketplaceConfig = JSON.parse(marketplaceContent);
  const marketplacePlugin = marketplaceConfig.plugins.find((p2) => p2.name === pluginName);
  if (!marketplacePlugin) {
    throw new Error(`Plugin ${pluginName} not found in marketplace.json`);
  }
  const pluginDir = path60.join(extensionDir, `plugin${createHash4("sha256").update(`${extensionDir}/${pluginName}`).digest("hex")}`);
  await fs59.promises.mkdir(pluginDir, { recursive: true });
  const pluginSource = await resolvePluginSource(marketplacePlugin, extensionDir, pluginDir);
  if (!fs59.existsSync(pluginSource)) {
    throw new Error(`Plugin source directory not found: ${pluginSource}`);
  }
  const strict = marketplacePlugin.strict ?? false;
  let mergedConfig;
  if (strict) {
    const pluginJsonPath = path60.join(pluginSource, ".claude-plugin", "plugin.json");
    if (!fs59.existsSync(pluginJsonPath)) {
      throw new Error(`Strict mode requires plugin.json at ${pluginJsonPath}`);
    }
    const pluginContent = fs59.readFileSync(pluginJsonPath, "utf-8");
    const pluginConfig = JSON.parse(pluginContent);
    mergedConfig = mergeClaudeConfigs(marketplacePlugin, pluginConfig);
  } else {
    mergedConfig = marketplacePlugin;
  }
  if (mergedConfig.mcpServers && typeof mergedConfig.mcpServers === "string") {
    const mcpServersPath = path60.isAbsolute(mergedConfig.mcpServers) ? mergedConfig.mcpServers : path60.join(pluginSource, mergedConfig.mcpServers);
    if (fs59.existsSync(mcpServersPath)) {
      try {
        const mcpContent = fs59.readFileSync(mcpServersPath, "utf-8");
        mergedConfig.mcpServers = JSON.parse(mcpContent);
      } catch (error2) {
        debugLogger62.warn(`Failed to parse MCP servers file ${mcpServersPath}: ${error2 instanceof Error ? error2.message : String(error2)}`);
      }
    }
  }
  const tmpDir = await ExtensionStorage.createTmpDir();
  try {
    await copyDirectory(pluginSource, tmpDir);
    const resourceConfigs = [
      { name: "commands", config: mergedConfig.commands },
      { name: "skills", config: mergedConfig.skills },
      { name: "agents", config: mergedConfig.agents }
    ];
    for (const { name: name3, config: config2 } of resourceConfigs) {
      const folderPath = path60.join(tmpDir, name3);
      const sourceFolderPath = path60.join(pluginSource, name3);
      if (config2) {
        if (fs59.existsSync(folderPath)) {
          fs59.rmSync(folderPath, { recursive: true, force: true });
        }
        await collectResources(config2, pluginSource, folderPath);
      } else if (!fs59.existsSync(sourceFolderPath) && fs59.existsSync(folderPath)) {
        fs59.rmSync(folderPath, { recursive: true, force: true });
      }
    }
    const agentsDestDir = path60.join(tmpDir, "agents");
    await convertAgentFiles(agentsDestDir);
    const qwenConfig = convertClaudeToQwenConfig(mergedConfig);
    const qwenConfigPath = path60.join(tmpDir, "qwen-extension.json");
    fs59.writeFileSync(qwenConfigPath, JSON.stringify(qwenConfig, null, 2), "utf-8");
    return {
      config: qwenConfig,
      convertedDir: tmpDir
    };
  } catch (error2) {
    try {
      fs59.rmSync(tmpDir, { recursive: true, force: true });
    } catch {
    }
    throw error2;
  }
}
async function collectResources(resourcePaths, pluginRoot, destDir) {
  const paths = Array.isArray(resourcePaths) ? resourcePaths : [resourcePaths];
  if (!fs59.existsSync(destDir)) {
    fs59.mkdirSync(destDir, { recursive: true });
  }
  const destFolderName = path60.basename(destDir);
  for (const resourcePath of paths) {
    const resolvedPath = path60.isAbsolute(resourcePath) ? resourcePath : path60.join(pluginRoot, resourcePath);
    if (!fs59.existsSync(resolvedPath)) {
      debugLogger62.warn(`Resource path not found: ${resolvedPath}`);
      continue;
    }
    const stat10 = fs59.statSync(resolvedPath);
    if (stat10.isDirectory()) {
      const dirName = path60.basename(resolvedPath);
      const parentDir = path60.dirname(resolvedPath);
      if (dirName === destFolderName && parentDir === pluginRoot) {
        debugLogger62.debug(`Skipping ${resolvedPath} as it's already in the correct location`);
        continue;
      }
      const finalDestDir = path60.join(destDir, dirName);
      const files = await glob("**/*", {
        cwd: resolvedPath,
        nodir: true,
        dot: false
      });
      for (const file of files) {
        const srcFile = path60.join(resolvedPath, file);
        const destFile = path60.join(finalDestDir, file);
        const destFileDir = path60.dirname(destFile);
        if (!fs59.existsSync(destFileDir)) {
          fs59.mkdirSync(destFileDir, { recursive: true });
        }
        fs59.copyFileSync(srcFile, destFile);
      }
    } else {
      const relativePath = path60.relative(pluginRoot, resolvedPath);
      const segments = relativePath.split(path60.sep);
      if (segments.length > 0 && segments[0] === destFolderName) {
        debugLogger62.debug(`Skipping ${resolvedPath} as it's already in ${destFolderName}/`);
        continue;
      }
      const fileName = path60.basename(resolvedPath);
      const destFile = path60.join(destDir, fileName);
      fs59.copyFileSync(resolvedPath, destFile);
    }
  }
}
function mergeClaudeConfigs(marketplacePlugin, pluginConfig) {
  if (!pluginConfig && marketplacePlugin.strict === true) {
    throw new Error(`Plugin ${marketplacePlugin.name} requires plugin.json (strict mode)`);
  }
  const merged = pluginConfig ? { ...pluginConfig } : {
    name: marketplacePlugin.name,
    version: "1.0.0"
    // Default version if not in marketplace
  };
  if (marketplacePlugin.name)
    merged.name = marketplacePlugin.name;
  if (marketplacePlugin.version)
    merged.version = marketplacePlugin.version;
  if (marketplacePlugin.description)
    merged.description = marketplacePlugin.description;
  if (marketplacePlugin.author)
    merged.author = marketplacePlugin.author;
  if (marketplacePlugin.homepage)
    merged.homepage = marketplacePlugin.homepage;
  if (marketplacePlugin.repository)
    merged.repository = marketplacePlugin.repository;
  if (marketplacePlugin.license)
    merged.license = marketplacePlugin.license;
  if (marketplacePlugin.keywords)
    merged.keywords = marketplacePlugin.keywords;
  if (marketplacePlugin.commands)
    merged.commands = marketplacePlugin.commands;
  if (marketplacePlugin.agents)
    merged.agents = marketplacePlugin.agents;
  if (marketplacePlugin.skills)
    merged.skills = marketplacePlugin.skills;
  if (marketplacePlugin.hooks)
    merged.hooks = marketplacePlugin.hooks;
  if (marketplacePlugin.mcpServers)
    merged.mcpServers = marketplacePlugin.mcpServers;
  if (marketplacePlugin.outputStyles)
    merged.outputStyles = marketplacePlugin.outputStyles;
  if (marketplacePlugin.lspServers)
    merged.lspServers = marketplacePlugin.lspServers;
  return merged;
}
async function resolvePluginSource(pluginConfig, marketplaceDir, pluginDir) {
  const source2 = pluginConfig.source;
  if (typeof source2 === "string") {
    if (source2.startsWith("http://") || source2.startsWith("https://")) {
      const installMetadata = {
        source: source2,
        type: "git",
        originSource: "Claude"
      };
      try {
        await downloadFromGitHubRelease(installMetadata, pluginDir);
      } catch {
        await cloneFromGit(installMetadata, pluginDir);
      }
      return pluginDir;
    }
    const pluginRoot = marketplaceDir;
    const sourcePath = path60.join(pluginRoot, source2);
    if (!fs59.existsSync(sourcePath)) {
      throw new Error(`Plugin source not found at ${sourcePath}`);
    }
    if (path60.resolve(sourcePath) === path60.resolve(marketplaceDir)) {
      return marketplaceDir;
    }
    await fs59.promises.cp(sourcePath, pluginDir, { recursive: true });
    return pluginDir;
  }
  if (source2.source === "github") {
    const installMetadata = {
      source: `https://github.com/${source2.repo}`,
      type: "git"
    };
    try {
      await downloadFromGitHubRelease(installMetadata, pluginDir);
    } catch {
      await cloneFromGit(installMetadata, pluginDir);
    }
    return pluginDir;
  }
  if (source2.source === "url") {
    const installMetadata = {
      source: source2.url,
      type: "git"
    };
    try {
      await downloadFromGitHubRelease(installMetadata, pluginDir);
    } catch {
      await cloneFromGit(installMetadata, pluginDir);
    }
    return pluginDir;
  }
  throw new Error(`Unsupported plugin source type: ${JSON.stringify(source2)}`);
}
var debugLogger62, CLAUDE_TOOLS_MAPPING, claudeBuildInToolsTransform;
var init_claude_converter = __esm({
  "packages/core/dist/src/extension/claude-converter.js"() {
    "use strict";
    init_esbuild_shims();
    init_esm11();
    init_storage2();
    init_github();
    init_gemini_converter();
    init_yaml_parser();
    init_debugLogger();
    debugLogger62 = createDebugLogger("CLAUDE_CONVERTER");
    CLAUDE_TOOLS_MAPPING = {
      AskUserQuestion: "None",
      Bash: "Shell",
      BashOutput: "None",
      Edit: "Edit",
      ExitPlanMode: "ExitPlanMode",
      Glob: "Glob",
      Grep: "Grep",
      KillShell: "None",
      NotebookEdit: "None",
      Read: "ReadFile",
      Skill: "Skill",
      Task: "Task",
      TodoWrite: "TodoWrite",
      WebFetch: "WebFetch",
      WebSearch: "WebSearch",
      Write: "WriteFile",
      LS: "ListFiles"
    };
    claudeBuildInToolsTransform = /* @__PURE__ */ __name((tools) => {
      const transformedTools = [];
      tools.forEach((tool) => {
        if (!CLAUDE_TOOLS_MAPPING[tool]) {
          transformedTools.push(tool);
        } else {
          if (CLAUDE_TOOLS_MAPPING[tool] === "None") {
            return;
          } else if (Array.isArray(CLAUDE_TOOLS_MAPPING[tool])) {
            transformedTools.push(...CLAUDE_TOOLS_MAPPING[tool]);
          } else {
            transformedTools.push(CLAUDE_TOOLS_MAPPING[tool]);
          }
        }
      });
      return transformedTools;
    }, "claudeBuildInToolsTransform");
    __name(parseStringOrArray, "parseStringOrArray");
    __name(convertClaudeAgentConfig, "convertClaudeAgentConfig");
    __name(convertAgentFiles, "convertAgentFiles");
    __name(convertClaudeToQwenConfig, "convertClaudeToQwenConfig");
    __name(convertClaudePluginPackage, "convertClaudePluginPackage");
    __name(collectResources, "collectResources");
    __name(mergeClaudeConfigs, "mergeClaudeConfigs");
    __name(resolvePluginSource, "resolvePluginSource");
  }
});

// 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 fs113 = __require("fs");
    var path125 = __require("path");
    var os47 = __require("os");
    var crypto14 = __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 parse14(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(parse14, "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 i3 = 0; i3 < length; i3++) {
        try {
          const key = keys[i3].trim();
          const attrs = _instructions(result, key);
          decrypted = DotenvModule.decrypt(attrs.ciphertext, attrs.key);
          break;
        } catch (error2) {
          if (i3 + 1 >= length) {
            throw error2;
          }
        }
      }
      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 (error2) {
        if (error2.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 error2;
      }
      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 (fs113.existsSync(filepath)) {
              possibleVaultPath = filepath.endsWith(".vault") ? filepath : `${filepath}.vault`;
            }
          }
        } else {
          possibleVaultPath = options2.path.endsWith(".vault") ? options2.path : `${options2.path}.vault`;
        }
      } else {
        possibleVaultPath = path125.resolve(process.cwd(), ".env.vault");
      }
      if (fs113.existsSync(possibleVaultPath)) {
        return possibleVaultPath;
      }
      return null;
    }
    __name(_vaultPath, "_vaultPath");
    function _resolveHome(envPath) {
      return envPath[0] === "~" ? path125.join(os47.homedir(), envPath.slice(1)) : envPath;
    }
    __name(_resolveHome, "_resolveHome");
    function _configVault(options2) {
      const debug3 = Boolean(options2 && options2.debug);
      const quiet = Boolean(options2 && options2.quiet);
      if (debug3 || !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 = path125.resolve(process.cwd(), ".env");
      let encoding = "utf8";
      const debug3 = Boolean(options2 && options2.debug);
      const quiet = Boolean(options2 && options2.quiet);
      if (options2 && options2.encoding) {
        encoding = options2.encoding;
      } else {
        if (debug3) {
          _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 path126 of optionPaths) {
        try {
          const parsed = DotenvModule.parse(fs113.readFileSync(path126, { encoding }));
          DotenvModule.populate(parsedAll, parsed, options2);
        } catch (e4) {
          if (debug3) {
            _debug(`Failed to load ${path126} ${e4.message}`);
          }
          lastError = e4;
        }
      }
      let processEnv = process.env;
      if (options2 && options2.processEnv != null) {
        processEnv = options2.processEnv;
      }
      const populated = DotenvModule.populate(processEnv, parsedAll, options2);
      if (debug3 || !quiet) {
        const keysCount = Object.keys(populated).length;
        const shortPaths = [];
        for (const filePath of optionPaths) {
          try {
            const relative11 = path125.relative(process.cwd(), filePath);
            shortPaths.push(relative11);
          } catch (e4) {
            if (debug3) {
              _debug(`Failed to load ${filePath} ${e4.message}`);
            }
            lastError = e4;
          }
        }
        _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 config2(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(config2, "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 = crypto14.createDecipheriv("aes-256-gcm", key, nonce);
        aesgcm.setAuthTag(authTag);
        return `${aesgcm.update(ciphertext)}${aesgcm.final()}`;
      } catch (error2) {
        const isRange = error2 instanceof RangeError;
        const invalidKeyLength = error2.message === "Invalid key length";
        const decryptionFailed = error2.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 error2;
        }
      }
    }
    __name(decrypt, "decrypt");
    function populate(processEnv, parsed, options2 = {}) {
      const debug3 = 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 (debug3) {
            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: config2,
      decrypt,
      parse: parse14,
      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/kleur/index.js
var require_kleur = __commonJS({
  "node_modules/kleur/index.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var { FORCE_COLOR, NODE_DISABLE_COLORS, TERM } = process.env;
    var $2 = {
      enabled: !NODE_DISABLE_COLORS && TERM !== "dumb" && FORCE_COLOR !== "0",
      // modifiers
      reset: init(0, 0),
      bold: init(1, 22),
      dim: init(2, 22),
      italic: init(3, 23),
      underline: init(4, 24),
      inverse: init(7, 27),
      hidden: init(8, 28),
      strikethrough: init(9, 29),
      // colors
      black: init(30, 39),
      red: init(31, 39),
      green: init(32, 39),
      yellow: init(33, 39),
      blue: init(34, 39),
      magenta: init(35, 39),
      cyan: init(36, 39),
      white: init(37, 39),
      gray: init(90, 39),
      grey: init(90, 39),
      // background colors
      bgBlack: init(40, 49),
      bgRed: init(41, 49),
      bgGreen: init(42, 49),
      bgYellow: init(43, 49),
      bgBlue: init(44, 49),
      bgMagenta: init(45, 49),
      bgCyan: init(46, 49),
      bgWhite: init(47, 49)
    };
    function run(arr, str2) {
      let i3 = 0, tmp, beg = "", end = "";
      for (; i3 < arr.length; i3++) {
        tmp = arr[i3];
        beg += tmp.open;
        end += tmp.close;
        if (str2.includes(tmp.close)) {
          str2 = str2.replace(tmp.rgx, tmp.close + tmp.open);
        }
      }
      return beg + str2 + end;
    }
    __name(run, "run");
    function chain2(has2, keys) {
      let ctx = { has: has2, keys };
      ctx.reset = $2.reset.bind(ctx);
      ctx.bold = $2.bold.bind(ctx);
      ctx.dim = $2.dim.bind(ctx);
      ctx.italic = $2.italic.bind(ctx);
      ctx.underline = $2.underline.bind(ctx);
      ctx.inverse = $2.inverse.bind(ctx);
      ctx.hidden = $2.hidden.bind(ctx);
      ctx.strikethrough = $2.strikethrough.bind(ctx);
      ctx.black = $2.black.bind(ctx);
      ctx.red = $2.red.bind(ctx);
      ctx.green = $2.green.bind(ctx);
      ctx.yellow = $2.yellow.bind(ctx);
      ctx.blue = $2.blue.bind(ctx);
      ctx.magenta = $2.magenta.bind(ctx);
      ctx.cyan = $2.cyan.bind(ctx);
      ctx.white = $2.white.bind(ctx);
      ctx.gray = $2.gray.bind(ctx);
      ctx.grey = $2.grey.bind(ctx);
      ctx.bgBlack = $2.bgBlack.bind(ctx);
      ctx.bgRed = $2.bgRed.bind(ctx);
      ctx.bgGreen = $2.bgGreen.bind(ctx);
      ctx.bgYellow = $2.bgYellow.bind(ctx);
      ctx.bgBlue = $2.bgBlue.bind(ctx);
      ctx.bgMagenta = $2.bgMagenta.bind(ctx);
      ctx.bgCyan = $2.bgCyan.bind(ctx);
      ctx.bgWhite = $2.bgWhite.bind(ctx);
      return ctx;
    }
    __name(chain2, "chain");
    function init(open4, close) {
      let blk = {
        open: `\x1B[${open4}m`,
        close: `\x1B[${close}m`,
        rgx: new RegExp(`\\x1b\\[${close}m`, "g")
      };
      return function(txt) {
        if (this !== void 0 && this.has !== void 0) {
          this.has.includes(open4) || (this.has.push(open4), this.keys.push(blk));
          return txt === void 0 ? this : $2.enabled ? run(this.keys, txt + "") : txt + "";
        }
        return txt === void 0 ? chain2([open4], [blk]) : $2.enabled ? run([blk], txt + "") : txt + "";
      };
    }
    __name(init, "init");
    module2.exports = $2;
  }
});

// node_modules/prompts/dist/util/action.js
var require_action = __commonJS({
  "node_modules/prompts/dist/util/action.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    module2.exports = (key, isSelect) => {
      if (key.meta && key.name !== "escape") return;
      if (key.ctrl) {
        if (key.name === "a") return "first";
        if (key.name === "c") return "abort";
        if (key.name === "d") return "abort";
        if (key.name === "e") return "last";
        if (key.name === "g") return "reset";
      }
      if (isSelect) {
        if (key.name === "j") return "down";
        if (key.name === "k") return "up";
      }
      if (key.name === "return") return "submit";
      if (key.name === "enter") return "submit";
      if (key.name === "backspace") return "delete";
      if (key.name === "delete") return "deleteForward";
      if (key.name === "abort") return "abort";
      if (key.name === "escape") return "exit";
      if (key.name === "tab") return "next";
      if (key.name === "pagedown") return "nextPage";
      if (key.name === "pageup") return "prevPage";
      if (key.name === "home") return "home";
      if (key.name === "end") return "end";
      if (key.name === "up") return "up";
      if (key.name === "down") return "down";
      if (key.name === "right") return "right";
      if (key.name === "left") return "left";
      return false;
    };
  }
});

// node_modules/prompts/dist/util/strip.js
var require_strip = __commonJS({
  "node_modules/prompts/dist/util/strip.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    module2.exports = (str2) => {
      const pattern = ["[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]+)*|[a-zA-Z\\d]+(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)", "(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PRZcf-ntqry=><~]))"].join("|");
      const RGX = new RegExp(pattern, "g");
      return typeof str2 === "string" ? str2.replace(RGX, "") : str2;
    };
  }
});

// node_modules/sisteransi/src/index.js
var require_src37 = __commonJS({
  "node_modules/sisteransi/src/index.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var ESC4 = "\x1B";
    var CSI = `${ESC4}[`;
    var beep2 = "\x07";
    var cursor = {
      to(x3, y2) {
        if (!y2) return `${CSI}${x3 + 1}G`;
        return `${CSI}${y2 + 1};${x3 + 1}H`;
      },
      move(x3, y2) {
        let ret = "";
        if (x3 < 0) ret += `${CSI}${-x3}D`;
        else if (x3 > 0) ret += `${CSI}${x3}C`;
        if (y2 < 0) ret += `${CSI}${-y2}A`;
        else if (y2 > 0) ret += `${CSI}${y2}B`;
        return ret;
      },
      up: /* @__PURE__ */ __name((count = 1) => `${CSI}${count}A`, "up"),
      down: /* @__PURE__ */ __name((count = 1) => `${CSI}${count}B`, "down"),
      forward: /* @__PURE__ */ __name((count = 1) => `${CSI}${count}C`, "forward"),
      backward: /* @__PURE__ */ __name((count = 1) => `${CSI}${count}D`, "backward"),
      nextLine: /* @__PURE__ */ __name((count = 1) => `${CSI}E`.repeat(count), "nextLine"),
      prevLine: /* @__PURE__ */ __name((count = 1) => `${CSI}F`.repeat(count), "prevLine"),
      left: `${CSI}G`,
      hide: `${CSI}?25l`,
      show: `${CSI}?25h`,
      save: `${ESC4}7`,
      restore: `${ESC4}8`
    };
    var scroll = {
      up: /* @__PURE__ */ __name((count = 1) => `${CSI}S`.repeat(count), "up"),
      down: /* @__PURE__ */ __name((count = 1) => `${CSI}T`.repeat(count), "down")
    };
    var erase = {
      screen: `${CSI}2J`,
      up: /* @__PURE__ */ __name((count = 1) => `${CSI}1J`.repeat(count), "up"),
      down: /* @__PURE__ */ __name((count = 1) => `${CSI}J`.repeat(count), "down"),
      line: `${CSI}2K`,
      lineEnd: `${CSI}K`,
      lineStart: `${CSI}1K`,
      lines(count) {
        let clear = "";
        for (let i3 = 0; i3 < count; i3++)
          clear += this.line + (i3 < count - 1 ? cursor.up() : "");
        if (count)
          clear += cursor.left;
        return clear;
      }
    };
    module2.exports = { cursor, scroll, erase, beep: beep2 };
  }
});

// node_modules/prompts/dist/util/clear.js
var require_clear = __commonJS({
  "node_modules/prompts/dist/util/clear.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    function _createForOfIteratorHelper(o3, allowArrayLike) {
      var it2 = typeof Symbol !== "undefined" && o3[Symbol.iterator] || o3["@@iterator"];
      if (!it2) {
        if (Array.isArray(o3) || (it2 = _unsupportedIterableToArray2(o3)) || allowArrayLike && o3 && typeof o3.length === "number") {
          if (it2) o3 = it2;
          var i3 = 0;
          var F4 = /* @__PURE__ */ __name(function F5() {
          }, "F");
          return { s: F4, n: /* @__PURE__ */ __name(function n3() {
            if (i3 >= o3.length) return { done: true };
            return { done: false, value: o3[i3++] };
          }, "n"), e: /* @__PURE__ */ __name(function e4(_e2) {
            throw _e2;
          }, "e"), f: F4 };
        }
        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 s5() {
        it2 = it2.call(o3);
      }, "s"), n: /* @__PURE__ */ __name(function n3() {
        var step = it2.next();
        normalCompletion = step.done;
        return step;
      }, "n"), e: /* @__PURE__ */ __name(function e4(_e2) {
        didErr = true;
        err = _e2;
      }, "e"), f: /* @__PURE__ */ __name(function f5() {
        try {
          if (!normalCompletion && it2.return != null) it2.return();
        } finally {
          if (didErr) throw err;
        }
      }, "f") };
    }
    __name(_createForOfIteratorHelper, "_createForOfIteratorHelper");
    function _unsupportedIterableToArray2(o3, minLen) {
      if (!o3) return;
      if (typeof o3 === "string") return _arrayLikeToArray2(o3, minLen);
      var n3 = Object.prototype.toString.call(o3).slice(8, -1);
      if (n3 === "Object" && o3.constructor) n3 = o3.constructor.name;
      if (n3 === "Map" || n3 === "Set") return Array.from(o3);
      if (n3 === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n3)) return _arrayLikeToArray2(o3, minLen);
    }
    __name(_unsupportedIterableToArray2, "_unsupportedIterableToArray");
    function _arrayLikeToArray2(arr, len) {
      if (len == null || len > arr.length) len = arr.length;
      for (var i3 = 0, arr2 = new Array(len); i3 < len; i3++) arr2[i3] = arr[i3];
      return arr2;
    }
    __name(_arrayLikeToArray2, "_arrayLikeToArray");
    var strip2 = require_strip();
    var _require2 = require_src37();
    var erase = _require2.erase;
    var cursor = _require2.cursor;
    var width = /* @__PURE__ */ __name((str2) => [...strip2(str2)].length, "width");
    module2.exports = function(prompt, perLine) {
      if (!perLine) return erase.line + cursor.to(0);
      let rows = 0;
      const lines = prompt.split(/\r?\n/);
      var _iterator = _createForOfIteratorHelper(lines), _step;
      try {
        for (_iterator.s(); !(_step = _iterator.n()).done; ) {
          let line = _step.value;
          rows += 1 + Math.floor(Math.max(width(line) - 1, 0) / perLine);
        }
      } catch (err) {
        _iterator.e(err);
      } finally {
        _iterator.f();
      }
      return erase.lines(rows);
    };
  }
});

// node_modules/prompts/dist/util/figures.js
var require_figures = __commonJS({
  "node_modules/prompts/dist/util/figures.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var main2 = {
      arrowUp: "\u2191",
      arrowDown: "\u2193",
      arrowLeft: "\u2190",
      arrowRight: "\u2192",
      radioOn: "\u25C9",
      radioOff: "\u25EF",
      tick: "\u2714",
      cross: "\u2716",
      ellipsis: "\u2026",
      pointerSmall: "\u203A",
      line: "\u2500",
      pointer: "\u276F"
    };
    var win2 = {
      arrowUp: main2.arrowUp,
      arrowDown: main2.arrowDown,
      arrowLeft: main2.arrowLeft,
      arrowRight: main2.arrowRight,
      radioOn: "(*)",
      radioOff: "( )",
      tick: "\u221A",
      cross: "\xD7",
      ellipsis: "...",
      pointerSmall: "\xBB",
      line: "\u2500",
      pointer: ">"
    };
    var figures = process.platform === "win32" ? win2 : main2;
    module2.exports = figures;
  }
});

// node_modules/prompts/dist/util/style.js
var require_style = __commonJS({
  "node_modules/prompts/dist/util/style.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var c4 = require_kleur();
    var figures = require_figures();
    var styles10 = Object.freeze({
      password: {
        scale: 1,
        render: /* @__PURE__ */ __name((input) => "*".repeat(input.length), "render")
      },
      emoji: {
        scale: 2,
        render: /* @__PURE__ */ __name((input) => "\u{1F603}".repeat(input.length), "render")
      },
      invisible: {
        scale: 0,
        render: /* @__PURE__ */ __name((input) => "", "render")
      },
      default: {
        scale: 1,
        render: /* @__PURE__ */ __name((input) => `${input}`, "render")
      }
    });
    var render3 = /* @__PURE__ */ __name((type) => styles10[type] || styles10.default, "render");
    var symbols = Object.freeze({
      aborted: c4.red(figures.cross),
      done: c4.green(figures.tick),
      exited: c4.yellow(figures.cross),
      default: c4.cyan("?")
    });
    var symbol = /* @__PURE__ */ __name((done, aborted2, exited) => aborted2 ? symbols.aborted : exited ? symbols.exited : done ? symbols.done : symbols.default, "symbol");
    var delimiter2 = /* @__PURE__ */ __name((completing) => c4.gray(completing ? figures.ellipsis : figures.pointerSmall), "delimiter");
    var item = /* @__PURE__ */ __name((expandable, expanded) => c4.gray(expandable ? expanded ? figures.pointerSmall : "+" : figures.line), "item");
    module2.exports = {
      styles: styles10,
      render: render3,
      symbols,
      symbol,
      delimiter: delimiter2,
      item
    };
  }
});

// node_modules/prompts/dist/util/lines.js
var require_lines = __commonJS({
  "node_modules/prompts/dist/util/lines.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var strip2 = require_strip();
    module2.exports = function(msg, perLine) {
      let lines = String(strip2(msg) || "").split(/\r?\n/);
      if (!perLine) return lines.length;
      return lines.map((l3) => Math.ceil(l3.length / perLine)).reduce((a2, b2) => a2 + b2);
    };
  }
});

// node_modules/prompts/dist/util/wrap.js
var require_wrap = __commonJS({
  "node_modules/prompts/dist/util/wrap.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    module2.exports = (msg, opts = {}) => {
      const tab2 = Number.isSafeInteger(parseInt(opts.margin)) ? new Array(parseInt(opts.margin)).fill(" ").join("") : opts.margin || "";
      const width = opts.width;
      return (msg || "").split(/\r?\n/g).map((line) => line.split(/\s+/g).reduce((arr, w2) => {
        if (w2.length + tab2.length >= width || arr[arr.length - 1].length + w2.length + 1 < width) arr[arr.length - 1] += ` ${w2}`;
        else arr.push(`${tab2}${w2}`);
        return arr;
      }, [tab2]).join("\n")).join("\n");
    };
  }
});

// node_modules/prompts/dist/util/entriesToDisplay.js
var require_entriesToDisplay = __commonJS({
  "node_modules/prompts/dist/util/entriesToDisplay.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    module2.exports = (cursor, total, maxVisible) => {
      maxVisible = maxVisible || total;
      let startIndex = Math.min(total - maxVisible, cursor - Math.floor(maxVisible / 2));
      if (startIndex < 0) startIndex = 0;
      let endIndex = Math.min(startIndex + maxVisible, total);
      return {
        startIndex,
        endIndex
      };
    };
  }
});

// node_modules/prompts/dist/util/index.js
var require_util17 = __commonJS({
  "node_modules/prompts/dist/util/index.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    module2.exports = {
      action: require_action(),
      clear: require_clear(),
      style: require_style(),
      strip: require_strip(),
      figures: require_figures(),
      lines: require_lines(),
      wrap: require_wrap(),
      entriesToDisplay: require_entriesToDisplay()
    };
  }
});

// node_modules/prompts/dist/elements/prompt.js
var require_prompt = __commonJS({
  "node_modules/prompts/dist/elements/prompt.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var readline4 = __require("readline");
    var _require2 = require_util17();
    var action = _require2.action;
    var EventEmitter11 = __require("events");
    var _require22 = require_src37();
    var beep2 = _require22.beep;
    var cursor = _require22.cursor;
    var color = require_kleur();
    var Prompt = class extends EventEmitter11 {
      static {
        __name(this, "Prompt");
      }
      constructor(opts = {}) {
        super();
        this.firstRender = true;
        this.in = opts.stdin || process.stdin;
        this.out = opts.stdout || process.stdout;
        this.onRender = (opts.onRender || (() => void 0)).bind(this);
        const rl = readline4.createInterface({
          input: this.in,
          escapeCodeTimeout: 50
        });
        readline4.emitKeypressEvents(this.in, rl);
        if (this.in.isTTY) this.in.setRawMode(true);
        const isSelect = ["SelectPrompt", "MultiselectPrompt"].indexOf(this.constructor.name) > -1;
        const keypress = /* @__PURE__ */ __name((str2, key) => {
          let a2 = action(key, isSelect);
          if (a2 === false) {
            this._ && this._(str2, key);
          } else if (typeof this[a2] === "function") {
            this[a2](key);
          } else {
            this.bell();
          }
        }, "keypress");
        this.close = () => {
          this.out.write(cursor.show);
          this.in.removeListener("keypress", keypress);
          if (this.in.isTTY) this.in.setRawMode(false);
          rl.close();
          this.emit(this.aborted ? "abort" : this.exited ? "exit" : "submit", this.value);
          this.closed = true;
        };
        this.in.on("keypress", keypress);
      }
      fire() {
        this.emit("state", {
          value: this.value,
          aborted: !!this.aborted,
          exited: !!this.exited
        });
      }
      bell() {
        this.out.write(beep2);
      }
      render() {
        this.onRender(color);
        if (this.firstRender) this.firstRender = false;
      }
    };
    module2.exports = Prompt;
  }
});

// node_modules/prompts/dist/elements/text.js
var require_text = __commonJS({
  "node_modules/prompts/dist/elements/text.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    function asyncGeneratorStep(gen, resolve30, reject, _next, _throw, key, arg) {
      try {
        var info = gen[key](arg);
        var value = info.value;
      } catch (error2) {
        reject(error2);
        return;
      }
      if (info.done) {
        resolve30(value);
      } else {
        Promise.resolve(value).then(_next, _throw);
      }
    }
    __name(asyncGeneratorStep, "asyncGeneratorStep");
    function _asyncToGenerator(fn) {
      return function() {
        var self2 = this, args = arguments;
        return new Promise(function(resolve30, reject) {
          var gen = fn.apply(self2, args);
          function _next(value) {
            asyncGeneratorStep(gen, resolve30, reject, _next, _throw, "next", value);
          }
          __name(_next, "_next");
          function _throw(err) {
            asyncGeneratorStep(gen, resolve30, reject, _next, _throw, "throw", err);
          }
          __name(_throw, "_throw");
          _next(void 0);
        });
      };
    }
    __name(_asyncToGenerator, "_asyncToGenerator");
    var color = require_kleur();
    var Prompt = require_prompt();
    var _require2 = require_src37();
    var erase = _require2.erase;
    var cursor = _require2.cursor;
    var _require22 = require_util17();
    var style = _require22.style;
    var clear = _require22.clear;
    var lines = _require22.lines;
    var figures = _require22.figures;
    var TextPrompt = class extends Prompt {
      static {
        __name(this, "TextPrompt");
      }
      constructor(opts = {}) {
        super(opts);
        this.transform = style.render(opts.style);
        this.scale = this.transform.scale;
        this.msg = opts.message;
        this.initial = opts.initial || ``;
        this.validator = opts.validate || (() => true);
        this.value = ``;
        this.errorMsg = opts.error || `Please Enter A Valid Value`;
        this.cursor = Number(!!this.initial);
        this.cursorOffset = 0;
        this.clear = clear(``, this.out.columns);
        this.render();
      }
      set value(v2) {
        if (!v2 && this.initial) {
          this.placeholder = true;
          this.rendered = color.gray(this.transform.render(this.initial));
        } else {
          this.placeholder = false;
          this.rendered = this.transform.render(v2);
        }
        this._value = v2;
        this.fire();
      }
      get value() {
        return this._value;
      }
      reset() {
        this.value = ``;
        this.cursor = Number(!!this.initial);
        this.cursorOffset = 0;
        this.fire();
        this.render();
      }
      exit() {
        this.abort();
      }
      abort() {
        this.value = this.value || this.initial;
        this.done = this.aborted = true;
        this.error = false;
        this.red = false;
        this.fire();
        this.render();
        this.out.write("\n");
        this.close();
      }
      validate() {
        var _this = this;
        return _asyncToGenerator(function* () {
          let valid = yield _this.validator(_this.value);
          if (typeof valid === `string`) {
            _this.errorMsg = valid;
            valid = false;
          }
          _this.error = !valid;
        })();
      }
      submit() {
        var _this2 = this;
        return _asyncToGenerator(function* () {
          _this2.value = _this2.value || _this2.initial;
          _this2.cursorOffset = 0;
          _this2.cursor = _this2.rendered.length;
          yield _this2.validate();
          if (_this2.error) {
            _this2.red = true;
            _this2.fire();
            _this2.render();
            return;
          }
          _this2.done = true;
          _this2.aborted = false;
          _this2.fire();
          _this2.render();
          _this2.out.write("\n");
          _this2.close();
        })();
      }
      next() {
        if (!this.placeholder) return this.bell();
        this.value = this.initial;
        this.cursor = this.rendered.length;
        this.fire();
        this.render();
      }
      moveCursor(n3) {
        if (this.placeholder) return;
        this.cursor = this.cursor + n3;
        this.cursorOffset += n3;
      }
      _(c4, key) {
        let s1 = this.value.slice(0, this.cursor);
        let s22 = this.value.slice(this.cursor);
        this.value = `${s1}${c4}${s22}`;
        this.red = false;
        this.cursor = this.placeholder ? 0 : s1.length + 1;
        this.render();
      }
      delete() {
        if (this.isCursorAtStart()) return this.bell();
        let s1 = this.value.slice(0, this.cursor - 1);
        let s22 = this.value.slice(this.cursor);
        this.value = `${s1}${s22}`;
        this.red = false;
        if (this.isCursorAtStart()) {
          this.cursorOffset = 0;
        } else {
          this.cursorOffset++;
          this.moveCursor(-1);
        }
        this.render();
      }
      deleteForward() {
        if (this.cursor * this.scale >= this.rendered.length || this.placeholder) return this.bell();
        let s1 = this.value.slice(0, this.cursor);
        let s22 = this.value.slice(this.cursor + 1);
        this.value = `${s1}${s22}`;
        this.red = false;
        if (this.isCursorAtEnd()) {
          this.cursorOffset = 0;
        } else {
          this.cursorOffset++;
        }
        this.render();
      }
      first() {
        this.cursor = 0;
        this.render();
      }
      last() {
        this.cursor = this.value.length;
        this.render();
      }
      left() {
        if (this.cursor <= 0 || this.placeholder) return this.bell();
        this.moveCursor(-1);
        this.render();
      }
      right() {
        if (this.cursor * this.scale >= this.rendered.length || this.placeholder) return this.bell();
        this.moveCursor(1);
        this.render();
      }
      isCursorAtStart() {
        return this.cursor === 0 || this.placeholder && this.cursor === 1;
      }
      isCursorAtEnd() {
        return this.cursor === this.rendered.length || this.placeholder && this.cursor === this.rendered.length + 1;
      }
      render() {
        if (this.closed) return;
        if (!this.firstRender) {
          if (this.outputError) this.out.write(cursor.down(lines(this.outputError, this.out.columns) - 1) + clear(this.outputError, this.out.columns));
          this.out.write(clear(this.outputText, this.out.columns));
        }
        super.render();
        this.outputError = "";
        this.outputText = [style.symbol(this.done, this.aborted), color.bold(this.msg), style.delimiter(this.done), this.red ? color.red(this.rendered) : this.rendered].join(` `);
        if (this.error) {
          this.outputError += this.errorMsg.split(`
`).reduce((a2, l3, i3) => a2 + `
${i3 ? " " : figures.pointerSmall} ${color.red().italic(l3)}`, ``);
        }
        this.out.write(erase.line + cursor.to(0) + this.outputText + cursor.save + this.outputError + cursor.restore + cursor.move(this.cursorOffset, 0));
      }
    };
    module2.exports = TextPrompt;
  }
});

// node_modules/prompts/dist/elements/select.js
var require_select = __commonJS({
  "node_modules/prompts/dist/elements/select.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var color = require_kleur();
    var Prompt = require_prompt();
    var _require2 = require_util17();
    var style = _require2.style;
    var clear = _require2.clear;
    var figures = _require2.figures;
    var wrap2 = _require2.wrap;
    var entriesToDisplay = _require2.entriesToDisplay;
    var _require22 = require_src37();
    var cursor = _require22.cursor;
    var SelectPrompt = class extends Prompt {
      static {
        __name(this, "SelectPrompt");
      }
      constructor(opts = {}) {
        super(opts);
        this.msg = opts.message;
        this.hint = opts.hint || "- Use arrow-keys. Return to submit.";
        this.warn = opts.warn || "- This option is disabled";
        this.cursor = opts.initial || 0;
        this.choices = opts.choices.map((ch, idx) => {
          if (typeof ch === "string") ch = {
            title: ch,
            value: idx
          };
          return {
            title: ch && (ch.title || ch.value || ch),
            value: ch && (ch.value === void 0 ? idx : ch.value),
            description: ch && ch.description,
            selected: ch && ch.selected,
            disabled: ch && ch.disabled
          };
        });
        this.optionsPerPage = opts.optionsPerPage || 10;
        this.value = (this.choices[this.cursor] || {}).value;
        this.clear = clear("", this.out.columns);
        this.render();
      }
      moveCursor(n3) {
        this.cursor = n3;
        this.value = this.choices[n3].value;
        this.fire();
      }
      reset() {
        this.moveCursor(0);
        this.fire();
        this.render();
      }
      exit() {
        this.abort();
      }
      abort() {
        this.done = this.aborted = true;
        this.fire();
        this.render();
        this.out.write("\n");
        this.close();
      }
      submit() {
        if (!this.selection.disabled) {
          this.done = true;
          this.aborted = false;
          this.fire();
          this.render();
          this.out.write("\n");
          this.close();
        } else this.bell();
      }
      first() {
        this.moveCursor(0);
        this.render();
      }
      last() {
        this.moveCursor(this.choices.length - 1);
        this.render();
      }
      up() {
        if (this.cursor === 0) {
          this.moveCursor(this.choices.length - 1);
        } else {
          this.moveCursor(this.cursor - 1);
        }
        this.render();
      }
      down() {
        if (this.cursor === this.choices.length - 1) {
          this.moveCursor(0);
        } else {
          this.moveCursor(this.cursor + 1);
        }
        this.render();
      }
      next() {
        this.moveCursor((this.cursor + 1) % this.choices.length);
        this.render();
      }
      _(c4, key) {
        if (c4 === " ") return this.submit();
      }
      get selection() {
        return this.choices[this.cursor];
      }
      render() {
        if (this.closed) return;
        if (this.firstRender) this.out.write(cursor.hide);
        else this.out.write(clear(this.outputText, this.out.columns));
        super.render();
        let _entriesToDisplay = entriesToDisplay(this.cursor, this.choices.length, this.optionsPerPage), startIndex = _entriesToDisplay.startIndex, endIndex = _entriesToDisplay.endIndex;
        this.outputText = [style.symbol(this.done, this.aborted), color.bold(this.msg), style.delimiter(false), this.done ? this.selection.title : this.selection.disabled ? color.yellow(this.warn) : color.gray(this.hint)].join(" ");
        if (!this.done) {
          this.outputText += "\n";
          for (let i3 = startIndex; i3 < endIndex; i3++) {
            let title, prefix, desc2 = "", v2 = this.choices[i3];
            if (i3 === startIndex && startIndex > 0) {
              prefix = figures.arrowUp;
            } else if (i3 === endIndex - 1 && endIndex < this.choices.length) {
              prefix = figures.arrowDown;
            } else {
              prefix = " ";
            }
            if (v2.disabled) {
              title = this.cursor === i3 ? color.gray().underline(v2.title) : color.strikethrough().gray(v2.title);
              prefix = (this.cursor === i3 ? color.bold().gray(figures.pointer) + " " : "  ") + prefix;
            } else {
              title = this.cursor === i3 ? color.cyan().underline(v2.title) : v2.title;
              prefix = (this.cursor === i3 ? color.cyan(figures.pointer) + " " : "  ") + prefix;
              if (v2.description && this.cursor === i3) {
                desc2 = ` - ${v2.description}`;
                if (prefix.length + title.length + desc2.length >= this.out.columns || v2.description.split(/\r?\n/).length > 1) {
                  desc2 = "\n" + wrap2(v2.description, {
                    margin: 3,
                    width: this.out.columns
                  });
                }
              }
            }
            this.outputText += `${prefix} ${title}${color.gray(desc2)}
`;
          }
        }
        this.out.write(this.outputText);
      }
    };
    module2.exports = SelectPrompt;
  }
});

// node_modules/prompts/dist/elements/toggle.js
var require_toggle = __commonJS({
  "node_modules/prompts/dist/elements/toggle.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var color = require_kleur();
    var Prompt = require_prompt();
    var _require2 = require_util17();
    var style = _require2.style;
    var clear = _require2.clear;
    var _require22 = require_src37();
    var cursor = _require22.cursor;
    var erase = _require22.erase;
    var TogglePrompt = class extends Prompt {
      static {
        __name(this, "TogglePrompt");
      }
      constructor(opts = {}) {
        super(opts);
        this.msg = opts.message;
        this.value = !!opts.initial;
        this.active = opts.active || "on";
        this.inactive = opts.inactive || "off";
        this.initialValue = this.value;
        this.render();
      }
      reset() {
        this.value = this.initialValue;
        this.fire();
        this.render();
      }
      exit() {
        this.abort();
      }
      abort() {
        this.done = this.aborted = true;
        this.fire();
        this.render();
        this.out.write("\n");
        this.close();
      }
      submit() {
        this.done = true;
        this.aborted = false;
        this.fire();
        this.render();
        this.out.write("\n");
        this.close();
      }
      deactivate() {
        if (this.value === false) return this.bell();
        this.value = false;
        this.render();
      }
      activate() {
        if (this.value === true) return this.bell();
        this.value = true;
        this.render();
      }
      delete() {
        this.deactivate();
      }
      left() {
        this.deactivate();
      }
      right() {
        this.activate();
      }
      down() {
        this.deactivate();
      }
      up() {
        this.activate();
      }
      next() {
        this.value = !this.value;
        this.fire();
        this.render();
      }
      _(c4, key) {
        if (c4 === " ") {
          this.value = !this.value;
        } else if (c4 === "1") {
          this.value = true;
        } else if (c4 === "0") {
          this.value = false;
        } else return this.bell();
        this.render();
      }
      render() {
        if (this.closed) return;
        if (this.firstRender) this.out.write(cursor.hide);
        else this.out.write(clear(this.outputText, this.out.columns));
        super.render();
        this.outputText = [style.symbol(this.done, this.aborted), color.bold(this.msg), style.delimiter(this.done), this.value ? this.inactive : color.cyan().underline(this.inactive), color.gray("/"), this.value ? color.cyan().underline(this.active) : this.active].join(" ");
        this.out.write(erase.line + cursor.to(0) + this.outputText);
      }
    };
    module2.exports = TogglePrompt;
  }
});

// node_modules/prompts/dist/dateparts/datepart.js
var require_datepart = __commonJS({
  "node_modules/prompts/dist/dateparts/datepart.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var DatePart = class _DatePart {
      static {
        __name(this, "DatePart");
      }
      constructor({
        token: token2,
        date: date4,
        parts,
        locales
      }) {
        this.token = token2;
        this.date = date4 || /* @__PURE__ */ new Date();
        this.parts = parts || [this];
        this.locales = locales || {};
      }
      up() {
      }
      down() {
      }
      next() {
        const currentIdx = this.parts.indexOf(this);
        return this.parts.find((part, idx) => idx > currentIdx && part instanceof _DatePart);
      }
      setTo(val) {
      }
      prev() {
        let parts = [].concat(this.parts).reverse();
        const currentIdx = parts.indexOf(this);
        return parts.find((part, idx) => idx > currentIdx && part instanceof _DatePart);
      }
      toString() {
        return String(this.date);
      }
    };
    module2.exports = DatePart;
  }
});

// node_modules/prompts/dist/dateparts/meridiem.js
var require_meridiem = __commonJS({
  "node_modules/prompts/dist/dateparts/meridiem.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var DatePart = require_datepart();
    var Meridiem = class extends DatePart {
      static {
        __name(this, "Meridiem");
      }
      constructor(opts = {}) {
        super(opts);
      }
      up() {
        this.date.setHours((this.date.getHours() + 12) % 24);
      }
      down() {
        this.up();
      }
      toString() {
        let meridiem = this.date.getHours() > 12 ? "pm" : "am";
        return /\A/.test(this.token) ? meridiem.toUpperCase() : meridiem;
      }
    };
    module2.exports = Meridiem;
  }
});

// node_modules/prompts/dist/dateparts/day.js
var require_day = __commonJS({
  "node_modules/prompts/dist/dateparts/day.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var DatePart = require_datepart();
    var pos2 = /* @__PURE__ */ __name((n3) => {
      n3 = n3 % 10;
      return n3 === 1 ? "st" : n3 === 2 ? "nd" : n3 === 3 ? "rd" : "th";
    }, "pos");
    var Day = class extends DatePart {
      static {
        __name(this, "Day");
      }
      constructor(opts = {}) {
        super(opts);
      }
      up() {
        this.date.setDate(this.date.getDate() + 1);
      }
      down() {
        this.date.setDate(this.date.getDate() - 1);
      }
      setTo(val) {
        this.date.setDate(parseInt(val.substr(-2)));
      }
      toString() {
        let date4 = this.date.getDate();
        let day = this.date.getDay();
        return this.token === "DD" ? String(date4).padStart(2, "0") : this.token === "Do" ? date4 + pos2(date4) : this.token === "d" ? day + 1 : this.token === "ddd" ? this.locales.weekdaysShort[day] : this.token === "dddd" ? this.locales.weekdays[day] : date4;
      }
    };
    module2.exports = Day;
  }
});

// node_modules/prompts/dist/dateparts/hours.js
var require_hours = __commonJS({
  "node_modules/prompts/dist/dateparts/hours.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var DatePart = require_datepart();
    var Hours = class extends DatePart {
      static {
        __name(this, "Hours");
      }
      constructor(opts = {}) {
        super(opts);
      }
      up() {
        this.date.setHours(this.date.getHours() + 1);
      }
      down() {
        this.date.setHours(this.date.getHours() - 1);
      }
      setTo(val) {
        this.date.setHours(parseInt(val.substr(-2)));
      }
      toString() {
        let hours = this.date.getHours();
        if (/h/.test(this.token)) hours = hours % 12 || 12;
        return this.token.length > 1 ? String(hours).padStart(2, "0") : hours;
      }
    };
    module2.exports = Hours;
  }
});

// node_modules/prompts/dist/dateparts/milliseconds.js
var require_milliseconds = __commonJS({
  "node_modules/prompts/dist/dateparts/milliseconds.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var DatePart = require_datepart();
    var Milliseconds = class extends DatePart {
      static {
        __name(this, "Milliseconds");
      }
      constructor(opts = {}) {
        super(opts);
      }
      up() {
        this.date.setMilliseconds(this.date.getMilliseconds() + 1);
      }
      down() {
        this.date.setMilliseconds(this.date.getMilliseconds() - 1);
      }
      setTo(val) {
        this.date.setMilliseconds(parseInt(val.substr(-this.token.length)));
      }
      toString() {
        return String(this.date.getMilliseconds()).padStart(4, "0").substr(0, this.token.length);
      }
    };
    module2.exports = Milliseconds;
  }
});

// node_modules/prompts/dist/dateparts/minutes.js
var require_minutes = __commonJS({
  "node_modules/prompts/dist/dateparts/minutes.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var DatePart = require_datepart();
    var Minutes = class extends DatePart {
      static {
        __name(this, "Minutes");
      }
      constructor(opts = {}) {
        super(opts);
      }
      up() {
        this.date.setMinutes(this.date.getMinutes() + 1);
      }
      down() {
        this.date.setMinutes(this.date.getMinutes() - 1);
      }
      setTo(val) {
        this.date.setMinutes(parseInt(val.substr(-2)));
      }
      toString() {
        let m3 = this.date.getMinutes();
        return this.token.length > 1 ? String(m3).padStart(2, "0") : m3;
      }
    };
    module2.exports = Minutes;
  }
});

// node_modules/prompts/dist/dateparts/month.js
var require_month = __commonJS({
  "node_modules/prompts/dist/dateparts/month.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var DatePart = require_datepart();
    var Month = class extends DatePart {
      static {
        __name(this, "Month");
      }
      constructor(opts = {}) {
        super(opts);
      }
      up() {
        this.date.setMonth(this.date.getMonth() + 1);
      }
      down() {
        this.date.setMonth(this.date.getMonth() - 1);
      }
      setTo(val) {
        val = parseInt(val.substr(-2)) - 1;
        this.date.setMonth(val < 0 ? 0 : val);
      }
      toString() {
        let month = this.date.getMonth();
        let tl = this.token.length;
        return tl === 2 ? String(month + 1).padStart(2, "0") : tl === 3 ? this.locales.monthsShort[month] : tl === 4 ? this.locales.months[month] : String(month + 1);
      }
    };
    module2.exports = Month;
  }
});

// node_modules/prompts/dist/dateparts/seconds.js
var require_seconds = __commonJS({
  "node_modules/prompts/dist/dateparts/seconds.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var DatePart = require_datepart();
    var Seconds = class extends DatePart {
      static {
        __name(this, "Seconds");
      }
      constructor(opts = {}) {
        super(opts);
      }
      up() {
        this.date.setSeconds(this.date.getSeconds() + 1);
      }
      down() {
        this.date.setSeconds(this.date.getSeconds() - 1);
      }
      setTo(val) {
        this.date.setSeconds(parseInt(val.substr(-2)));
      }
      toString() {
        let s5 = this.date.getSeconds();
        return this.token.length > 1 ? String(s5).padStart(2, "0") : s5;
      }
    };
    module2.exports = Seconds;
  }
});

// node_modules/prompts/dist/dateparts/year.js
var require_year = __commonJS({
  "node_modules/prompts/dist/dateparts/year.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var DatePart = require_datepart();
    var Year = class extends DatePart {
      static {
        __name(this, "Year");
      }
      constructor(opts = {}) {
        super(opts);
      }
      up() {
        this.date.setFullYear(this.date.getFullYear() + 1);
      }
      down() {
        this.date.setFullYear(this.date.getFullYear() - 1);
      }
      setTo(val) {
        this.date.setFullYear(val.substr(-4));
      }
      toString() {
        let year = String(this.date.getFullYear()).padStart(4, "0");
        return this.token.length === 2 ? year.substr(-2) : year;
      }
    };
    module2.exports = Year;
  }
});

// node_modules/prompts/dist/dateparts/index.js
var require_dateparts = __commonJS({
  "node_modules/prompts/dist/dateparts/index.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    module2.exports = {
      DatePart: require_datepart(),
      Meridiem: require_meridiem(),
      Day: require_day(),
      Hours: require_hours(),
      Milliseconds: require_milliseconds(),
      Minutes: require_minutes(),
      Month: require_month(),
      Seconds: require_seconds(),
      Year: require_year()
    };
  }
});

// node_modules/prompts/dist/elements/date.js
var require_date = __commonJS({
  "node_modules/prompts/dist/elements/date.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    function asyncGeneratorStep(gen, resolve30, reject, _next, _throw, key, arg) {
      try {
        var info = gen[key](arg);
        var value = info.value;
      } catch (error2) {
        reject(error2);
        return;
      }
      if (info.done) {
        resolve30(value);
      } else {
        Promise.resolve(value).then(_next, _throw);
      }
    }
    __name(asyncGeneratorStep, "asyncGeneratorStep");
    function _asyncToGenerator(fn) {
      return function() {
        var self2 = this, args = arguments;
        return new Promise(function(resolve30, reject) {
          var gen = fn.apply(self2, args);
          function _next(value) {
            asyncGeneratorStep(gen, resolve30, reject, _next, _throw, "next", value);
          }
          __name(_next, "_next");
          function _throw(err) {
            asyncGeneratorStep(gen, resolve30, reject, _next, _throw, "throw", err);
          }
          __name(_throw, "_throw");
          _next(void 0);
        });
      };
    }
    __name(_asyncToGenerator, "_asyncToGenerator");
    var color = require_kleur();
    var Prompt = require_prompt();
    var _require2 = require_util17();
    var style = _require2.style;
    var clear = _require2.clear;
    var figures = _require2.figures;
    var _require22 = require_src37();
    var erase = _require22.erase;
    var cursor = _require22.cursor;
    var _require3 = require_dateparts();
    var DatePart = _require3.DatePart;
    var Meridiem = _require3.Meridiem;
    var Day = _require3.Day;
    var Hours = _require3.Hours;
    var Milliseconds = _require3.Milliseconds;
    var Minutes = _require3.Minutes;
    var Month = _require3.Month;
    var Seconds = _require3.Seconds;
    var Year = _require3.Year;
    var regex3 = /\\(.)|"((?:\\["\\]|[^"])+)"|(D[Do]?|d{3,4}|d)|(M{1,4})|(YY(?:YY)?)|([aA])|([Hh]{1,2})|(m{1,2})|(s{1,2})|(S{1,4})|./g;
    var regexGroups = {
      1: ({
        token: token2
      }) => token2.replace(/\\(.)/g, "$1"),
      2: (opts) => new Day(opts),
      // Day // TODO
      3: (opts) => new Month(opts),
      // Month
      4: (opts) => new Year(opts),
      // Year
      5: (opts) => new Meridiem(opts),
      // AM/PM // TODO (special)
      6: (opts) => new Hours(opts),
      // Hours
      7: (opts) => new Minutes(opts),
      // Minutes
      8: (opts) => new Seconds(opts),
      // Seconds
      9: (opts) => new Milliseconds(opts)
      // Fractional seconds
    };
    var dfltLocales = {
      months: "January,February,March,April,May,June,July,August,September,October,November,December".split(","),
      monthsShort: "Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec".split(","),
      weekdays: "Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday".split(","),
      weekdaysShort: "Sun,Mon,Tue,Wed,Thu,Fri,Sat".split(",")
    };
    var DatePrompt = class extends Prompt {
      static {
        __name(this, "DatePrompt");
      }
      constructor(opts = {}) {
        super(opts);
        this.msg = opts.message;
        this.cursor = 0;
        this.typed = "";
        this.locales = Object.assign(dfltLocales, opts.locales);
        this._date = opts.initial || /* @__PURE__ */ new Date();
        this.errorMsg = opts.error || "Please Enter A Valid Value";
        this.validator = opts.validate || (() => true);
        this.mask = opts.mask || "YYYY-MM-DD HH:mm:ss";
        this.clear = clear("", this.out.columns);
        this.render();
      }
      get value() {
        return this.date;
      }
      get date() {
        return this._date;
      }
      set date(date4) {
        if (date4) this._date.setTime(date4.getTime());
      }
      set mask(mask) {
        let result;
        this.parts = [];
        while (result = regex3.exec(mask)) {
          let match2 = result.shift();
          let idx = result.findIndex((gr2) => gr2 != null);
          this.parts.push(idx in regexGroups ? regexGroups[idx]({
            token: result[idx] || match2,
            date: this.date,
            parts: this.parts,
            locales: this.locales
          }) : result[idx] || match2);
        }
        let parts = this.parts.reduce((arr, i3) => {
          if (typeof i3 === "string" && typeof arr[arr.length - 1] === "string") arr[arr.length - 1] += i3;
          else arr.push(i3);
          return arr;
        }, []);
        this.parts.splice(0);
        this.parts.push(...parts);
        this.reset();
      }
      moveCursor(n3) {
        this.typed = "";
        this.cursor = n3;
        this.fire();
      }
      reset() {
        this.moveCursor(this.parts.findIndex((p2) => p2 instanceof DatePart));
        this.fire();
        this.render();
      }
      exit() {
        this.abort();
      }
      abort() {
        this.done = this.aborted = true;
        this.error = false;
        this.fire();
        this.render();
        this.out.write("\n");
        this.close();
      }
      validate() {
        var _this = this;
        return _asyncToGenerator(function* () {
          let valid = yield _this.validator(_this.value);
          if (typeof valid === "string") {
            _this.errorMsg = valid;
            valid = false;
          }
          _this.error = !valid;
        })();
      }
      submit() {
        var _this2 = this;
        return _asyncToGenerator(function* () {
          yield _this2.validate();
          if (_this2.error) {
            _this2.color = "red";
            _this2.fire();
            _this2.render();
            return;
          }
          _this2.done = true;
          _this2.aborted = false;
          _this2.fire();
          _this2.render();
          _this2.out.write("\n");
          _this2.close();
        })();
      }
      up() {
        this.typed = "";
        this.parts[this.cursor].up();
        this.render();
      }
      down() {
        this.typed = "";
        this.parts[this.cursor].down();
        this.render();
      }
      left() {
        let prev = this.parts[this.cursor].prev();
        if (prev == null) return this.bell();
        this.moveCursor(this.parts.indexOf(prev));
        this.render();
      }
      right() {
        let next = this.parts[this.cursor].next();
        if (next == null) return this.bell();
        this.moveCursor(this.parts.indexOf(next));
        this.render();
      }
      next() {
        let next = this.parts[this.cursor].next();
        this.moveCursor(next ? this.parts.indexOf(next) : this.parts.findIndex((part) => part instanceof DatePart));
        this.render();
      }
      _(c4) {
        if (/\d/.test(c4)) {
          this.typed += c4;
          this.parts[this.cursor].setTo(this.typed);
          this.render();
        }
      }
      render() {
        if (this.closed) return;
        if (this.firstRender) this.out.write(cursor.hide);
        else this.out.write(clear(this.outputText, this.out.columns));
        super.render();
        this.outputText = [style.symbol(this.done, this.aborted), color.bold(this.msg), style.delimiter(false), this.parts.reduce((arr, p2, idx) => arr.concat(idx === this.cursor && !this.done ? color.cyan().underline(p2.toString()) : p2), []).join("")].join(" ");
        if (this.error) {
          this.outputText += this.errorMsg.split("\n").reduce((a2, l3, i3) => a2 + `
${i3 ? ` ` : figures.pointerSmall} ${color.red().italic(l3)}`, ``);
        }
        this.out.write(erase.line + cursor.to(0) + this.outputText);
      }
    };
    module2.exports = DatePrompt;
  }
});

// node_modules/prompts/dist/elements/number.js
var require_number = __commonJS({
  "node_modules/prompts/dist/elements/number.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    function asyncGeneratorStep(gen, resolve30, reject, _next, _throw, key, arg) {
      try {
        var info = gen[key](arg);
        var value = info.value;
      } catch (error2) {
        reject(error2);
        return;
      }
      if (info.done) {
        resolve30(value);
      } else {
        Promise.resolve(value).then(_next, _throw);
      }
    }
    __name(asyncGeneratorStep, "asyncGeneratorStep");
    function _asyncToGenerator(fn) {
      return function() {
        var self2 = this, args = arguments;
        return new Promise(function(resolve30, reject) {
          var gen = fn.apply(self2, args);
          function _next(value) {
            asyncGeneratorStep(gen, resolve30, reject, _next, _throw, "next", value);
          }
          __name(_next, "_next");
          function _throw(err) {
            asyncGeneratorStep(gen, resolve30, reject, _next, _throw, "throw", err);
          }
          __name(_throw, "_throw");
          _next(void 0);
        });
      };
    }
    __name(_asyncToGenerator, "_asyncToGenerator");
    var color = require_kleur();
    var Prompt = require_prompt();
    var _require2 = require_src37();
    var cursor = _require2.cursor;
    var erase = _require2.erase;
    var _require22 = require_util17();
    var style = _require22.style;
    var figures = _require22.figures;
    var clear = _require22.clear;
    var lines = _require22.lines;
    var isNumber3 = /[0-9]/;
    var isDef = /* @__PURE__ */ __name((any2) => any2 !== void 0, "isDef");
    var round = /* @__PURE__ */ __name((number4, precision) => {
      let factor = Math.pow(10, precision);
      return Math.round(number4 * factor) / factor;
    }, "round");
    var NumberPrompt = class extends Prompt {
      static {
        __name(this, "NumberPrompt");
      }
      constructor(opts = {}) {
        super(opts);
        this.transform = style.render(opts.style);
        this.msg = opts.message;
        this.initial = isDef(opts.initial) ? opts.initial : "";
        this.float = !!opts.float;
        this.round = opts.round || 2;
        this.inc = opts.increment || 1;
        this.min = isDef(opts.min) ? opts.min : -Infinity;
        this.max = isDef(opts.max) ? opts.max : Infinity;
        this.errorMsg = opts.error || `Please Enter A Valid Value`;
        this.validator = opts.validate || (() => true);
        this.color = `cyan`;
        this.value = ``;
        this.typed = ``;
        this.lastHit = 0;
        this.render();
      }
      set value(v2) {
        if (!v2 && v2 !== 0) {
          this.placeholder = true;
          this.rendered = color.gray(this.transform.render(`${this.initial}`));
          this._value = ``;
        } else {
          this.placeholder = false;
          this.rendered = this.transform.render(`${round(v2, this.round)}`);
          this._value = round(v2, this.round);
        }
        this.fire();
      }
      get value() {
        return this._value;
      }
      parse(x3) {
        return this.float ? parseFloat(x3) : parseInt(x3);
      }
      valid(c4) {
        return c4 === `-` || c4 === `.` && this.float || isNumber3.test(c4);
      }
      reset() {
        this.typed = ``;
        this.value = ``;
        this.fire();
        this.render();
      }
      exit() {
        this.abort();
      }
      abort() {
        let x3 = this.value;
        this.value = x3 !== `` ? x3 : this.initial;
        this.done = this.aborted = true;
        this.error = false;
        this.fire();
        this.render();
        this.out.write(`
`);
        this.close();
      }
      validate() {
        var _this = this;
        return _asyncToGenerator(function* () {
          let valid = yield _this.validator(_this.value);
          if (typeof valid === `string`) {
            _this.errorMsg = valid;
            valid = false;
          }
          _this.error = !valid;
        })();
      }
      submit() {
        var _this2 = this;
        return _asyncToGenerator(function* () {
          yield _this2.validate();
          if (_this2.error) {
            _this2.color = `red`;
            _this2.fire();
            _this2.render();
            return;
          }
          let x3 = _this2.value;
          _this2.value = x3 !== `` ? x3 : _this2.initial;
          _this2.done = true;
          _this2.aborted = false;
          _this2.error = false;
          _this2.fire();
          _this2.render();
          _this2.out.write(`
`);
          _this2.close();
        })();
      }
      up() {
        this.typed = ``;
        if (this.value === "") {
          this.value = this.min - this.inc;
        }
        if (this.value >= this.max) return this.bell();
        this.value += this.inc;
        this.color = `cyan`;
        this.fire();
        this.render();
      }
      down() {
        this.typed = ``;
        if (this.value === "") {
          this.value = this.min + this.inc;
        }
        if (this.value <= this.min) return this.bell();
        this.value -= this.inc;
        this.color = `cyan`;
        this.fire();
        this.render();
      }
      delete() {
        let val = this.value.toString();
        if (val.length === 0) return this.bell();
        this.value = this.parse(val = val.slice(0, -1)) || ``;
        if (this.value !== "" && this.value < this.min) {
          this.value = this.min;
        }
        this.color = `cyan`;
        this.fire();
        this.render();
      }
      next() {
        this.value = this.initial;
        this.fire();
        this.render();
      }
      _(c4, key) {
        if (!this.valid(c4)) return this.bell();
        const now = Date.now();
        if (now - this.lastHit > 1e3) this.typed = ``;
        this.typed += c4;
        this.lastHit = now;
        this.color = `cyan`;
        if (c4 === `.`) return this.fire();
        this.value = Math.min(this.parse(this.typed), this.max);
        if (this.value > this.max) this.value = this.max;
        if (this.value < this.min) this.value = this.min;
        this.fire();
        this.render();
      }
      render() {
        if (this.closed) return;
        if (!this.firstRender) {
          if (this.outputError) this.out.write(cursor.down(lines(this.outputError, this.out.columns) - 1) + clear(this.outputError, this.out.columns));
          this.out.write(clear(this.outputText, this.out.columns));
        }
        super.render();
        this.outputError = "";
        this.outputText = [style.symbol(this.done, this.aborted), color.bold(this.msg), style.delimiter(this.done), !this.done || !this.done && !this.placeholder ? color[this.color]().underline(this.rendered) : this.rendered].join(` `);
        if (this.error) {
          this.outputError += this.errorMsg.split(`
`).reduce((a2, l3, i3) => a2 + `
${i3 ? ` ` : figures.pointerSmall} ${color.red().italic(l3)}`, ``);
        }
        this.out.write(erase.line + cursor.to(0) + this.outputText + cursor.save + this.outputError + cursor.restore);
      }
    };
    module2.exports = NumberPrompt;
  }
});

// node_modules/prompts/dist/elements/multiselect.js
var require_multiselect = __commonJS({
  "node_modules/prompts/dist/elements/multiselect.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var color = require_kleur();
    var _require2 = require_src37();
    var cursor = _require2.cursor;
    var Prompt = require_prompt();
    var _require22 = require_util17();
    var clear = _require22.clear;
    var figures = _require22.figures;
    var style = _require22.style;
    var wrap2 = _require22.wrap;
    var entriesToDisplay = _require22.entriesToDisplay;
    var MultiselectPrompt = class extends Prompt {
      static {
        __name(this, "MultiselectPrompt");
      }
      constructor(opts = {}) {
        super(opts);
        this.msg = opts.message;
        this.cursor = opts.cursor || 0;
        this.scrollIndex = opts.cursor || 0;
        this.hint = opts.hint || "";
        this.warn = opts.warn || "- This option is disabled -";
        this.minSelected = opts.min;
        this.showMinError = false;
        this.maxChoices = opts.max;
        this.instructions = opts.instructions;
        this.optionsPerPage = opts.optionsPerPage || 10;
        this.value = opts.choices.map((ch, idx) => {
          if (typeof ch === "string") ch = {
            title: ch,
            value: idx
          };
          return {
            title: ch && (ch.title || ch.value || ch),
            description: ch && ch.description,
            value: ch && (ch.value === void 0 ? idx : ch.value),
            selected: ch && ch.selected,
            disabled: ch && ch.disabled
          };
        });
        this.clear = clear("", this.out.columns);
        if (!opts.overrideRender) {
          this.render();
        }
      }
      reset() {
        this.value.map((v2) => !v2.selected);
        this.cursor = 0;
        this.fire();
        this.render();
      }
      selected() {
        return this.value.filter((v2) => v2.selected);
      }
      exit() {
        this.abort();
      }
      abort() {
        this.done = this.aborted = true;
        this.fire();
        this.render();
        this.out.write("\n");
        this.close();
      }
      submit() {
        const selected = this.value.filter((e4) => e4.selected);
        if (this.minSelected && selected.length < this.minSelected) {
          this.showMinError = true;
          this.render();
        } else {
          this.done = true;
          this.aborted = false;
          this.fire();
          this.render();
          this.out.write("\n");
          this.close();
        }
      }
      first() {
        this.cursor = 0;
        this.render();
      }
      last() {
        this.cursor = this.value.length - 1;
        this.render();
      }
      next() {
        this.cursor = (this.cursor + 1) % this.value.length;
        this.render();
      }
      up() {
        if (this.cursor === 0) {
          this.cursor = this.value.length - 1;
        } else {
          this.cursor--;
        }
        this.render();
      }
      down() {
        if (this.cursor === this.value.length - 1) {
          this.cursor = 0;
        } else {
          this.cursor++;
        }
        this.render();
      }
      left() {
        this.value[this.cursor].selected = false;
        this.render();
      }
      right() {
        if (this.value.filter((e4) => e4.selected).length >= this.maxChoices) return this.bell();
        this.value[this.cursor].selected = true;
        this.render();
      }
      handleSpaceToggle() {
        const v2 = this.value[this.cursor];
        if (v2.selected) {
          v2.selected = false;
          this.render();
        } else if (v2.disabled || this.value.filter((e4) => e4.selected).length >= this.maxChoices) {
          return this.bell();
        } else {
          v2.selected = true;
          this.render();
        }
      }
      toggleAll() {
        if (this.maxChoices !== void 0 || this.value[this.cursor].disabled) {
          return this.bell();
        }
        const newSelected = !this.value[this.cursor].selected;
        this.value.filter((v2) => !v2.disabled).forEach((v2) => v2.selected = newSelected);
        this.render();
      }
      _(c4, key) {
        if (c4 === " ") {
          this.handleSpaceToggle();
        } else if (c4 === "a") {
          this.toggleAll();
        } else {
          return this.bell();
        }
      }
      renderInstructions() {
        if (this.instructions === void 0 || this.instructions) {
          if (typeof this.instructions === "string") {
            return this.instructions;
          }
          return `
Instructions:
    ${figures.arrowUp}/${figures.arrowDown}: Highlight option
    ${figures.arrowLeft}/${figures.arrowRight}/[space]: Toggle selection
` + (this.maxChoices === void 0 ? `    a: Toggle all
` : "") + `    enter/return: Complete answer`;
        }
        return "";
      }
      renderOption(cursor2, v2, i3, arrowIndicator) {
        const prefix = (v2.selected ? color.green(figures.radioOn) : figures.radioOff) + " " + arrowIndicator + " ";
        let title, desc2;
        if (v2.disabled) {
          title = cursor2 === i3 ? color.gray().underline(v2.title) : color.strikethrough().gray(v2.title);
        } else {
          title = cursor2 === i3 ? color.cyan().underline(v2.title) : v2.title;
          if (cursor2 === i3 && v2.description) {
            desc2 = ` - ${v2.description}`;
            if (prefix.length + title.length + desc2.length >= this.out.columns || v2.description.split(/\r?\n/).length > 1) {
              desc2 = "\n" + wrap2(v2.description, {
                margin: prefix.length,
                width: this.out.columns
              });
            }
          }
        }
        return prefix + title + color.gray(desc2 || "");
      }
      // shared with autocompleteMultiselect
      paginateOptions(options2) {
        if (options2.length === 0) {
          return color.red("No matches for this query.");
        }
        let _entriesToDisplay = entriesToDisplay(this.cursor, options2.length, this.optionsPerPage), startIndex = _entriesToDisplay.startIndex, endIndex = _entriesToDisplay.endIndex;
        let prefix, styledOptions = [];
        for (let i3 = startIndex; i3 < endIndex; i3++) {
          if (i3 === startIndex && startIndex > 0) {
            prefix = figures.arrowUp;
          } else if (i3 === endIndex - 1 && endIndex < options2.length) {
            prefix = figures.arrowDown;
          } else {
            prefix = " ";
          }
          styledOptions.push(this.renderOption(this.cursor, options2[i3], i3, prefix));
        }
        return "\n" + styledOptions.join("\n");
      }
      // shared with autocomleteMultiselect
      renderOptions(options2) {
        if (!this.done) {
          return this.paginateOptions(options2);
        }
        return "";
      }
      renderDoneOrInstructions() {
        if (this.done) {
          return this.value.filter((e4) => e4.selected).map((v2) => v2.title).join(", ");
        }
        const output = [color.gray(this.hint), this.renderInstructions()];
        if (this.value[this.cursor].disabled) {
          output.push(color.yellow(this.warn));
        }
        return output.join(" ");
      }
      render() {
        if (this.closed) return;
        if (this.firstRender) this.out.write(cursor.hide);
        super.render();
        let prompt = [style.symbol(this.done, this.aborted), color.bold(this.msg), style.delimiter(false), this.renderDoneOrInstructions()].join(" ");
        if (this.showMinError) {
          prompt += color.red(`You must select a minimum of ${this.minSelected} choices.`);
          this.showMinError = false;
        }
        prompt += this.renderOptions(this.value);
        this.out.write(this.clear + prompt);
        this.clear = clear(prompt, this.out.columns);
      }
    };
    module2.exports = MultiselectPrompt;
  }
});

// node_modules/prompts/dist/elements/autocomplete.js
var require_autocomplete = __commonJS({
  "node_modules/prompts/dist/elements/autocomplete.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    function asyncGeneratorStep(gen, resolve30, reject, _next, _throw, key, arg) {
      try {
        var info = gen[key](arg);
        var value = info.value;
      } catch (error2) {
        reject(error2);
        return;
      }
      if (info.done) {
        resolve30(value);
      } else {
        Promise.resolve(value).then(_next, _throw);
      }
    }
    __name(asyncGeneratorStep, "asyncGeneratorStep");
    function _asyncToGenerator(fn) {
      return function() {
        var self2 = this, args = arguments;
        return new Promise(function(resolve30, reject) {
          var gen = fn.apply(self2, args);
          function _next(value) {
            asyncGeneratorStep(gen, resolve30, reject, _next, _throw, "next", value);
          }
          __name(_next, "_next");
          function _throw(err) {
            asyncGeneratorStep(gen, resolve30, reject, _next, _throw, "throw", err);
          }
          __name(_throw, "_throw");
          _next(void 0);
        });
      };
    }
    __name(_asyncToGenerator, "_asyncToGenerator");
    var color = require_kleur();
    var Prompt = require_prompt();
    var _require2 = require_src37();
    var erase = _require2.erase;
    var cursor = _require2.cursor;
    var _require22 = require_util17();
    var style = _require22.style;
    var clear = _require22.clear;
    var figures = _require22.figures;
    var wrap2 = _require22.wrap;
    var entriesToDisplay = _require22.entriesToDisplay;
    var getVal = /* @__PURE__ */ __name((arr, i3) => arr[i3] && (arr[i3].value || arr[i3].title || arr[i3]), "getVal");
    var getTitle = /* @__PURE__ */ __name((arr, i3) => arr[i3] && (arr[i3].title || arr[i3].value || arr[i3]), "getTitle");
    var getIndex = /* @__PURE__ */ __name((arr, valOrTitle) => {
      const index = arr.findIndex((el) => el.value === valOrTitle || el.title === valOrTitle);
      return index > -1 ? index : void 0;
    }, "getIndex");
    var AutocompletePrompt = class extends Prompt {
      static {
        __name(this, "AutocompletePrompt");
      }
      constructor(opts = {}) {
        super(opts);
        this.msg = opts.message;
        this.suggest = opts.suggest;
        this.choices = opts.choices;
        this.initial = typeof opts.initial === "number" ? opts.initial : getIndex(opts.choices, opts.initial);
        this.select = this.initial || opts.cursor || 0;
        this.i18n = {
          noMatches: opts.noMatches || "no matches found"
        };
        this.fallback = opts.fallback || this.initial;
        this.clearFirst = opts.clearFirst || false;
        this.suggestions = [];
        this.input = "";
        this.limit = opts.limit || 10;
        this.cursor = 0;
        this.transform = style.render(opts.style);
        this.scale = this.transform.scale;
        this.render = this.render.bind(this);
        this.complete = this.complete.bind(this);
        this.clear = clear("", this.out.columns);
        this.complete(this.render);
        this.render();
      }
      set fallback(fb) {
        this._fb = Number.isSafeInteger(parseInt(fb)) ? parseInt(fb) : fb;
      }
      get fallback() {
        let choice2;
        if (typeof this._fb === "number") choice2 = this.choices[this._fb];
        else if (typeof this._fb === "string") choice2 = {
          title: this._fb
        };
        return choice2 || this._fb || {
          title: this.i18n.noMatches
        };
      }
      moveSelect(i3) {
        this.select = i3;
        if (this.suggestions.length > 0) this.value = getVal(this.suggestions, i3);
        else this.value = this.fallback.value;
        this.fire();
      }
      complete(cb) {
        var _this = this;
        return _asyncToGenerator(function* () {
          const p2 = _this.completing = _this.suggest(_this.input, _this.choices);
          const suggestions = yield p2;
          if (_this.completing !== p2) return;
          _this.suggestions = suggestions.map((s5, i3, arr) => ({
            title: getTitle(arr, i3),
            value: getVal(arr, i3),
            description: s5.description
          }));
          _this.completing = false;
          const l3 = Math.max(suggestions.length - 1, 0);
          _this.moveSelect(Math.min(l3, _this.select));
          cb && cb();
        })();
      }
      reset() {
        this.input = "";
        this.complete(() => {
          this.moveSelect(this.initial !== void 0 ? this.initial : 0);
          this.render();
        });
        this.render();
      }
      exit() {
        if (this.clearFirst && this.input.length > 0) {
          this.reset();
        } else {
          this.done = this.exited = true;
          this.aborted = false;
          this.fire();
          this.render();
          this.out.write("\n");
          this.close();
        }
      }
      abort() {
        this.done = this.aborted = true;
        this.exited = false;
        this.fire();
        this.render();
        this.out.write("\n");
        this.close();
      }
      submit() {
        this.done = true;
        this.aborted = this.exited = false;
        this.fire();
        this.render();
        this.out.write("\n");
        this.close();
      }
      _(c4, key) {
        let s1 = this.input.slice(0, this.cursor);
        let s22 = this.input.slice(this.cursor);
        this.input = `${s1}${c4}${s22}`;
        this.cursor = s1.length + 1;
        this.complete(this.render);
        this.render();
      }
      delete() {
        if (this.cursor === 0) return this.bell();
        let s1 = this.input.slice(0, this.cursor - 1);
        let s22 = this.input.slice(this.cursor);
        this.input = `${s1}${s22}`;
        this.complete(this.render);
        this.cursor = this.cursor - 1;
        this.render();
      }
      deleteForward() {
        if (this.cursor * this.scale >= this.rendered.length) return this.bell();
        let s1 = this.input.slice(0, this.cursor);
        let s22 = this.input.slice(this.cursor + 1);
        this.input = `${s1}${s22}`;
        this.complete(this.render);
        this.render();
      }
      first() {
        this.moveSelect(0);
        this.render();
      }
      last() {
        this.moveSelect(this.suggestions.length - 1);
        this.render();
      }
      up() {
        if (this.select === 0) {
          this.moveSelect(this.suggestions.length - 1);
        } else {
          this.moveSelect(this.select - 1);
        }
        this.render();
      }
      down() {
        if (this.select === this.suggestions.length - 1) {
          this.moveSelect(0);
        } else {
          this.moveSelect(this.select + 1);
        }
        this.render();
      }
      next() {
        if (this.select === this.suggestions.length - 1) {
          this.moveSelect(0);
        } else this.moveSelect(this.select + 1);
        this.render();
      }
      nextPage() {
        this.moveSelect(Math.min(this.select + this.limit, this.suggestions.length - 1));
        this.render();
      }
      prevPage() {
        this.moveSelect(Math.max(this.select - this.limit, 0));
        this.render();
      }
      left() {
        if (this.cursor <= 0) return this.bell();
        this.cursor = this.cursor - 1;
        this.render();
      }
      right() {
        if (this.cursor * this.scale >= this.rendered.length) return this.bell();
        this.cursor = this.cursor + 1;
        this.render();
      }
      renderOption(v2, hovered, isStart, isEnd) {
        let desc2;
        let prefix = isStart ? figures.arrowUp : isEnd ? figures.arrowDown : " ";
        let title = hovered ? color.cyan().underline(v2.title) : v2.title;
        prefix = (hovered ? color.cyan(figures.pointer) + " " : "  ") + prefix;
        if (v2.description) {
          desc2 = ` - ${v2.description}`;
          if (prefix.length + title.length + desc2.length >= this.out.columns || v2.description.split(/\r?\n/).length > 1) {
            desc2 = "\n" + wrap2(v2.description, {
              margin: 3,
              width: this.out.columns
            });
          }
        }
        return prefix + " " + title + color.gray(desc2 || "");
      }
      render() {
        if (this.closed) return;
        if (this.firstRender) this.out.write(cursor.hide);
        else this.out.write(clear(this.outputText, this.out.columns));
        super.render();
        let _entriesToDisplay = entriesToDisplay(this.select, this.choices.length, this.limit), startIndex = _entriesToDisplay.startIndex, endIndex = _entriesToDisplay.endIndex;
        this.outputText = [style.symbol(this.done, this.aborted, this.exited), color.bold(this.msg), style.delimiter(this.completing), this.done && this.suggestions[this.select] ? this.suggestions[this.select].title : this.rendered = this.transform.render(this.input)].join(" ");
        if (!this.done) {
          const suggestions = this.suggestions.slice(startIndex, endIndex).map((item, i3) => this.renderOption(item, this.select === i3 + startIndex, i3 === 0 && startIndex > 0, i3 + startIndex === endIndex - 1 && endIndex < this.choices.length)).join("\n");
          this.outputText += `
` + (suggestions || color.gray(this.fallback.title));
        }
        this.out.write(erase.line + cursor.to(0) + this.outputText);
      }
    };
    module2.exports = AutocompletePrompt;
  }
});

// node_modules/prompts/dist/elements/autocompleteMultiselect.js
var require_autocompleteMultiselect = __commonJS({
  "node_modules/prompts/dist/elements/autocompleteMultiselect.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var color = require_kleur();
    var _require2 = require_src37();
    var cursor = _require2.cursor;
    var MultiselectPrompt = require_multiselect();
    var _require22 = require_util17();
    var clear = _require22.clear;
    var style = _require22.style;
    var figures = _require22.figures;
    var AutocompleteMultiselectPrompt = class extends MultiselectPrompt {
      static {
        __name(this, "AutocompleteMultiselectPrompt");
      }
      constructor(opts = {}) {
        opts.overrideRender = true;
        super(opts);
        this.inputValue = "";
        this.clear = clear("", this.out.columns);
        this.filteredOptions = this.value;
        this.render();
      }
      last() {
        this.cursor = this.filteredOptions.length - 1;
        this.render();
      }
      next() {
        this.cursor = (this.cursor + 1) % this.filteredOptions.length;
        this.render();
      }
      up() {
        if (this.cursor === 0) {
          this.cursor = this.filteredOptions.length - 1;
        } else {
          this.cursor--;
        }
        this.render();
      }
      down() {
        if (this.cursor === this.filteredOptions.length - 1) {
          this.cursor = 0;
        } else {
          this.cursor++;
        }
        this.render();
      }
      left() {
        this.filteredOptions[this.cursor].selected = false;
        this.render();
      }
      right() {
        if (this.value.filter((e4) => e4.selected).length >= this.maxChoices) return this.bell();
        this.filteredOptions[this.cursor].selected = true;
        this.render();
      }
      delete() {
        if (this.inputValue.length) {
          this.inputValue = this.inputValue.substr(0, this.inputValue.length - 1);
          this.updateFilteredOptions();
        }
      }
      updateFilteredOptions() {
        const currentHighlight = this.filteredOptions[this.cursor];
        this.filteredOptions = this.value.filter((v2) => {
          if (this.inputValue) {
            if (typeof v2.title === "string") {
              if (v2.title.toLowerCase().includes(this.inputValue.toLowerCase())) {
                return true;
              }
            }
            if (typeof v2.value === "string") {
              if (v2.value.toLowerCase().includes(this.inputValue.toLowerCase())) {
                return true;
              }
            }
            return false;
          }
          return true;
        });
        const newHighlightIndex = this.filteredOptions.findIndex((v2) => v2 === currentHighlight);
        this.cursor = newHighlightIndex < 0 ? 0 : newHighlightIndex;
        this.render();
      }
      handleSpaceToggle() {
        const v2 = this.filteredOptions[this.cursor];
        if (v2.selected) {
          v2.selected = false;
          this.render();
        } else if (v2.disabled || this.value.filter((e4) => e4.selected).length >= this.maxChoices) {
          return this.bell();
        } else {
          v2.selected = true;
          this.render();
        }
      }
      handleInputChange(c4) {
        this.inputValue = this.inputValue + c4;
        this.updateFilteredOptions();
      }
      _(c4, key) {
        if (c4 === " ") {
          this.handleSpaceToggle();
        } else {
          this.handleInputChange(c4);
        }
      }
      renderInstructions() {
        if (this.instructions === void 0 || this.instructions) {
          if (typeof this.instructions === "string") {
            return this.instructions;
          }
          return `
Instructions:
    ${figures.arrowUp}/${figures.arrowDown}: Highlight option
    ${figures.arrowLeft}/${figures.arrowRight}/[space]: Toggle selection
    [a,b,c]/delete: Filter choices
    enter/return: Complete answer
`;
        }
        return "";
      }
      renderCurrentInput() {
        return `
Filtered results for: ${this.inputValue ? this.inputValue : color.gray("Enter something to filter")}
`;
      }
      renderOption(cursor2, v2, i3) {
        let title;
        if (v2.disabled) title = cursor2 === i3 ? color.gray().underline(v2.title) : color.strikethrough().gray(v2.title);
        else title = cursor2 === i3 ? color.cyan().underline(v2.title) : v2.title;
        return (v2.selected ? color.green(figures.radioOn) : figures.radioOff) + "  " + title;
      }
      renderDoneOrInstructions() {
        if (this.done) {
          return this.value.filter((e4) => e4.selected).map((v2) => v2.title).join(", ");
        }
        const output = [color.gray(this.hint), this.renderInstructions(), this.renderCurrentInput()];
        if (this.filteredOptions.length && this.filteredOptions[this.cursor].disabled) {
          output.push(color.yellow(this.warn));
        }
        return output.join(" ");
      }
      render() {
        if (this.closed) return;
        if (this.firstRender) this.out.write(cursor.hide);
        super.render();
        let prompt = [style.symbol(this.done, this.aborted), color.bold(this.msg), style.delimiter(false), this.renderDoneOrInstructions()].join(" ");
        if (this.showMinError) {
          prompt += color.red(`You must select a minimum of ${this.minSelected} choices.`);
          this.showMinError = false;
        }
        prompt += this.renderOptions(this.filteredOptions);
        this.out.write(this.clear + prompt);
        this.clear = clear(prompt, this.out.columns);
      }
    };
    module2.exports = AutocompleteMultiselectPrompt;
  }
});

// node_modules/prompts/dist/elements/confirm.js
var require_confirm = __commonJS({
  "node_modules/prompts/dist/elements/confirm.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var color = require_kleur();
    var Prompt = require_prompt();
    var _require2 = require_util17();
    var style = _require2.style;
    var clear = _require2.clear;
    var _require22 = require_src37();
    var erase = _require22.erase;
    var cursor = _require22.cursor;
    var ConfirmPrompt = class extends Prompt {
      static {
        __name(this, "ConfirmPrompt");
      }
      constructor(opts = {}) {
        super(opts);
        this.msg = opts.message;
        this.value = opts.initial;
        this.initialValue = !!opts.initial;
        this.yesMsg = opts.yes || "yes";
        this.yesOption = opts.yesOption || "(Y/n)";
        this.noMsg = opts.no || "no";
        this.noOption = opts.noOption || "(y/N)";
        this.render();
      }
      reset() {
        this.value = this.initialValue;
        this.fire();
        this.render();
      }
      exit() {
        this.abort();
      }
      abort() {
        this.done = this.aborted = true;
        this.fire();
        this.render();
        this.out.write("\n");
        this.close();
      }
      submit() {
        this.value = this.value || false;
        this.done = true;
        this.aborted = false;
        this.fire();
        this.render();
        this.out.write("\n");
        this.close();
      }
      _(c4, key) {
        if (c4.toLowerCase() === "y") {
          this.value = true;
          return this.submit();
        }
        if (c4.toLowerCase() === "n") {
          this.value = false;
          return this.submit();
        }
        return this.bell();
      }
      render() {
        if (this.closed) return;
        if (this.firstRender) this.out.write(cursor.hide);
        else this.out.write(clear(this.outputText, this.out.columns));
        super.render();
        this.outputText = [style.symbol(this.done, this.aborted), color.bold(this.msg), style.delimiter(this.done), this.done ? this.value ? this.yesMsg : this.noMsg : color.gray(this.initialValue ? this.yesOption : this.noOption)].join(" ");
        this.out.write(erase.line + cursor.to(0) + this.outputText);
      }
    };
    module2.exports = ConfirmPrompt;
  }
});

// node_modules/prompts/dist/elements/index.js
var require_elements = __commonJS({
  "node_modules/prompts/dist/elements/index.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    module2.exports = {
      TextPrompt: require_text(),
      SelectPrompt: require_select(),
      TogglePrompt: require_toggle(),
      DatePrompt: require_date(),
      NumberPrompt: require_number(),
      MultiselectPrompt: require_multiselect(),
      AutocompletePrompt: require_autocomplete(),
      AutocompleteMultiselectPrompt: require_autocompleteMultiselect(),
      ConfirmPrompt: require_confirm()
    };
  }
});

// node_modules/prompts/dist/prompts.js
var require_prompts = __commonJS({
  "node_modules/prompts/dist/prompts.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    var $2 = exports2;
    var el = require_elements();
    var noop8 = /* @__PURE__ */ __name((v2) => v2, "noop");
    function toPrompt(type, args, opts = {}) {
      return new Promise((res, rej) => {
        const p2 = new el[type](args);
        const onAbort = opts.onAbort || noop8;
        const onSubmit = opts.onSubmit || noop8;
        const onExit = opts.onExit || noop8;
        p2.on("state", args.onState || noop8);
        p2.on("submit", (x3) => res(onSubmit(x3)));
        p2.on("exit", (x3) => res(onExit(x3)));
        p2.on("abort", (x3) => rej(onAbort(x3)));
      });
    }
    __name(toPrompt, "toPrompt");
    $2.text = (args) => toPrompt("TextPrompt", args);
    $2.password = (args) => {
      args.style = "password";
      return $2.text(args);
    };
    $2.invisible = (args) => {
      args.style = "invisible";
      return $2.text(args);
    };
    $2.number = (args) => toPrompt("NumberPrompt", args);
    $2.date = (args) => toPrompt("DatePrompt", args);
    $2.confirm = (args) => toPrompt("ConfirmPrompt", args);
    $2.list = (args) => {
      const sep9 = args.separator || ",";
      return toPrompt("TextPrompt", args, {
        onSubmit: /* @__PURE__ */ __name((str2) => str2.split(sep9).map((s5) => s5.trim()), "onSubmit")
      });
    };
    $2.toggle = (args) => toPrompt("TogglePrompt", args);
    $2.select = (args) => toPrompt("SelectPrompt", args);
    $2.multiselect = (args) => {
      args.choices = [].concat(args.choices || []);
      const toSelected = /* @__PURE__ */ __name((items) => items.filter((item) => item.selected).map((item) => item.value), "toSelected");
      return toPrompt("MultiselectPrompt", args, {
        onAbort: toSelected,
        onSubmit: toSelected
      });
    };
    $2.autocompleteMultiselect = (args) => {
      args.choices = [].concat(args.choices || []);
      const toSelected = /* @__PURE__ */ __name((items) => items.filter((item) => item.selected).map((item) => item.value), "toSelected");
      return toPrompt("AutocompleteMultiselectPrompt", args, {
        onAbort: toSelected,
        onSubmit: toSelected
      });
    };
    var byTitle = /* @__PURE__ */ __name((input, choices) => Promise.resolve(choices.filter((item) => item.title.slice(0, input.length).toLowerCase() === input.toLowerCase())), "byTitle");
    $2.autocomplete = (args) => {
      args.suggest = args.suggest || byTitle;
      args.choices = [].concat(args.choices || []);
      return toPrompt("AutocompletePrompt", args);
    };
  }
});

// node_modules/prompts/dist/index.js
var require_dist6 = __commonJS({
  "node_modules/prompts/dist/index.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    function ownKeys2(object3, enumerableOnly) {
      var keys = Object.keys(object3);
      if (Object.getOwnPropertySymbols) {
        var symbols = Object.getOwnPropertySymbols(object3);
        if (enumerableOnly) {
          symbols = symbols.filter(function(sym) {
            return Object.getOwnPropertyDescriptor(object3, sym).enumerable;
          });
        }
        keys.push.apply(keys, symbols);
      }
      return keys;
    }
    __name(ownKeys2, "ownKeys");
    function _objectSpread(target) {
      for (var i3 = 1; i3 < arguments.length; i3++) {
        var source2 = arguments[i3] != null ? arguments[i3] : {};
        if (i3 % 2) {
          ownKeys2(Object(source2), true).forEach(function(key) {
            _defineProperty2(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 _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");
    function _createForOfIteratorHelper(o3, allowArrayLike) {
      var it2 = typeof Symbol !== "undefined" && o3[Symbol.iterator] || o3["@@iterator"];
      if (!it2) {
        if (Array.isArray(o3) || (it2 = _unsupportedIterableToArray2(o3)) || allowArrayLike && o3 && typeof o3.length === "number") {
          if (it2) o3 = it2;
          var i3 = 0;
          var F4 = /* @__PURE__ */ __name(function F5() {
          }, "F");
          return { s: F4, n: /* @__PURE__ */ __name(function n3() {
            if (i3 >= o3.length) return { done: true };
            return { done: false, value: o3[i3++] };
          }, "n"), e: /* @__PURE__ */ __name(function e4(_e2) {
            throw _e2;
          }, "e"), f: F4 };
        }
        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 s5() {
        it2 = it2.call(o3);
      }, "s"), n: /* @__PURE__ */ __name(function n3() {
        var step = it2.next();
        normalCompletion = step.done;
        return step;
      }, "n"), e: /* @__PURE__ */ __name(function e4(_e2) {
        didErr = true;
        err = _e2;
      }, "e"), f: /* @__PURE__ */ __name(function f5() {
        try {
          if (!normalCompletion && it2.return != null) it2.return();
        } finally {
          if (didErr) throw err;
        }
      }, "f") };
    }
    __name(_createForOfIteratorHelper, "_createForOfIteratorHelper");
    function _unsupportedIterableToArray2(o3, minLen) {
      if (!o3) return;
      if (typeof o3 === "string") return _arrayLikeToArray2(o3, minLen);
      var n3 = Object.prototype.toString.call(o3).slice(8, -1);
      if (n3 === "Object" && o3.constructor) n3 = o3.constructor.name;
      if (n3 === "Map" || n3 === "Set") return Array.from(o3);
      if (n3 === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n3)) return _arrayLikeToArray2(o3, minLen);
    }
    __name(_unsupportedIterableToArray2, "_unsupportedIterableToArray");
    function _arrayLikeToArray2(arr, len) {
      if (len == null || len > arr.length) len = arr.length;
      for (var i3 = 0, arr2 = new Array(len); i3 < len; i3++) arr2[i3] = arr[i3];
      return arr2;
    }
    __name(_arrayLikeToArray2, "_arrayLikeToArray");
    function asyncGeneratorStep(gen, resolve30, reject, _next, _throw, key, arg) {
      try {
        var info = gen[key](arg);
        var value = info.value;
      } catch (error2) {
        reject(error2);
        return;
      }
      if (info.done) {
        resolve30(value);
      } else {
        Promise.resolve(value).then(_next, _throw);
      }
    }
    __name(asyncGeneratorStep, "asyncGeneratorStep");
    function _asyncToGenerator(fn) {
      return function() {
        var self2 = this, args = arguments;
        return new Promise(function(resolve30, reject) {
          var gen = fn.apply(self2, args);
          function _next(value) {
            asyncGeneratorStep(gen, resolve30, reject, _next, _throw, "next", value);
          }
          __name(_next, "_next");
          function _throw(err) {
            asyncGeneratorStep(gen, resolve30, reject, _next, _throw, "throw", err);
          }
          __name(_throw, "_throw");
          _next(void 0);
        });
      };
    }
    __name(_asyncToGenerator, "_asyncToGenerator");
    var prompts3 = require_prompts();
    var passOn = ["suggest", "format", "onState", "validate", "onRender", "type"];
    var noop8 = /* @__PURE__ */ __name(() => {
    }, "noop");
    function prompt() {
      return _prompt.apply(this, arguments);
    }
    __name(prompt, "prompt");
    function _prompt() {
      _prompt = _asyncToGenerator(function* (questions = [], {
        onSubmit = noop8,
        onCancel = noop8
      } = {}) {
        const answers = {};
        const override2 = prompt._override || {};
        questions = [].concat(questions);
        let answer, question, quit, name3, type, lastPrompt;
        const getFormattedAnswer = /* @__PURE__ */ function() {
          var _ref = _asyncToGenerator(function* (question2, answer2, skipValidation = false) {
            if (!skipValidation && question2.validate && question2.validate(answer2) !== true) {
              return;
            }
            return question2.format ? yield question2.format(answer2, answers) : answer2;
          });
          return /* @__PURE__ */ __name(function getFormattedAnswer2(_x, _x2) {
            return _ref.apply(this, arguments);
          }, "getFormattedAnswer");
        }();
        var _iterator = _createForOfIteratorHelper(questions), _step;
        try {
          for (_iterator.s(); !(_step = _iterator.n()).done; ) {
            question = _step.value;
            var _question = question;
            name3 = _question.name;
            type = _question.type;
            if (typeof type === "function") {
              type = yield type(answer, _objectSpread({}, answers), question);
              question["type"] = type;
            }
            if (!type) continue;
            for (let key in question) {
              if (passOn.includes(key)) continue;
              let value = question[key];
              question[key] = typeof value === "function" ? yield value(answer, _objectSpread({}, answers), lastPrompt) : value;
            }
            lastPrompt = question;
            if (typeof question.message !== "string") {
              throw new Error("prompt message is required");
            }
            var _question2 = question;
            name3 = _question2.name;
            type = _question2.type;
            if (prompts3[type] === void 0) {
              throw new Error(`prompt type (${type}) is not defined`);
            }
            if (override2[question.name] !== void 0) {
              answer = yield getFormattedAnswer(question, override2[question.name]);
              if (answer !== void 0) {
                answers[name3] = answer;
                continue;
              }
            }
            try {
              answer = prompt._injected ? getInjectedAnswer(prompt._injected, question.initial) : yield prompts3[type](question);
              answers[name3] = answer = yield getFormattedAnswer(question, answer, true);
              quit = yield onSubmit(question, answer, answers);
            } catch (err) {
              quit = !(yield onCancel(question, answers));
            }
            if (quit) return answers;
          }
        } catch (err) {
          _iterator.e(err);
        } finally {
          _iterator.f();
        }
        return answers;
      });
      return _prompt.apply(this, arguments);
    }
    __name(_prompt, "_prompt");
    function getInjectedAnswer(injected, deafultValue) {
      const answer = injected.shift();
      if (answer instanceof Error) {
        throw answer;
      }
      return answer === void 0 ? deafultValue : answer;
    }
    __name(getInjectedAnswer, "getInjectedAnswer");
    function inject(answers) {
      prompt._injected = (prompt._injected || []).concat(answers);
    }
    __name(inject, "inject");
    function override(answers) {
      prompt._override = Object.assign({}, answers);
    }
    __name(override, "override");
    module2.exports = Object.assign(prompt, {
      prompt,
      prompts: prompts3,
      inject,
      override
    });
  }
});

// node_modules/prompts/lib/util/action.js
var require_action2 = __commonJS({
  "node_modules/prompts/lib/util/action.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    module2.exports = (key, isSelect) => {
      if (key.meta && key.name !== "escape") return;
      if (key.ctrl) {
        if (key.name === "a") return "first";
        if (key.name === "c") return "abort";
        if (key.name === "d") return "abort";
        if (key.name === "e") return "last";
        if (key.name === "g") return "reset";
      }
      if (isSelect) {
        if (key.name === "j") return "down";
        if (key.name === "k") return "up";
      }
      if (key.name === "return") return "submit";
      if (key.name === "enter") return "submit";
      if (key.name === "backspace") return "delete";
      if (key.name === "delete") return "deleteForward";
      if (key.name === "abort") return "abort";
      if (key.name === "escape") return "exit";
      if (key.name === "tab") return "next";
      if (key.name === "pagedown") return "nextPage";
      if (key.name === "pageup") return "prevPage";
      if (key.name === "home") return "home";
      if (key.name === "end") return "end";
      if (key.name === "up") return "up";
      if (key.name === "down") return "down";
      if (key.name === "right") return "right";
      if (key.name === "left") return "left";
      return false;
    };
  }
});

// node_modules/prompts/lib/util/strip.js
var require_strip2 = __commonJS({
  "node_modules/prompts/lib/util/strip.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    module2.exports = (str2) => {
      const pattern = [
        "[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]+)*|[a-zA-Z\\d]+(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)",
        "(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PRZcf-ntqry=><~]))"
      ].join("|");
      const RGX = new RegExp(pattern, "g");
      return typeof str2 === "string" ? str2.replace(RGX, "") : str2;
    };
  }
});

// node_modules/prompts/lib/util/clear.js
var require_clear2 = __commonJS({
  "node_modules/prompts/lib/util/clear.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var strip2 = require_strip2();
    var { erase, cursor } = require_src37();
    var width = /* @__PURE__ */ __name((str2) => [...strip2(str2)].length, "width");
    module2.exports = function(prompt, perLine) {
      if (!perLine) return erase.line + cursor.to(0);
      let rows = 0;
      const lines = prompt.split(/\r?\n/);
      for (let line of lines) {
        rows += 1 + Math.floor(Math.max(width(line) - 1, 0) / perLine);
      }
      return erase.lines(rows);
    };
  }
});

// node_modules/prompts/lib/util/figures.js
var require_figures2 = __commonJS({
  "node_modules/prompts/lib/util/figures.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var main2 = {
      arrowUp: "\u2191",
      arrowDown: "\u2193",
      arrowLeft: "\u2190",
      arrowRight: "\u2192",
      radioOn: "\u25C9",
      radioOff: "\u25EF",
      tick: "\u2714",
      cross: "\u2716",
      ellipsis: "\u2026",
      pointerSmall: "\u203A",
      line: "\u2500",
      pointer: "\u276F"
    };
    var win2 = {
      arrowUp: main2.arrowUp,
      arrowDown: main2.arrowDown,
      arrowLeft: main2.arrowLeft,
      arrowRight: main2.arrowRight,
      radioOn: "(*)",
      radioOff: "( )",
      tick: "\u221A",
      cross: "\xD7",
      ellipsis: "...",
      pointerSmall: "\xBB",
      line: "\u2500",
      pointer: ">"
    };
    var figures = process.platform === "win32" ? win2 : main2;
    module2.exports = figures;
  }
});

// node_modules/prompts/lib/util/style.js
var require_style2 = __commonJS({
  "node_modules/prompts/lib/util/style.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var c4 = require_kleur();
    var figures = require_figures2();
    var styles10 = Object.freeze({
      password: { scale: 1, render: /* @__PURE__ */ __name((input) => "*".repeat(input.length), "render") },
      emoji: { scale: 2, render: /* @__PURE__ */ __name((input) => "\u{1F603}".repeat(input.length), "render") },
      invisible: { scale: 0, render: /* @__PURE__ */ __name((input) => "", "render") },
      default: { scale: 1, render: /* @__PURE__ */ __name((input) => `${input}`, "render") }
    });
    var render3 = /* @__PURE__ */ __name((type) => styles10[type] || styles10.default, "render");
    var symbols = Object.freeze({
      aborted: c4.red(figures.cross),
      done: c4.green(figures.tick),
      exited: c4.yellow(figures.cross),
      default: c4.cyan("?")
    });
    var symbol = /* @__PURE__ */ __name((done, aborted2, exited) => aborted2 ? symbols.aborted : exited ? symbols.exited : done ? symbols.done : symbols.default, "symbol");
    var delimiter2 = /* @__PURE__ */ __name((completing) => c4.gray(completing ? figures.ellipsis : figures.pointerSmall), "delimiter");
    var item = /* @__PURE__ */ __name((expandable, expanded) => c4.gray(expandable ? expanded ? figures.pointerSmall : "+" : figures.line), "item");
    module2.exports = {
      styles: styles10,
      render: render3,
      symbols,
      symbol,
      delimiter: delimiter2,
      item
    };
  }
});

// node_modules/prompts/lib/util/lines.js
var require_lines2 = __commonJS({
  "node_modules/prompts/lib/util/lines.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var strip2 = require_strip2();
    module2.exports = function(msg, perLine) {
      let lines = String(strip2(msg) || "").split(/\r?\n/);
      if (!perLine) return lines.length;
      return lines.map((l3) => Math.ceil(l3.length / perLine)).reduce((a2, b2) => a2 + b2);
    };
  }
});

// node_modules/prompts/lib/util/wrap.js
var require_wrap2 = __commonJS({
  "node_modules/prompts/lib/util/wrap.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    module2.exports = (msg, opts = {}) => {
      const tab2 = Number.isSafeInteger(parseInt(opts.margin)) ? new Array(parseInt(opts.margin)).fill(" ").join("") : opts.margin || "";
      const width = opts.width;
      return (msg || "").split(/\r?\n/g).map((line) => line.split(/\s+/g).reduce((arr, w2) => {
        if (w2.length + tab2.length >= width || arr[arr.length - 1].length + w2.length + 1 < width)
          arr[arr.length - 1] += ` ${w2}`;
        else arr.push(`${tab2}${w2}`);
        return arr;
      }, [tab2]).join("\n")).join("\n");
    };
  }
});

// node_modules/prompts/lib/util/entriesToDisplay.js
var require_entriesToDisplay2 = __commonJS({
  "node_modules/prompts/lib/util/entriesToDisplay.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    module2.exports = (cursor, total, maxVisible) => {
      maxVisible = maxVisible || total;
      let startIndex = Math.min(total - maxVisible, cursor - Math.floor(maxVisible / 2));
      if (startIndex < 0) startIndex = 0;
      let endIndex = Math.min(startIndex + maxVisible, total);
      return { startIndex, endIndex };
    };
  }
});

// node_modules/prompts/lib/util/index.js
var require_util18 = __commonJS({
  "node_modules/prompts/lib/util/index.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    module2.exports = {
      action: require_action2(),
      clear: require_clear2(),
      style: require_style2(),
      strip: require_strip2(),
      figures: require_figures2(),
      lines: require_lines2(),
      wrap: require_wrap2(),
      entriesToDisplay: require_entriesToDisplay2()
    };
  }
});

// node_modules/prompts/lib/elements/prompt.js
var require_prompt2 = __commonJS({
  "node_modules/prompts/lib/elements/prompt.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var readline4 = __require("readline");
    var { action } = require_util18();
    var EventEmitter11 = __require("events");
    var { beep: beep2, cursor } = require_src37();
    var color = require_kleur();
    var Prompt = class extends EventEmitter11 {
      static {
        __name(this, "Prompt");
      }
      constructor(opts = {}) {
        super();
        this.firstRender = true;
        this.in = opts.stdin || process.stdin;
        this.out = opts.stdout || process.stdout;
        this.onRender = (opts.onRender || (() => void 0)).bind(this);
        const rl = readline4.createInterface({ input: this.in, escapeCodeTimeout: 50 });
        readline4.emitKeypressEvents(this.in, rl);
        if (this.in.isTTY) this.in.setRawMode(true);
        const isSelect = ["SelectPrompt", "MultiselectPrompt"].indexOf(this.constructor.name) > -1;
        const keypress = /* @__PURE__ */ __name((str2, key) => {
          let a2 = action(key, isSelect);
          if (a2 === false) {
            this._ && this._(str2, key);
          } else if (typeof this[a2] === "function") {
            this[a2](key);
          } else {
            this.bell();
          }
        }, "keypress");
        this.close = () => {
          this.out.write(cursor.show);
          this.in.removeListener("keypress", keypress);
          if (this.in.isTTY) this.in.setRawMode(false);
          rl.close();
          this.emit(this.aborted ? "abort" : this.exited ? "exit" : "submit", this.value);
          this.closed = true;
        };
        this.in.on("keypress", keypress);
      }
      fire() {
        this.emit("state", {
          value: this.value,
          aborted: !!this.aborted,
          exited: !!this.exited
        });
      }
      bell() {
        this.out.write(beep2);
      }
      render() {
        this.onRender(color);
        if (this.firstRender) this.firstRender = false;
      }
    };
    module2.exports = Prompt;
  }
});

// node_modules/prompts/lib/elements/text.js
var require_text2 = __commonJS({
  "node_modules/prompts/lib/elements/text.js"(exports2, module2) {
    init_esbuild_shims();
    var color = require_kleur();
    var Prompt = require_prompt2();
    var { erase, cursor } = require_src37();
    var { style, clear, lines, figures } = require_util18();
    var TextPrompt = class extends Prompt {
      static {
        __name(this, "TextPrompt");
      }
      constructor(opts = {}) {
        super(opts);
        this.transform = style.render(opts.style);
        this.scale = this.transform.scale;
        this.msg = opts.message;
        this.initial = opts.initial || ``;
        this.validator = opts.validate || (() => true);
        this.value = ``;
        this.errorMsg = opts.error || `Please Enter A Valid Value`;
        this.cursor = Number(!!this.initial);
        this.cursorOffset = 0;
        this.clear = clear(``, this.out.columns);
        this.render();
      }
      set value(v2) {
        if (!v2 && this.initial) {
          this.placeholder = true;
          this.rendered = color.gray(this.transform.render(this.initial));
        } else {
          this.placeholder = false;
          this.rendered = this.transform.render(v2);
        }
        this._value = v2;
        this.fire();
      }
      get value() {
        return this._value;
      }
      reset() {
        this.value = ``;
        this.cursor = Number(!!this.initial);
        this.cursorOffset = 0;
        this.fire();
        this.render();
      }
      exit() {
        this.abort();
      }
      abort() {
        this.value = this.value || this.initial;
        this.done = this.aborted = true;
        this.error = false;
        this.red = false;
        this.fire();
        this.render();
        this.out.write("\n");
        this.close();
      }
      async validate() {
        let valid = await this.validator(this.value);
        if (typeof valid === `string`) {
          this.errorMsg = valid;
          valid = false;
        }
        this.error = !valid;
      }
      async submit() {
        this.value = this.value || this.initial;
        this.cursorOffset = 0;
        this.cursor = this.rendered.length;
        await this.validate();
        if (this.error) {
          this.red = true;
          this.fire();
          this.render();
          return;
        }
        this.done = true;
        this.aborted = false;
        this.fire();
        this.render();
        this.out.write("\n");
        this.close();
      }
      next() {
        if (!this.placeholder) return this.bell();
        this.value = this.initial;
        this.cursor = this.rendered.length;
        this.fire();
        this.render();
      }
      moveCursor(n3) {
        if (this.placeholder) return;
        this.cursor = this.cursor + n3;
        this.cursorOffset += n3;
      }
      _(c4, key) {
        let s1 = this.value.slice(0, this.cursor);
        let s22 = this.value.slice(this.cursor);
        this.value = `${s1}${c4}${s22}`;
        this.red = false;
        this.cursor = this.placeholder ? 0 : s1.length + 1;
        this.render();
      }
      delete() {
        if (this.isCursorAtStart()) return this.bell();
        let s1 = this.value.slice(0, this.cursor - 1);
        let s22 = this.value.slice(this.cursor);
        this.value = `${s1}${s22}`;
        this.red = false;
        if (this.isCursorAtStart()) {
          this.cursorOffset = 0;
        } else {
          this.cursorOffset++;
          this.moveCursor(-1);
        }
        this.render();
      }
      deleteForward() {
        if (this.cursor * this.scale >= this.rendered.length || this.placeholder) return this.bell();
        let s1 = this.value.slice(0, this.cursor);
        let s22 = this.value.slice(this.cursor + 1);
        this.value = `${s1}${s22}`;
        this.red = false;
        if (this.isCursorAtEnd()) {
          this.cursorOffset = 0;
        } else {
          this.cursorOffset++;
        }
        this.render();
      }
      first() {
        this.cursor = 0;
        this.render();
      }
      last() {
        this.cursor = this.value.length;
        this.render();
      }
      left() {
        if (this.cursor <= 0 || this.placeholder) return this.bell();
        this.moveCursor(-1);
        this.render();
      }
      right() {
        if (this.cursor * this.scale >= this.rendered.length || this.placeholder) return this.bell();
        this.moveCursor(1);
        this.render();
      }
      isCursorAtStart() {
        return this.cursor === 0 || this.placeholder && this.cursor === 1;
      }
      isCursorAtEnd() {
        return this.cursor === this.rendered.length || this.placeholder && this.cursor === this.rendered.length + 1;
      }
      render() {
        if (this.closed) return;
        if (!this.firstRender) {
          if (this.outputError)
            this.out.write(cursor.down(lines(this.outputError, this.out.columns) - 1) + clear(this.outputError, this.out.columns));
          this.out.write(clear(this.outputText, this.out.columns));
        }
        super.render();
        this.outputError = "";
        this.outputText = [
          style.symbol(this.done, this.aborted),
          color.bold(this.msg),
          style.delimiter(this.done),
          this.red ? color.red(this.rendered) : this.rendered
        ].join(` `);
        if (this.error) {
          this.outputError += this.errorMsg.split(`
`).reduce((a2, l3, i3) => a2 + `
${i3 ? " " : figures.pointerSmall} ${color.red().italic(l3)}`, ``);
        }
        this.out.write(erase.line + cursor.to(0) + this.outputText + cursor.save + this.outputError + cursor.restore + cursor.move(this.cursorOffset, 0));
      }
    };
    module2.exports = TextPrompt;
  }
});

// node_modules/prompts/lib/elements/select.js
var require_select2 = __commonJS({
  "node_modules/prompts/lib/elements/select.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var color = require_kleur();
    var Prompt = require_prompt2();
    var { style, clear, figures, wrap: wrap2, entriesToDisplay } = require_util18();
    var { cursor } = require_src37();
    var SelectPrompt = class extends Prompt {
      static {
        __name(this, "SelectPrompt");
      }
      constructor(opts = {}) {
        super(opts);
        this.msg = opts.message;
        this.hint = opts.hint || "- Use arrow-keys. Return to submit.";
        this.warn = opts.warn || "- This option is disabled";
        this.cursor = opts.initial || 0;
        this.choices = opts.choices.map((ch, idx) => {
          if (typeof ch === "string")
            ch = { title: ch, value: idx };
          return {
            title: ch && (ch.title || ch.value || ch),
            value: ch && (ch.value === void 0 ? idx : ch.value),
            description: ch && ch.description,
            selected: ch && ch.selected,
            disabled: ch && ch.disabled
          };
        });
        this.optionsPerPage = opts.optionsPerPage || 10;
        this.value = (this.choices[this.cursor] || {}).value;
        this.clear = clear("", this.out.columns);
        this.render();
      }
      moveCursor(n3) {
        this.cursor = n3;
        this.value = this.choices[n3].value;
        this.fire();
      }
      reset() {
        this.moveCursor(0);
        this.fire();
        this.render();
      }
      exit() {
        this.abort();
      }
      abort() {
        this.done = this.aborted = true;
        this.fire();
        this.render();
        this.out.write("\n");
        this.close();
      }
      submit() {
        if (!this.selection.disabled) {
          this.done = true;
          this.aborted = false;
          this.fire();
          this.render();
          this.out.write("\n");
          this.close();
        } else
          this.bell();
      }
      first() {
        this.moveCursor(0);
        this.render();
      }
      last() {
        this.moveCursor(this.choices.length - 1);
        this.render();
      }
      up() {
        if (this.cursor === 0) {
          this.moveCursor(this.choices.length - 1);
        } else {
          this.moveCursor(this.cursor - 1);
        }
        this.render();
      }
      down() {
        if (this.cursor === this.choices.length - 1) {
          this.moveCursor(0);
        } else {
          this.moveCursor(this.cursor + 1);
        }
        this.render();
      }
      next() {
        this.moveCursor((this.cursor + 1) % this.choices.length);
        this.render();
      }
      _(c4, key) {
        if (c4 === " ") return this.submit();
      }
      get selection() {
        return this.choices[this.cursor];
      }
      render() {
        if (this.closed) return;
        if (this.firstRender) this.out.write(cursor.hide);
        else this.out.write(clear(this.outputText, this.out.columns));
        super.render();
        let { startIndex, endIndex } = entriesToDisplay(this.cursor, this.choices.length, this.optionsPerPage);
        this.outputText = [
          style.symbol(this.done, this.aborted),
          color.bold(this.msg),
          style.delimiter(false),
          this.done ? this.selection.title : this.selection.disabled ? color.yellow(this.warn) : color.gray(this.hint)
        ].join(" ");
        if (!this.done) {
          this.outputText += "\n";
          for (let i3 = startIndex; i3 < endIndex; i3++) {
            let title, prefix, desc2 = "", v2 = this.choices[i3];
            if (i3 === startIndex && startIndex > 0) {
              prefix = figures.arrowUp;
            } else if (i3 === endIndex - 1 && endIndex < this.choices.length) {
              prefix = figures.arrowDown;
            } else {
              prefix = " ";
            }
            if (v2.disabled) {
              title = this.cursor === i3 ? color.gray().underline(v2.title) : color.strikethrough().gray(v2.title);
              prefix = (this.cursor === i3 ? color.bold().gray(figures.pointer) + " " : "  ") + prefix;
            } else {
              title = this.cursor === i3 ? color.cyan().underline(v2.title) : v2.title;
              prefix = (this.cursor === i3 ? color.cyan(figures.pointer) + " " : "  ") + prefix;
              if (v2.description && this.cursor === i3) {
                desc2 = ` - ${v2.description}`;
                if (prefix.length + title.length + desc2.length >= this.out.columns || v2.description.split(/\r?\n/).length > 1) {
                  desc2 = "\n" + wrap2(v2.description, { margin: 3, width: this.out.columns });
                }
              }
            }
            this.outputText += `${prefix} ${title}${color.gray(desc2)}
`;
          }
        }
        this.out.write(this.outputText);
      }
    };
    module2.exports = SelectPrompt;
  }
});

// node_modules/prompts/lib/elements/toggle.js
var require_toggle2 = __commonJS({
  "node_modules/prompts/lib/elements/toggle.js"(exports2, module2) {
    init_esbuild_shims();
    var color = require_kleur();
    var Prompt = require_prompt2();
    var { style, clear } = require_util18();
    var { cursor, erase } = require_src37();
    var TogglePrompt = class extends Prompt {
      static {
        __name(this, "TogglePrompt");
      }
      constructor(opts = {}) {
        super(opts);
        this.msg = opts.message;
        this.value = !!opts.initial;
        this.active = opts.active || "on";
        this.inactive = opts.inactive || "off";
        this.initialValue = this.value;
        this.render();
      }
      reset() {
        this.value = this.initialValue;
        this.fire();
        this.render();
      }
      exit() {
        this.abort();
      }
      abort() {
        this.done = this.aborted = true;
        this.fire();
        this.render();
        this.out.write("\n");
        this.close();
      }
      submit() {
        this.done = true;
        this.aborted = false;
        this.fire();
        this.render();
        this.out.write("\n");
        this.close();
      }
      deactivate() {
        if (this.value === false) return this.bell();
        this.value = false;
        this.render();
      }
      activate() {
        if (this.value === true) return this.bell();
        this.value = true;
        this.render();
      }
      delete() {
        this.deactivate();
      }
      left() {
        this.deactivate();
      }
      right() {
        this.activate();
      }
      down() {
        this.deactivate();
      }
      up() {
        this.activate();
      }
      next() {
        this.value = !this.value;
        this.fire();
        this.render();
      }
      _(c4, key) {
        if (c4 === " ") {
          this.value = !this.value;
        } else if (c4 === "1") {
          this.value = true;
        } else if (c4 === "0") {
          this.value = false;
        } else return this.bell();
        this.render();
      }
      render() {
        if (this.closed) return;
        if (this.firstRender) this.out.write(cursor.hide);
        else this.out.write(clear(this.outputText, this.out.columns));
        super.render();
        this.outputText = [
          style.symbol(this.done, this.aborted),
          color.bold(this.msg),
          style.delimiter(this.done),
          this.value ? this.inactive : color.cyan().underline(this.inactive),
          color.gray("/"),
          this.value ? color.cyan().underline(this.active) : this.active
        ].join(" ");
        this.out.write(erase.line + cursor.to(0) + this.outputText);
      }
    };
    module2.exports = TogglePrompt;
  }
});

// node_modules/prompts/lib/dateparts/datepart.js
var require_datepart2 = __commonJS({
  "node_modules/prompts/lib/dateparts/datepart.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var DatePart = class _DatePart {
      static {
        __name(this, "DatePart");
      }
      constructor({ token: token2, date: date4, parts, locales }) {
        this.token = token2;
        this.date = date4 || /* @__PURE__ */ new Date();
        this.parts = parts || [this];
        this.locales = locales || {};
      }
      up() {
      }
      down() {
      }
      next() {
        const currentIdx = this.parts.indexOf(this);
        return this.parts.find((part, idx) => idx > currentIdx && part instanceof _DatePart);
      }
      setTo(val) {
      }
      prev() {
        let parts = [].concat(this.parts).reverse();
        const currentIdx = parts.indexOf(this);
        return parts.find((part, idx) => idx > currentIdx && part instanceof _DatePart);
      }
      toString() {
        return String(this.date);
      }
    };
    module2.exports = DatePart;
  }
});

// node_modules/prompts/lib/dateparts/meridiem.js
var require_meridiem2 = __commonJS({
  "node_modules/prompts/lib/dateparts/meridiem.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var DatePart = require_datepart2();
    var Meridiem = class extends DatePart {
      static {
        __name(this, "Meridiem");
      }
      constructor(opts = {}) {
        super(opts);
      }
      up() {
        this.date.setHours((this.date.getHours() + 12) % 24);
      }
      down() {
        this.up();
      }
      toString() {
        let meridiem = this.date.getHours() > 12 ? "pm" : "am";
        return /\A/.test(this.token) ? meridiem.toUpperCase() : meridiem;
      }
    };
    module2.exports = Meridiem;
  }
});

// node_modules/prompts/lib/dateparts/day.js
var require_day2 = __commonJS({
  "node_modules/prompts/lib/dateparts/day.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var DatePart = require_datepart2();
    var pos2 = /* @__PURE__ */ __name((n3) => {
      n3 = n3 % 10;
      return n3 === 1 ? "st" : n3 === 2 ? "nd" : n3 === 3 ? "rd" : "th";
    }, "pos");
    var Day = class extends DatePart {
      static {
        __name(this, "Day");
      }
      constructor(opts = {}) {
        super(opts);
      }
      up() {
        this.date.setDate(this.date.getDate() + 1);
      }
      down() {
        this.date.setDate(this.date.getDate() - 1);
      }
      setTo(val) {
        this.date.setDate(parseInt(val.substr(-2)));
      }
      toString() {
        let date4 = this.date.getDate();
        let day = this.date.getDay();
        return this.token === "DD" ? String(date4).padStart(2, "0") : this.token === "Do" ? date4 + pos2(date4) : this.token === "d" ? day + 1 : this.token === "ddd" ? this.locales.weekdaysShort[day] : this.token === "dddd" ? this.locales.weekdays[day] : date4;
      }
    };
    module2.exports = Day;
  }
});

// node_modules/prompts/lib/dateparts/hours.js
var require_hours2 = __commonJS({
  "node_modules/prompts/lib/dateparts/hours.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var DatePart = require_datepart2();
    var Hours = class extends DatePart {
      static {
        __name(this, "Hours");
      }
      constructor(opts = {}) {
        super(opts);
      }
      up() {
        this.date.setHours(this.date.getHours() + 1);
      }
      down() {
        this.date.setHours(this.date.getHours() - 1);
      }
      setTo(val) {
        this.date.setHours(parseInt(val.substr(-2)));
      }
      toString() {
        let hours = this.date.getHours();
        if (/h/.test(this.token))
          hours = hours % 12 || 12;
        return this.token.length > 1 ? String(hours).padStart(2, "0") : hours;
      }
    };
    module2.exports = Hours;
  }
});

// node_modules/prompts/lib/dateparts/milliseconds.js
var require_milliseconds2 = __commonJS({
  "node_modules/prompts/lib/dateparts/milliseconds.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var DatePart = require_datepart2();
    var Milliseconds = class extends DatePart {
      static {
        __name(this, "Milliseconds");
      }
      constructor(opts = {}) {
        super(opts);
      }
      up() {
        this.date.setMilliseconds(this.date.getMilliseconds() + 1);
      }
      down() {
        this.date.setMilliseconds(this.date.getMilliseconds() - 1);
      }
      setTo(val) {
        this.date.setMilliseconds(parseInt(val.substr(-this.token.length)));
      }
      toString() {
        return String(this.date.getMilliseconds()).padStart(4, "0").substr(0, this.token.length);
      }
    };
    module2.exports = Milliseconds;
  }
});

// node_modules/prompts/lib/dateparts/minutes.js
var require_minutes2 = __commonJS({
  "node_modules/prompts/lib/dateparts/minutes.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var DatePart = require_datepart2();
    var Minutes = class extends DatePart {
      static {
        __name(this, "Minutes");
      }
      constructor(opts = {}) {
        super(opts);
      }
      up() {
        this.date.setMinutes(this.date.getMinutes() + 1);
      }
      down() {
        this.date.setMinutes(this.date.getMinutes() - 1);
      }
      setTo(val) {
        this.date.setMinutes(parseInt(val.substr(-2)));
      }
      toString() {
        let m3 = this.date.getMinutes();
        return this.token.length > 1 ? String(m3).padStart(2, "0") : m3;
      }
    };
    module2.exports = Minutes;
  }
});

// node_modules/prompts/lib/dateparts/month.js
var require_month2 = __commonJS({
  "node_modules/prompts/lib/dateparts/month.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var DatePart = require_datepart2();
    var Month = class extends DatePart {
      static {
        __name(this, "Month");
      }
      constructor(opts = {}) {
        super(opts);
      }
      up() {
        this.date.setMonth(this.date.getMonth() + 1);
      }
      down() {
        this.date.setMonth(this.date.getMonth() - 1);
      }
      setTo(val) {
        val = parseInt(val.substr(-2)) - 1;
        this.date.setMonth(val < 0 ? 0 : val);
      }
      toString() {
        let month = this.date.getMonth();
        let tl = this.token.length;
        return tl === 2 ? String(month + 1).padStart(2, "0") : tl === 3 ? this.locales.monthsShort[month] : tl === 4 ? this.locales.months[month] : String(month + 1);
      }
    };
    module2.exports = Month;
  }
});

// node_modules/prompts/lib/dateparts/seconds.js
var require_seconds2 = __commonJS({
  "node_modules/prompts/lib/dateparts/seconds.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var DatePart = require_datepart2();
    var Seconds = class extends DatePart {
      static {
        __name(this, "Seconds");
      }
      constructor(opts = {}) {
        super(opts);
      }
      up() {
        this.date.setSeconds(this.date.getSeconds() + 1);
      }
      down() {
        this.date.setSeconds(this.date.getSeconds() - 1);
      }
      setTo(val) {
        this.date.setSeconds(parseInt(val.substr(-2)));
      }
      toString() {
        let s5 = this.date.getSeconds();
        return this.token.length > 1 ? String(s5).padStart(2, "0") : s5;
      }
    };
    module2.exports = Seconds;
  }
});

// node_modules/prompts/lib/dateparts/year.js
var require_year2 = __commonJS({
  "node_modules/prompts/lib/dateparts/year.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var DatePart = require_datepart2();
    var Year = class extends DatePart {
      static {
        __name(this, "Year");
      }
      constructor(opts = {}) {
        super(opts);
      }
      up() {
        this.date.setFullYear(this.date.getFullYear() + 1);
      }
      down() {
        this.date.setFullYear(this.date.getFullYear() - 1);
      }
      setTo(val) {
        this.date.setFullYear(val.substr(-4));
      }
      toString() {
        let year = String(this.date.getFullYear()).padStart(4, "0");
        return this.token.length === 2 ? year.substr(-2) : year;
      }
    };
    module2.exports = Year;
  }
});

// node_modules/prompts/lib/dateparts/index.js
var require_dateparts2 = __commonJS({
  "node_modules/prompts/lib/dateparts/index.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    module2.exports = {
      DatePart: require_datepart2(),
      Meridiem: require_meridiem2(),
      Day: require_day2(),
      Hours: require_hours2(),
      Milliseconds: require_milliseconds2(),
      Minutes: require_minutes2(),
      Month: require_month2(),
      Seconds: require_seconds2(),
      Year: require_year2()
    };
  }
});

// node_modules/prompts/lib/elements/date.js
var require_date2 = __commonJS({
  "node_modules/prompts/lib/elements/date.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var color = require_kleur();
    var Prompt = require_prompt2();
    var { style, clear, figures } = require_util18();
    var { erase, cursor } = require_src37();
    var { DatePart, Meridiem, Day, Hours, Milliseconds, Minutes, Month, Seconds, Year } = require_dateparts2();
    var regex3 = /\\(.)|"((?:\\["\\]|[^"])+)"|(D[Do]?|d{3,4}|d)|(M{1,4})|(YY(?:YY)?)|([aA])|([Hh]{1,2})|(m{1,2})|(s{1,2})|(S{1,4})|./g;
    var regexGroups = {
      1: ({ token: token2 }) => token2.replace(/\\(.)/g, "$1"),
      2: (opts) => new Day(opts),
      // Day // TODO
      3: (opts) => new Month(opts),
      // Month
      4: (opts) => new Year(opts),
      // Year
      5: (opts) => new Meridiem(opts),
      // AM/PM // TODO (special)
      6: (opts) => new Hours(opts),
      // Hours
      7: (opts) => new Minutes(opts),
      // Minutes
      8: (opts) => new Seconds(opts),
      // Seconds
      9: (opts) => new Milliseconds(opts)
      // Fractional seconds
    };
    var dfltLocales = {
      months: "January,February,March,April,May,June,July,August,September,October,November,December".split(","),
      monthsShort: "Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec".split(","),
      weekdays: "Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday".split(","),
      weekdaysShort: "Sun,Mon,Tue,Wed,Thu,Fri,Sat".split(",")
    };
    var DatePrompt = class extends Prompt {
      static {
        __name(this, "DatePrompt");
      }
      constructor(opts = {}) {
        super(opts);
        this.msg = opts.message;
        this.cursor = 0;
        this.typed = "";
        this.locales = Object.assign(dfltLocales, opts.locales);
        this._date = opts.initial || /* @__PURE__ */ new Date();
        this.errorMsg = opts.error || "Please Enter A Valid Value";
        this.validator = opts.validate || (() => true);
        this.mask = opts.mask || "YYYY-MM-DD HH:mm:ss";
        this.clear = clear("", this.out.columns);
        this.render();
      }
      get value() {
        return this.date;
      }
      get date() {
        return this._date;
      }
      set date(date4) {
        if (date4) this._date.setTime(date4.getTime());
      }
      set mask(mask) {
        let result;
        this.parts = [];
        while (result = regex3.exec(mask)) {
          let match2 = result.shift();
          let idx = result.findIndex((gr2) => gr2 != null);
          this.parts.push(idx in regexGroups ? regexGroups[idx]({ token: result[idx] || match2, date: this.date, parts: this.parts, locales: this.locales }) : result[idx] || match2);
        }
        let parts = this.parts.reduce((arr, i3) => {
          if (typeof i3 === "string" && typeof arr[arr.length - 1] === "string")
            arr[arr.length - 1] += i3;
          else arr.push(i3);
          return arr;
        }, []);
        this.parts.splice(0);
        this.parts.push(...parts);
        this.reset();
      }
      moveCursor(n3) {
        this.typed = "";
        this.cursor = n3;
        this.fire();
      }
      reset() {
        this.moveCursor(this.parts.findIndex((p2) => p2 instanceof DatePart));
        this.fire();
        this.render();
      }
      exit() {
        this.abort();
      }
      abort() {
        this.done = this.aborted = true;
        this.error = false;
        this.fire();
        this.render();
        this.out.write("\n");
        this.close();
      }
      async validate() {
        let valid = await this.validator(this.value);
        if (typeof valid === "string") {
          this.errorMsg = valid;
          valid = false;
        }
        this.error = !valid;
      }
      async submit() {
        await this.validate();
        if (this.error) {
          this.color = "red";
          this.fire();
          this.render();
          return;
        }
        this.done = true;
        this.aborted = false;
        this.fire();
        this.render();
        this.out.write("\n");
        this.close();
      }
      up() {
        this.typed = "";
        this.parts[this.cursor].up();
        this.render();
      }
      down() {
        this.typed = "";
        this.parts[this.cursor].down();
        this.render();
      }
      left() {
        let prev = this.parts[this.cursor].prev();
        if (prev == null) return this.bell();
        this.moveCursor(this.parts.indexOf(prev));
        this.render();
      }
      right() {
        let next = this.parts[this.cursor].next();
        if (next == null) return this.bell();
        this.moveCursor(this.parts.indexOf(next));
        this.render();
      }
      next() {
        let next = this.parts[this.cursor].next();
        this.moveCursor(next ? this.parts.indexOf(next) : this.parts.findIndex((part) => part instanceof DatePart));
        this.render();
      }
      _(c4) {
        if (/\d/.test(c4)) {
          this.typed += c4;
          this.parts[this.cursor].setTo(this.typed);
          this.render();
        }
      }
      render() {
        if (this.closed) return;
        if (this.firstRender) this.out.write(cursor.hide);
        else this.out.write(clear(this.outputText, this.out.columns));
        super.render();
        this.outputText = [
          style.symbol(this.done, this.aborted),
          color.bold(this.msg),
          style.delimiter(false),
          this.parts.reduce((arr, p2, idx) => arr.concat(idx === this.cursor && !this.done ? color.cyan().underline(p2.toString()) : p2), []).join("")
        ].join(" ");
        if (this.error) {
          this.outputText += this.errorMsg.split("\n").reduce(
            (a2, l3, i3) => a2 + `
${i3 ? ` ` : figures.pointerSmall} ${color.red().italic(l3)}`,
            ``
          );
        }
        this.out.write(erase.line + cursor.to(0) + this.outputText);
      }
    };
    module2.exports = DatePrompt;
  }
});

// node_modules/prompts/lib/elements/number.js
var require_number2 = __commonJS({
  "node_modules/prompts/lib/elements/number.js"(exports2, module2) {
    init_esbuild_shims();
    var color = require_kleur();
    var Prompt = require_prompt2();
    var { cursor, erase } = require_src37();
    var { style, figures, clear, lines } = require_util18();
    var isNumber3 = /[0-9]/;
    var isDef = /* @__PURE__ */ __name((any2) => any2 !== void 0, "isDef");
    var round = /* @__PURE__ */ __name((number4, precision) => {
      let factor = Math.pow(10, precision);
      return Math.round(number4 * factor) / factor;
    }, "round");
    var NumberPrompt = class extends Prompt {
      static {
        __name(this, "NumberPrompt");
      }
      constructor(opts = {}) {
        super(opts);
        this.transform = style.render(opts.style);
        this.msg = opts.message;
        this.initial = isDef(opts.initial) ? opts.initial : "";
        this.float = !!opts.float;
        this.round = opts.round || 2;
        this.inc = opts.increment || 1;
        this.min = isDef(opts.min) ? opts.min : -Infinity;
        this.max = isDef(opts.max) ? opts.max : Infinity;
        this.errorMsg = opts.error || `Please Enter A Valid Value`;
        this.validator = opts.validate || (() => true);
        this.color = `cyan`;
        this.value = ``;
        this.typed = ``;
        this.lastHit = 0;
        this.render();
      }
      set value(v2) {
        if (!v2 && v2 !== 0) {
          this.placeholder = true;
          this.rendered = color.gray(this.transform.render(`${this.initial}`));
          this._value = ``;
        } else {
          this.placeholder = false;
          this.rendered = this.transform.render(`${round(v2, this.round)}`);
          this._value = round(v2, this.round);
        }
        this.fire();
      }
      get value() {
        return this._value;
      }
      parse(x3) {
        return this.float ? parseFloat(x3) : parseInt(x3);
      }
      valid(c4) {
        return c4 === `-` || c4 === `.` && this.float || isNumber3.test(c4);
      }
      reset() {
        this.typed = ``;
        this.value = ``;
        this.fire();
        this.render();
      }
      exit() {
        this.abort();
      }
      abort() {
        let x3 = this.value;
        this.value = x3 !== `` ? x3 : this.initial;
        this.done = this.aborted = true;
        this.error = false;
        this.fire();
        this.render();
        this.out.write(`
`);
        this.close();
      }
      async validate() {
        let valid = await this.validator(this.value);
        if (typeof valid === `string`) {
          this.errorMsg = valid;
          valid = false;
        }
        this.error = !valid;
      }
      async submit() {
        await this.validate();
        if (this.error) {
          this.color = `red`;
          this.fire();
          this.render();
          return;
        }
        let x3 = this.value;
        this.value = x3 !== `` ? x3 : this.initial;
        this.done = true;
        this.aborted = false;
        this.error = false;
        this.fire();
        this.render();
        this.out.write(`
`);
        this.close();
      }
      up() {
        this.typed = ``;
        if (this.value === "") {
          this.value = this.min - this.inc;
        }
        if (this.value >= this.max) return this.bell();
        this.value += this.inc;
        this.color = `cyan`;
        this.fire();
        this.render();
      }
      down() {
        this.typed = ``;
        if (this.value === "") {
          this.value = this.min + this.inc;
        }
        if (this.value <= this.min) return this.bell();
        this.value -= this.inc;
        this.color = `cyan`;
        this.fire();
        this.render();
      }
      delete() {
        let val = this.value.toString();
        if (val.length === 0) return this.bell();
        this.value = this.parse(val = val.slice(0, -1)) || ``;
        if (this.value !== "" && this.value < this.min) {
          this.value = this.min;
        }
        this.color = `cyan`;
        this.fire();
        this.render();
      }
      next() {
        this.value = this.initial;
        this.fire();
        this.render();
      }
      _(c4, key) {
        if (!this.valid(c4)) return this.bell();
        const now = Date.now();
        if (now - this.lastHit > 1e3) this.typed = ``;
        this.typed += c4;
        this.lastHit = now;
        this.color = `cyan`;
        if (c4 === `.`) return this.fire();
        this.value = Math.min(this.parse(this.typed), this.max);
        if (this.value > this.max) this.value = this.max;
        if (this.value < this.min) this.value = this.min;
        this.fire();
        this.render();
      }
      render() {
        if (this.closed) return;
        if (!this.firstRender) {
          if (this.outputError)
            this.out.write(cursor.down(lines(this.outputError, this.out.columns) - 1) + clear(this.outputError, this.out.columns));
          this.out.write(clear(this.outputText, this.out.columns));
        }
        super.render();
        this.outputError = "";
        this.outputText = [
          style.symbol(this.done, this.aborted),
          color.bold(this.msg),
          style.delimiter(this.done),
          !this.done || !this.done && !this.placeholder ? color[this.color]().underline(this.rendered) : this.rendered
        ].join(` `);
        if (this.error) {
          this.outputError += this.errorMsg.split(`
`).reduce((a2, l3, i3) => a2 + `
${i3 ? ` ` : figures.pointerSmall} ${color.red().italic(l3)}`, ``);
        }
        this.out.write(erase.line + cursor.to(0) + this.outputText + cursor.save + this.outputError + cursor.restore);
      }
    };
    module2.exports = NumberPrompt;
  }
});

// node_modules/prompts/lib/elements/multiselect.js
var require_multiselect2 = __commonJS({
  "node_modules/prompts/lib/elements/multiselect.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var color = require_kleur();
    var { cursor } = require_src37();
    var Prompt = require_prompt2();
    var { clear, figures, style, wrap: wrap2, entriesToDisplay } = require_util18();
    var MultiselectPrompt = class extends Prompt {
      static {
        __name(this, "MultiselectPrompt");
      }
      constructor(opts = {}) {
        super(opts);
        this.msg = opts.message;
        this.cursor = opts.cursor || 0;
        this.scrollIndex = opts.cursor || 0;
        this.hint = opts.hint || "";
        this.warn = opts.warn || "- This option is disabled -";
        this.minSelected = opts.min;
        this.showMinError = false;
        this.maxChoices = opts.max;
        this.instructions = opts.instructions;
        this.optionsPerPage = opts.optionsPerPage || 10;
        this.value = opts.choices.map((ch, idx) => {
          if (typeof ch === "string")
            ch = { title: ch, value: idx };
          return {
            title: ch && (ch.title || ch.value || ch),
            description: ch && ch.description,
            value: ch && (ch.value === void 0 ? idx : ch.value),
            selected: ch && ch.selected,
            disabled: ch && ch.disabled
          };
        });
        this.clear = clear("", this.out.columns);
        if (!opts.overrideRender) {
          this.render();
        }
      }
      reset() {
        this.value.map((v2) => !v2.selected);
        this.cursor = 0;
        this.fire();
        this.render();
      }
      selected() {
        return this.value.filter((v2) => v2.selected);
      }
      exit() {
        this.abort();
      }
      abort() {
        this.done = this.aborted = true;
        this.fire();
        this.render();
        this.out.write("\n");
        this.close();
      }
      submit() {
        const selected = this.value.filter((e4) => e4.selected);
        if (this.minSelected && selected.length < this.minSelected) {
          this.showMinError = true;
          this.render();
        } else {
          this.done = true;
          this.aborted = false;
          this.fire();
          this.render();
          this.out.write("\n");
          this.close();
        }
      }
      first() {
        this.cursor = 0;
        this.render();
      }
      last() {
        this.cursor = this.value.length - 1;
        this.render();
      }
      next() {
        this.cursor = (this.cursor + 1) % this.value.length;
        this.render();
      }
      up() {
        if (this.cursor === 0) {
          this.cursor = this.value.length - 1;
        } else {
          this.cursor--;
        }
        this.render();
      }
      down() {
        if (this.cursor === this.value.length - 1) {
          this.cursor = 0;
        } else {
          this.cursor++;
        }
        this.render();
      }
      left() {
        this.value[this.cursor].selected = false;
        this.render();
      }
      right() {
        if (this.value.filter((e4) => e4.selected).length >= this.maxChoices) return this.bell();
        this.value[this.cursor].selected = true;
        this.render();
      }
      handleSpaceToggle() {
        const v2 = this.value[this.cursor];
        if (v2.selected) {
          v2.selected = false;
          this.render();
        } else if (v2.disabled || this.value.filter((e4) => e4.selected).length >= this.maxChoices) {
          return this.bell();
        } else {
          v2.selected = true;
          this.render();
        }
      }
      toggleAll() {
        if (this.maxChoices !== void 0 || this.value[this.cursor].disabled) {
          return this.bell();
        }
        const newSelected = !this.value[this.cursor].selected;
        this.value.filter((v2) => !v2.disabled).forEach((v2) => v2.selected = newSelected);
        this.render();
      }
      _(c4, key) {
        if (c4 === " ") {
          this.handleSpaceToggle();
        } else if (c4 === "a") {
          this.toggleAll();
        } else {
          return this.bell();
        }
      }
      renderInstructions() {
        if (this.instructions === void 0 || this.instructions) {
          if (typeof this.instructions === "string") {
            return this.instructions;
          }
          return `
Instructions:
    ${figures.arrowUp}/${figures.arrowDown}: Highlight option
    ${figures.arrowLeft}/${figures.arrowRight}/[space]: Toggle selection
` + (this.maxChoices === void 0 ? `    a: Toggle all
` : "") + `    enter/return: Complete answer`;
        }
        return "";
      }
      renderOption(cursor2, v2, i3, arrowIndicator) {
        const prefix = (v2.selected ? color.green(figures.radioOn) : figures.radioOff) + " " + arrowIndicator + " ";
        let title, desc2;
        if (v2.disabled) {
          title = cursor2 === i3 ? color.gray().underline(v2.title) : color.strikethrough().gray(v2.title);
        } else {
          title = cursor2 === i3 ? color.cyan().underline(v2.title) : v2.title;
          if (cursor2 === i3 && v2.description) {
            desc2 = ` - ${v2.description}`;
            if (prefix.length + title.length + desc2.length >= this.out.columns || v2.description.split(/\r?\n/).length > 1) {
              desc2 = "\n" + wrap2(v2.description, { margin: prefix.length, width: this.out.columns });
            }
          }
        }
        return prefix + title + color.gray(desc2 || "");
      }
      // shared with autocompleteMultiselect
      paginateOptions(options2) {
        if (options2.length === 0) {
          return color.red("No matches for this query.");
        }
        let { startIndex, endIndex } = entriesToDisplay(this.cursor, options2.length, this.optionsPerPage);
        let prefix, styledOptions = [];
        for (let i3 = startIndex; i3 < endIndex; i3++) {
          if (i3 === startIndex && startIndex > 0) {
            prefix = figures.arrowUp;
          } else if (i3 === endIndex - 1 && endIndex < options2.length) {
            prefix = figures.arrowDown;
          } else {
            prefix = " ";
          }
          styledOptions.push(this.renderOption(this.cursor, options2[i3], i3, prefix));
        }
        return "\n" + styledOptions.join("\n");
      }
      // shared with autocomleteMultiselect
      renderOptions(options2) {
        if (!this.done) {
          return this.paginateOptions(options2);
        }
        return "";
      }
      renderDoneOrInstructions() {
        if (this.done) {
          return this.value.filter((e4) => e4.selected).map((v2) => v2.title).join(", ");
        }
        const output = [color.gray(this.hint), this.renderInstructions()];
        if (this.value[this.cursor].disabled) {
          output.push(color.yellow(this.warn));
        }
        return output.join(" ");
      }
      render() {
        if (this.closed) return;
        if (this.firstRender) this.out.write(cursor.hide);
        super.render();
        let prompt = [
          style.symbol(this.done, this.aborted),
          color.bold(this.msg),
          style.delimiter(false),
          this.renderDoneOrInstructions()
        ].join(" ");
        if (this.showMinError) {
          prompt += color.red(`You must select a minimum of ${this.minSelected} choices.`);
          this.showMinError = false;
        }
        prompt += this.renderOptions(this.value);
        this.out.write(this.clear + prompt);
        this.clear = clear(prompt, this.out.columns);
      }
    };
    module2.exports = MultiselectPrompt;
  }
});

// node_modules/prompts/lib/elements/autocomplete.js
var require_autocomplete2 = __commonJS({
  "node_modules/prompts/lib/elements/autocomplete.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var color = require_kleur();
    var Prompt = require_prompt2();
    var { erase, cursor } = require_src37();
    var { style, clear, figures, wrap: wrap2, entriesToDisplay } = require_util18();
    var getVal = /* @__PURE__ */ __name((arr, i3) => arr[i3] && (arr[i3].value || arr[i3].title || arr[i3]), "getVal");
    var getTitle = /* @__PURE__ */ __name((arr, i3) => arr[i3] && (arr[i3].title || arr[i3].value || arr[i3]), "getTitle");
    var getIndex = /* @__PURE__ */ __name((arr, valOrTitle) => {
      const index = arr.findIndex((el) => el.value === valOrTitle || el.title === valOrTitle);
      return index > -1 ? index : void 0;
    }, "getIndex");
    var AutocompletePrompt = class extends Prompt {
      static {
        __name(this, "AutocompletePrompt");
      }
      constructor(opts = {}) {
        super(opts);
        this.msg = opts.message;
        this.suggest = opts.suggest;
        this.choices = opts.choices;
        this.initial = typeof opts.initial === "number" ? opts.initial : getIndex(opts.choices, opts.initial);
        this.select = this.initial || opts.cursor || 0;
        this.i18n = { noMatches: opts.noMatches || "no matches found" };
        this.fallback = opts.fallback || this.initial;
        this.clearFirst = opts.clearFirst || false;
        this.suggestions = [];
        this.input = "";
        this.limit = opts.limit || 10;
        this.cursor = 0;
        this.transform = style.render(opts.style);
        this.scale = this.transform.scale;
        this.render = this.render.bind(this);
        this.complete = this.complete.bind(this);
        this.clear = clear("", this.out.columns);
        this.complete(this.render);
        this.render();
      }
      set fallback(fb) {
        this._fb = Number.isSafeInteger(parseInt(fb)) ? parseInt(fb) : fb;
      }
      get fallback() {
        let choice2;
        if (typeof this._fb === "number")
          choice2 = this.choices[this._fb];
        else if (typeof this._fb === "string")
          choice2 = { title: this._fb };
        return choice2 || this._fb || { title: this.i18n.noMatches };
      }
      moveSelect(i3) {
        this.select = i3;
        if (this.suggestions.length > 0)
          this.value = getVal(this.suggestions, i3);
        else this.value = this.fallback.value;
        this.fire();
      }
      async complete(cb) {
        const p2 = this.completing = this.suggest(this.input, this.choices);
        const suggestions = await p2;
        if (this.completing !== p2) return;
        this.suggestions = suggestions.map((s5, i3, arr) => ({ title: getTitle(arr, i3), value: getVal(arr, i3), description: s5.description }));
        this.completing = false;
        const l3 = Math.max(suggestions.length - 1, 0);
        this.moveSelect(Math.min(l3, this.select));
        cb && cb();
      }
      reset() {
        this.input = "";
        this.complete(() => {
          this.moveSelect(this.initial !== void 0 ? this.initial : 0);
          this.render();
        });
        this.render();
      }
      exit() {
        if (this.clearFirst && this.input.length > 0) {
          this.reset();
        } else {
          this.done = this.exited = true;
          this.aborted = false;
          this.fire();
          this.render();
          this.out.write("\n");
          this.close();
        }
      }
      abort() {
        this.done = this.aborted = true;
        this.exited = false;
        this.fire();
        this.render();
        this.out.write("\n");
        this.close();
      }
      submit() {
        this.done = true;
        this.aborted = this.exited = false;
        this.fire();
        this.render();
        this.out.write("\n");
        this.close();
      }
      _(c4, key) {
        let s1 = this.input.slice(0, this.cursor);
        let s22 = this.input.slice(this.cursor);
        this.input = `${s1}${c4}${s22}`;
        this.cursor = s1.length + 1;
        this.complete(this.render);
        this.render();
      }
      delete() {
        if (this.cursor === 0) return this.bell();
        let s1 = this.input.slice(0, this.cursor - 1);
        let s22 = this.input.slice(this.cursor);
        this.input = `${s1}${s22}`;
        this.complete(this.render);
        this.cursor = this.cursor - 1;
        this.render();
      }
      deleteForward() {
        if (this.cursor * this.scale >= this.rendered.length) return this.bell();
        let s1 = this.input.slice(0, this.cursor);
        let s22 = this.input.slice(this.cursor + 1);
        this.input = `${s1}${s22}`;
        this.complete(this.render);
        this.render();
      }
      first() {
        this.moveSelect(0);
        this.render();
      }
      last() {
        this.moveSelect(this.suggestions.length - 1);
        this.render();
      }
      up() {
        if (this.select === 0) {
          this.moveSelect(this.suggestions.length - 1);
        } else {
          this.moveSelect(this.select - 1);
        }
        this.render();
      }
      down() {
        if (this.select === this.suggestions.length - 1) {
          this.moveSelect(0);
        } else {
          this.moveSelect(this.select + 1);
        }
        this.render();
      }
      next() {
        if (this.select === this.suggestions.length - 1) {
          this.moveSelect(0);
        } else this.moveSelect(this.select + 1);
        this.render();
      }
      nextPage() {
        this.moveSelect(Math.min(this.select + this.limit, this.suggestions.length - 1));
        this.render();
      }
      prevPage() {
        this.moveSelect(Math.max(this.select - this.limit, 0));
        this.render();
      }
      left() {
        if (this.cursor <= 0) return this.bell();
        this.cursor = this.cursor - 1;
        this.render();
      }
      right() {
        if (this.cursor * this.scale >= this.rendered.length) return this.bell();
        this.cursor = this.cursor + 1;
        this.render();
      }
      renderOption(v2, hovered, isStart, isEnd) {
        let desc2;
        let prefix = isStart ? figures.arrowUp : isEnd ? figures.arrowDown : " ";
        let title = hovered ? color.cyan().underline(v2.title) : v2.title;
        prefix = (hovered ? color.cyan(figures.pointer) + " " : "  ") + prefix;
        if (v2.description) {
          desc2 = ` - ${v2.description}`;
          if (prefix.length + title.length + desc2.length >= this.out.columns || v2.description.split(/\r?\n/).length > 1) {
            desc2 = "\n" + wrap2(v2.description, { margin: 3, width: this.out.columns });
          }
        }
        return prefix + " " + title + color.gray(desc2 || "");
      }
      render() {
        if (this.closed) return;
        if (this.firstRender) this.out.write(cursor.hide);
        else this.out.write(clear(this.outputText, this.out.columns));
        super.render();
        let { startIndex, endIndex } = entriesToDisplay(this.select, this.choices.length, this.limit);
        this.outputText = [
          style.symbol(this.done, this.aborted, this.exited),
          color.bold(this.msg),
          style.delimiter(this.completing),
          this.done && this.suggestions[this.select] ? this.suggestions[this.select].title : this.rendered = this.transform.render(this.input)
        ].join(" ");
        if (!this.done) {
          const suggestions = this.suggestions.slice(startIndex, endIndex).map((item, i3) => this.renderOption(
            item,
            this.select === i3 + startIndex,
            i3 === 0 && startIndex > 0,
            i3 + startIndex === endIndex - 1 && endIndex < this.choices.length
          )).join("\n");
          this.outputText += `
` + (suggestions || color.gray(this.fallback.title));
        }
        this.out.write(erase.line + cursor.to(0) + this.outputText);
      }
    };
    module2.exports = AutocompletePrompt;
  }
});

// node_modules/prompts/lib/elements/autocompleteMultiselect.js
var require_autocompleteMultiselect2 = __commonJS({
  "node_modules/prompts/lib/elements/autocompleteMultiselect.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var color = require_kleur();
    var { cursor } = require_src37();
    var MultiselectPrompt = require_multiselect2();
    var { clear, style, figures } = require_util18();
    var AutocompleteMultiselectPrompt = class extends MultiselectPrompt {
      static {
        __name(this, "AutocompleteMultiselectPrompt");
      }
      constructor(opts = {}) {
        opts.overrideRender = true;
        super(opts);
        this.inputValue = "";
        this.clear = clear("", this.out.columns);
        this.filteredOptions = this.value;
        this.render();
      }
      last() {
        this.cursor = this.filteredOptions.length - 1;
        this.render();
      }
      next() {
        this.cursor = (this.cursor + 1) % this.filteredOptions.length;
        this.render();
      }
      up() {
        if (this.cursor === 0) {
          this.cursor = this.filteredOptions.length - 1;
        } else {
          this.cursor--;
        }
        this.render();
      }
      down() {
        if (this.cursor === this.filteredOptions.length - 1) {
          this.cursor = 0;
        } else {
          this.cursor++;
        }
        this.render();
      }
      left() {
        this.filteredOptions[this.cursor].selected = false;
        this.render();
      }
      right() {
        if (this.value.filter((e4) => e4.selected).length >= this.maxChoices) return this.bell();
        this.filteredOptions[this.cursor].selected = true;
        this.render();
      }
      delete() {
        if (this.inputValue.length) {
          this.inputValue = this.inputValue.substr(0, this.inputValue.length - 1);
          this.updateFilteredOptions();
        }
      }
      updateFilteredOptions() {
        const currentHighlight = this.filteredOptions[this.cursor];
        this.filteredOptions = this.value.filter((v2) => {
          if (this.inputValue) {
            if (typeof v2.title === "string") {
              if (v2.title.toLowerCase().includes(this.inputValue.toLowerCase())) {
                return true;
              }
            }
            if (typeof v2.value === "string") {
              if (v2.value.toLowerCase().includes(this.inputValue.toLowerCase())) {
                return true;
              }
            }
            return false;
          }
          return true;
        });
        const newHighlightIndex = this.filteredOptions.findIndex((v2) => v2 === currentHighlight);
        this.cursor = newHighlightIndex < 0 ? 0 : newHighlightIndex;
        this.render();
      }
      handleSpaceToggle() {
        const v2 = this.filteredOptions[this.cursor];
        if (v2.selected) {
          v2.selected = false;
          this.render();
        } else if (v2.disabled || this.value.filter((e4) => e4.selected).length >= this.maxChoices) {
          return this.bell();
        } else {
          v2.selected = true;
          this.render();
        }
      }
      handleInputChange(c4) {
        this.inputValue = this.inputValue + c4;
        this.updateFilteredOptions();
      }
      _(c4, key) {
        if (c4 === " ") {
          this.handleSpaceToggle();
        } else {
          this.handleInputChange(c4);
        }
      }
      renderInstructions() {
        if (this.instructions === void 0 || this.instructions) {
          if (typeof this.instructions === "string") {
            return this.instructions;
          }
          return `
Instructions:
    ${figures.arrowUp}/${figures.arrowDown}: Highlight option
    ${figures.arrowLeft}/${figures.arrowRight}/[space]: Toggle selection
    [a,b,c]/delete: Filter choices
    enter/return: Complete answer
`;
        }
        return "";
      }
      renderCurrentInput() {
        return `
Filtered results for: ${this.inputValue ? this.inputValue : color.gray("Enter something to filter")}
`;
      }
      renderOption(cursor2, v2, i3) {
        let title;
        if (v2.disabled) title = cursor2 === i3 ? color.gray().underline(v2.title) : color.strikethrough().gray(v2.title);
        else title = cursor2 === i3 ? color.cyan().underline(v2.title) : v2.title;
        return (v2.selected ? color.green(figures.radioOn) : figures.radioOff) + "  " + title;
      }
      renderDoneOrInstructions() {
        if (this.done) {
          return this.value.filter((e4) => e4.selected).map((v2) => v2.title).join(", ");
        }
        const output = [color.gray(this.hint), this.renderInstructions(), this.renderCurrentInput()];
        if (this.filteredOptions.length && this.filteredOptions[this.cursor].disabled) {
          output.push(color.yellow(this.warn));
        }
        return output.join(" ");
      }
      render() {
        if (this.closed) return;
        if (this.firstRender) this.out.write(cursor.hide);
        super.render();
        let prompt = [
          style.symbol(this.done, this.aborted),
          color.bold(this.msg),
          style.delimiter(false),
          this.renderDoneOrInstructions()
        ].join(" ");
        if (this.showMinError) {
          prompt += color.red(`You must select a minimum of ${this.minSelected} choices.`);
          this.showMinError = false;
        }
        prompt += this.renderOptions(this.filteredOptions);
        this.out.write(this.clear + prompt);
        this.clear = clear(prompt, this.out.columns);
      }
    };
    module2.exports = AutocompleteMultiselectPrompt;
  }
});

// node_modules/prompts/lib/elements/confirm.js
var require_confirm2 = __commonJS({
  "node_modules/prompts/lib/elements/confirm.js"(exports2, module2) {
    init_esbuild_shims();
    var color = require_kleur();
    var Prompt = require_prompt2();
    var { style, clear } = require_util18();
    var { erase, cursor } = require_src37();
    var ConfirmPrompt = class extends Prompt {
      static {
        __name(this, "ConfirmPrompt");
      }
      constructor(opts = {}) {
        super(opts);
        this.msg = opts.message;
        this.value = opts.initial;
        this.initialValue = !!opts.initial;
        this.yesMsg = opts.yes || "yes";
        this.yesOption = opts.yesOption || "(Y/n)";
        this.noMsg = opts.no || "no";
        this.noOption = opts.noOption || "(y/N)";
        this.render();
      }
      reset() {
        this.value = this.initialValue;
        this.fire();
        this.render();
      }
      exit() {
        this.abort();
      }
      abort() {
        this.done = this.aborted = true;
        this.fire();
        this.render();
        this.out.write("\n");
        this.close();
      }
      submit() {
        this.value = this.value || false;
        this.done = true;
        this.aborted = false;
        this.fire();
        this.render();
        this.out.write("\n");
        this.close();
      }
      _(c4, key) {
        if (c4.toLowerCase() === "y") {
          this.value = true;
          return this.submit();
        }
        if (c4.toLowerCase() === "n") {
          this.value = false;
          return this.submit();
        }
        return this.bell();
      }
      render() {
        if (this.closed) return;
        if (this.firstRender) this.out.write(cursor.hide);
        else this.out.write(clear(this.outputText, this.out.columns));
        super.render();
        this.outputText = [
          style.symbol(this.done, this.aborted),
          color.bold(this.msg),
          style.delimiter(this.done),
          this.done ? this.value ? this.yesMsg : this.noMsg : color.gray(this.initialValue ? this.yesOption : this.noOption)
        ].join(" ");
        this.out.write(erase.line + cursor.to(0) + this.outputText);
      }
    };
    module2.exports = ConfirmPrompt;
  }
});

// node_modules/prompts/lib/elements/index.js
var require_elements2 = __commonJS({
  "node_modules/prompts/lib/elements/index.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    module2.exports = {
      TextPrompt: require_text2(),
      SelectPrompt: require_select2(),
      TogglePrompt: require_toggle2(),
      DatePrompt: require_date2(),
      NumberPrompt: require_number2(),
      MultiselectPrompt: require_multiselect2(),
      AutocompletePrompt: require_autocomplete2(),
      AutocompleteMultiselectPrompt: require_autocompleteMultiselect2(),
      ConfirmPrompt: require_confirm2()
    };
  }
});

// node_modules/prompts/lib/prompts.js
var require_prompts2 = __commonJS({
  "node_modules/prompts/lib/prompts.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    var $2 = exports2;
    var el = require_elements2();
    var noop8 = /* @__PURE__ */ __name((v2) => v2, "noop");
    function toPrompt(type, args, opts = {}) {
      return new Promise((res, rej) => {
        const p2 = new el[type](args);
        const onAbort = opts.onAbort || noop8;
        const onSubmit = opts.onSubmit || noop8;
        const onExit = opts.onExit || noop8;
        p2.on("state", args.onState || noop8);
        p2.on("submit", (x3) => res(onSubmit(x3)));
        p2.on("exit", (x3) => res(onExit(x3)));
        p2.on("abort", (x3) => rej(onAbort(x3)));
      });
    }
    __name(toPrompt, "toPrompt");
    $2.text = (args) => toPrompt("TextPrompt", args);
    $2.password = (args) => {
      args.style = "password";
      return $2.text(args);
    };
    $2.invisible = (args) => {
      args.style = "invisible";
      return $2.text(args);
    };
    $2.number = (args) => toPrompt("NumberPrompt", args);
    $2.date = (args) => toPrompt("DatePrompt", args);
    $2.confirm = (args) => toPrompt("ConfirmPrompt", args);
    $2.list = (args) => {
      const sep9 = args.separator || ",";
      return toPrompt("TextPrompt", args, {
        onSubmit: /* @__PURE__ */ __name((str2) => str2.split(sep9).map((s5) => s5.trim()), "onSubmit")
      });
    };
    $2.toggle = (args) => toPrompt("TogglePrompt", args);
    $2.select = (args) => toPrompt("SelectPrompt", args);
    $2.multiselect = (args) => {
      args.choices = [].concat(args.choices || []);
      const toSelected = /* @__PURE__ */ __name((items) => items.filter((item) => item.selected).map((item) => item.value), "toSelected");
      return toPrompt("MultiselectPrompt", args, {
        onAbort: toSelected,
        onSubmit: toSelected
      });
    };
    $2.autocompleteMultiselect = (args) => {
      args.choices = [].concat(args.choices || []);
      const toSelected = /* @__PURE__ */ __name((items) => items.filter((item) => item.selected).map((item) => item.value), "toSelected");
      return toPrompt("AutocompleteMultiselectPrompt", args, {
        onAbort: toSelected,
        onSubmit: toSelected
      });
    };
    var byTitle = /* @__PURE__ */ __name((input, choices) => Promise.resolve(
      choices.filter((item) => item.title.slice(0, input.length).toLowerCase() === input.toLowerCase())
    ), "byTitle");
    $2.autocomplete = (args) => {
      args.suggest = args.suggest || byTitle;
      args.choices = [].concat(args.choices || []);
      return toPrompt("AutocompletePrompt", args);
    };
  }
});

// node_modules/prompts/lib/index.js
var require_lib4 = __commonJS({
  "node_modules/prompts/lib/index.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var prompts3 = require_prompts2();
    var passOn = ["suggest", "format", "onState", "validate", "onRender", "type"];
    var noop8 = /* @__PURE__ */ __name(() => {
    }, "noop");
    async function prompt(questions = [], { onSubmit = noop8, onCancel = noop8 } = {}) {
      const answers = {};
      const override2 = prompt._override || {};
      questions = [].concat(questions);
      let answer, question, quit, name3, type, lastPrompt;
      const getFormattedAnswer = /* @__PURE__ */ __name(async (question2, answer2, skipValidation = false) => {
        if (!skipValidation && question2.validate && question2.validate(answer2) !== true) {
          return;
        }
        return question2.format ? await question2.format(answer2, answers) : answer2;
      }, "getFormattedAnswer");
      for (question of questions) {
        ({ name: name3, type } = question);
        if (typeof type === "function") {
          type = await type(answer, { ...answers }, question);
          question["type"] = type;
        }
        if (!type) continue;
        for (let key in question) {
          if (passOn.includes(key)) continue;
          let value = question[key];
          question[key] = typeof value === "function" ? await value(answer, { ...answers }, lastPrompt) : value;
        }
        lastPrompt = question;
        if (typeof question.message !== "string") {
          throw new Error("prompt message is required");
        }
        ({ name: name3, type } = question);
        if (prompts3[type] === void 0) {
          throw new Error(`prompt type (${type}) is not defined`);
        }
        if (override2[question.name] !== void 0) {
          answer = await getFormattedAnswer(question, override2[question.name]);
          if (answer !== void 0) {
            answers[name3] = answer;
            continue;
          }
        }
        try {
          answer = prompt._injected ? getInjectedAnswer(prompt._injected, question.initial) : await prompts3[type](question);
          answers[name3] = answer = await getFormattedAnswer(question, answer, true);
          quit = await onSubmit(question, answer, answers);
        } catch (err) {
          quit = !await onCancel(question, answers);
        }
        if (quit) return answers;
      }
      return answers;
    }
    __name(prompt, "prompt");
    function getInjectedAnswer(injected, deafultValue) {
      const answer = injected.shift();
      if (answer instanceof Error) {
        throw answer;
      }
      return answer === void 0 ? deafultValue : answer;
    }
    __name(getInjectedAnswer, "getInjectedAnswer");
    function inject(answers) {
      prompt._injected = (prompt._injected || []).concat(answers);
    }
    __name(inject, "inject");
    function override(answers) {
      prompt._override = Object.assign({}, answers);
    }
    __name(override, "override");
    module2.exports = Object.assign(prompt, { prompt, prompts: prompts3, inject, override });
  }
});

// node_modules/prompts/index.js
var require_prompts3 = __commonJS({
  "node_modules/prompts/index.js"(exports2, module2) {
    init_esbuild_shims();
    function isNodeLT(tar) {
      tar = (Array.isArray(tar) ? tar : tar.split(".")).map(Number);
      let i3 = 0, src = process.versions.node.split(".").map(Number);
      for (; i3 < tar.length; i3++) {
        if (src[i3] > tar[i3]) return false;
        if (tar[i3] > src[i3]) return true;
      }
      return false;
    }
    __name(isNodeLT, "isNodeLT");
    module2.exports = isNodeLT("8.6.0") ? require_dist6() : require_lib4();
  }
});

// packages/core/dist/src/extension/extensionSettings.js
import * as fs60 from "node:fs/promises";
import * as fsSync3 from "node:fs";
import * as path61 from "node:path";
async function maybePromptForSettings(extensionConfig, extensionId, requestSetting, previousExtensionConfig, previousSettings) {
  const { name: extensionName, settings } = extensionConfig;
  if ((!settings || settings.length === 0) && (!previousExtensionConfig?.settings || previousExtensionConfig.settings.length === 0)) {
    return;
  }
  const scope = ExtensionSettingScope.USER;
  const envFilePath = getEnvFilePath(extensionName, scope);
  const keychain = new KeychainTokenStorage(getKeychainStorageName(extensionName, extensionId, scope));
  if (!settings || settings.length === 0) {
    await clearSettings(envFilePath, keychain);
    return;
  }
  const settingsChanges = getSettingsChanges(settings, previousExtensionConfig?.settings ?? []);
  const allSettings = { ...previousSettings };
  for (const removedEnvSetting of settingsChanges.removeEnv) {
    delete allSettings[removedEnvSetting.envVar];
  }
  for (const removedSensitiveSetting of settingsChanges.removeSensitive) {
    await keychain.deleteSecret(removedSensitiveSetting.envVar);
  }
  for (const setting of settingsChanges.promptForSensitive.concat(settingsChanges.promptForEnv)) {
    const answer = await requestSetting(setting);
    allSettings[setting.envVar] = answer;
  }
  const nonSensitiveSettings = {};
  for (const setting of settings) {
    const value = allSettings[setting.envVar];
    if (value === void 0) {
      continue;
    }
    if (setting.sensitive) {
      await keychain.setSecret(setting.envVar, value);
    } else {
      nonSensitiveSettings[setting.envVar] = value;
    }
  }
  const envContent = formatEnvContent(nonSensitiveSettings);
  await fs60.writeFile(envFilePath, envContent);
}
function formatEnvContent(settings) {
  let envContent = "";
  for (const [key, value] of Object.entries(settings)) {
    const formattedValue = value.includes(" ") ? `"${value}"` : value;
    envContent += `${key}=${formattedValue}
`;
  }
  return envContent;
}
async function promptForSetting(setting) {
  const response = await (0, import_prompts4.default)({
    type: setting.sensitive ? "password" : "text",
    name: "value",
    message: `${setting.name}
${setting.description}`
  });
  return response.value;
}
async function getScopedEnvContents(extensionConfig, extensionId, scope) {
  const { name: extensionName } = extensionConfig;
  const keychain = new KeychainTokenStorage(getKeychainStorageName(extensionName, extensionId, scope));
  const envFilePath = getEnvFilePath(extensionName, scope);
  let customEnv = {};
  if (fsSync3.existsSync(envFilePath)) {
    const envFile = fsSync3.readFileSync(envFilePath, "utf-8");
    customEnv = dotenv.parse(envFile);
  }
  if (extensionConfig.settings) {
    for (const setting of extensionConfig.settings) {
      if (setting.sensitive) {
        const secret = await keychain.getSecret(setting.envVar);
        if (secret) {
          customEnv[setting.envVar] = secret;
        }
      }
    }
  }
  return customEnv;
}
async function getEnvContents(extensionConfig, extensionId) {
  if (!extensionConfig.settings || extensionConfig.settings.length === 0) {
    return Promise.resolve({});
  }
  const userSettings = await getScopedEnvContents(extensionConfig, extensionId, ExtensionSettingScope.USER);
  const workspaceSettings = await getScopedEnvContents(extensionConfig, extensionId, ExtensionSettingScope.WORKSPACE);
  return { ...userSettings, ...workspaceSettings };
}
async function updateSetting(extensionConfig, extensionId, settingKey, requestSetting, scope) {
  const { name: extensionName, settings } = extensionConfig;
  if (!settings || settings.length === 0) {
    debugLogger63.debug(`updateSetting: Extension "${extensionName}" has no settings`);
    return;
  }
  const settingToUpdate = settings.find((s5) => s5.name === settingKey || s5.envVar === settingKey);
  if (!settingToUpdate) {
    debugLogger63.debug(`updateSetting: Setting "${settingKey}" not found for extension "${extensionName}"`);
    return;
  }
  const newValue = await requestSetting(settingToUpdate);
  const keychain = new KeychainTokenStorage(getKeychainStorageName(extensionName, extensionId, scope));
  if (settingToUpdate.sensitive) {
    await keychain.setSecret(settingToUpdate.envVar, newValue);
    return;
  }
  const envFilePath = getEnvFilePath(extensionName, scope);
  let envContent = "";
  if (fsSync3.existsSync(envFilePath)) {
    envContent = await fs60.readFile(envFilePath, "utf-8");
  }
  const parsedEnv = dotenv.parse(envContent);
  parsedEnv[settingToUpdate.envVar] = newValue;
  const nonSensitiveSettings = {};
  const sensitiveEnvVars = new Set(settings.filter((s5) => s5.sensitive).map((s5) => s5.envVar));
  for (const [key, value] of Object.entries(parsedEnv)) {
    if (!sensitiveEnvVars.has(key)) {
      nonSensitiveSettings[key] = value;
    }
  }
  const newEnvContent = formatEnvContent(nonSensitiveSettings);
  await fs60.writeFile(envFilePath, newEnvContent);
}
function getSettingsChanges(settings, oldSettings) {
  const isSameSetting = /* @__PURE__ */ __name((a2, b2) => a2.envVar === b2.envVar && (a2.sensitive ?? false) === (b2.sensitive ?? false), "isSameSetting");
  const sensitiveOld = oldSettings.filter((s5) => s5.sensitive ?? false);
  const sensitiveNew = settings.filter((s5) => s5.sensitive ?? false);
  const envOld = oldSettings.filter((s5) => !(s5.sensitive ?? false));
  const envNew = settings.filter((s5) => !(s5.sensitive ?? false));
  return {
    promptForSensitive: sensitiveNew.filter((s5) => !sensitiveOld.some((old) => isSameSetting(s5, old))),
    removeSensitive: sensitiveOld.filter((s5) => !sensitiveNew.some((neu) => isSameSetting(s5, neu))),
    promptForEnv: envNew.filter((s5) => !envOld.some((old) => isSameSetting(s5, old))),
    removeEnv: envOld.filter((s5) => !envNew.some((neu) => isSameSetting(s5, neu)))
  };
}
async function clearSettings(envFilePath, keychain) {
  if (fsSync3.existsSync(envFilePath)) {
    await fs60.writeFile(envFilePath, "");
  }
  if (!await keychain.isAvailable()) {
    return;
  }
  const secrets = await keychain.listSecrets();
  for (const secret of secrets) {
    await keychain.deleteSecret(secret);
  }
  return;
}
var dotenv, import_prompts4, debugLogger63, ExtensionSettingScope, getKeychainStorageName, getEnvFilePath;
var init_extensionSettings = __esm({
  "packages/core/dist/src/extension/extensionSettings.js"() {
    "use strict";
    init_esbuild_shims();
    dotenv = __toESM(require_main(), 1);
    init_storage2();
    import_prompts4 = __toESM(require_prompts3(), 1);
    init_variables();
    init_keychain_token_storage();
    init_debugLogger();
    debugLogger63 = createDebugLogger("EXT_SETTINGS");
    (function(ExtensionSettingScope2) {
      ExtensionSettingScope2["USER"] = "user";
      ExtensionSettingScope2["WORKSPACE"] = "workspace";
    })(ExtensionSettingScope || (ExtensionSettingScope = {}));
    getKeychainStorageName = /* @__PURE__ */ __name((extensionName, extensionId, scope) => {
      const base = `Qwen Code Extensions ${extensionName} ${extensionId}`;
      if (scope === ExtensionSettingScope.WORKSPACE) {
        return `${base} ${process.cwd()}`;
      }
      return base;
    }, "getKeychainStorageName");
    getEnvFilePath = /* @__PURE__ */ __name((extensionName, scope) => {
      if (scope === ExtensionSettingScope.WORKSPACE) {
        return path61.join(process.cwd(), EXTENSION_SETTINGS_FILENAME);
      }
      return new ExtensionStorage(extensionName).getEnvFilePath();
    }, "getEnvFilePath");
    __name(maybePromptForSettings, "maybePromptForSettings");
    __name(formatEnvContent, "formatEnvContent");
    __name(promptForSetting, "promptForSetting");
    __name(getScopedEnvContents, "getScopedEnvContents");
    __name(getEnvContents, "getEnvContents");
    __name(updateSetting, "updateSetting");
    __name(getSettingsChanges, "getSettingsChanges");
    __name(clearSettings, "clearSettings");
  }
});

// packages/core/dist/src/extension/extensionManager.js
import * as fs61 from "node:fs";
import * as path62 from "node:path";
import * as os22 from "node:os";
import { createHash as createHash5 } from "node:crypto";
function ensureLeadingAndTrailingSlash2(dirPath) {
  let result = dirPath.replace(/\\/g, "/");
  if (result.charAt(0) !== "/") {
    result = "/" + result;
  }
  if (result.charAt(result.length - 1) !== "/") {
    result = result + "/";
  }
  return result;
}
function getTelemetryConfig(cwd7, telemetrySettings) {
  const config2 = new Config({
    telemetry: telemetrySettings,
    interactive: false,
    targetDir: cwd7,
    cwd: cwd7,
    model: "",
    debugMode: false
  });
  return config2;
}
function filterMcpConfig(original) {
  const { trust, ...rest } = original;
  return Object.freeze(rest);
}
function getContextFileNames(config2) {
  if (!config2.contextFileName || config2.contextFileName.length === 0) {
    return ["QWEN.md"];
  } else if (!Array.isArray(config2.contextFileName)) {
    return [config2.contextFileName];
  }
  return config2.contextFileName;
}
async function loadCommandsFromDir(dir) {
  const globOptions = {
    nodir: true,
    dot: true,
    follow: true
  };
  try {
    const mdFiles = await glob("**/*.md", {
      ...globOptions,
      cwd: dir
    });
    const commandNames = mdFiles.map((file) => {
      const relativePathWithExt = path62.relative(dir, path62.join(dir, file));
      const relativePath = relativePathWithExt.substring(0, relativePathWithExt.length - 3);
      const commandName = relativePath.split(path62.sep).map((segment) => segment.replaceAll(":", "_")).join(":");
      return commandName;
    });
    return commandNames;
  } catch (error2) {
    const isEnoent = error2.code === "ENOENT";
    const isAbortError3 = error2 instanceof Error && error2.name === "AbortError";
    if (!isEnoent && !isAbortError3) {
      debugLogger64.error(`Error loading commands from ${dir}:`, error2);
    }
    return [];
  }
}
async function convertGeminiOrClaudeExtension(extensionDir, pluginName) {
  let newExtensionDir = extensionDir;
  let originSource = "QwenCode";
  const configFilePath2 = path62.join(extensionDir, EXTENSIONS_CONFIG_FILENAME);
  if (fs61.existsSync(configFilePath2)) {
    newExtensionDir = extensionDir;
  } else if (isGeminiExtensionConfig(extensionDir)) {
    newExtensionDir = (await convertGeminiExtensionPackage(extensionDir)).convertedDir;
    originSource = "Gemini";
  } else if (pluginName) {
    newExtensionDir = (await convertClaudePluginPackage(extensionDir, pluginName)).convertedDir;
    originSource = "Claude";
  }
  return { extensionDir: newExtensionDir, originSource };
}
async function copyExtension(source2, destination) {
  await fs61.promises.cp(source2, destination, { recursive: true });
}
function getExtensionId(config2, installMetadata) {
  let idValue = config2.name;
  const githubUrlParts = installMetadata && (installMetadata.type === "git" || installMetadata.type === "github-release") ? parseGitHubRepoForReleases(installMetadata.source) : null;
  if (githubUrlParts) {
    idValue = `https://github.com/${githubUrlParts.owner}/${githubUrlParts.repo}`;
  } else {
    idValue = installMetadata?.source ?? config2.name;
  }
  return hashValue(idValue);
}
function hashValue(value) {
  return createHash5("sha256").update(value).digest("hex");
}
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), underscores (_), dots (.), and dashes (-) are allowed.`);
  }
}
var debugLogger64, SettingScope, ExtensionUpdateState, ExtensionManager;
var init_extensionManager = __esm({
  "packages/core/dist/src/extension/extensionManager.js"() {
    "use strict";
    init_esbuild_shims();
    init_src2();
    init_errors();
    init_variables();
    init_envVarResolver();
    init_github();
    init_override();
    init_gemini_converter();
    init_claude_converter();
    init_esm11();
    init_storage2();
    init_extensionSettings();
    init_loggers();
    init_types();
    init_skill_load();
    init_subagent_manager();
    init_debugLogger();
    debugLogger64 = createDebugLogger("EXTENSIONS");
    (function(SettingScope3) {
      SettingScope3["User"] = "User";
      SettingScope3["Workspace"] = "Workspace";
      SettingScope3["System"] = "System";
      SettingScope3["SystemDefaults"] = "SystemDefaults";
    })(SettingScope || (SettingScope = {}));
    (function(ExtensionUpdateState3) {
      ExtensionUpdateState3["CHECKING_FOR_UPDATES"] = "checking for updates";
      ExtensionUpdateState3["UPDATED_NEEDS_RESTART"] = "updated, needs restart";
      ExtensionUpdateState3["UPDATING"] = "updating";
      ExtensionUpdateState3["UPDATED"] = "updated";
      ExtensionUpdateState3["UPDATE_AVAILABLE"] = "update available";
      ExtensionUpdateState3["UP_TO_DATE"] = "up to date";
      ExtensionUpdateState3["ERROR"] = "error";
      ExtensionUpdateState3["NOT_UPDATABLE"] = "not updatable";
      ExtensionUpdateState3["UNKNOWN"] = "unknown";
    })(ExtensionUpdateState || (ExtensionUpdateState = {}));
    __name(ensureLeadingAndTrailingSlash2, "ensureLeadingAndTrailingSlash");
    __name(getTelemetryConfig, "getTelemetryConfig");
    __name(filterMcpConfig, "filterMcpConfig");
    __name(getContextFileNames, "getContextFileNames");
    __name(loadCommandsFromDir, "loadCommandsFromDir");
    __name(convertGeminiOrClaudeExtension, "convertGeminiOrClaudeExtension");
    ExtensionManager = class {
      static {
        __name(this, "ExtensionManager");
      }
      extensionCache = null;
      // Enablement configuration (directly implemented)
      configDir;
      configFilePath;
      enabledExtensionNamesOverride;
      workspaceDir;
      config;
      telemetrySettings;
      isWorkspaceTrusted;
      requestConsent;
      requestSetting;
      requestChoicePlugin;
      constructor(options2) {
        this.workspaceDir = options2.workspaceDir ?? process.cwd();
        this.enabledExtensionNamesOverride = options2.enabledExtensionOverrides?.map((name3) => name3.toLowerCase()) ?? [];
        this.configDir = ExtensionStorage.getUserExtensionsDir();
        this.configFilePath = path62.join(this.configDir, "extension-enablement.json");
        this.requestSetting = options2.requestSetting;
        this.requestChoicePlugin = options2.requestChoicePlugin || (() => Promise.resolve(""));
        this.requestConsent = options2.requestConsent || (() => Promise.resolve());
        this.config = options2.config;
        this.telemetrySettings = options2.telemetrySettings;
        this.isWorkspaceTrusted = options2.isWorkspaceTrusted;
      }
      setConfig(config2) {
        this.config = config2;
      }
      setRequestConsent(requestConsent) {
        this.requestConsent = requestConsent;
      }
      setRequestSetting(requestSetting) {
        this.requestSetting = requestSetting;
      }
      setRequestChoicePlugin(requestChoicePlugin) {
        this.requestChoicePlugin = requestChoicePlugin;
      }
      // ==========================================================================
      // Enablement functionality (directly implemented)
      // ==========================================================================
      /**
       * Validates that override extension names exist in the extensions list.
       */
      validateExtensionOverrides(extensions) {
        for (const name3 of this.enabledExtensionNamesOverride) {
          if (name3 === "none")
            continue;
          if (!extensions.some((ext2) => ext2.config.name.toLowerCase() === name3.toLowerCase())) {
            debugLogger64.error(`Extension not found: ${name3}`);
          }
        }
      }
      /**
       * Determines if an extension is enabled based on its name and the current path.
       */
      isEnabled(extensionName, currentPath) {
        const checkPath = currentPath ?? this.workspaceDir;
        if (this.enabledExtensionNamesOverride.length === 1 && this.enabledExtensionNamesOverride[0] === "none") {
          return false;
        }
        if (this.enabledExtensionNamesOverride.length > 0) {
          return this.enabledExtensionNamesOverride.includes(extensionName.toLowerCase());
        }
        const config2 = this.readEnablementConfig();
        const extensionConfig = config2[extensionName];
        let enabled = true;
        const allOverrides = extensionConfig?.overrides ?? [];
        for (const rule of allOverrides) {
          const override = Override.fromFileRule(rule);
          if (override.matchesPath(ensureLeadingAndTrailingSlash2(checkPath))) {
            enabled = !override.isDisable;
          }
        }
        return enabled;
      }
      /**
       * Enables an extension at the specified scope.
       */
      async enableExtension(name3, scope, cwd7) {
        const currentDir = cwd7 ?? this.workspaceDir;
        if (scope === SettingScope.System || scope === SettingScope.SystemDefaults) {
          throw new Error("System and SystemDefaults scopes are not supported.");
        }
        const extension = this.getLoadedExtensions().find((ext2) => ext2.name === name3);
        if (!extension) {
          throw new Error(`Extension with name ${name3} does not exist.`);
        }
        const scopePath = scope === SettingScope.Workspace ? currentDir : os22.homedir();
        this.enableByPath(name3, true, scopePath);
        const config2 = getTelemetryConfig(currentDir, this.telemetrySettings);
        logExtensionEnable(config2, new ExtensionEnableEvent(name3, scope));
        extension.isActive = true;
        await this.refreshTools();
      }
      /**
       * Disables an extension at the specified scope.
       */
      async disableExtension(name3, scope, cwd7) {
        const currentDir = cwd7 ?? this.workspaceDir;
        const config2 = getTelemetryConfig(currentDir, this.telemetrySettings);
        if (scope === SettingScope.System || scope === SettingScope.SystemDefaults) {
          throw new Error("System and SystemDefaults scopes are not supported.");
        }
        const extension = this.getLoadedExtensions().find((ext2) => ext2.name === name3);
        if (!extension) {
          throw new Error(`Extension with name ${name3} does not exist.`);
        }
        const scopePath = scope === SettingScope.Workspace ? currentDir : os22.homedir();
        this.disableByPath(name3, true, scopePath);
        logExtensionDisable(config2, new ExtensionDisableEvent(name3, scope));
        extension.isActive = false;
        await this.refreshTools();
      }
      /**
       * Removes enablement configuration for an extension.
       */
      removeEnablementConfig(extensionName) {
        const config2 = this.readEnablementConfig();
        if (config2[extensionName]) {
          delete config2[extensionName];
          this.writeEnablementConfig(config2);
        }
      }
      enableByPath(extensionName, includeSubdirs, scopePath) {
        const config2 = this.readEnablementConfig();
        if (!config2[extensionName]) {
          config2[extensionName] = { overrides: [] };
        }
        const override = Override.fromInput(scopePath, includeSubdirs);
        const overrides = config2[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());
        config2[extensionName].overrides = overrides;
        this.writeEnablementConfig(config2);
      }
      disableByPath(extensionName, includeSubdirs, scopePath) {
        this.enableByPath(extensionName, includeSubdirs, `!${scopePath}`);
      }
      readEnablementConfig() {
        try {
          const content = fs61.readFileSync(this.configFilePath, "utf-8");
          return JSON.parse(content);
        } catch (error2) {
          if (error2 instanceof Error && "code" in error2 && error2.code === "ENOENT") {
            return {};
          }
          debugLogger64.error("Error reading extension enablement config:", error2);
          return {};
        }
      }
      writeEnablementConfig(config2) {
        fs61.mkdirSync(this.configDir, { recursive: true });
        fs61.writeFileSync(this.configFilePath, JSON.stringify(config2, null, 2));
      }
      /**
       * Refreshes the extension cache from disk.
       */
      async refreshCache() {
        this.extensionCache = /* @__PURE__ */ new Map();
        const extensions = await this.loadExtensionsFromDir(os22.homedir());
        extensions.forEach((extension) => {
          this.extensionCache.set(extension.name, extension);
        });
      }
      getLoadedExtensions() {
        if (!this.extensionCache) {
          return [];
        }
        return [...this.extensionCache.values()];
      }
      // ==========================================================================
      // Extension loading methods
      // ==========================================================================
      /**
       * Loads an extension by name.
       */
      async loadExtensionByName(name3, workspaceDir) {
        const cwd7 = workspaceDir ?? this.workspaceDir;
        const userExtensionsDir = ExtensionStorage.getUserExtensionsDir();
        if (!fs61.existsSync(userExtensionsDir)) {
          return null;
        }
        for (const subdir of fs61.readdirSync(userExtensionsDir)) {
          const extensionDir = path62.join(userExtensionsDir, subdir);
          if (!fs61.statSync(extensionDir).isDirectory()) {
            continue;
          }
          const extension = await this.loadExtension({
            extensionDir,
            workspaceDir: cwd7
          });
          if (extension && extension.config.name.toLowerCase() === name3.toLowerCase()) {
            return extension;
          }
        }
        return null;
      }
      async loadExtensionsFromDir(dir) {
        const storage = new Storage(dir);
        const extensionsDir = storage.getExtensionsDir();
        let subdirs;
        try {
          subdirs = fs61.readdirSync(extensionsDir);
        } catch {
          return [];
        }
        const extensions = [];
        for (const subdir of subdirs) {
          const extensionDir = path62.join(extensionsDir, subdir);
          const extension = await this.loadExtension({
            extensionDir,
            workspaceDir: dir
          });
          if (extension != null) {
            extensions.push(extension);
          }
        }
        return extensions;
      }
      async loadExtension(context2) {
        const { extensionDir, workspaceDir } = context2;
        if (!fs61.statSync(extensionDir).isDirectory()) {
          return null;
        }
        const installMetadata = this.loadInstallMetadata(extensionDir);
        let effectiveExtensionPath = extensionDir;
        if (installMetadata?.type === "link") {
          effectiveExtensionPath = installMetadata.source;
        }
        try {
          let config2 = this.loadExtensionConfig({
            extensionDir: effectiveExtensionPath,
            workspaceDir
          });
          config2 = resolveEnvVarsInObject(config2);
          const extension = {
            id: getExtensionId(config2, installMetadata),
            name: config2.name,
            version: config2.version,
            path: effectiveExtensionPath,
            installMetadata,
            isActive: this.isEnabled(config2.name, this.workspaceDir),
            config: config2,
            settings: config2.settings,
            contextFiles: []
          };
          if (config2.mcpServers) {
            extension.mcpServers = Object.fromEntries(Object.entries(config2.mcpServers).map(([key, value]) => [
              key,
              filterMcpConfig(value)
            ]));
          }
          extension.commands = await loadCommandsFromDir(`${effectiveExtensionPath}/commands`);
          extension.contextFiles = getContextFileNames(config2).map((contextFileName) => path62.join(effectiveExtensionPath, contextFileName)).filter((contextFilePath) => fs61.existsSync(contextFilePath));
          extension.skills = await loadSkillsFromDir(`${effectiveExtensionPath}/skills`);
          extension.agents = await loadSubagentFromDir(`${effectiveExtensionPath}/agents`);
          return extension;
        } catch (e4) {
          debugLogger64.warn(`Warning: Skipping extension in ${effectiveExtensionPath}: ${getErrorMessage(e4)}`);
          return null;
        }
      }
      loadInstallMetadata(extensionDir) {
        const metadataFilePath = path62.join(extensionDir, INSTALL_METADATA_FILENAME);
        try {
          const configContent = fs61.readFileSync(metadataFilePath, "utf-8");
          const metadata = JSON.parse(configContent);
          return metadata;
        } catch (_e2) {
          return void 0;
        }
      }
      loadExtensionConfig(context2) {
        const { extensionDir, workspaceDir = this.workspaceDir } = context2;
        const configFilePath2 = path62.join(extensionDir, EXTENSIONS_CONFIG_FILENAME);
        if (!fs61.existsSync(configFilePath2)) {
          throw new Error(`Configuration file not found at ${configFilePath2}`);
        }
        try {
          const configContent = fs61.readFileSync(configFilePath2, "utf-8");
          const config2 = recursivelyHydrateStrings(JSON.parse(configContent), {
            extensionPath: extensionDir,
            CLAUDE_PLUGIN_ROOT: extensionDir,
            workspacePath: workspaceDir,
            "/": path62.sep,
            pathSeparator: path62.sep
          });
          if (!config2.name) {
            throw new Error(`Invalid configuration in ${configFilePath2}: missing "name"`);
          }
          validateName(config2.name);
          return config2;
        } catch (e4) {
          throw new Error(`Failed to load extension config from ${configFilePath2}: ${getErrorMessage(e4)}`);
        }
      }
      // ==========================================================================
      // Extension installation/uninstallation
      // ==========================================================================
      /**
       * Installs an extension.
       */
      async installExtension(installMetadata, requestConsent, requestSetting, cwd7, previousExtensionConfig) {
        const currentDir = cwd7 ?? this.workspaceDir;
        const telemetryConfig = getTelemetryConfig(currentDir, this.telemetrySettings);
        let extension;
        const isUpdate = !!previousExtensionConfig;
        let newExtensionConfig = null;
        let localSourcePath;
        try {
          if (!this.isWorkspaceTrusted) {
            throw new Error(`Could not install extension from untrusted folder at ${installMetadata.source}`);
          }
          const extensionsDir = ExtensionStorage.getUserExtensionsDir();
          await fs61.promises.mkdir(extensionsDir, { recursive: true });
          if (!path62.isAbsolute(installMetadata.source) && (installMetadata.type === "local" || installMetadata.type === "link")) {
            installMetadata.source = path62.resolve(currentDir, installMetadata.source);
          }
          let tempDir;
          if (installMetadata.originSource === "Claude" && installMetadata.marketplaceConfig && !installMetadata.pluginName) {
            const pluginName = await this.requestChoicePlugin(installMetadata.marketplaceConfig);
            installMetadata.pluginName = pluginName;
          }
          if (installMetadata.type === "git" || installMetadata.type === "github-release") {
            tempDir = await ExtensionStorage.createTmpDir();
            try {
              const result = await downloadFromGitHubRelease(installMetadata, tempDir);
              if (installMetadata.type === "git" || installMetadata.type === "github-release") {
                installMetadata.type = result.type;
                installMetadata.releaseTag = result.tagName;
              }
            } catch (_error) {
              await cloneFromGit(installMetadata, tempDir);
              if (installMetadata.type === "github-release") {
                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 {
            const { extensionDir, originSource } = await convertGeminiOrClaudeExtension(localSourcePath, installMetadata.pluginName);
            localSourcePath = extensionDir;
            installMetadata.originSource = originSource;
            newExtensionConfig = this.loadExtensionConfig({
              extensionDir: localSourcePath,
              workspaceDir: currentDir
            });
            if (isUpdate && installMetadata.autoUpdate) {
              const oldSettings = new Set(previousExtensionConfig.settings?.map((s5) => s5.name) || []);
              const newSettings = new Set(newExtensionConfig.settings?.map((s5) => s5.name) || []);
              const settingsAreEqual = oldSettings.size === newSettings.size && [...oldSettings].every((value) => newSettings.has(value));
              if (!settingsAreEqual && installMetadata.autoUpdate) {
                throw new Error(`Extension "${newExtensionConfig.name}" has settings changes and cannot be auto-updated. Please update manually.`);
              }
            }
            const newExtensionName = newExtensionConfig.name;
            const previous = this.getLoadedExtensions().find((installed) => installed.name === newExtensionName);
            if (isUpdate && !previous) {
              throw new Error(`Extension "${newExtensionName}" was not already installed, cannot update it.`);
            } else if (!isUpdate && previous) {
              throw new Error(`Extension "${newExtensionName}" is already installed. Please uninstall it first.`);
            }
            const commands = await loadCommandsFromDir(`${localSourcePath}/commands`);
            const previousCommands = previous?.commands ?? [];
            const skills = await loadSkillsFromDir(`${localSourcePath}/skills`);
            const previousSkills = previous?.skills ?? [];
            const subagents = await loadSubagentFromDir(`${localSourcePath}/agents`);
            const previousSubagents = previous?.agents ?? [];
            if (requestConsent) {
              await requestConsent({
                extensionConfig: newExtensionConfig,
                commands,
                skills,
                subagents,
                previousExtensionConfig,
                previousCommands,
                previousSkills,
                previousSubagents,
                originSource: installMetadata.originSource
              });
            } else {
              await this.requestConsent({
                extensionConfig: newExtensionConfig,
                commands,
                skills,
                subagents,
                previousExtensionConfig,
                previousCommands,
                previousSkills,
                previousSubagents,
                originSource: installMetadata.originSource
              });
            }
            const extensionStorage = new ExtensionStorage(newExtensionName);
            const destinationPath = extensionStorage.getExtensionDir();
            const extensionId = getExtensionId(newExtensionConfig, installMetadata);
            let previousSettings;
            if (isUpdate) {
              previousSettings = await getEnvContents(previousExtensionConfig, extensionId);
              await this.uninstallExtension(newExtensionName, isUpdate);
            }
            await fs61.promises.mkdir(destinationPath, { recursive: true });
            if (isUpdate) {
              await maybePromptForSettings(newExtensionConfig, extensionId, requestSetting || this.requestSetting || promptForSetting, previousExtensionConfig, previousSettings);
            } else {
              await maybePromptForSettings(newExtensionConfig, extensionId, requestSetting || this.requestSetting || promptForSetting);
            }
            if (installMetadata.type !== "link") {
              await copyExtension(localSourcePath, destinationPath);
            }
            const metadataString = JSON.stringify(installMetadata, null, 2);
            const metadataPath = path62.join(destinationPath, INSTALL_METADATA_FILENAME);
            await fs61.promises.writeFile(metadataPath, metadataString);
            extension = await this.loadExtension({ extensionDir: destinationPath });
            if (!extension) {
              throw new Error(`Extension not found`);
            }
            if (this.extensionCache) {
              this.extensionCache.set(extension.name, extension);
            }
            if (isUpdate) {
              logExtensionUpdateEvent(telemetryConfig, new ExtensionUpdateEvent(newExtensionConfig.name, getExtensionId(newExtensionConfig, installMetadata), newExtensionConfig.version, previousExtensionConfig.version, installMetadata.type, "success"));
              this.refreshTools();
            } else {
              logExtensionInstallEvent(telemetryConfig, new ExtensionInstallEvent(newExtensionConfig.name, newExtensionConfig.version, installMetadata.source, "success"));
              this.enableExtension(newExtensionConfig.name, SettingScope.User);
            }
          } finally {
            if (tempDir) {
              await fs61.promises.rm(tempDir, { recursive: true, force: true });
            }
            if (localSourcePath !== tempDir && installMetadata.type !== "link" && installMetadata.type !== "local") {
              await fs61.promises.rm(localSourcePath, {
                recursive: true,
                force: true
              });
            }
          }
          return extension;
        } catch (error2) {
          if (!newExtensionConfig && localSourcePath) {
            try {
              newExtensionConfig = this.loadExtensionConfig({
                extensionDir: localSourcePath,
                workspaceDir: currentDir
              });
            } catch {
            }
          }
          const config2 = newExtensionConfig ?? previousExtensionConfig;
          const extensionId = config2 ? getExtensionId(config2, installMetadata) : void 0;
          if (isUpdate) {
            logExtensionUpdateEvent(telemetryConfig, new ExtensionUpdateEvent(config2?.name ?? "", extensionId ?? "", newExtensionConfig?.version ?? "", previousExtensionConfig.version, installMetadata.type, "error"));
          } else {
            logExtensionInstallEvent(telemetryConfig, new ExtensionInstallEvent(newExtensionConfig?.name ?? "", newExtensionConfig?.version ?? "", installMetadata.source, "error"));
          }
          throw error2;
        }
      }
      /**
       * Uninstalls an extension.
       */
      async uninstallExtension(extensionIdentifier, isUpdate, cwd7) {
        const currentDir = cwd7 ?? this.workspaceDir;
        const telemetryConfig = getTelemetryConfig(currentDir, this.telemetrySettings);
        const installedExtensions = this.getLoadedExtensions();
        const extension = installedExtensions.find((installed) => installed.config.name.toLowerCase() === extensionIdentifier.toLowerCase() || installed.installMetadata?.source.toLowerCase() === extensionIdentifier.toLowerCase());
        if (!extension) {
          throw new Error(`Extension not found.`);
        }
        const storage = new ExtensionStorage(extension.installMetadata?.type === "link" ? extension.name : path62.basename(extension.path));
        await fs61.promises.rm(storage.getExtensionDir(), {
          recursive: true,
          force: true
        });
        if (this.extensionCache) {
          this.extensionCache.delete(extension.name);
        }
        if (isUpdate)
          return;
        this.removeEnablementConfig(extension.name);
        this.refreshTools();
        logExtensionUninstall(telemetryConfig, new ExtensionUninstallEvent(extension.name, "success"));
      }
      async performWorkspaceExtensionMigration(extensions, requestConsent, requestSetting) {
        const failedInstallNames = [];
        for (const extension of extensions) {
          try {
            const installMetadata = {
              source: extension.path,
              type: "local",
              originSource: extension.installMetadata?.originSource || "QwenCode"
            };
            await this.installExtension(installMetadata, requestConsent, requestSetting);
          } catch (_2) {
            failedInstallNames.push(extension.config.name);
          }
        }
        return failedInstallNames;
      }
      async checkForAllExtensionUpdates(callback) {
        const extensions = this.getLoadedExtensions();
        const promises8 = [];
        for (const extension of extensions) {
          if (!extension.installMetadata) {
            callback(extension.name, ExtensionUpdateState.NOT_UPDATABLE);
            continue;
          }
          callback(extension.name, ExtensionUpdateState.CHECKING_FOR_UPDATES);
          promises8.push(checkForExtensionUpdate(extension, this).then((state) => callback(extension.name, state)));
        }
        await Promise.all(promises8);
      }
      async updateExtension(extension, currentState, callback, enableExtensionReloading = true) {
        if (currentState === ExtensionUpdateState.UPDATING) {
          return void 0;
        }
        callback(extension.name, ExtensionUpdateState.UPDATING);
        const installMetadata = this.loadInstallMetadata(extension.path);
        if (!installMetadata?.type) {
          callback(extension.name, ExtensionUpdateState.ERROR);
          throw new Error(`Extension ${extension.name} cannot be updated, type is unknown.`);
        }
        if (installMetadata?.type === "link") {
          callback(extension.name, ExtensionUpdateState.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 {
          const previousExtensionConfig = this.loadExtensionConfig({
            extensionDir: extension.path
          });
          let updatedExtension;
          try {
            updatedExtension = await this.installExtension(installMetadata, void 0, void 0, void 0, previousExtensionConfig);
          } catch (e4) {
            callback(extension.name, ExtensionUpdateState.ERROR);
            throw new Error(`Updated extension not found after installation, got error:
${e4}`);
          }
          const updatedVersion = updatedExtension.version;
          callback(extension.name, enableExtensionReloading ? ExtensionUpdateState.UPDATED : ExtensionUpdateState.UPDATED_NEEDS_RESTART);
          return {
            name: extension.name,
            originalVersion,
            updatedVersion
          };
        } catch (e4) {
          debugLogger64.error(`Error updating extension, rolling back. ${getErrorMessage(e4)}`);
          callback(extension.name, ExtensionUpdateState.ERROR);
          await copyExtension(tempDir, extension.path);
          throw e4;
        } finally {
          await fs61.promises.rm(tempDir, { recursive: true, force: true });
        }
      }
      async updateAllUpdatableExtensions(extensionsState, callback, enableExtensionReloading = true) {
        const extensions = this.getLoadedExtensions();
        return (await Promise.all(extensions.filter((extension) => extensionsState.get(extension.name)?.status === ExtensionUpdateState.UPDATE_AVAILABLE).map((extension) => this.updateExtension(extension, extensionsState.get(extension.name).status, callback, enableExtensionReloading)))).filter((updateInfo) => !!updateInfo);
      }
      async refreshMemory() {
        if (!this.config)
          return;
        this.config.getToolRegistry().restartMcpServers();
        this.config.getSkillManager()?.refreshCache();
        this.config.getSubagentManager().refreshCache();
        this.config.refreshHierarchicalMemory();
      }
      async refreshTools() {
        if (!this.config)
          return;
        this.refreshMemory();
      }
    };
    __name(copyExtension, "copyExtension");
    __name(getExtensionId, "getExtensionId");
    __name(hashValue, "hashValue");
    __name(validateName, "validateName");
  }
});

// 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((v2) => !!process.env[v2]);
    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 fs62 from "node:fs";
import * as path63 from "node:path";
import * as process13 from "node:process";
function isPathWithinRoot(pathToCheck, rootDirectory) {
  const relative11 = path63.relative(rootDirectory, pathToCheck);
  return !relative11.startsWith(`..${path63.sep}`) && relative11 !== ".." && !path63.isAbsolute(relative11);
}
var debugLogger65, WorkspaceContext;
var init_workspaceContext = __esm({
  "packages/core/dist/src/utils/workspaceContext.js"() {
    "use strict";
    init_esbuild_shims();
    init_errors();
    init_debugLogger();
    debugLogger65 = createDebugLogger("WORKSPACE");
    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 (e4) {
            debugLogger65.error("Error in WorkspaceContext listener:", e4);
          }
        }
      }
      /**
       * 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 = process13.cwd()) {
        try {
          const resolved = this.resolveAndValidateDir(directory, basePath);
          if (this.directories.has(resolved)) {
            return;
          }
          this.directories.add(resolved);
          this.notifyDirectoriesChanged();
        } catch (err) {
          debugLogger65.warn(`Skipping unreadable directory: ${directory} (${err instanceof Error ? err.message : String(err)})`);
        }
      }
      resolveAndValidateDir(directory, basePath = process13.cwd()) {
        const absolutePath = path63.isAbsolute(directory) ? directory : path63.resolve(basePath, directory);
        if (!fs62.existsSync(absolutePath)) {
          throw new Error(`Directory does not exist: ${absolutePath}`);
        }
        const stats = fs62.statSync(absolutePath);
        if (!stats.isDirectory()) {
          throw new Error(`Path is not a directory: ${absolutePath}`);
        }
        return fs62.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((d2) => this.directories.has(d2))) {
          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 (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 fs62.realpathSync(pathToCheck);
        } catch (e4) {
          if (isNodeError(e4) && e4.code === "ENOENT" && e4.path && // realpathSync does not set e.path correctly for symlinks to
          // non-existent files.
          !this.isFileSymlink(e4.path)) {
            return e4.path;
          }
          throw e4;
        }
      }
      /**
       * Checks if a file path is a symbolic link that points to a file.
       */
      isFileSymlink(filePath) {
        try {
          return !fs62.readlinkSync(filePath).endsWith("/");
        } catch (_error) {
          return false;
        }
      }
    };
    __name(isPathWithinRoot, "isPathWithinRoot");
  }
});

// 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 i3 = 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 (; i3 < cells.length; i3++) {
    cells[i3] = cells[i3].trim().replace(other.slashPipe, "|");
  }
  return cells;
}
function rtrim(str2, c4, invert) {
  const l3 = str2.length;
  if (l3 === 0) {
    return "";
  }
  let suffLen = 0;
  while (suffLen < l3) {
    const currChar = str2.charAt(l3 - suffLen - 1);
    if (currChar === c4 && !invert) {
      suffLen++;
    } else if (currChar !== c4 && invert) {
      suffLen++;
    } else {
      break;
    }
  }
  return str2.slice(0, l3 - suffLen);
}
function findClosingBracket(str2, b2) {
  if (str2.indexOf(b2[1]) === -1) {
    return -1;
  }
  let level = 0;
  for (let i3 = 0; i3 < str2.length; i3++) {
    if (str2[i3] === "\\") {
      i3++;
    } else if (str2[i3] === b2[0]) {
      level++;
    } else if (str2[i3] === b2[1]) {
      level--;
      if (level < 0) {
        return i3;
      }
    }
  }
  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, hr2, heading, bullet, lheadingCore, lheading, lheadingGfm, _paragraph, blockText, _blockLabel, def, list2, _tag, _comment, html, paragraph, blockquote, blockNormal, gfmTable, blockGfm, blockPedantic, escape5, inlineCode, br2, inlineText, _punctuation, _punctuationOrSpace, _notPunctuationOrSpace, punctuation, _punctuationGfmStrongEm, _punctuationOrSpaceGfmStrongEm, _notPunctuationOrSpaceGfmStrongEm, blockSkip, emStrongLDelimCore, emStrongLDelim, emStrongLDelimGfm, emStrongRDelimAstCore, emStrongRDelimAst, emStrongRDelimAstGfm, emStrongRDelimUnd, anyPunctuation, autolink, _inlineComment, tag, _inlineLabel, link, 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|$)|$)/;
    hr2 = /^ {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();
    list2 = 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", hr2).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: hr2,
      html,
      lheading,
      list: list2,
      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", hr2).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", hr2).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", hr2).replace("heading", " *#{1,6} *[^\n]").replace("lheading", lheading).replace("|table", "").replace("blockquote", " {0,3}>").replace("|fences", "").replace("|list", "").replace("|html", "").replace("|tag", "").getRegex()
    };
    escape5 = /^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/;
    inlineCode = /^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/;
    br2 = /^( {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 = /(?:\[(?:\\.|[^\[\]\\])*\]|\\.|`[^`]*`|[^\[\]\\`])*?/;
    link = 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: br2,
      code: inlineCode,
      del: noopTest,
      emStrongLDelim,
      emStrongRDelimAst,
      emStrongRDelimUnd,
      escape: escape5,
      link,
      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(br2).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 i3;
            for (i3 = 0; i3 < lines.length; i3++) {
              if (this.rules.other.blockquoteStart.test(lines[i3])) {
                currentLines.push(lines[i3]);
                inBlockquote = true;
              } else if (!inBlockquote) {
                currentLines.push(lines[i3]);
              } else {
                break;
              }
            }
            lines = lines.slice(i3);
            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, (t5) => " ".repeat(3 * t5.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 i3 = 0; i3 < list22.items.length; i3++) {
            this.lexer.state.top = false;
            list22.items[i3].tokens = this.lexer.blockTokens(list22.items[i3].text, []);
            if (!list22.loose) {
              const spacers = list22.items[i3].tokens.filter((t5) => t5.type === "space");
              const hasMultipleLineBreaks = spacers.length > 0 && spacers.some((t5) => this.rules.other.anyLine.test(t5.raw));
              list22.loose = hasMultipleLineBreaks;
            }
          }
          if (list22.loose) {
            for (let i3 = 0; i3 < list22.items.length; i3++) {
              list22.items[i3].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 i3 = 0; i3 < headers.length; i3++) {
          item.header.push({
            text: headers[i3],
            tokens: this.lexer.inline(headers[i3]),
            header: true,
            align: item.align[i3]
          });
        }
        for (const row of rows) {
          item.rows.push(splitCells(row, item.header.length).map((cell, i3) => {
            return {
              text: cell,
              tokens: this.lexer.inline(cell),
              header: false,
              align: item.align[i3]
            };
          }));
        }
        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 i3 = 0; i3 < this.inlineQueue.length; i3++) {
          const next = this.inlineQueue[i3];
          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 j2 = 0; j2 < token2.items.length; j2++) {
          const item = token2.items[j2];
          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 j2 = 0; j2 < token2.header.length; j2++) {
          cell += this.tablecell(token2.header[j2]);
        }
        header += this.tablerow({ text: cell });
        let body = "";
        for (let j2 = 0; j2 < token2.rows.length; j2++) {
          const row = token2.rows[j2];
          cell = "";
          for (let k2 = 0; k2 < row.length; k2++) {
            cell += this.tablecell(row[k2]);
          }
          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 i3 = 0; i3 < tokens.length; i3++) {
          const anyToken = tokens[i3];
          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 (i3 + 1 < tokens.length && tokens[i3 + 1].type === "text") {
                textToken = tokens[++i3];
                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 i3 = 0; i3 < tokens.length; i3++) {
          const anyToken = tokens[i3];
          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 (e4) {
            return throwError(e4);
          }
        }, "parse2");
        return parse22;
      }
      onError(silent, async) {
        return (e4) => {
          e4.message += "\nPlease report this to https://github.com/markedjs/marked.";
          if (silent) {
            const msg = "<p>An error occurred:</p><pre>" + escape22(e4.message + "", true) + "</pre>";
            if (async) {
              return Promise.resolve(msg);
            }
            return msg;
          }
          if (async) {
            return Promise.reject(e4);
          }
          throw e4;
        };
      }
    };
    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 fs63 from "node:fs/promises";
import * as path64 from "node:path";
async function findProjectRoot(startDir) {
  let currentDir = path64.resolve(startDir);
  while (true) {
    const gitPath = path64.join(currentDir, ".git");
    try {
      const stats = await fs63.lstat(gitPath);
      if (stats.isDirectory()) {
        return currentDir;
      }
    } catch {
    }
    const parentDir = path64.dirname(currentDir);
    if (parentDir === currentDir) {
      break;
    }
    currentDir = parentDir;
  }
  return path64.resolve(startDir);
}
function hasMessage(err) {
  return typeof err === "object" && err !== null && "message" in err && typeof err.message === "string";
}
function findImports(content) {
  const imports = [];
  let i3 = 0;
  const len = content.length;
  while (i3 < len) {
    i3 = content.indexOf("@", i3);
    if (i3 === -1)
      break;
    if (i3 > 0 && !isWhitespace3(content[i3 - 1])) {
      i3++;
      continue;
    }
    let j2 = i3 + 1;
    while (j2 < len && !isWhitespace3(content[j2]) && content[j2] !== "\n" && content[j2] !== "\r") {
      j2++;
    }
    const importPath = content.slice(i3 + 1, j2);
    if (importPath.length > 0 && (importPath[0] === "." || importPath[0] === "/" || isLetter(importPath[0]))) {
      imports.push({
        start: i3,
        _end: j2,
        path: importPath
      });
    }
    i3 = j2 + 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 isFileNotFoundError(err) {
  return typeof err === "object" && err !== null && "code" in err && err.code === "ENOENT";
}
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) {
          logger.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, importState = {
  processedFiles: /* @__PURE__ */ new Set(),
  maxDepth: 5,
  currentDepth: 0
}, projectRoot, importFormat = "tree") {
  if (!projectRoot) {
    projectRoot = await findProjectRoot(basePath);
  }
  if (importState.currentDepth >= importState.maxDepth) {
    logger.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 = path64.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 i3 = imports2.length - 1; i3 >= 0; i3--) {
        const { start, path: importPath } = imports2[i3];
        if (codeRegions2.some(([regionStart, regionEnd]) => start >= regionStart && start < regionEnd)) {
          continue;
        }
        if (!validateImportPath(importPath, fileBasePath, [projectRoot || ""])) {
          continue;
        }
        const fullPath = path64.resolve(fileBasePath, importPath);
        const normalizedFullPath = path64.normalize(fullPath);
        if (processedFiles.has(normalizedFullPath))
          continue;
        try {
          await fs63.access(fullPath);
          const importedContent = await fs63.readFile(fullPath, "utf-8");
          await processFlat(importedContent, path64.dirname(fullPath), normalizedFullPath, depth + 1);
        } catch (error2) {
          if (!isFileNotFoundError(error2)) {
            logger.warn(`Failed to import ${fullPath}: ${hasMessage(error2) ? error2.message : "Unknown error"}`);
          }
        }
      }
    }
    __name(processFlat, "processFlat");
    const rootPath = path64.normalize(importState.currentFile || path64.resolve(basePath));
    await processFlat(content, basePath, rootPath, 0);
    const flatContent = flatFiles.map((f5) => `--- File: ${f5.path} ---
${f5.content.trim()}
--- End of File: ${f5.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(([s5, e4]) => start >= s5 && start < e4)) {
      result += `@${importPath}`;
      continue;
    }
    if (!validateImportPath(importPath, basePath, [projectRoot || ""])) {
      result += `<!-- Import failed: ${importPath} - Path traversal attempt -->`;
      continue;
    }
    const fullPath = path64.resolve(basePath, importPath);
    if (importState.processedFiles.has(fullPath)) {
      result += `<!-- File already processed: ${importPath} -->`;
      continue;
    }
    try {
      await fs63.access(fullPath);
      const fileContent = await fs63.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, path64.dirname(fullPath), newImportState, projectRoot, importFormat);
      result += `<!-- Imported from: ${importPath} -->
${imported.content}
<!-- End of import from: ${importPath} -->`;
      imports.push(imported.importTree);
    } catch (err) {
      if (isFileNotFoundError(err)) {
        result += `@${importPath}`;
        continue;
      }
      let message = "Unknown error";
      if (hasMessage(err)) {
        message = err.message;
      } else if (typeof err === "string") {
        message = err;
      }
      logger.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 = path64.resolve(basePath, importPath);
  return allowedDirectories.some((allowedDir) => isSubpath(allowedDir, resolvedPath));
}
var logger;
var init_memoryImportProcessor = __esm({
  "packages/core/dist/src/utils/memoryImportProcessor.js"() {
    "use strict";
    init_esbuild_shims();
    init_paths();
    init_marked_esm();
    init_debugLogger();
    logger = createDebugLogger("IMPORT_PROCESSOR");
    __name(findProjectRoot, "findProjectRoot");
    __name(hasMessage, "hasMessage");
    __name(findImports, "findImports");
    __name(isWhitespace3, "isWhitespace");
    __name(isLetter, "isLetter");
    __name(isFileNotFoundError, "isFileNotFoundError");
    __name(findCodeRegions, "findCodeRegions");
    __name(processImports, "processImports");
    __name(validateImportPath, "validateImportPath");
  }
});

// packages/core/dist/src/utils/memoryDiscovery.js
import * as fs64 from "node:fs/promises";
import * as fsSync4 from "node:fs";
import * as path65 from "node:path";
import { homedir as homedir12 } from "node:os";
async function findProjectRoot2(startDir) {
  let currentDir = path65.resolve(startDir);
  while (true) {
    const gitPath = path65.join(currentDir, ".git");
    try {
      const stats = await fs64.lstat(gitPath);
      if (stats.isDirectory()) {
        return currentDir;
      }
    } catch (error2) {
      const isENOENT = typeof error2 === "object" && error2 !== null && "code" in error2 && error2.code === "ENOENT";
      const isTestEnv = process.env["NODE_ENV"] === "test" || process.env["VITEST"];
      if (!isENOENT && !isTestEnv) {
        if (typeof error2 === "object" && error2 !== null && "code" in error2) {
          const fsError = error2;
          logger2.warn(`Error checking for .git directory at ${gitPath}: ${fsError.message}`);
        } else {
          logger2.warn(`Non-standard error checking for .git directory at ${gitPath}: ${String(error2)}`);
        }
      }
    }
    const parentDir = path65.dirname(currentDir);
    if (parentDir === currentDir) {
      return null;
    }
    currentDir = parentDir;
  }
}
async function getGeminiMdFilePathsInternal(currentWorkingDirectory, includeDirectoriesToReadGemini, userHomePath, fileService, extensionContextFilePaths = [], folderTrust) {
  const dirs = /* @__PURE__ */ new Set([
    ...includeDirectoriesToReadGemini,
    currentWorkingDirectory
  ]);
  const CONCURRENT_LIMIT = 10;
  const dirsArray = Array.from(dirs);
  const pathsArrays = [];
  for (let i3 = 0; i3 < dirsArray.length; i3 += CONCURRENT_LIMIT) {
    const batch = dirsArray.slice(i3, i3 + CONCURRENT_LIMIT);
    const batchPromises = batch.map((dir) => getGeminiMdFilePathsInternalForEachDir(dir, userHomePath, fileService, extensionContextFilePaths, folderTrust));
    const batchResults = await Promise.allSettled(batchPromises);
    for (const result of batchResults) {
      if (result.status === "fulfilled") {
        pathsArrays.push(result.value);
      } else {
        const error2 = result.reason;
        const message = error2 instanceof Error ? error2.message : String(error2);
        logger2.error(`Error discovering files in directory: ${message}`);
      }
    }
  }
  const paths = pathsArrays.flat();
  return Array.from(new Set(paths));
}
async function getGeminiMdFilePathsInternalForEachDir(dir, userHomePath, fileService, extensionContextFilePaths = [], folderTrust) {
  const allPaths = /* @__PURE__ */ new Set();
  const geminiMdFilenames = getAllGeminiMdFilenames();
  for (const geminiMdFilename of geminiMdFilenames) {
    const resolvedHome = path65.resolve(userHomePath);
    const globalMemoryPath = path65.join(resolvedHome, QWEN_DIR, geminiMdFilename);
    try {
      await fs64.access(globalMemoryPath, fsSync4.constants.R_OK);
      allPaths.add(globalMemoryPath);
      logger2.debug(`Found readable global ${geminiMdFilename}: ${globalMemoryPath}`);
    } catch {
    }
    const resolvedDir = dir ? path65.resolve(dir) : resolvedHome;
    const isHomeDirectory = resolvedDir === resolvedHome;
    if (isHomeDirectory) {
      const homeContextPath = path65.join(resolvedHome, geminiMdFilename);
      try {
        await fs64.access(homeContextPath, fsSync4.constants.R_OK);
        if (homeContextPath !== globalMemoryPath) {
          allPaths.add(homeContextPath);
          logger2.debug(`Found readable home ${geminiMdFilename}: ${homeContextPath}`);
        }
      } catch {
      }
    } else if (dir && folderTrust) {
      const resolvedCwd = path65.resolve(dir);
      logger2.debug(`Searching for ${geminiMdFilename} starting from CWD: ${resolvedCwd}`);
      const projectRoot = await findProjectRoot2(resolvedCwd);
      logger2.debug(`Determined project root: ${projectRoot ?? "None"}`);
      const upwardPaths = [];
      let currentDir = resolvedCwd;
      const ultimateStopDir = projectRoot ? path65.dirname(projectRoot) : path65.dirname(resolvedHome);
      while (currentDir && currentDir !== path65.dirname(currentDir)) {
        if (currentDir === path65.join(resolvedHome, QWEN_DIR)) {
          break;
        }
        const potentialPath = path65.join(currentDir, geminiMdFilename);
        try {
          await fs64.access(potentialPath, fsSync4.constants.R_OK);
          if (potentialPath !== globalMemoryPath) {
            upwardPaths.unshift(potentialPath);
          }
        } catch {
        }
        if (currentDir === ultimateStopDir) {
          break;
        }
        currentDir = path65.dirname(currentDir);
      }
      upwardPaths.forEach((p2) => allPaths.add(p2));
    }
  }
  for (const extensionPath of extensionContextFilePaths) {
    allPaths.add(extensionPath);
  }
  const finalPaths = Array.from(allPaths);
  logger2.debug(`Final ordered ${getAllGeminiMdFilenames()} paths to read: ${JSON.stringify(finalPaths)}`);
  return finalPaths;
}
async function readGeminiMdFiles(filePaths, importFormat = "tree") {
  const CONCURRENT_LIMIT = 20;
  const results = [];
  for (let i3 = 0; i3 < filePaths.length; i3 += CONCURRENT_LIMIT) {
    const batch = filePaths.slice(i3, i3 + CONCURRENT_LIMIT);
    const batchPromises = batch.map(async (filePath) => {
      try {
        const content = await fs64.readFile(filePath, "utf-8");
        const processedResult = await processImports(content, path65.dirname(filePath), void 0, void 0, importFormat);
        logger2.debug(`Successfully read and processed imports: ${filePath} (Length: ${processedResult.content.length})`);
        return { filePath, content: processedResult.content };
      } catch (error2) {
        const isTestEnv = process.env["NODE_ENV"] === "test" || process.env["VITEST"];
        if (!isTestEnv) {
          const message = error2 instanceof Error ? error2.message : String(error2);
          logger2.warn(`Warning: Could not read ${getAllGeminiMdFilenames()} file at ${filePath}. Error: ${message}`);
        }
        logger2.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 error2 = result.reason;
        const message = error2 instanceof Error ? error2.message : String(error2);
        logger2.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 = path65.isAbsolute(item.filePath) ? path65.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, fileService, extensionContextFilePaths = [], folderTrust, importFormat = "tree") {
  logger2.debug(`Loading server hierarchical memory for CWD: ${currentWorkingDirectory} (importFormat: ${importFormat})`);
  const userHomePath = homedir12();
  const filePaths = await getGeminiMdFilePathsInternal(currentWorkingDirectory, includeDirectoriesToReadGemini, userHomePath, fileService, extensionContextFilePaths, folderTrust);
  if (filePaths.length === 0) {
    logger2.debug("No QWEN.md files found in hierarchy.");
    return { memoryContent: "", fileCount: 0 };
  }
  const contentsWithPaths = await readGeminiMdFiles(filePaths, importFormat);
  const combinedInstructions = concatenateInstructions(contentsWithPaths, currentWorkingDirectory);
  const memoryFilenames = new Set(getAllGeminiMdFilenames());
  const fileCount = contentsWithPaths.filter((item) => memoryFilenames.has(path65.basename(item.filePath))).length;
  return {
    memoryContent: combinedInstructions,
    fileCount
    // Only count the context files
  };
}
var logger2;
var init_memoryDiscovery = __esm({
  "packages/core/dist/src/utils/memoryDiscovery.js"() {
    "use strict";
    init_esbuild_shims();
    init_memoryTool();
    init_memoryImportProcessor();
    init_paths();
    init_debugLogger();
    logger2 = createDebugLogger("MEMORY_DISCOVERY");
    __name(findProjectRoot2, "findProjectRoot");
    __name(getGeminiMdFilePathsInternal, "getGeminiMdFilePathsInternal");
    __name(getGeminiMdFilePathsInternalForEachDir, "getGeminiMdFilePathsInternalForEachDir");
    __name(readGeminiMdFiles, "readGeminiMdFiles");
    __name(concatenateInstructions, "concatenateInstructions");
    __name(loadServerHierarchicalMemory, "loadServerHierarchicalMemory");
  }
});

// packages/core/dist/src/utils/configResolver.js
function resolveField(layers, defaultValue, defaultSource2 = { kind: "default" }) {
  for (const layer2 of layers) {
    if (isValuePresent(layer2.value)) {
      return { value: layer2.value, source: layer2.source };
    }
  }
  return { value: defaultValue, source: defaultSource2 };
}
function resolveOptionalField(layers) {
  for (const layer2 of layers) {
    if (isValuePresent(layer2.value)) {
      return { value: layer2.value, source: layer2.source };
    }
  }
  return void 0;
}
function isValuePresent(value) {
  if (value === void 0 || value === null) {
    return false;
  }
  if (typeof value === "string" && value.trim() === "") {
    return false;
  }
  return true;
}
function cliSource(detail) {
  return { kind: "cli", detail };
}
function envSource(envKey) {
  return { kind: "env", envKey };
}
function settingsSource(settingsPath) {
  return { kind: "settings", settingsPath };
}
function modelProvidersSource(authType, modelId, detail) {
  return { kind: "modelProviders", authType, modelId, detail };
}
function defaultSource(detail) {
  return { kind: "default", detail };
}
function computedSource(detail) {
  return { kind: "computed", detail };
}
function envLayer(env7, key, transform2) {
  const rawValue = env7[key];
  const value = rawValue !== void 0 ? transform2 ? transform2(rawValue) : rawValue : void 0;
  return {
    value,
    source: envSource(key)
  };
}
function layer(value, source2) {
  return { value, source: source2 };
}
var init_configResolver = __esm({
  "packages/core/dist/src/utils/configResolver.js"() {
    "use strict";
    init_esbuild_shims();
    __name(resolveField, "resolveField");
    __name(resolveOptionalField, "resolveOptionalField");
    __name(isValuePresent, "isValuePresent");
    __name(cliSource, "cliSource");
    __name(envSource, "envSource");
    __name(settingsSource, "settingsSource");
    __name(modelProvidersSource, "modelProvidersSource");
    __name(defaultSource, "defaultSource");
    __name(computedSource, "computedSource");
    __name(envLayer, "envLayer");
    __name(layer, "layer");
  }
});

// packages/core/dist/src/models/modelConfigResolver.js
function resolveModelConfig(input) {
  const { authType, cli, settings, env: env7, modelProvider, proxy } = input;
  const warnings = [];
  const sources = {};
  if (authType === AuthType2.QWEN_OAUTH) {
    return resolveQwenOAuthConfig(input, warnings);
  }
  const envMapping = authType ? AUTH_ENV_MAPPINGS[authType] : { model: [], apiKey: [], baseUrl: [] };
  const modelLayers = [];
  if (authType && modelProvider) {
    modelLayers.push(layer(modelProvider.id, modelProvidersSource(authType, modelProvider.id, "model.id")));
  }
  if (cli?.model) {
    modelLayers.push(layer(cli.model, cliSource("--model")));
  }
  for (const envKey of envMapping.model) {
    modelLayers.push(envLayer(env7, envKey));
  }
  if (settings?.model) {
    modelLayers.push(layer(settings.model, settingsSource("model.name")));
  }
  const defaultModel = authType ? DEFAULT_MODELS[authType] : "";
  const modelResult = resolveField(modelLayers, defaultModel, defaultSource(defaultModel));
  sources["model"] = modelResult.source;
  const apiKeyLayers = [];
  if (authType && modelProvider?.envKey) {
    const apiKeyFromEnv = env7[modelProvider.envKey];
    if (apiKeyFromEnv) {
      apiKeyLayers.push(layer(apiKeyFromEnv, {
        kind: "env",
        envKey: modelProvider.envKey,
        via: modelProvidersSource(authType, modelProvider.id, "envKey")
      }));
    }
  }
  if (cli?.apiKey) {
    apiKeyLayers.push(layer(cli.apiKey, cliSource("--openaiApiKey")));
  }
  for (const envKey of envMapping.apiKey) {
    apiKeyLayers.push(envLayer(env7, envKey));
  }
  if (settings?.apiKey) {
    apiKeyLayers.push(layer(settings.apiKey, settingsSource("security.auth.apiKey")));
  }
  const apiKeyResult = resolveOptionalField(apiKeyLayers);
  if (apiKeyResult) {
    sources["apiKey"] = apiKeyResult.source;
  }
  const baseUrlLayers = [];
  if (authType && modelProvider?.baseUrl) {
    baseUrlLayers.push(layer(modelProvider.baseUrl, modelProvidersSource(authType, modelProvider.id, "baseUrl")));
  }
  if (cli?.baseUrl) {
    baseUrlLayers.push(layer(cli.baseUrl, cliSource("--openaiBaseUrl")));
  }
  for (const envKey of envMapping.baseUrl) {
    baseUrlLayers.push(envLayer(env7, envKey));
  }
  if (settings?.baseUrl) {
    baseUrlLayers.push(layer(settings.baseUrl, settingsSource("security.auth.baseUrl")));
  }
  const baseUrlResult = resolveOptionalField(baseUrlLayers);
  if (baseUrlResult) {
    sources["baseUrl"] = baseUrlResult.source;
  }
  let apiKeyEnvKey;
  if (authType && modelProvider?.envKey) {
    apiKeyEnvKey = modelProvider.envKey;
    sources["apiKeyEnvKey"] = modelProvidersSource(authType, modelProvider.id, "envKey");
  }
  const generationConfig = resolveGenerationConfig(settings?.generationConfig, modelProvider?.generationConfig, authType, modelProvider?.id, sources);
  const config2 = {
    authType,
    model: modelResult.value || "",
    apiKey: apiKeyResult?.value,
    apiKeyEnvKey,
    baseUrl: baseUrlResult?.value,
    proxy,
    ...generationConfig
  };
  if (proxy) {
    sources["proxy"] = computedSource("Config.getProxy()");
  }
  sources["authType"] = computedSource("provided by caller");
  return { config: config2, sources, warnings };
}
function resolveQwenOAuthConfig(input, warnings) {
  const { cli, settings, proxy, modelProvider } = input;
  const sources = {};
  const allowedModels = new Set(QWEN_OAUTH_ALLOWED_MODELS);
  const requestedModel = cli?.model || settings?.model;
  let resolvedModel;
  let modelSource;
  if (requestedModel && allowedModels.has(requestedModel)) {
    resolvedModel = requestedModel;
    modelSource = cli?.model ? cliSource("--model") : settingsSource("model.name");
  } else {
    if (requestedModel) {
      const isVisionModel = requestedModel.includes("vl") || requestedModel.includes("vision");
      const extraMessage = isVisionModel ? ` Note: vision-model has been removed since coder-model now supports vision capabilities.` : "";
      warnings.push(`Warning: Unsupported Qwen OAuth model '${requestedModel}', falling back to '${DEFAULT_QWEN_MODEL}'.${extraMessage}`);
    }
    resolvedModel = DEFAULT_QWEN_MODEL;
    modelSource = defaultSource(`fallback to '${DEFAULT_QWEN_MODEL}'`);
  }
  sources["model"] = modelSource;
  sources["apiKey"] = computedSource("Qwen OAuth dynamic token");
  sources["authType"] = computedSource("provided by caller");
  if (proxy) {
    sources["proxy"] = computedSource("Config.getProxy()");
  }
  const generationConfig = resolveGenerationConfig(settings?.generationConfig, modelProvider?.generationConfig, AuthType2.QWEN_OAUTH, resolvedModel, sources);
  const config2 = {
    authType: AuthType2.QWEN_OAUTH,
    model: resolvedModel,
    apiKey: "QWEN_OAUTH_DYNAMIC_TOKEN",
    proxy,
    ...generationConfig
  };
  return { config: config2, sources, warnings };
}
function resolveGenerationConfig(settingsConfig, modelProviderConfig, authType, modelId, sources) {
  const result = {};
  for (const field of MODEL_GENERATION_CONFIG_FIELDS) {
    if (authType && modelProviderConfig && field in modelProviderConfig) {
      result[field] = modelProviderConfig[field];
      sources[field] = modelProvidersSource(authType, modelId || "", `generationConfig.${field}`);
    } else if (settingsConfig && field in settingsConfig) {
      result[field] = settingsConfig[field];
      sources[field] = settingsSource(`model.generationConfig.${field}`);
    }
  }
  return result;
}
var init_modelConfigResolver = __esm({
  "packages/core/dist/src/models/modelConfigResolver.js"() {
    "use strict";
    init_esbuild_shims();
    init_contentGenerator();
    init_models();
    init_configResolver();
    init_constants3();
    init_contentGenerator();
    __name(resolveModelConfig, "resolveModelConfig");
    __name(resolveQwenOAuthConfig, "resolveQwenOAuthConfig");
    __name(resolveGenerationConfig, "resolveGenerationConfig");
  }
});

// packages/core/dist/src/models/index.js
var init_models5 = __esm({
  "packages/core/dist/src/models/index.js"() {
    "use strict";
    init_esbuild_shims();
    init_types4();
    init_modelRegistry();
    init_modelsConfig();
    init_constants3();
    init_modelConfigResolver();
  }
});

// packages/core/dist/src/config/config.js
import * as path66 from "node:path";
import process14 from "node:process";
import { randomUUID as randomUUID5 } from "node:crypto";
function isSdkMcpServerConfig(config2) {
  return config2.type === "sdk";
}
function normalizeConfigOutputFormat(format4) {
  if (!format4) {
    return void 0;
  }
  switch (format4) {
    case "stream-json":
      return OutputFormat.STREAM_JSON;
    case "json":
    case OutputFormat.JSON:
      return OutputFormat.JSON;
    case "text":
    case OutputFormat.TEXT:
    default:
      return OutputFormat.TEXT;
  }
}
var import_undici4, ApprovalMode, APPROVAL_MODES, APPROVAL_MODE_INFO, 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_undici4 = __toESM(require_undici(), 1);
    init_baseLlmClient();
    init_client2();
    init_contentGenerator();
    init_fileDiscoveryService();
    init_fileSystemService();
    init_gitService();
    init_edit();
    init_exitPlanMode();
    init_glob2();
    init_grep2();
    init_ls();
    init_memoryTool();
    init_read_file();
    init_ripgrepUtils();
    init_ripGrep();
    init_shell();
    init_skill();
    init_task();
    init_todoWrite();
    init_tool_registry();
    init_web_fetch();
    init_web_search();
    init_write_file();
    init_lsp();
    init_ideContext();
    init_types10();
    init_prompt_registry();
    init_skill_manager();
    init_subagent_manager();
    init_telemetry();
    init_extensionManager();
    init_browser();
    init_ignorePatterns();
    init_workspaceContext();
    init_tool_utils();
    init_errors();
    init_constants4();
    init_models();
    init_storage();
    init_chatRecordingService();
    init_sessionService();
    init_memoryDiscovery();
    init_debugLogger();
    init_models5();
    (function(ApprovalMode2) {
      ApprovalMode2["PLAN"] = "plan";
      ApprovalMode2["DEFAULT"] = "default";
      ApprovalMode2["AUTO_EDIT"] = "auto-edit";
      ApprovalMode2["YOLO"] = "yolo";
    })(ApprovalMode || (ApprovalMode = {}));
    APPROVAL_MODES = Object.values(ApprovalMode);
    APPROVAL_MODE_INFO = {
      [ApprovalMode.PLAN]: {
        id: ApprovalMode.PLAN,
        name: "Plan",
        description: "Analyze only, do not modify files or execute commands"
      },
      [ApprovalMode.DEFAULT]: {
        id: ApprovalMode.DEFAULT,
        name: "Default",
        description: "Require approval for file edits or shell commands"
      },
      [ApprovalMode.AUTO_EDIT]: {
        id: ApprovalMode.AUTO_EDIT,
        name: "Auto Edit",
        description: "Automatically approve file edits"
      },
      [ApprovalMode.YOLO]: {
        id: ApprovalMode.YOLO,
        name: "YOLO",
        description: "Automatically approve all tools"
      }
    };
    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;
      type;
      constructor(command2, args, env7, cwd7, url2, httpUrl, headers, tcp, timeout2, trust, description, includeTools, excludeTools, extensionName, oauth, authProviderType, targetAudience, targetServiceAccount, type) {
        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;
        this.type = type;
      }
    };
    __name(isSdkMcpServerConfig, "isSdkMcpServerConfig");
    (function(AuthProviderType2) {
      AuthProviderType2["DYNAMIC_DISCOVERY"] = "dynamic_discovery";
      AuthProviderType2["GOOGLE_CREDENTIALS"] = "google_credentials";
      AuthProviderType2["SERVICE_ACCOUNT_IMPERSONATION"] = "service_account_impersonation";
    })(AuthProviderType || (AuthProviderType = {}));
    __name(normalizeConfigOutputFormat, "normalizeConfigOutputFormat");
    Config = class {
      static {
        __name(this, "Config");
      }
      sessionId;
      sessionData;
      debugLogger;
      toolRegistry;
      promptRegistry;
      subagentManager;
      extensionManager;
      skillManager = null;
      fileSystemService;
      contentGeneratorConfig;
      contentGeneratorConfigSources = {};
      contentGenerator;
      embeddingModel;
      modelsConfig;
      modelProvidersConfig;
      sandbox;
      targetDir;
      workspaceContext;
      debugMode;
      inputFormat;
      outputFormat;
      includePartialMessages;
      question;
      coreTools;
      allowedTools;
      excludeTools;
      toolDiscoveryCommand;
      toolCallCommand;
      mcpServerCommand;
      mcpServers;
      lspEnabled;
      lspClient;
      allowedMcpServers;
      excludedMcpServers;
      sessionSubagents;
      userMemory;
      sdkMode;
      geminiMdFileCount;
      approvalMode;
      accessibility;
      telemetrySettings;
      gitCoAuthor;
      usageStatisticsEnabled;
      geminiClient;
      baseLlmClient;
      fileFiltering;
      fileDiscoveryService = null;
      gitService = void 0;
      sessionService = void 0;
      chatRecordingService = void 0;
      checkpointing;
      proxy;
      cwd;
      bugCommand;
      outputLanguageFilePath;
      noBrowser;
      folderTrustFeature;
      folderTrust;
      ideMode;
      maxSessionTurns;
      sessionTokenLimit;
      listExtensions;
      overrideExtensions;
      summarizeToolOutput;
      cliVersion;
      experimentalZedIntegration = false;
      chatRecordingEnabled;
      loadMemoryFromIncludeDirectories = false;
      importFormat;
      webSearch;
      chatCompression;
      interactive;
      trustedFolder;
      useRipgrep;
      useBuiltinRipgrep;
      shouldUseNodePtyShell;
      skipNextSpeakerCheck;
      shellExecutionConfig;
      skipLoopDetection;
      skipStartupContext;
      warnings;
      initialized = false;
      storage;
      fileExclusions;
      truncateToolOutputThreshold;
      truncateToolOutputLines;
      enableToolOutputTruncation;
      eventEmitter;
      channel;
      defaultFileEncoding;
      constructor(params) {
        this.sessionId = params.sessionId ?? randomUUID5();
        this.sessionData = params.sessionData;
        setDebugLogSession(this);
        this.debugLogger = createDebugLogger();
        this.embeddingModel = params.embeddingModel ?? DEFAULT_QWEN_EMBEDDING_MODEL;
        this.fileSystemService = new StandardFileSystemService();
        this.sandbox = params.sandbox;
        this.targetDir = path66.resolve(params.targetDir);
        this.workspaceContext = new WorkspaceContext(this.targetDir, params.includeDirectories ?? []);
        this.debugMode = params.debugMode;
        this.inputFormat = params.inputFormat ?? InputFormat.TEXT;
        const normalizedOutputFormat = normalizeConfigOutputFormat(params.outputFormat ?? params.output?.format);
        this.outputFormat = normalizedOutputFormat ?? OutputFormat.TEXT;
        this.includePartialMessages = params.includePartialMessages ?? false;
        this.question = params.question;
        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.lspEnabled = params.lsp?.enabled ?? false;
        this.lspClient = params.lspClient;
        this.allowedMcpServers = params.allowedMcpServers;
        this.excludedMcpServers = params.excludedMcpServers;
        this.sessionSubagents = params.sessionSubagents ?? [];
        this.sdkMode = params.sdkMode ?? false;
        this.userMemory = params.userMemory ?? "";
        this.geminiMdFileCount = params.geminiMdFileCount ?? 0;
        this.approvalMode = params.approvalMode ?? ApprovalMode.DEFAULT;
        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 ?? true,
          name: "Qwen-Coder",
          email: "qwen-coder@alibabacloud.com"
        };
        this.usageStatisticsEnabled = params.usageStatisticsEnabled ?? true;
        this.outputLanguageFilePath = params.outputLanguageFilePath;
        this.fileFiltering = {
          respectGitIgnore: params.fileFiltering?.respectGitIgnore ?? true,
          respectQwenIgnore: params.fileFiltering?.respectQwenIgnore ?? true,
          enableRecursiveFileSearch: params.fileFiltering?.enableRecursiveFileSearch ?? true,
          enableFuzzySearch: params.fileFiltering?.enableFuzzySearch ?? true
        };
        this.checkpointing = params.checkpointing ?? false;
        this.proxy = params.proxy;
        this.cwd = params.cwd ?? process14.cwd();
        this.fileDiscoveryService = params.fileDiscoveryService ?? null;
        this.bugCommand = params.bugCommand;
        this.maxSessionTurns = params.maxSessionTurns ?? -1;
        this.sessionTokenLimit = params.sessionTokenLimit ?? -1;
        this.experimentalZedIntegration = params.experimentalZedIntegration ?? false;
        this.listExtensions = params.listExtensions ?? false;
        this.overrideExtensions = params.overrideExtensions;
        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.modelProvidersConfig = params.modelProvidersConfig;
        this.cliVersion = params.cliVersion;
        this.chatRecordingEnabled = params.chatRecording ?? true;
        this.loadMemoryFromIncludeDirectories = params.loadMemoryFromIncludeDirectories ?? false;
        this.importFormat = params.importFormat ?? "tree";
        this.chatCompression = params.chatCompression;
        this.interactive = params.interactive ?? false;
        this.trustedFolder = params.trustedFolder;
        this.skipLoopDetection = params.skipLoopDetection ?? false;
        this.skipStartupContext = params.skipStartupContext ?? false;
        this.warnings = params.warnings ?? [];
        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.channel = params.channel;
        this.defaultFileEncoding = params.defaultFileEncoding ?? FileEncoding.UTF8;
        this.storage = new Storage(this.targetDir);
        this.inputFormat = params.inputFormat ?? InputFormat.TEXT;
        this.fileExclusions = new FileExclusions(this);
        this.eventEmitter = params.eventEmitter;
        if (params.contextFileName) {
          setGeminiMdFilename(params.contextFileName);
        }
        this.modelsConfig = new ModelsConfig({
          initialAuthType: params.authType ?? params.generationConfig?.authType,
          modelProvidersConfig: this.modelProvidersConfig,
          generationConfig: {
            model: params.model,
            ...params.generationConfig || {},
            baseUrl: params.generationConfig?.baseUrl
          },
          generationConfigSources: params.generationConfigSources,
          onModelChange: this.handleModelChange.bind(this)
        });
        if (this.telemetrySettings.enabled) {
          initializeTelemetry(this);
        }
        if (this.getProxy()) {
          (0, import_undici4.setGlobalDispatcher)(new import_undici4.ProxyAgent(this.getProxy()));
        }
        this.geminiClient = new GeminiClient(this);
        this.chatRecordingService = this.chatRecordingEnabled ? new ChatRecordingService(this) : void 0;
        this.extensionManager = new ExtensionManager({
          workspaceDir: this.targetDir,
          enabledExtensionOverrides: this.overrideExtensions,
          isWorkspaceTrusted: this.isTrustedFolder()
        });
      }
      /**
       * Must only be called once, throws if called again.
       * @param options Optional initialization options including sendSdkMcpMessage callback
       */
      async initialize(options2) {
        if (this.initialized) {
          throw Error("Config was already initialized");
        }
        this.initialized = true;
        this.debugLogger.info("Config initialization started");
        this.getFileService();
        if (this.getCheckpointingEnabled()) {
          await this.getGitService();
        }
        this.promptRegistry = new PromptRegistry();
        this.extensionManager.setConfig(this);
        await this.extensionManager.refreshCache();
        this.debugLogger.debug("Extension manager initialized");
        this.subagentManager = new SubagentManager(this);
        this.skillManager = new SkillManager(this);
        await this.skillManager.startWatching();
        this.debugLogger.debug("Skill manager initialized");
        if (this.sessionSubagents.length > 0) {
          this.subagentManager.loadSessionSubagents(this.sessionSubagents);
        }
        await this.extensionManager.refreshCache();
        await this.refreshHierarchicalMemory();
        this.debugLogger.debug("Hierarchical memory loaded");
        this.toolRegistry = await this.createToolRegistry(options2?.sendSdkMcpMessage);
        this.debugLogger.info(`Tool registry initialized with ${this.toolRegistry.getAllToolNames().length} tools`);
        await this.geminiClient.initialize();
        this.debugLogger.info("Gemini client initialized");
        this.modelsConfig.detectAndCaptureRuntimeModel();
        logStartSession(this, new StartSessionEvent(this));
        this.debugLogger.info("Config initialization completed");
      }
      async refreshHierarchicalMemory() {
        const { memoryContent, fileCount } = await loadServerHierarchicalMemory(this.getWorkingDir(), this.shouldLoadMemoryFromIncludeDirectories() ? this.getWorkspaceContext().getDirectories() : [], this.getFileService(), this.getExtensionContextFilePaths(), this.isTrustedFolder(), this.getImportFormat());
        this.setUserMemory(memoryContent);
        this.setGeminiMdFileCount(fileCount);
      }
      getContentGenerator() {
        return this.contentGenerator;
      }
      /**
       * Get the ModelsConfig instance for model-related operations.
       * External code (e.g., CLI) can use this to access model configuration.
       */
      getModelsConfig() {
        return this.modelsConfig;
      }
      /**
       * Updates the credentials in the generation config.
       * Exclusive for `OpenAIKeyPrompt` to update credentials via `/auth`
       * Delegates to ModelsConfig.
       */
      updateCredentials(credentials, settingsGenerationConfig) {
        this.modelsConfig.updateCredentials(credentials, settingsGenerationConfig);
      }
      /**
       * Reload model providers configuration at runtime.
       * This enables hot-reloading of modelProviders settings without restarting the CLI.
       * Should be called before refreshAuth when settings.json has been updated.
       *
       * @param modelProvidersConfig - The updated model providers configuration
       */
      reloadModelProvidersConfig(modelProvidersConfig) {
        this.modelsConfig.reloadModelProvidersConfig(modelProvidersConfig);
      }
      /**
       * Refresh authentication and rebuild ContentGenerator.
       */
      async refreshAuth(authMethod, isInitialAuth) {
        const modelId = this.modelsConfig.getModel();
        this.modelsConfig.syncAfterAuthRefresh(authMethod, modelId);
        const requireCached = this.modelsConfig.consumeRequireCachedCredentialsFlag();
        const { config: config2, sources } = resolveContentGeneratorConfigWithSources(this, authMethod, this.modelsConfig.getGenerationConfig(), this.modelsConfig.getGenerationConfigSources(), {
          strictModelProvider: this.modelsConfig.isStrictModelProviderSelection()
        });
        const newContentGeneratorConfig = config2;
        this.contentGenerator = await createContentGenerator(newContentGeneratorConfig, this, requireCached ? true : isInitialAuth);
        this.contentGeneratorConfig = newContentGeneratorConfig;
        this.contentGeneratorConfigSources = sources;
        this.baseLlmClient = new BaseLlmClient(this.contentGenerator, this);
      }
      /**
       * 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;
      }
      /**
       * Returns warnings generated during configuration resolution.
       * These warnings are collected from model configuration resolution
       * and should be displayed to the user during startup.
       */
      getWarnings() {
        return this.warnings;
      }
      getDebugLogger() {
        return this.debugLogger;
      }
      /**
       * Starts a new session and resets session-scoped services.
       */
      startNewSession(sessionId, sessionData) {
        this.sessionId = sessionId ?? randomUUID5();
        this.sessionData = sessionData;
        setDebugLogSession(this);
        this.debugLogger = createDebugLogger();
        this.chatRecordingService = this.chatRecordingEnabled ? new ChatRecordingService(this) : void 0;
        if (this.initialized) {
          logStartSession(this, new StartSessionEvent(this));
        }
        return this.sessionId;
      }
      /**
       * Returns the resumed session data if this session was resumed from a previous one.
       */
      getResumedSessionData() {
        return this.sessionData;
      }
      shouldLoadMemoryFromIncludeDirectories() {
        return this.loadMemoryFromIncludeDirectories;
      }
      getImportFormat() {
        return this.importFormat;
      }
      getContentGeneratorConfig() {
        return this.contentGeneratorConfig;
      }
      getContentGeneratorConfigSources() {
        if (Object.keys(this.contentGeneratorConfigSources).length === 0 && this.modelsConfig) {
          return this.modelsConfig.getGenerationConfigSources();
        }
        return this.contentGeneratorConfigSources;
      }
      getModel() {
        return this.contentGeneratorConfig?.model || this.modelsConfig.getModel();
      }
      /**
       * Set model programmatically (e.g., VLM auto-switch, fallback).
       * Delegates to ModelsConfig.
       */
      async setModel(newModel, metadata) {
        await this.modelsConfig.setModel(newModel, metadata);
        if (this.contentGeneratorConfig) {
          this.contentGeneratorConfig.model = newModel;
        }
      }
      /**
       * Handle model change from ModelsConfig.
       * This updates the content generator config with the new model settings.
       */
      async handleModelChange(authType, requiresRefresh) {
        if (!this.contentGeneratorConfig) {
          return;
        }
        if (authType === AuthType2.QWEN_OAUTH && !requiresRefresh) {
          const { config: config2, sources } = resolveContentGeneratorConfigWithSources(this, authType, this.modelsConfig.getGenerationConfig(), this.modelsConfig.getGenerationConfigSources(), {
            strictModelProvider: this.modelsConfig.isStrictModelProviderSelection()
          });
          this.contentGeneratorConfig.model = config2.model;
          this.contentGeneratorConfig.samplingParams = config2.samplingParams;
          this.contentGeneratorConfig.contextWindowSize = config2.contextWindowSize;
          this.contentGeneratorConfig.enableCacheControl = config2.enableCacheControl;
          if ("model" in sources) {
            this.contentGeneratorConfigSources["model"] = sources["model"];
          }
          if ("samplingParams" in sources) {
            this.contentGeneratorConfigSources["samplingParams"] = sources["samplingParams"];
          }
          if ("enableCacheControl" in sources) {
            this.contentGeneratorConfigSources["enableCacheControl"] = sources["enableCacheControl"];
          }
          if ("contextWindowSize" in sources) {
            this.contentGeneratorConfigSources["contextWindowSize"] = sources["contextWindowSize"];
          }
          return;
        }
        await this.refreshAuth(authType);
      }
      /**
       * Get available models for the current authType.
       * Delegates to ModelsConfig.
       */
      getAvailableModels() {
        return this.modelsConfig.getAvailableModels();
      }
      /**
       * Get available models for a specific authType.
       * Delegates to ModelsConfig.
       */
      getAvailableModelsForAuthType(authType) {
        return this.modelsConfig.getAvailableModelsForAuthType(authType);
      }
      /**
       * Get all configured models across authTypes.
       * Delegates to ModelsConfig.
       */
      getAllConfiguredModels(authTypes) {
        return this.modelsConfig.getAllConfiguredModels(authTypes);
      }
      /**
       * Get the currently active runtime model snapshot.
       * Delegates to ModelsConfig.
       */
      getActiveRuntimeModelSnapshot() {
        return this.modelsConfig.getActiveRuntimeModelSnapshot();
      }
      /**
       * Switch authType+model.
       * Supports both registry-backed models and runtime model snapshots.
       *
       * For runtime models, the modelId should be in format `$runtime|${authType}|${modelId}`.
       * This triggers a refresh of the ContentGenerator when required (always on authType changes).
       * For qwen-oauth model switches that are hot-update safe, this may update in place.
       *
       * @param authType - Target authentication type
       * @param modelId - Target model ID (or `$runtime|${authType}|${modelId}` for runtime models)
       * @param options - Additional options like requireCachedCredentials
       */
      async switchModel(authType, modelId, options2) {
        await this.modelsConfig.switchModel(authType, modelId, options2);
      }
      getMaxSessionTurns() {
        return this.maxSessionTurns;
      }
      getSessionTokenLimit() {
        return this.sessionTokenLimit;
      }
      getEmbeddingModel() {
        return this.embeddingModel;
      }
      getSandbox() {
        return this.sandbox;
      }
      isRestrictiveSandbox() {
        const sandboxConfig = this.getSandbox();
        const seatbeltProfile = process14.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;
      }
      /**
       * Shuts down the Config and releases all resources.
       * This method is idempotent and safe to call multiple times.
       * It handles the case where initialization was not completed.
       */
      async shutdown() {
        if (!this.initialized) {
          return;
        }
        try {
          this.skillManager?.stopWatching();
          if (this.toolRegistry) {
            await this.toolRegistry.stop();
          }
        } catch (error2) {
          this.debugLogger.error("Error during Config shutdown:", error2);
        }
      }
      getPromptRegistry() {
        return this.promptRegistry;
      }
      getDebugMode() {
        return this.debugMode;
      }
      getQuestion() {
        return this.question;
      }
      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() {
        let mcpServers = { ...this.mcpServers || {} };
        const extensions = this.getActiveExtensions();
        for (const extension of extensions) {
          Object.entries(extension.config.mcpServers || {}).forEach(([key, server]) => {
            if (mcpServers[key])
              return;
            mcpServers[key] = {
              ...server,
              extensionName: extension.config.name
            };
          });
        }
        if (this.allowedMcpServers) {
          mcpServers = Object.fromEntries(Object.entries(mcpServers).filter(([key]) => this.allowedMcpServers?.includes(key)));
        }
        if (this.excludedMcpServers) {
          mcpServers = Object.fromEntries(Object.entries(mcpServers).filter(([key]) => !this.excludedMcpServers?.includes(key)));
        }
        return mcpServers;
      }
      addMcpServers(servers) {
        if (this.initialized) {
          throw new Error("Cannot modify mcpServers after initialization");
        }
        this.mcpServers = { ...this.mcpServers, ...servers };
      }
      isLspEnabled() {
        return this.lspEnabled;
      }
      getLspClient() {
        return this.lspClient;
      }
      /**
       * Allows wiring an LSP client after Config construction but before initialize().
       */
      setLspClient(client) {
        if (this.initialized) {
          throw new Error("Cannot set LSP client after initialization");
        }
        this.lspClient = client;
      }
      getSessionSubagents() {
        return this.sessionSubagents;
      }
      setSessionSubagents(subagents) {
        if (this.initialized) {
          throw new Error("Cannot modify sessionSubagents after initialization");
        }
        this.sessionSubagents = subagents;
      }
      getSdkMode() {
        return this.sdkMode;
      }
      setSdkMode(value) {
        this.sdkMode = value;
      }
      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;
      }
      getInputFormat() {
        return this.inputFormat;
      }
      getIncludePartialMessages() {
        return this.includePartialMessages;
      }
      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;
      }
      getFileFilteringEnableFuzzySearch() {
        return this.fileFiltering.enableFuzzySearch;
      }
      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() {
        const extensionContextFilePaths = this.getActiveExtensions().flatMap((e4) => e4.contextFiles);
        return [
          ...extensionContextFilePaths,
          ...this.outputLanguageFilePath ? [this.outputLanguageFilePath] : []
        ];
      }
      getExperimentalZedIntegration() {
        return this.experimentalZedIntegration;
      }
      getListExtensions() {
        return this.listExtensions;
      }
      getExtensionManager() {
        return this.extensionManager;
      }
      getExtensions() {
        const extensions = this.extensionManager.getLoadedExtensions();
        if (this.overrideExtensions) {
          return extensions.filter((e4) => this.overrideExtensions?.includes(e4.name));
        } else {
          return extensions;
        }
      }
      getActiveExtensions() {
        return this.getExtensions().filter((e4) => e4.isActive);
      }
      getBlockedMcpServers() {
        const mcpServers = { ...this.mcpServers || {} };
        const extensions = this.getActiveExtensions();
        for (const extension of extensions) {
          Object.entries(extension.config.mcpServers || {}).forEach(([key, server]) => {
            if (mcpServers[key])
              return;
            mcpServers[key] = {
              ...server,
              extensionName: extension.config.name
            };
          });
        }
        const blockedMcpServers = [];
        if (this.allowedMcpServers) {
          Object.entries(mcpServers).forEach(([key, server]) => {
            const isAllowed = this.allowedMcpServers?.includes(key);
            if (!isAllowed) {
              blockedMcpServers.push({
                name: key,
                extensionName: server.extensionName || ""
              });
            }
          });
        }
        return 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;
      }
      getChannel() {
        return this.channel;
      }
      /**
       * Get the default file encoding for new files.
       * @returns FileEncodingType
       */
      getDefaultFileEncoding() {
        return this.defaultFileEncoding;
      }
      /**
       * 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(config2) {
        this.shellExecutionConfig = {
          terminalWidth: config2.terminalWidth ?? this.shellExecutionConfig.terminalWidth,
          terminalHeight: config2.terminalHeight ?? this.shellExecutionConfig.terminalHeight,
          showColor: config2.showColor ?? this.shellExecutionConfig.showColor,
          pager: config2.pager ?? this.shellExecutionConfig.pager
        };
      }
      getScreenReader() {
        return this.accessibility.screenReader ?? false;
      }
      getSkipLoopDetection() {
        return this.skipLoopDetection;
      }
      getSkipStartupContext() {
        return this.skipStartupContext;
      }
      getEnableToolOutputTruncation() {
        return this.enableToolOutputTruncation;
      }
      getTruncateToolOutputThreshold() {
        if (!this.enableToolOutputTruncation || this.truncateToolOutputThreshold <= 0) {
          return Number.POSITIVE_INFINITY;
        }
        return this.truncateToolOutputThreshold;
      }
      getTruncateToolOutputLines() {
        if (!this.enableToolOutputTruncation || this.truncateToolOutputLines <= 0) {
          return Number.POSITIVE_INFINITY;
        }
        return this.truncateToolOutputLines;
      }
      getOutputFormat() {
        return this.outputFormat;
      }
      async getGitService() {
        if (!this.gitService) {
          this.gitService = new GitService(this.targetDir, this.storage);
          await this.gitService.initialize();
        }
        return this.gitService;
      }
      /**
       * Returns the chat recording service.
       */
      getChatRecordingService() {
        if (!this.chatRecordingEnabled) {
          return void 0;
        }
        if (!this.chatRecordingService) {
          this.chatRecordingService = new ChatRecordingService(this);
        }
        return this.chatRecordingService;
      }
      /**
       * Gets or creates a SessionService for managing chat sessions.
       */
      getSessionService() {
        if (!this.sessionService) {
          this.sessionService = new SessionService(this.targetDir);
        }
        return this.sessionService;
      }
      getFileExclusions() {
        return this.fileExclusions;
      }
      getSubagentManager() {
        return this.subagentManager;
      }
      getSkillManager() {
        return this.skillManager;
      }
      async createToolRegistry(sendSdkMcpMessage) {
        const registry2 = new ToolRegistry(this, this.eventEmitter, sendSdkMcpMessage);
        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) {
            this.debugLogger.warn(`Skipping tool registration: ${className} is missing static Name property. Tools must define a static Name property to be registered.`);
            return;
          }
          if (isToolEnabled(toolName, coreToolsConfig, excludeToolsConfig)) {
            try {
              registry2.registerTool(new ToolClass(...args));
            } catch (error2) {
              this.debugLogger.error(`Failed to register tool ${className} (${toolName}):`, error2);
              throw error2;
            }
          }
        }, "registerCoreTool");
        registerCoreTool(TaskTool, this);
        registerCoreTool(SkillTool, this);
        registerCoreTool(LSTool, this);
        registerCoreTool(ReadFileTool, this);
        if (this.getUseRipgrep()) {
          let useRipgrep = false;
          let errorString = void 0;
          try {
            useRipgrep = await canUseRipgrep(this.getUseBuiltinRipgrep());
          } catch (error2) {
            errorString = getErrorMessage(error2);
          }
          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);
        registerCoreTool(EditTool, this);
        registerCoreTool(WriteFileTool, this);
        registerCoreTool(ShellTool, this);
        registerCoreTool(MemoryTool);
        registerCoreTool(TodoWriteTool, this);
        !this.sdkMode && registerCoreTool(ExitPlanModeTool, this);
        registerCoreTool(WebFetchTool, this);
        if (this.getWebSearchConfig()) {
          registerCoreTool(WebSearchTool, this);
        }
        if (this.isLspEnabled() && this.getLspClient()) {
          registerCoreTool(LspTool, this);
        }
        await registry2.discoverAllTools();
        this.debugLogger.debug(`ToolRegistry created: ${JSON.stringify(registry2.getAllToolNames())} (${registry2.getAllToolNames().length} tools)`);
        return registry2;
      }
    };
  }
});

// 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, error2) {
        const output = {};
        if (response !== void 0) {
          output.response = stripAnsi(response);
        }
        if (stats) {
          output.stats = stats;
        }
        if (error2) {
          output.error = error2;
        }
        return JSON.stringify(output, null, 2);
      }
      formatError(error2, code2) {
        const jsonError = {
          type: error2.constructor.name,
          message: stripAnsi(error2.message),
          ...code2 && { code: code2 }
        };
        return this.format(void 0, void 0, jsonError);
      }
    };
  }
});

// packages/core/dist/src/core/geminiRequest.js
var init_geminiRequest = __esm({
  "packages/core/dist/src/core/geminiRequest.js"() {
    "use strict";
    init_esbuild_shims();
    init_node();
    init_partUtils();
  }
});

// packages/core/dist/src/core/logger.js
import path67 from "node:path";
import { promises as fs65 } from "node:fs";
function encodeTagName(str2) {
  return encodeURIComponent(str2);
}
var LOG_FILE_NAME, MessageSenderType, Logger;
var init_logger = __esm({
  "packages/core/dist/src/core/logger.js"() {
    "use strict";
    init_esbuild_shims();
    init_debugLogger();
    LOG_FILE_NAME = "logs.json";
    (function(MessageSenderType2) {
      MessageSenderType2["USER"] = "user";
      MessageSenderType2["MODEL_SWITCH"] = "model_switch";
    })(MessageSenderType || (MessageSenderType = {}));
    __name(encodeTagName, "encodeTagName");
    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
      debugLogger;
      constructor(sessionId, storage) {
        this.storage = storage;
        this.sessionId = sessionId;
        this.debugLogger = createDebugLogger("LOGGER");
      }
      async _readLogFile() {
        if (!this.logFilePath) {
          throw new Error("Log file path not set during read attempt.");
        }
        try {
          const fileContent = await fs65.readFile(this.logFilePath, "utf-8");
          const parsedLogs = JSON.parse(fileContent);
          if (!Array.isArray(parsedLogs)) {
            this.debugLogger.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 (error2) {
          const nodeError = error2;
          if (nodeError.code === "ENOENT") {
            return [];
          }
          if (error2 instanceof SyntaxError) {
            this.debugLogger.debug(`Invalid JSON in log file ${this.logFilePath}. Backing up and starting fresh.`, error2);
            await this._backupCorruptedLogFile("invalid_json");
            return [];
          }
          this.debugLogger.debug(`Failed to read or parse log file ${this.logFilePath}:`, error2);
          throw error2;
        }
      }
      async _backupCorruptedLogFile(reason) {
        if (!this.logFilePath)
          return;
        const backupPath = `${this.logFilePath}.${reason}.${Date.now()}.bak`;
        try {
          await fs65.rename(this.logFilePath, backupPath);
          this.debugLogger.debug(`Backed up corrupted log file to ${backupPath}`);
        } catch (_backupError) {
        }
      }
      async initialize() {
        if (this.initialized) {
          return;
        }
        this.qwenDir = this.storage.getProjectTempDir();
        this.logFilePath = path67.join(this.qwenDir, LOG_FILE_NAME);
        try {
          await fs65.mkdir(this.qwenDir, { recursive: true });
          let fileExisted = true;
          try {
            await fs65.access(this.logFilePath);
          } catch (_e2) {
            fileExisted = false;
          }
          this.logs = await this._readLogFile();
          if (!fileExisted && this.logs.length === 0) {
            await fs65.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) {
          this.debugLogger.error("Failed to initialize logger:", err);
          this.initialized = false;
        }
      }
      async _updateLogFile(entryToAppend) {
        if (!this.logFilePath) {
          this.debugLogger.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) {
          this.debugLogger.debug("Critical error reading log file before append:", readError);
          throw readError;
        }
        const sessionLogsOnDisk = currentLogsOnDisk.filter((e4) => e4.sessionId === entryToAppend.sessionId);
        const nextMessageIdForSession = sessionLogsOnDisk.length > 0 ? Math.max(...sessionLogsOnDisk.map((e4) => e4.messageId)) + 1 : 0;
        entryToAppend.messageId = nextMessageIdForSession;
        const entryExists = currentLogsOnDisk.some((e4) => e4.sessionId === entryToAppend.sessionId && e4.messageId === entryToAppend.messageId && e4.timestamp === entryToAppend.timestamp && // Timestamps are good for distinguishing
        e4.message === entryToAppend.message);
        if (entryExists) {
          this.debugLogger.debug(`Duplicate log entry detected and skipped: session ${entryToAppend.sessionId}, messageId ${entryToAppend.messageId}`);
          this.logs = currentLogsOnDisk;
          return null;
        }
        currentLogsOnDisk.push(entryToAppend);
        try {
          await fs65.writeFile(this.logFilePath, JSON.stringify(currentLogsOnDisk, null, 2), "utf-8");
          this.logs = currentLogsOnDisk;
          return entryToAppend;
        } catch (error2) {
          this.debugLogger.debug("Error writing to log file:", error2);
          throw error2;
        }
      }
      async getPreviousUserMessages() {
        if (!this.initialized)
          return [];
        return this.logs.filter((entry) => entry.type === MessageSenderType.USER).sort((a2, b2) => {
          const dateA = new Date(a2.timestamp).getTime();
          const dateB = new Date(b2.timestamp).getTime();
          return dateB - dateA;
        }).map((entry) => entry.message);
      }
      async logMessage(type, message) {
        if (!this.initialized || this.sessionId === void 0) {
          this.debugLogger.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 path67.join(this.qwenDir, `checkpoint-${encodedTag}.json`);
      }
      async _getCheckpointPath(tag2) {
        const newPath = this._checkpointPath(tag2);
        try {
          await fs65.access(newPath);
          return newPath;
        } catch (error2) {
          const nodeError = error2;
          if (nodeError.code !== "ENOENT") {
            throw error2;
          }
        }
        const oldPath = path67.join(this.qwenDir, `checkpoint-${tag2}.json`);
        try {
          await fs65.access(oldPath);
          return oldPath;
        } catch (error2) {
          const nodeError = error2;
          if (nodeError.code !== "ENOENT") {
            throw error2;
          }
        }
        return newPath;
      }
      async saveCheckpoint(conversation, tag2) {
        if (!this.initialized) {
          this.debugLogger.error("Logger not initialized or checkpoint file path not set. Cannot save a checkpoint.");
          return;
        }
        const path125 = this._checkpointPath(tag2);
        try {
          await fs65.writeFile(path125, JSON.stringify(conversation, null, 2), "utf-8");
        } catch (error2) {
          this.debugLogger.error("Error writing to checkpoint file:", error2);
        }
      }
      async loadCheckpoint(tag2) {
        if (!this.initialized) {
          this.debugLogger.error("Logger not initialized or checkpoint file path not set. Cannot load checkpoint.");
          return [];
        }
        const path125 = await this._getCheckpointPath(tag2);
        try {
          const fileContent = await fs65.readFile(path125, "utf-8");
          const parsedContent = JSON.parse(fileContent);
          if (!Array.isArray(parsedContent)) {
            this.debugLogger.warn(`Checkpoint file at ${path125} is not a valid JSON array. Returning empty checkpoint.`);
            return [];
          }
          return parsedContent;
        } catch (error2) {
          const nodeError = error2;
          if (nodeError.code === "ENOENT") {
            return [];
          }
          this.debugLogger.error(`Failed to read or parse checkpoint file ${path125}:`, error2);
          return [];
        }
      }
      async deleteCheckpoint(tag2) {
        if (!this.initialized || !this.qwenDir) {
          this.debugLogger.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 fs65.unlink(newPath);
          deletedSomething = true;
        } catch (error2) {
          const nodeError = error2;
          if (nodeError.code !== "ENOENT") {
            this.debugLogger.error(`Failed to delete checkpoint file ${newPath}:`, error2);
            throw error2;
          }
        }
        const oldPath = path67.join(this.qwenDir, `checkpoint-${tag2}.json`);
        if (newPath !== oldPath) {
          try {
            await fs65.unlink(oldPath);
            deletedSomething = true;
          } catch (error2) {
            const nodeError = error2;
            if (nodeError.code !== "ENOENT") {
              this.debugLogger.error(`Failed to delete checkpoint file ${oldPath}:`, error2);
              throw error2;
            }
          }
        }
        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 fs65.access(filePath);
          return true;
        } catch (error2) {
          const nodeError = error2;
          if (nodeError.code === "ENOENT") {
            return false;
          }
          this.debugLogger.error(`Failed to check checkpoint existence for ${filePath ?? `path for tag "${tag2}"`}:`, error2);
          throw error2;
        }
      }
      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(config2, toolCallRequest, abortSignal, options2 = {}) {
  return new Promise((resolve30, reject) => {
    new CoreToolScheduler({
      config: config2,
      chatRecordingService: config2.getChatRecordingService(),
      outputUpdateHandler: options2.outputUpdateHandler,
      onAllToolCallsComplete: /* @__PURE__ */ __name(async (completedToolCalls) => {
        if (options2.onAllToolCallsComplete) {
          await options2.onAllToolCallsComplete(completedToolCalls);
        }
        resolve30(completedToolCalls[0].response);
      }, "onAllToolCallsComplete"),
      onToolCallsUpdate: options2.onToolCallsUpdate,
      getPreferredEditor: /* @__PURE__ */ __name(() => void 0, "getPreferredEditor"),
      onEditorClose: /* @__PURE__ */ __name(() => {
      }, "onEditorClose")
    }).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/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 platform16 = navigator.platform.toLowerCase();
        return platform16 === "win32" || platform16 === "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 = (path125, { windows } = {}) => {
      const segs = path125.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 finished2 = 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;
              finished2 = true;
              if (scanToEnd === true) {
                continue;
              }
              break;
            }
            if (braceEscaped !== true && code2 === CHAR_COMMA2) {
              isBrace = token2.isBrace = true;
              isGlob = token2.isGlob = true;
              finished2 = true;
              if (scanToEnd === true) {
                continue;
              }
              break;
            }
            if (code2 === CHAR_RIGHT_CURLY_BRACE) {
              braces--;
              if (braces === 0) {
                braceEscaped = false;
                isBrace = token2.isBrace = true;
                finished2 = 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 (finished2 === 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;
            finished2 = 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;
                  finished2 = true;
                  break;
                }
              }
              continue;
            }
            break;
          }
        }
        if (code2 === CHAR_ASTERISK) {
          if (prev === CHAR_ASTERISK) isGlobstar = token2.isGlobstar = true;
          isGlob = token2.isGlob = true;
          finished2 = true;
          if (scanToEnd === true) {
            continue;
          }
          break;
        }
        if (code2 === CHAR_QUESTION_MARK) {
          isGlob = token2.isGlob = true;
          finished2 = 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;
              finished2 = 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) {
                finished2 = true;
                break;
              }
            }
            continue;
          }
          break;
        }
        if (isGlob === true) {
          finished2 = 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 n3 = prevIndex ? prevIndex + 1 : start;
          const i3 = slashes[idx];
          const value = input.slice(n3, i3);
          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 = i3;
        }
        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_parse7 = __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((v2) => utils.escapeRegex(v2)).join("..");
      }
      return value;
    }, "expandRange");
    var syntaxError2 = /* @__PURE__ */ __name((type, char) => {
      return `Missing ${type}: "${char}" - use "\\\\${char}" to match literal characters`;
    }, "syntaxError");
    var parse14 = /* @__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 = (n3 = 1) => input[state.index + n3];
      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 = parse14(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, (m3, esc2, chars, first2, rest, index) => {
          if (first2 === "\\") {
            backslashes = true;
            return m3;
          }
          if (first2 === "?") {
            if (esc2) {
              return esc2 + 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 (esc2) {
              return esc2 + first2 + (rest ? star3 : "");
            }
            return star3;
          }
          return esc2 ? m3 : `\\${m3}`;
        });
        if (backslashes === true) {
          if (opts.unescape === true) {
            output = output.replace(/\\/g, "");
          } else {
            output = output.replace(/\\+/g, (m3) => {
              return m3.length % 2 === 0 ? "\\\\" : m3 ? "\\" : "";
            });
          }
        }
        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 open4 = {
            type: "brace",
            value,
            output: "(",
            outputIndex: state.output.length,
            tokensIndex: state.tokens.length
          };
          braces.push(open4);
          push2(open4);
          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 i3 = arr.length - 1; i3 >= 0; i3--) {
              tokens.pop();
              if (arr[i3].type === "brace") {
                break;
              }
              if (arr[i3].type !== "dots") {
                range.unshift(arr[i3].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 t5 of toks) {
              state.output += t5.output || t5.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");
    parse14.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 = parse14;
  }
});

// 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 parse14 = require_parse7();
    var utils = require_utils14();
    var constants4 = require_constants11();
    var isObject4 = /* @__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 = isObject4(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((p2) => picomatch3.parse(p2, options2));
      return parse14(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 = parse14.fastpaths(input, options2);
      }
      if (!parsed.output) {
        parsed = parse14(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 fs66 from "node:fs";
import path68 from "node:path";
function loadIgnoreRules(options2) {
  const ignorer = new Ignore2();
  if (options2.useGitignore) {
    const gitignorePath = path68.join(options2.projectRoot, ".gitignore");
    if (fs66.existsSync(gitignorePath)) {
      ignorer.add(fs66.readFileSync(gitignorePath, "utf8"));
    }
  }
  if (options2.useQwenignore) {
    const qwenignorePath = path68.join(options2.projectRoot, ".qwenignore");
    if (fs66.existsSync(qwenignorePath)) {
      ignorer.add(fs66.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 p2 of patterns) {
          const pattern = p2.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(path125) {
      let normalized2 = (0, path_1.normalize)(path125);
      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(path125, separator) {
      return path125.replace(SLASHES_REGEX, separator);
    }
    __name(convertSlashes, "convertSlashes");
    exports2.convertSlashes = convertSlashes;
    var WINDOWS_ROOT_DIR_REGEX = /^[a-z]:[\\/]$/i;
    function isRootDirectory(path125) {
      return path125 === "/" || WINDOWS_ROOT_DIR_REGEX.test(path125);
    }
    __name(isRootDirectory, "isRootDirectory");
    exports2.isRootDirectory = isRootDirectory;
    function normalizePath2(path125, options2) {
      const { resolvePaths, normalizePath: normalizePath3, pathSeparator } = options2;
      const pathNeedsCleaning = process.platform === "win32" && path125.includes("/") || path125.startsWith(".");
      if (resolvePaths)
        path125 = (0, path_1.resolve)(path125);
      if (normalizePath3 || pathNeedsCleaning)
        path125 = cleanPath(path125);
      if (path125 === ".")
        return "";
      const needsSeperator = path125[path125.length - 1] !== pathSeparator;
      return convertSlashes(needsSeperator ? path125 + pathSeparator : path125, pathSeparator);
    }
    __name(normalizePath2, "normalizePath");
    exports2.normalizePath = normalizePath2;
  }
});

// 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 path125 = directoryPath || ".";
      if (filters.every((filter4) => filter4(path125, true))) {
        paths.push(path125);
      }
    }, "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(path125, state, callback) {
      const { queue, options: { suppressErrors } } = state;
      queue.enqueue();
      fs_1.default.realpath(path125, (error2, resolvedPath) => {
        if (error2)
          return queue.dequeue(suppressErrors ? null : error2, state);
        fs_1.default.stat(resolvedPath, (error3, stat10) => {
          if (error3)
            return queue.dequeue(suppressErrors ? null : error3, state);
          if (stat10.isDirectory() && isRecursive(path125, resolvedPath, state))
            return queue.dequeue(null, state);
          callback(stat10, resolvedPath);
          queue.dequeue(null, state);
        });
      });
    }, "resolveSymlinksAsync");
    var resolveSymlinks = /* @__PURE__ */ __name(function(path125, state, callback) {
      const { queue, options: { suppressErrors } } = state;
      queue.enqueue();
      try {
        const resolvedPath = fs_1.default.realpathSync(path125);
        const stat10 = fs_1.default.statSync(resolvedPath);
        if (stat10.isDirectory() && isRecursive(path125, resolvedPath, state))
          return;
        callback(stat10, resolvedPath);
      } catch (e4) {
        if (!suppressErrors)
          throw e4;
      }
    }, "resolveSymlinks");
    function build(options2, isSynchronous) {
      if (!options2.resolveSymlinks || options2.excludeSymlinks)
        return null;
      return isSynchronous ? resolveSymlinks : resolveSymlinksAsync;
    }
    __name(build, "build");
    exports2.build = build;
    function isRecursive(path125, resolved, state) {
      if (state.options.useRealPaths)
        return isRecursiveUsingRealPaths(resolved, state);
      let parent = (0, path_1.dirname)(path125);
      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(path125, 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, error2, callback) => {
      report(error2, callback, state.counts, state.options.suppressErrors);
      return null;
    }, "onlyCountsAsync");
    var defaultAsync = /* @__PURE__ */ __name((state, error2, callback) => {
      report(error2, callback, state.paths, state.options.suppressErrors);
      return null;
    }, "defaultAsync");
    var limitFilesAsync = /* @__PURE__ */ __name((state, error2, callback) => {
      report(error2, callback, state.paths.slice(0, state.options.maxFiles), state.options.suppressErrors);
      return null;
    }, "limitFilesAsync");
    var groupsAsync = /* @__PURE__ */ __name((state, error2, callback) => {
      report(error2, callback, state.groups, state.options.suppressErrors);
      return null;
    }, "groupsAsync");
    function report(error2, callback, output, suppressErrors) {
      if (error2 && !suppressErrors)
        callback(error2, 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, (error2, entries = []) => {
        callback(entries, directoryPath, currentDepth);
        state.queue.dequeue(state.options.suppressErrors ? null : error2, 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 (e4) {
        if (!state.options.suppressErrors)
          throw e4;
      }
      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 Queue2 = class {
      static {
        __name(this, "Queue");
      }
      onQueueEmpty;
      count = 0;
      constructor(onQueueEmpty) {
        this.onQueueEmpty = onQueueEmpty;
      }
      enqueue() {
        this.count++;
        return this.count;
      }
      dequeue(error2, output) {
        if (this.onQueueEmpty && (--this.count <= 0 || error2)) {
          this.onQueueEmpty(error2, output);
          if (error2) {
            output.controller.abort();
            this.onQueueEmpty = void 0;
          }
        }
      }
    };
    exports2.Queue = Queue2;
  }
});

// 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(o3, m3, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc2 = Object.getOwnPropertyDescriptor(m3, k2);
      if (!desc2 || ("get" in desc2 ? !m3.__esModule : desc2.writable || desc2.configurable)) {
        desc2 = { enumerable: true, get: /* @__PURE__ */ __name(function() {
          return m3[k2];
        }, "get") };
      }
      Object.defineProperty(o3, k22, desc2);
    } : function(o3, m3, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o3[k22] = m3[k2];
    });
    var __setModuleDefault = exports2 && exports2.__setModuleDefault || (Object.create ? function(o3, v2) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v2 });
    } : function(o3, v2) {
      o3["default"] = v2;
    });
    var __importStar = exports2 && exports2.__importStar || function(mod2) {
      if (mod2 && mod2.__esModule) return mod2;
      var result = {};
      if (mod2 != null) {
        for (var k2 in mod2) if (k2 !== "default" && Object.prototype.hasOwnProperty.call(mod2, k2)) __createBinding(result, mod2, k2);
      }
      __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((error2, state) => this.callbackInvoker(state, error2, 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 i3 = 0; i3 < entries.length; ++i3) {
          const entry = entries[i3];
          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 path125 = joinPath.joinDirectoryPath(entry.name, directoryPath, this.state.options.pathSeparator);
            if (exclude && exclude(entry.name, path125))
              continue;
            this.pushDirectory(path125, paths, filters);
            this.walkDirectory(this.state, path125, path125, depth - 1, this.walk);
          } else if (this.resolveSymlink && entry.isSymbolicLink()) {
            let path125 = joinPath.joinPathWithBasePath(entry.name, directoryPath);
            this.resolveSymlink(path125, this.state, (stat10, resolvedPath) => {
              if (stat10.isDirectory()) {
                resolvedPath = (0, utils_1.normalizePath)(resolvedPath, this.state.options);
                if (exclude && exclude(entry.name, useRealPaths ? resolvedPath : path125 + pathSeparator))
                  return;
                this.walkDirectory(this.state, resolvedPath, useRealPaths ? resolvedPath : path125 + pathSeparator, depth - 1, this.walk);
              } else {
                resolvedPath = useRealPaths ? resolvedPath : path125;
                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_async2 = __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((resolve30, reject) => {
        callback(root, options2, (err, output) => {
          if (err)
            return reject(err);
          resolve30(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_async2();
    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 (_e2) {
    }
    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((path125) => isMatch(path125));
        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_dist7 = __commonJS({
  "packages/core/node_modules/fdir/dist/index.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    var __createBinding = exports2 && exports2.__createBinding || (Object.create ? function(o3, m3, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc2 = Object.getOwnPropertyDescriptor(m3, k2);
      if (!desc2 || ("get" in desc2 ? !m3.__esModule : desc2.writable || desc2.configurable)) {
        desc2 = { enumerable: true, get: /* @__PURE__ */ __name(function() {
          return m3[k2];
        }, "get") };
      }
      Object.defineProperty(o3, k22, desc2);
    } : function(o3, m3, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o3[k22] = m3[k2];
    });
    var __exportStar = exports2 && exports2.__exportStar || function(m3, exports3) {
      for (var p2 in m3) if (p2 !== "default" && !Object.prototype.hasOwnProperty.call(exports3, p2)) __createBinding(exports3, m3, p2);
    };
    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 crypto11 from "node:crypto";
var crawlCache, cacheTimers, getCacheKey, read2, 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 = crypto11.createHash("sha256");
      hash.update(directory);
      hash.update(ignoreContent);
      if (maxDepth !== void 0) {
        hash.update(String(maxDepth));
      }
      return hash.digest("hex");
    }, "getCacheKey");
    read2 = /* @__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 path69 from "node:path";
function toPosixPath(p2) {
  return p2.split(path69.sep).join(path69.posix.sep);
}
async function crawl(options2) {
  if (options2.cache) {
    const cacheKey = getCacheKey(options2.crawlDirectory, options2.ignore.getFingerprint(), options2.maxDepth);
    const cachedResults = read2(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((_2, dirPath) => {
      const relativePath = path69.posix.relative(posixCrawlDirectory, dirPath);
      return dirFilter(`${relativePath}/`);
    });
    if (options2.maxDepth !== void 0) {
      api.withMaxDepth(options2.maxDepth);
    }
    results = await api.crawl(options2.crawlDirectory).withPromise();
  } catch (_e2) {
    return [];
  }
  const relativeToCrawlDir = path69.posix.relative(posixCwd, posixCrawlDirectory);
  const relativeToCwdResults = results.map((p2) => path69.posix.join(relativeToCrawlDir, p2));
  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_dist7(), 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(number4) {
  return number4;
}
function toInt(number4) {
  return number4;
}
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, normalize12, 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 (normalize12) {
      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((v2) => parseInt(v2, 10)).sort((a2, b2) => b2 - a2);
  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 i3 = 0, len = this.runesList.length; i3 < len; ++i3) {
    iter2(i3);
  }
  return getResultFromScoreMap(scoreMap, this.opts.limit);
}
function asyncMatcher(token2, len, iter2, onFinish) {
  return new Promise((resolve30, reject) => {
    const INCREMENT = 1e3;
    let i3 = 0, end = Math.min(INCREMENT, len);
    const step = /* @__PURE__ */ __name(() => {
      if (token2.cancelled)
        return reject("search cancelled");
      for (; i3 < end; ++i3) {
        iter2(i3);
      }
      if (end < len) {
        end = Math.min(end + INCREMENT, len);
        isNode ? setImmediate(step) : setTimeout(step);
      } else {
        resolve30(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((a2, b2) => {
      if (a2.score === b2.score) {
        for (const tiebreaker of opts.tiebreakers) {
          const diff4 = tiebreaker(a2, b2, 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, isNode, 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 i3 = "\u0300".codePointAt(0); i3 <= "\u036F".codePointAt(0); ++i3) {
      const diacritic = String.fromCodePoint(i3);
      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 i3 = ranges[lowerChar][0]; i3 <= ranges[lowerChar][1]; ++i3) {
        normalized[i3] = i3 % 2 === 0 ? upperChar : lowerChar;
      }
    }
    __name(normalizeRune, "normalizeRune");
    __name(toShort, "toShort");
    __name(toInt, "toInt");
    __name(maxInt16, "maxInt16");
    strToRunes = /* @__PURE__ */ __name((str2) => str2.split("").map((s5) => s5.codePointAt(0)), "strToRunes");
    whitespaceRunes = new Set(
      " \f\n\r	\v\xA0\u1680\u2028\u2029\u202F\u205F\u3000\uFEFF".split("").map((v2) => v2.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, normalize12, forward, input, pattern, withPos, slab2) => {
      const M2 = pattern.length;
      if (M2 === 0) {
        return [{ start: 0, end: 0, score: 0 }, createPosSet(withPos)];
      }
      const N2 = input.length;
      if (slab2 !== null && N2 * M2 > slab2.i16.length) {
        return fuzzyMatchV1(caseSensitive, normalize12, 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, B2 = null, F4 = null;
      [offset16, H0] = alloc16(offset16, slab2, N2);
      [offset16, C0] = alloc16(offset16, slab2, N2);
      [offset16, B2] = alloc16(offset16, slab2, N2);
      [offset32, F4] = alloc32(offset32, slab2, M2);
      const [, T2] = alloc32(offset32, slab2, N2);
      for (let i3 = 0; i3 < T2.length; i3++) {
        T2[i3] = input[i3];
      }
      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 = T2.subarray(idx);
      let H0sub = H0.subarray(idx).subarray(0, Tsub.length), C0sub = C0.subarray(idx).subarray(0, Tsub.length), Bsub = B2.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 (normalize12) {
            char = normalizeRune(char);
          }
        }
        Tsub[off] = char;
        const bonus = bonusFor(prevCharClass, charClass);
        Bsub[off] = bonus;
        prevCharClass = charClass;
        if (char === pchar) {
          if (pidx < M2) {
            F4[pidx] = toInt(idx + off);
            pidx++;
            pchar = pattern[Math.min(pidx, M2 - 1)];
          }
          lastIdx = idx + off;
        }
        if (char === pchar0) {
          const score = SCORE_MATCH + bonus * BONUS_FIRST_CHAR_MULTIPLIER;
          H0sub[off] = score;
          C0sub[off] = 1;
          if (M2 === 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 !== M2) {
        return [{ start: -1, end: -1, score: 0 }, null];
      }
      if (M2 === 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 = F4[0];
      const width = lastIdx - f0 + 1;
      let H2 = null;
      [offset16, H2] = alloc16(offset16, slab2, width * M2);
      {
        const toCopy = H0.subarray(f0, lastIdx + 1);
        for (const [i3, v2] of toCopy.entries()) {
          H2[i3] = v2;
        }
      }
      let [, C2] = alloc16(offset16, slab2, width * M2);
      {
        const toCopy = C0.subarray(f0, lastIdx + 1);
        for (const [i3, v2] of toCopy.entries()) {
          C2[i3] = v2;
        }
      }
      const Fsub = F4.subarray(1);
      const Psub = pattern.slice(1).slice(0, Fsub.length);
      for (const [off, f5] of Fsub.entries()) {
        let inGap2 = false;
        const pchar2 = Psub[off], pidx2 = off + 1, row = pidx2 * width, Tsub2 = T2.subarray(f5, lastIdx + 1), Bsub2 = B2.subarray(f5).subarray(0, Tsub2.length), Csub = C2.subarray(row + f5 - f0).subarray(0, Tsub2.length), Cdiag = C2.subarray(row + f5 - f0 - 1 - width).subarray(0, Tsub2.length), Hsub = H2.subarray(row + f5 - f0).subarray(0, Tsub2.length), Hdiag = H2.subarray(row + f5 - f0 - 1 - width).subarray(0, Tsub2.length), Hleft = H2.subarray(row + f5 - f0 - 1).subarray(0, Tsub2.length);
        Hleft[0] = 0;
        for (const [off2, char] of Tsub2.entries()) {
          const col = off2 + f5;
          let s1 = 0, s22 = 0, consecutive = 0;
          if (inGap2) {
            s22 = Hleft[off2] + SCORE_GAP_EXTENTION;
          } else {
            s22 = Hleft[off2] + SCORE_GAP_START;
          }
          if (pchar2 === char) {
            s1 = Hdiag[off2] + SCORE_MATCH;
            let b2 = Bsub2[off2];
            consecutive = Cdiag[off2] + 1;
            if (b2 === BONUS_BOUNDARY) {
              consecutive = 1;
            } else if (consecutive > 1) {
              b2 = maxInt16(b2, maxInt16(BONUS_CONSECUTIVE, B2[col - consecutive + 1]));
            }
            if (s1 + b2 < s22) {
              s1 += Bsub2[off2];
              consecutive = 0;
            } else {
              s1 += b2;
            }
          }
          Csub[off2] = consecutive;
          inGap2 = s1 < s22;
          const score = maxInt16(maxInt16(s1, s22), 0);
          if (pidx2 === M2 - 1 && (forward && score > maxScore || !forward && score >= maxScore)) {
            maxScore = score;
            maxScorePos = col;
          }
          Hsub[off2] = score;
        }
      }
      const pos2 = createPosSet(withPos);
      let j2 = f0;
      if (withPos && pos2 !== null) {
        let i3 = M2 - 1;
        j2 = maxScorePos;
        let preferMatch = true;
        while (true) {
          const I3 = i3 * width, j0 = j2 - f0, s5 = H2[I3 + j0];
          let s1 = 0, s22 = 0;
          if (i3 > 0 && j2 >= F4[i3]) {
            s1 = H2[I3 - width + j0 - 1];
          }
          if (j2 > F4[i3]) {
            s22 = H2[I3 + j0 - 1];
          }
          if (s5 > s1 && (s5 > s22 || s5 === s22 && preferMatch)) {
            pos2.add(j2);
            if (i3 === 0) {
              break;
            }
            i3--;
          }
          preferMatch = C2[I3 + j0] > 1 || I3 + width + j0 + 1 < C2.length && C2[I3 + width + j0 + 1] > 0;
          j2--;
        }
      }
      return [{ start: j2, end: maxScorePos + 1, score: maxScore }, pos2];
    }, "fuzzyMatchV2");
    __name(calculateScore, "calculateScore");
    fuzzyMatchV1 = /* @__PURE__ */ __name((caseSensitive, normalize12, 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 (normalize12) {
          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,
          normalize12,
          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, normalize12, 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 (normalize12) {
          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, normalize12, 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, normalize12) => {
      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 (normalize12) {
        queryRunes = queryRunes.map(normalizeRune);
      }
      return {
        queryRunes,
        caseSensitive
      };
    }, "buildPatternForBasicMatch");
    __name(getResultFromScoreMap, "getResultFromScoreMap");
    __name(getBasicMatchIter, "getBasicMatchIter");
    __name(basicMatch, "basicMatch");
    isNode = typeof __require !== "undefined" && typeof window === "undefined";
    __name(asyncMatcher, "asyncMatcher");
    __name(asyncBasicMatch, "asyncBasicMatch");
    defaultOpts2 = {
      limit: Infinity,
      selector: /* @__PURE__ */ __name((v2) => v2, "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 path70 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 [i3, p2] of allPaths.entries()) {
    if (i3 % 1e3 === 0) {
      await new Promise((resolve30) => setImmediate(resolve30));
      if (signal?.aborted) {
        throw new AbortError2();
      }
    }
    if (patternFilter(p2)) {
      results.push(p2);
    }
  }
  results.sort((a2, b2) => {
    const aIsDir = a2.endsWith("/");
    const bIsDir = b2.endsWith("/");
    if (aIsDir && !bIsDir)
      return -1;
    if (!aIsDir && bIsDir)
      return 1;
    return a2 < b2 ? -1 : a2 > b2 ? 1 : 0;
  });
  return results;
}
var import_picomatch2, AbortError2, 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();
    AbortError2 = 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.enableFuzzySearch !== false || !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 [i3, candidate] of filteredCandidates.entries()) {
          if (i3 % 1e3 === 0) {
            await new Promise((resolve30) => setImmediate(resolve30));
            if (options2.signal?.aborted) {
              throw new AbortError2();
            }
          }
          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.enableFuzzySearch !== false) {
          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 : path70.dirname(pattern);
        const results = await crawl({
          crawlDirectory: path70.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/subagentGenerator.js
async function subagentGenerator(userDescription, config2, 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 config2.getBaseLlmClient().generateJson({
    model: config2.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 fs67 from "fs/promises";
import * as path71 from "path";
async function getProjectSummaryInfo() {
  const summaryPath = path71.join(process.cwd(), ".qwen", "PROJECT_SUMMARY.md");
  try {
    await fs67.access(summaryPath);
  } catch {
    return {
      hasHistory: false
    };
  }
  try {
    const content = await fs67.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 date4 = new Date(timestamp2);
      const now = /* @__PURE__ */ new Date();
      const diffMs = now.getTime() - date4.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/utils/promptIdContext.js
import { AsyncLocalStorage as AsyncLocalStorage2 } from "node:async_hooks";
var promptIdContext;
var init_promptIdContext = __esm({
  "packages/core/dist/src/utils/promptIdContext.js"() {
    "use strict";
    init_esbuild_shims();
    promptIdContext = new AsyncLocalStorage2();
  }
});

// packages/core/dist/src/ide/ide-installer.js
import * as child_process from "node:child_process";
import * as process15 from "node:process";
import * as path72 from "node:path";
import * as fs68 from "node:fs";
import * as os23 from "node:os";
function getVsCodeCommand(platform16 = process15.platform) {
  return platform16 === "win32" ? "code.cmd" : "code";
}
async function findVsCodeCommand(platform16 = process15.platform) {
  const vscodeCommand = getVsCodeCommand(platform16);
  try {
    if (platform16 === "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 = os23.homedir();
  if (platform16 === "darwin") {
    locations.push("/Applications/Visual Studio Code.app/Contents/Resources/app/bin/code", path72.join(homeDir, "Library/Application Support/Code/bin/code"));
  } else if (platform16 === "linux") {
    locations.push("/usr/share/code/bin/code", "/snap/bin/code", path72.join(homeDir, ".local/share/code/bin/code"));
  } else if (platform16 === "win32") {
    locations.push(path72.join(process15.env["ProgramFiles"] || "C:\\Program Files", "Microsoft VS Code", "bin", "code.cmd"), path72.join(homeDir, "AppData", "Local", "Programs", "Microsoft VS Code", "bin", "code.cmd"));
  }
  for (const location of locations) {
    if (fs68.existsSync(location)) {
      return location;
    }
  }
  return null;
}
function getIdeInstaller(ide, platform16 = process15.platform) {
  switch (ide.name) {
    case IDE_DEFINITIONS.vscode.name:
    case IDE_DEFINITIONS.firebasestudio.name:
      return new VsCodeInstaller(ide, platform16);
    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_constants5();
    __name(getVsCodeCommand, "getVsCodeCommand");
    __name(findVsCodeCommand, "findVsCodeCommand");
    VsCodeInstaller = class {
      static {
        __name(this, "VsCodeInstaller");
      }
      ideInfo;
      platform;
      vsCodeCommand;
      constructor(ideInfo, platform16 = process15.platform) {
        this.ideInfo = ideInfo;
        this.platform = platform16;
        this.vsCodeCommand = findVsCodeCommand(platform16);
      }
      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 isWindows9 = process15.platform === "win32";
        try {
          const result = child_process.spawnSync(isWindows9 ? `"${commandPath}"` : commandPath, [
            "--install-extension",
            "qwenlm.qwen-code-vscode-ide-companion",
            "--force"
          ], { stdio: "pipe", shell: isWindows9 });
          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_types5();
    init_builtin_agents();
    init_validation();
    init_subagent_manager();
    init_subagent();
    init_subagent_events();
  }
});

// packages/core/dist/src/skills/index.js
var init_skills = __esm({
  "packages/core/dist/src/skills/index.js"() {
    "use strict";
    init_esbuild_shims();
    init_types11();
    init_skill_manager();
  }
});

// packages/core/dist/src/extension/marketplace.js
import * as fs69 from "node:fs";
import * as path73 from "node:path";
import * as https5 from "node:https";
import { stat as stat7 } from "node:fs/promises";
function parseSourceAndPluginName(source2) {
  const urlSchemes = ["http://", "https://", "git@", "sso://"];
  let repoEndIndex = source2.length;
  let hasPluginName = false;
  for (const scheme of urlSchemes) {
    if (source2.startsWith(scheme)) {
      const afterScheme = source2.substring(scheme.length);
      const lastColonIndex = afterScheme.lastIndexOf(":");
      if (lastColonIndex !== -1) {
        const potentialPluginName = afterScheme.substring(lastColonIndex + 1);
        if (potentialPluginName && !potentialPluginName.includes("/") && !/^\d+/.test(potentialPluginName)) {
          repoEndIndex = scheme.length + lastColonIndex;
          hasPluginName = true;
        }
      }
      break;
    }
  }
  if (repoEndIndex === source2.length && !urlSchemes.some((s5) => source2.startsWith(s5))) {
    const lastColonIndex = source2.lastIndexOf(":");
    if (lastColonIndex > 1) {
      repoEndIndex = lastColonIndex;
      hasPluginName = true;
    }
  }
  if (hasPluginName) {
    return {
      repo: source2.substring(0, repoEndIndex),
      pluginName: source2.substring(repoEndIndex + 1)
    };
  }
  return { repo: source2 };
}
function isOwnerRepoFormat(source2) {
  const ownerRepoRegex = /^[a-zA-Z0-9_.-]+\/[a-zA-Z0-9_.-]+$/;
  return ownerRepoRegex.test(source2);
}
function convertOwnerRepoToGitHubUrl(ownerRepo) {
  return `https://github.com/${ownerRepo}`;
}
function isGitUrl(source2) {
  return source2.startsWith("http://") || source2.startsWith("https://") || source2.startsWith("git@") || source2.startsWith("sso://");
}
function fetchUrl(url2, headers) {
  return new Promise((resolve30) => {
    https5.get(url2, { headers }, (res) => {
      if (res.statusCode !== 200) {
        resolve30(null);
        return;
      }
      const chunks = [];
      res.on("data", (chunk) => chunks.push(chunk));
      res.on("end", () => {
        resolve30(Buffer.concat(chunks).toString());
      });
    }).on("error", () => resolve30(null));
  });
}
async function fetchGitHubMarketplaceConfig(owner, repo) {
  const token2 = process.env["GITHUB_TOKEN"];
  const apiUrl = `https://api.github.com/repos/${owner}/${repo}/contents/.claude-plugin/marketplace.json`;
  const apiHeaders = {
    "User-Agent": "qwen-code",
    Accept: "application/vnd.github.v3.raw"
  };
  if (token2) {
    apiHeaders["Authorization"] = `token ${token2}`;
  }
  let content = await fetchUrl(apiUrl, apiHeaders);
  if (!content) {
    const rawUrl = `https://raw.githubusercontent.com/${owner}/${repo}/HEAD/.claude-plugin/marketplace.json`;
    const rawHeaders = {
      "User-Agent": "qwen-code"
    };
    content = await fetchUrl(rawUrl, rawHeaders);
  }
  if (!content) {
    return null;
  }
  try {
    return JSON.parse(content);
  } catch {
    return null;
  }
}
async function readLocalMarketplaceConfig(localPath) {
  const marketplaceConfigPath = path73.join(localPath, ".claude-plugin", "marketplace.json");
  try {
    const content = await fs69.promises.readFile(marketplaceConfigPath, "utf-8");
    return JSON.parse(content);
  } catch {
    return null;
  }
}
async function parseInstallSource(source2) {
  const { repo, pluginName } = parseSourceAndPluginName(source2);
  let installMetadata;
  let repoSource = repo;
  let marketplaceConfig = null;
  let isLocalPath = false;
  try {
    await stat7(repo);
    isLocalPath = true;
  } catch {
  }
  if (isLocalPath) {
    installMetadata = {
      source: repo,
      type: "local",
      pluginName
    };
    marketplaceConfig = await readLocalMarketplaceConfig(repo);
  } else if (isGitUrl(repo)) {
    installMetadata = {
      source: repoSource,
      type: "git",
      pluginName
    };
    try {
      const { owner, repo: repoName } = parseGitHubRepoForReleases(repoSource);
      marketplaceConfig = await fetchGitHubMarketplaceConfig(owner, repoName);
    } catch {
    }
  } else if (isOwnerRepoFormat(repo)) {
    repoSource = convertOwnerRepoToGitHubUrl(repo);
    installMetadata = {
      source: repoSource,
      type: "git",
      pluginName
    };
    try {
      const [owner, repoName] = repo.split("/");
      marketplaceConfig = await fetchGitHubMarketplaceConfig(owner, repoName);
    } catch {
    }
  } else {
    throw new Error(`Install source not found: ${repo}`);
  }
  if (marketplaceConfig) {
    installMetadata.marketplaceConfig = marketplaceConfig;
    installMetadata.originSource = "Claude";
  }
  return installMetadata;
}
var init_marketplace = __esm({
  "packages/core/dist/src/extension/marketplace.js"() {
    "use strict";
    init_esbuild_shims();
    init_github();
    __name(parseSourceAndPluginName, "parseSourceAndPluginName");
    __name(isOwnerRepoFormat, "isOwnerRepoFormat");
    __name(convertOwnerRepoToGitHubUrl, "convertOwnerRepoToGitHubUrl");
    __name(isGitUrl, "isGitUrl");
    __name(fetchUrl, "fetchUrl");
    __name(fetchGitHubMarketplaceConfig, "fetchGitHubMarketplaceConfig");
    __name(readLocalMarketplaceConfig, "readLocalMarketplaceConfig");
    __name(parseInstallSource, "parseInstallSource");
  }
});

// packages/core/dist/src/extension/index.js
var init_extension = __esm({
  "packages/core/dist/src/extension/index.js"() {
    "use strict";
    init_esbuild_shims();
    init_extensionManager();
    init_variables();
    init_github();
    init_extensionSettings();
    init_marketplace();
    init_claude_converter();
  }
});

// packages/core/dist/src/prompts/mcp-prompts.js
function getMCPServerPrompts(config2, serverName) {
  const promptRegistry = config2.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/lsp/constants.js
var DEFAULT_LSP_STARTUP_TIMEOUT_MS, DEFAULT_LSP_REQUEST_TIMEOUT_MS, DEFAULT_LSP_WARMUP_DELAY_MS, DEFAULT_LSP_COMMAND_CHECK_TIMEOUT_MS, DEFAULT_LSP_MAX_RESTARTS, DEFAULT_LSP_SOCKET_RETRY_DELAY_MS, DEFAULT_LSP_SOCKET_MAX_RETRY_DELAY_MS, SYMBOL_KIND_LABELS, DIAGNOSTIC_SEVERITY_LABELS, CODE_ACTION_KIND_LABELS;
var init_constants8 = __esm({
  "packages/core/dist/src/lsp/constants.js"() {
    "use strict";
    init_esbuild_shims();
    DEFAULT_LSP_STARTUP_TIMEOUT_MS = 1e4;
    DEFAULT_LSP_REQUEST_TIMEOUT_MS = 15e3;
    DEFAULT_LSP_WARMUP_DELAY_MS = 150;
    DEFAULT_LSP_COMMAND_CHECK_TIMEOUT_MS = 2e3;
    DEFAULT_LSP_MAX_RESTARTS = 3;
    DEFAULT_LSP_SOCKET_RETRY_DELAY_MS = 250;
    DEFAULT_LSP_SOCKET_MAX_RETRY_DELAY_MS = 1e3;
    SYMBOL_KIND_LABELS = {
      1: "File",
      2: "Module",
      3: "Namespace",
      4: "Package",
      5: "Class",
      6: "Method",
      7: "Property",
      8: "Field",
      9: "Constructor",
      10: "Enum",
      11: "Interface",
      12: "Function",
      13: "Variable",
      14: "Constant",
      15: "String",
      16: "Number",
      17: "Boolean",
      18: "Array",
      19: "Object",
      20: "Key",
      21: "Null",
      22: "EnumMember",
      23: "Struct",
      24: "Event",
      25: "Operator",
      26: "TypeParameter"
    };
    DIAGNOSTIC_SEVERITY_LABELS = {
      1: "error",
      2: "warning",
      3: "information",
      4: "hint"
    };
    CODE_ACTION_KIND_LABELS = {
      "": "quickfix",
      quickfix: "quickfix",
      refactor: "refactor",
      "refactor.extract": "refactor.extract",
      "refactor.inline": "refactor.inline",
      "refactor.rewrite": "refactor.rewrite",
      source: "source",
      "source.organizeImports": "source.organizeImports",
      "source.fixAll": "source.fixAll"
    };
  }
});

// packages/core/dist/src/lsp/LspConfigLoader.js
import * as fs70 from "node:fs";
import * as path74 from "path";
import { pathToFileURL as pathToFileURL3 } from "url";
var debugLogger66, LspConfigLoader;
var init_LspConfigLoader = __esm({
  "packages/core/dist/src/lsp/LspConfigLoader.js"() {
    "use strict";
    init_esbuild_shims();
    init_variables();
    init_debugLogger();
    debugLogger66 = createDebugLogger("LSP");
    LspConfigLoader = class {
      static {
        __name(this, "LspConfigLoader");
      }
      workspaceRoot;
      constructor(workspaceRoot) {
        this.workspaceRoot = workspaceRoot;
      }
      /**
       * Load user .lsp.json configuration.
       * Supports basic format: { "language": { "command": "...", "extensionToLanguage": {...} } }
       */
      async loadUserConfigs() {
        const lspConfigPath = path74.join(this.workspaceRoot, ".lsp.json");
        if (!fs70.existsSync(lspConfigPath)) {
          return [];
        }
        try {
          const configContent = fs70.readFileSync(lspConfigPath, "utf-8");
          const data = JSON.parse(configContent);
          return this.parseConfigSource(data, lspConfigPath);
        } catch (error2) {
          debugLogger66.warn("Failed to load user .lsp.json config:", error2);
          return [];
        }
      }
      /**
       * Load LSP configurations declared by extensions (Claude plugins).
       */
      async loadExtensionConfigs(extensions) {
        const configs = [];
        for (const extension of extensions) {
          const lspServers = extension.config?.lspServers;
          if (!lspServers) {
            continue;
          }
          const originBase = `extension ${extension.name}`;
          if (typeof lspServers === "string") {
            const configPath = this.resolveExtensionConfigPath(extension.path, lspServers);
            if (!fs70.existsSync(configPath)) {
              debugLogger66.warn(`LSP config not found for ${originBase}: ${configPath}`);
              continue;
            }
            try {
              const configContent = fs70.readFileSync(configPath, "utf-8");
              const data = JSON.parse(configContent);
              const hydrated = this.hydrateExtensionLspConfig(data, extension.path);
              configs.push(...this.parseConfigSource(hydrated, `${originBase} (${configPath})`));
            } catch (error2) {
              debugLogger66.warn(`Failed to load extension LSP config from ${configPath}:`, error2);
            }
          } else if (this.isRecord(lspServers)) {
            const hydrated = this.hydrateExtensionLspConfig(lspServers, extension.path);
            configs.push(...this.parseConfigSource(hydrated, `${originBase} (lspServers)`));
          } else {
            debugLogger66.warn(`LSP config for ${originBase} must be an object or a JSON file path.`);
          }
        }
        return configs;
      }
      /**
       * Merge configs: built-in presets + extension configs + user configs
       */
      mergeConfigs(detectedLanguages, extensionConfigs, userConfigs) {
        const presets = this.getBuiltInPresets(detectedLanguages);
        const mergedConfigs = [...presets];
        const applyConfigs = /* @__PURE__ */ __name((configs) => {
          for (const config2 of configs) {
            const existingIndex = mergedConfigs.findIndex((c4) => c4.name === config2.name);
            if (existingIndex !== -1) {
              mergedConfigs[existingIndex] = config2;
            } else {
              mergedConfigs.push(config2);
            }
          }
        }, "applyConfigs");
        applyConfigs(extensionConfigs);
        applyConfigs(userConfigs);
        return mergedConfigs;
      }
      collectExtensionToLanguageOverrides(configs) {
        const overrides = {};
        for (const config2 of configs) {
          if (!config2.extensionToLanguage) {
            continue;
          }
          for (const [key, value] of Object.entries(config2.extensionToLanguage)) {
            if (typeof value !== "string") {
              continue;
            }
            const normalized2 = key.startsWith(".") ? key.slice(1) : key;
            if (!normalized2) {
              continue;
            }
            overrides[normalized2.toLowerCase()] = value;
          }
        }
        return overrides;
      }
      /**
       * Get built-in preset configurations
       */
      getBuiltInPresets(detectedLanguages) {
        const presets = [];
        const rootUri = pathToFileURL3(this.workspaceRoot).toString();
        if (detectedLanguages.includes("typescript") || detectedLanguages.includes("javascript")) {
          presets.push({
            name: "typescript-language-server",
            languages: [
              "typescript",
              "javascript",
              "typescriptreact",
              "javascriptreact"
            ],
            command: "typescript-language-server",
            args: ["--stdio"],
            transport: "stdio",
            initializationOptions: {},
            rootUri,
            workspaceFolder: this.workspaceRoot,
            trustRequired: true
          });
        }
        if (detectedLanguages.includes("python")) {
          presets.push({
            name: "pylsp",
            languages: ["python"],
            command: "pylsp",
            args: [],
            transport: "stdio",
            initializationOptions: {},
            rootUri,
            workspaceFolder: this.workspaceRoot,
            trustRequired: true
          });
        }
        if (detectedLanguages.includes("go")) {
          presets.push({
            name: "gopls",
            languages: ["go"],
            command: "gopls",
            args: [],
            transport: "stdio",
            initializationOptions: {},
            rootUri,
            workspaceFolder: this.workspaceRoot,
            trustRequired: true
          });
        }
        return presets;
      }
      /**
       * Parse configuration source and extract server configs.
       * Expects basic format keyed by language identifier.
       */
      parseConfigSource(source2, origin) {
        if (!this.isRecord(source2)) {
          return [];
        }
        const configs = [];
        for (const [key, spec] of Object.entries(source2)) {
          if (!this.isRecord(spec)) {
            continue;
          }
          const languages = [key];
          const name3 = typeof spec["command"] === "string" ? spec["command"] : key;
          const config2 = this.buildServerConfig(name3, languages, spec, origin);
          if (config2) {
            configs.push(config2);
          }
        }
        return configs;
      }
      resolveExtensionConfigPath(extensionPath, configPath) {
        return path74.isAbsolute(configPath) ? path74.resolve(configPath) : path74.resolve(extensionPath, configPath);
      }
      hydrateExtensionLspConfig(source2, extensionPath) {
        return recursivelyHydrateStrings(source2, {
          extensionPath,
          CLAUDE_PLUGIN_ROOT: extensionPath,
          workspacePath: this.workspaceRoot,
          "/": path74.sep,
          pathSeparator: path74.sep
        });
      }
      buildServerConfig(name3, languages, spec, origin) {
        const transport = this.normalizeTransport(spec["transport"]);
        const command2 = typeof spec["command"] === "string" ? spec["command"] : void 0;
        const args = this.normalizeStringArray(spec["args"]) ?? [];
        const env7 = this.normalizeEnv(spec["env"]);
        const initializationOptions = this.isRecord(spec["initializationOptions"]) ? spec["initializationOptions"] : void 0;
        const settings = this.isRecord(spec["settings"]) ? spec["settings"] : void 0;
        const extensionToLanguage = this.normalizeExtensionToLanguage(spec["extensionToLanguage"]);
        const workspaceFolder = this.resolveWorkspaceFolder(spec["workspaceFolder"]);
        const rootUri = pathToFileURL3(workspaceFolder).toString();
        const startupTimeout = this.normalizeTimeout(spec["startupTimeout"]);
        const shutdownTimeout = this.normalizeTimeout(spec["shutdownTimeout"]);
        const restartOnCrash = typeof spec["restartOnCrash"] === "boolean" ? spec["restartOnCrash"] : void 0;
        const maxRestarts = this.normalizeMaxRestarts(spec["maxRestarts"]);
        const trustRequired = typeof spec["trustRequired"] === "boolean" ? spec["trustRequired"] : true;
        const socket = this.normalizeSocketOptions(spec);
        if (transport === "stdio" && !command2) {
          debugLogger66.warn(`LSP config error in ${origin}: ${name3} missing command`);
          return null;
        }
        if (transport !== "stdio" && !socket) {
          debugLogger66.warn(`LSP config error in ${origin}: ${name3} missing socket info`);
          return null;
        }
        return {
          name: name3,
          languages,
          command: command2,
          args,
          transport,
          env: env7,
          initializationOptions,
          settings,
          extensionToLanguage,
          rootUri,
          workspaceFolder,
          startupTimeout,
          shutdownTimeout,
          restartOnCrash,
          maxRestarts,
          trustRequired,
          socket
        };
      }
      isRecord(value) {
        return typeof value === "object" && value !== null && !Array.isArray(value);
      }
      normalizeStringArray(value) {
        if (!Array.isArray(value)) {
          return void 0;
        }
        return value.filter((item) => typeof item === "string");
      }
      normalizeEnv(value) {
        if (!this.isRecord(value)) {
          return void 0;
        }
        const env7 = {};
        for (const [key, val] of Object.entries(value)) {
          if (typeof val === "string" || typeof val === "number" || typeof val === "boolean") {
            env7[key] = String(val);
          }
        }
        return Object.keys(env7).length > 0 ? env7 : void 0;
      }
      normalizeExtensionToLanguage(value) {
        if (!this.isRecord(value)) {
          return void 0;
        }
        const mapping = {};
        for (const [key, lang] of Object.entries(value)) {
          if (typeof lang !== "string") {
            continue;
          }
          const normalized2 = key.startsWith(".") ? key.slice(1) : key;
          if (!normalized2) {
            continue;
          }
          mapping[normalized2.toLowerCase()] = lang;
        }
        return Object.keys(mapping).length > 0 ? mapping : void 0;
      }
      normalizeTransport(value) {
        if (typeof value !== "string") {
          return "stdio";
        }
        const normalized2 = value.toLowerCase();
        if (normalized2 === "tcp" || normalized2 === "socket") {
          return normalized2;
        }
        return "stdio";
      }
      normalizeTimeout(value) {
        if (typeof value !== "number") {
          return void 0;
        }
        if (!Number.isFinite(value) || value <= 0) {
          return void 0;
        }
        return value;
      }
      normalizeMaxRestarts(value) {
        if (typeof value !== "number") {
          return void 0;
        }
        if (!Number.isFinite(value) || value < 0) {
          return void 0;
        }
        return value;
      }
      normalizeSocketOptions(value) {
        const socketValue = value["socket"];
        if (typeof socketValue === "string") {
          return { path: socketValue };
        }
        const source2 = this.isRecord(socketValue) ? socketValue : value;
        const host = typeof source2["host"] === "string" ? source2["host"] : void 0;
        const pathValue = typeof source2["path"] === "string" ? source2["path"] : typeof source2["socketPath"] === "string" ? source2["socketPath"] : void 0;
        const portValue = source2["port"];
        const port = typeof portValue === "number" ? portValue : typeof portValue === "string" ? Number(portValue) : void 0;
        const socket = {};
        if (host) {
          socket.host = host;
        }
        if (Number.isFinite(port) && port > 0) {
          socket.port = port;
        }
        if (pathValue) {
          socket.path = pathValue;
        }
        if (!socket.path && !socket.port) {
          return void 0;
        }
        return socket;
      }
      resolveWorkspaceFolder(value) {
        if (typeof value !== "string" || value.trim() === "") {
          return this.workspaceRoot;
        }
        const resolved = path74.isAbsolute(value) ? path74.resolve(value) : path74.resolve(this.workspaceRoot, value);
        const root = path74.resolve(this.workspaceRoot);
        if (resolved === root || resolved.startsWith(root + path74.sep)) {
          return resolved;
        }
        debugLogger66.warn(`LSP workspaceFolder must be within ${this.workspaceRoot}; using workspace root instead.`);
        return this.workspaceRoot;
      }
    };
  }
});

// packages/core/dist/src/lsp/LspConnectionFactory.js
import * as cp from "node:child_process";
import * as net from "node:net";
var debugLogger67, JsonRpcConnection, LspConnectionFactory;
var init_LspConnectionFactory = __esm({
  "packages/core/dist/src/lsp/LspConnectionFactory.js"() {
    "use strict";
    init_esbuild_shims();
    init_constants8();
    init_debugLogger();
    debugLogger67 = createDebugLogger("LSP");
    JsonRpcConnection = class {
      static {
        __name(this, "JsonRpcConnection");
      }
      writer;
      disposer;
      buffer = "";
      nextId = 1;
      disposed = false;
      pendingRequests = /* @__PURE__ */ new Map();
      notificationHandlers = [];
      requestHandlers = [];
      constructor(writer, disposer) {
        this.writer = writer;
        this.disposer = disposer;
      }
      listen(readable) {
        readable.on("data", (chunk) => this.handleData(chunk));
        readable.on("error", (error2) => this.disposePending(error2 instanceof Error ? error2 : new Error(String(error2))));
      }
      send(message) {
        this.writeMessage(message);
      }
      onNotification(handler) {
        this.notificationHandlers.push(handler);
      }
      onRequest(handler) {
        this.requestHandlers.push(handler);
      }
      async initialize(params) {
        return this.sendRequest("initialize", params);
      }
      async shutdown() {
        try {
          await this.sendRequest("shutdown", {});
        } catch (_error) {
        } finally {
          this.end();
        }
      }
      request(method, params) {
        return this.sendRequest(method, params);
      }
      end() {
        if (this.disposed) {
          return;
        }
        this.disposed = true;
        this.disposePending();
        this.disposer?.();
      }
      sendRequest(method, params) {
        if (this.disposed) {
          return Promise.resolve(void 0);
        }
        const id = this.nextId++;
        const payload = {
          jsonrpc: "2.0",
          id,
          method,
          params
        };
        const requestPromise = new Promise((resolve30, reject) => {
          const timer = setTimeout(() => {
            this.pendingRequests.delete(id);
            reject(new Error(`LSP request timeout: ${method}`));
          }, DEFAULT_LSP_REQUEST_TIMEOUT_MS);
          this.pendingRequests.set(id, { resolve: resolve30, reject, timer });
        });
        this.writeMessage(payload);
        return requestPromise;
      }
      async handleServerRequest(message) {
        const handler = this.requestHandlers[this.requestHandlers.length - 1];
        if (!handler) {
          this.writeMessage({
            jsonrpc: "2.0",
            id: message.id,
            error: {
              code: -32601,
              message: `Method not supported: ${message.method}`
            }
          });
          return;
        }
        try {
          const result = await handler(message);
          this.writeMessage({
            jsonrpc: "2.0",
            id: message.id,
            result: result ?? null
          });
        } catch (error2) {
          this.writeMessage({
            jsonrpc: "2.0",
            id: message.id,
            error: {
              code: -32603,
              message: error2.message ?? "Internal error"
            }
          });
        }
      }
      handleData(chunk) {
        if (this.disposed) {
          return;
        }
        this.buffer += chunk.toString("utf8");
        while (true) {
          const headerEnd = this.buffer.indexOf("\r\n\r\n");
          if (headerEnd === -1) {
            break;
          }
          const header = this.buffer.slice(0, headerEnd);
          const lengthMatch = /Content-Length:\s*(\d+)/i.exec(header);
          if (!lengthMatch) {
            this.buffer = this.buffer.slice(headerEnd + 4);
            continue;
          }
          const contentLength = Number(lengthMatch[1]);
          const messageStart = headerEnd + 4;
          const messageEnd = messageStart + contentLength;
          if (this.buffer.length < messageEnd) {
            break;
          }
          const body = this.buffer.slice(messageStart, messageEnd);
          this.buffer = this.buffer.slice(messageEnd);
          try {
            const message = JSON.parse(body);
            this.routeMessage(message);
          } catch {
          }
        }
      }
      routeMessage(message) {
        if (typeof message?.id !== "undefined" && !message.method) {
          const pending = this.pendingRequests.get(message.id);
          if (!pending) {
            return;
          }
          clearTimeout(pending.timer);
          this.pendingRequests.delete(message.id);
          if (message.error) {
            pending.reject(new Error(message.error.message || "LSP request failed"));
          } else {
            pending.resolve(message.result);
          }
          return;
        }
        if (message?.method && typeof message.id !== "undefined") {
          void this.handleServerRequest(message);
          return;
        }
        if (message?.method) {
          for (const handler of this.notificationHandlers) {
            try {
              handler(message);
            } catch {
            }
          }
        }
      }
      writeMessage(message) {
        if (this.disposed) {
          return;
        }
        const json2 = JSON.stringify(message);
        const header = `Content-Length: ${Buffer.byteLength(json2, "utf8")}\r
\r
`;
        this.writer(header + json2);
      }
      disposePending(error2) {
        for (const [, pending] of Array.from(this.pendingRequests)) {
          clearTimeout(pending.timer);
          pending.reject(error2 ?? new Error("LSP connection closed"));
        }
        this.pendingRequests.clear();
      }
    };
    LspConnectionFactory = class _LspConnectionFactory {
      static {
        __name(this, "LspConnectionFactory");
      }
      /**
       * 创建基于 stdio 的 LSP 连接
       */
      static async createStdioConnection(command2, args, options2, timeoutMs = 1e4) {
        return new Promise((resolve30, reject) => {
          const spawnOptions = {
            stdio: "pipe",
            ...options2
          };
          const processInstance = cp.spawn(command2, args, spawnOptions);
          const timeoutId = setTimeout(() => {
            reject(new Error("LSP server spawn timeout"));
            if (!processInstance.killed) {
              processInstance.kill();
            }
          }, timeoutMs);
          processInstance.once("error", (error2) => {
            clearTimeout(timeoutId);
            reject(new Error(`Failed to spawn LSP server: ${error2.message}`));
          });
          processInstance.once("spawn", () => {
            clearTimeout(timeoutId);
            if (!processInstance.stdout || !processInstance.stdin) {
              reject(new Error("LSP server stdio not available"));
              return;
            }
            const connection = new JsonRpcConnection((payload) => processInstance.stdin?.write(payload), () => processInstance.stdin?.end());
            connection.listen(processInstance.stdout);
            processInstance.once("exit", () => connection.end());
            processInstance.once("close", () => connection.end());
            resolve30({
              connection,
              process: processInstance
            });
          });
        });
      }
      /**
       * 创建基于 TCP 的 LSP 连接
       */
      static async createTcpConnection(host, port, timeoutMs = 1e4) {
        return _LspConnectionFactory.createSocketConnection({ host, port }, timeoutMs);
      }
      /**
       * 创建基于 socket 的 LSP 连接（支持 TCP 或 unix socket）
       */
      static async createSocketConnection(options2, timeoutMs = 1e4) {
        return new Promise((resolve30, reject) => {
          let socketOptions;
          if (options2.path) {
            socketOptions = { path: options2.path };
          } else {
            if (!options2.port) {
              reject(new Error("Socket transport requires port or path"));
              return;
            }
            socketOptions = {
              host: options2.host ?? "127.0.0.1",
              port: options2.port
            };
          }
          const socket = net.createConnection(socketOptions);
          const timeoutId = setTimeout(() => {
            reject(new Error("LSP server connection timeout"));
            socket.destroy();
          }, timeoutMs);
          const onError2 = /* @__PURE__ */ __name((error2) => {
            clearTimeout(timeoutId);
            reject(new Error(`Failed to connect to LSP server: ${error2.message}`));
          }, "onError");
          socket.once("error", onError2);
          socket.on("connect", () => {
            clearTimeout(timeoutId);
            socket.off("error", onError2);
            const connection = new JsonRpcConnection((payload) => socket.write(payload), () => socket.destroy());
            connection.listen(socket);
            socket.once("close", () => connection.end());
            socket.once("error", () => connection.end());
            resolve30({
              connection,
              socket
            });
          });
        });
      }
      /**
       * 关闭 LSP 连接
       */
      static async closeConnection(lspConnection) {
        if (lspConnection.connection) {
          try {
            await lspConnection.connection.shutdown();
          } catch (e4) {
            debugLogger67.warn("LSP shutdown failed:", e4);
          } finally {
            lspConnection.connection.end();
          }
        }
        if (lspConnection.process && !lspConnection.process.killed) {
          lspConnection.process.kill();
        }
        if (lspConnection.socket && !lspConnection.socket.destroyed) {
          lspConnection.socket.destroy();
        }
      }
    };
  }
});

// packages/core/dist/src/lsp/LspLanguageDetector.js
import * as fs71 from "node:fs";
import * as path75 from "path";
var DEFAULT_EXTENSION_TO_LANGUAGE, MARKER_TO_LANGUAGE, COMMON_MARKERS, DEFAULT_EXCLUDE_PATTERNS, LspLanguageDetector;
var init_LspLanguageDetector = __esm({
  "packages/core/dist/src/lsp/LspLanguageDetector.js"() {
    "use strict";
    init_esbuild_shims();
    init_esm11();
    DEFAULT_EXTENSION_TO_LANGUAGE = {
      js: "javascript",
      ts: "typescript",
      jsx: "javascriptreact",
      tsx: "typescriptreact",
      py: "python",
      go: "go",
      rs: "rust",
      java: "java",
      cpp: "cpp",
      c: "c",
      php: "php",
      rb: "ruby",
      cs: "csharp",
      vue: "vue",
      svelte: "svelte",
      html: "html",
      css: "css",
      json: "json",
      yaml: "yaml",
      yml: "yaml"
    };
    MARKER_TO_LANGUAGE = {
      "package.json": "javascript",
      "tsconfig.json": "typescript",
      "pyproject.toml": "python",
      "go.mod": "go",
      "Cargo.toml": "rust",
      "pom.xml": "java",
      "build.gradle": "java",
      "composer.json": "php",
      Gemfile: "ruby",
      "*.sln": "csharp",
      "mix.exs": "elixir",
      "deno.json": "deno"
    };
    COMMON_MARKERS = [
      "package.json",
      "tsconfig.json",
      "pyproject.toml",
      "go.mod",
      "Cargo.toml",
      "pom.xml",
      "build.gradle",
      "composer.json",
      "Gemfile",
      "mix.exs",
      "deno.json"
    ];
    DEFAULT_EXCLUDE_PATTERNS = [
      "**/node_modules/**",
      "**/.git/**",
      "**/dist/**",
      "**/build/**"
    ];
    LspLanguageDetector = class {
      static {
        __name(this, "LspLanguageDetector");
      }
      workspaceContext;
      fileDiscoveryService;
      constructor(workspaceContext, fileDiscoveryService) {
        this.workspaceContext = workspaceContext;
        this.fileDiscoveryService = fileDiscoveryService;
      }
      /**
       * Detect programming languages in workspace by analyzing files and markers.
       * Returns languages sorted by frequency (most common first).
       *
       * @param extensionOverrides - Custom extension to language mappings
       * @returns Array of detected language IDs
       */
      async detectLanguages(extensionOverrides = {}) {
        const extensionMap = this.getExtensionToLanguageMap(extensionOverrides);
        const extensions = Object.keys(extensionMap);
        const patterns = extensions.length > 0 ? [`**/*.{${extensions.join(",")}}`] : ["**/*"];
        const files = /* @__PURE__ */ new Set();
        const searchRoots = this.workspaceContext.getDirectories();
        for (const root of searchRoots) {
          for (const pattern of patterns) {
            try {
              const matches = globSync(pattern, {
                cwd: root,
                ignore: DEFAULT_EXCLUDE_PATTERNS,
                absolute: true,
                nodir: true
              });
              for (const match2 of matches) {
                if (this.fileDiscoveryService.shouldIgnoreFile(match2)) {
                  continue;
                }
                files.add(match2);
              }
            } catch {
            }
          }
        }
        const languageCounts = /* @__PURE__ */ new Map();
        for (const file of Array.from(files)) {
          const ext2 = path75.extname(file).slice(1).toLowerCase();
          if (ext2) {
            const lang = this.mapExtensionToLanguage(ext2, extensionMap);
            if (lang) {
              languageCounts.set(lang, (languageCounts.get(lang) || 0) + 1);
            }
          }
        }
        const rootMarkers = await this.detectRootMarkers();
        for (const marker of rootMarkers) {
          const lang = this.mapMarkerToLanguage(marker);
          if (lang) {
            const currentCount = languageCounts.get(lang) || 0;
            languageCounts.set(lang, currentCount + 100);
          }
        }
        return Array.from(languageCounts.entries()).sort((a2, b2) => b2[1] - a2[1]).map(([lang]) => lang);
      }
      /**
       * Detect root marker files in workspace directories
       */
      async detectRootMarkers() {
        const markers = /* @__PURE__ */ new Set();
        for (const root of this.workspaceContext.getDirectories()) {
          for (const marker of COMMON_MARKERS) {
            try {
              const fullPath = path75.join(root, marker);
              if (fs71.existsSync(fullPath)) {
                markers.add(marker);
              }
            } catch {
            }
          }
        }
        return Array.from(markers);
      }
      /**
       * Map file extension to programming language ID
       */
      mapExtensionToLanguage(ext2, extensionMap) {
        return extensionMap[ext2] || null;
      }
      /**
       * Get extension to language mapping with overrides applied
       */
      getExtensionToLanguageMap(extensionOverrides = {}) {
        const extToLang = { ...DEFAULT_EXTENSION_TO_LANGUAGE };
        for (const [key, value] of Object.entries(extensionOverrides)) {
          const normalized2 = key.startsWith(".") ? key.slice(1) : key;
          if (!normalized2) {
            continue;
          }
          extToLang[normalized2.toLowerCase()] = value;
        }
        return extToLang;
      }
      /**
       * Map root marker file to programming language ID
       */
      mapMarkerToLanguage(marker) {
        return MARKER_TO_LANGUAGE[marker] || null;
      }
    };
  }
});

// packages/core/dist/src/lsp/LspResponseNormalizer.js
var LspResponseNormalizer;
var init_LspResponseNormalizer = __esm({
  "packages/core/dist/src/lsp/LspResponseNormalizer.js"() {
    "use strict";
    init_esbuild_shims();
    init_constants8();
    LspResponseNormalizer = class {
      static {
        __name(this, "LspResponseNormalizer");
      }
      // ============================================================================
      // Diagnostic Normalization
      // ============================================================================
      /**
       * Normalize diagnostic result from LSP response
       */
      normalizeDiagnostic(item, serverName) {
        if (!item || typeof item !== "object") {
          return null;
        }
        const itemObj = item;
        const range = this.normalizeRange(itemObj["range"]);
        if (!range) {
          return null;
        }
        const message = typeof itemObj["message"] === "string" ? itemObj["message"] : "";
        if (!message) {
          return null;
        }
        const severityNum = typeof itemObj["severity"] === "number" ? itemObj["severity"] : void 0;
        const severity = severityNum ? DIAGNOSTIC_SEVERITY_LABELS[severityNum] : void 0;
        const code2 = itemObj["code"];
        const codeValue = typeof code2 === "string" || typeof code2 === "number" ? code2 : void 0;
        const source2 = typeof itemObj["source"] === "string" ? itemObj["source"] : void 0;
        const tags = this.normalizeDiagnosticTags(itemObj["tags"]);
        const relatedInfo = this.normalizeDiagnosticRelatedInfo(itemObj["relatedInformation"]);
        return {
          range,
          severity,
          code: codeValue,
          source: source2,
          message,
          tags: tags.length > 0 ? tags : void 0,
          relatedInformation: relatedInfo.length > 0 ? relatedInfo : void 0,
          serverName
        };
      }
      /**
       * Convert diagnostic back to LSP format for requests
       */
      denormalizeDiagnostic(diagnostic) {
        const severityMap = {
          error: 1,
          warning: 2,
          information: 3,
          hint: 4
        };
        return {
          range: diagnostic.range,
          message: diagnostic.message,
          severity: diagnostic.severity ? severityMap[diagnostic.severity] : void 0,
          code: diagnostic.code,
          source: diagnostic.source
        };
      }
      /**
       * Normalize diagnostic tags
       */
      normalizeDiagnosticTags(tags) {
        if (!Array.isArray(tags)) {
          return [];
        }
        const result = [];
        for (const tag2 of tags) {
          if (tag2 === 1) {
            result.push("unnecessary");
          } else if (tag2 === 2) {
            result.push("deprecated");
          }
        }
        return result;
      }
      /**
       * Normalize diagnostic related information
       */
      normalizeDiagnosticRelatedInfo(info) {
        if (!Array.isArray(info)) {
          return [];
        }
        const result = [];
        for (const item of info) {
          if (!item || typeof item !== "object") {
            continue;
          }
          const itemObj = item;
          const location = itemObj["location"];
          if (!location || typeof location !== "object") {
            continue;
          }
          const locObj = location;
          const uri = locObj["uri"];
          const range = this.normalizeRange(locObj["range"]);
          const message = itemObj["message"];
          if (typeof uri === "string" && range && typeof message === "string") {
            result.push({
              location: { uri, range },
              message
            });
          }
        }
        return result;
      }
      /**
       * Normalize file diagnostics result
       */
      normalizeFileDiagnostics(item, serverName) {
        if (!item || typeof item !== "object") {
          return null;
        }
        const itemObj = item;
        const uri = typeof itemObj["uri"] === "string" ? itemObj["uri"] : "";
        if (!uri) {
          return null;
        }
        const items = itemObj["items"];
        if (!Array.isArray(items)) {
          return null;
        }
        const diagnostics = [];
        for (const diagItem of items) {
          const normalized2 = this.normalizeDiagnostic(diagItem, serverName);
          if (normalized2) {
            diagnostics.push(normalized2);
          }
        }
        return {
          uri,
          diagnostics,
          serverName
        };
      }
      // ============================================================================
      // Code Action Normalization
      // ============================================================================
      /**
       * Normalize code action result
       */
      normalizeCodeAction(item, serverName) {
        if (!item || typeof item !== "object") {
          return null;
        }
        const itemObj = item;
        if (itemObj["command"] && typeof itemObj["title"] === "string" && !itemObj["kind"]) {
          return {
            title: itemObj["title"],
            command: {
              title: itemObj["title"],
              command: itemObj["command"] ?? "",
              arguments: itemObj["arguments"]
            },
            serverName
          };
        }
        const title = typeof itemObj["title"] === "string" ? itemObj["title"] : "";
        if (!title) {
          return null;
        }
        const kind2 = typeof itemObj["kind"] === "string" ? CODE_ACTION_KIND_LABELS[itemObj["kind"]] ?? itemObj["kind"] : void 0;
        const isPreferred = typeof itemObj["isPreferred"] === "boolean" ? itemObj["isPreferred"] : void 0;
        const edit2 = this.normalizeWorkspaceEdit(itemObj["edit"]);
        const command2 = this.normalizeCommand(itemObj["command"]);
        const diagnostics = [];
        if (Array.isArray(itemObj["diagnostics"])) {
          for (const diag3 of itemObj["diagnostics"]) {
            const normalized2 = this.normalizeDiagnostic(diag3, serverName);
            if (normalized2) {
              diagnostics.push(normalized2);
            }
          }
        }
        return {
          title,
          kind: kind2,
          diagnostics: diagnostics.length > 0 ? diagnostics : void 0,
          isPreferred,
          edit: edit2 ?? void 0,
          command: command2 ?? void 0,
          data: itemObj["data"],
          serverName
        };
      }
      // ============================================================================
      // Workspace Edit Normalization
      // ============================================================================
      /**
       * Normalize workspace edit
       */
      normalizeWorkspaceEdit(edit2) {
        if (!edit2 || typeof edit2 !== "object") {
          return null;
        }
        const editObj = edit2;
        const result = {};
        if (editObj["changes"] && typeof editObj["changes"] === "object") {
          const changes = editObj["changes"];
          result.changes = {};
          for (const [uri, edits] of Object.entries(changes)) {
            if (Array.isArray(edits)) {
              const normalizedEdits = [];
              for (const e4 of edits) {
                const normalized2 = this.normalizeTextEdit(e4);
                if (normalized2) {
                  normalizedEdits.push(normalized2);
                }
              }
              if (normalizedEdits.length > 0) {
                result.changes[uri] = normalizedEdits;
              }
            }
          }
        }
        if (Array.isArray(editObj["documentChanges"])) {
          result.documentChanges = [];
          for (const docChange of editObj["documentChanges"]) {
            const normalized2 = this.normalizeTextDocumentEdit(docChange);
            if (normalized2) {
              result.documentChanges.push(normalized2);
            }
          }
        }
        if ((!result.changes || Object.keys(result.changes).length === 0) && (!result.documentChanges || result.documentChanges.length === 0)) {
          return null;
        }
        return result;
      }
      /**
       * Normalize text edit
       */
      normalizeTextEdit(edit2) {
        if (!edit2 || typeof edit2 !== "object") {
          return null;
        }
        const editObj = edit2;
        const range = this.normalizeRange(editObj["range"]);
        if (!range) {
          return null;
        }
        const newText = typeof editObj["newText"] === "string" ? editObj["newText"] : "";
        return { range, newText };
      }
      /**
       * Normalize text document edit
       */
      normalizeTextDocumentEdit(docEdit) {
        if (!docEdit || typeof docEdit !== "object") {
          return null;
        }
        const docEditObj = docEdit;
        const textDocument = docEditObj["textDocument"];
        if (!textDocument || typeof textDocument !== "object") {
          return null;
        }
        const textDocObj = textDocument;
        const uri = typeof textDocObj["uri"] === "string" ? textDocObj["uri"] : "";
        if (!uri) {
          return null;
        }
        const version2 = typeof textDocObj["version"] === "number" ? textDocObj["version"] : null;
        const edits = docEditObj["edits"];
        if (!Array.isArray(edits)) {
          return null;
        }
        const normalizedEdits = [];
        for (const e4 of edits) {
          const normalized2 = this.normalizeTextEdit(e4);
          if (normalized2) {
            normalizedEdits.push(normalized2);
          }
        }
        if (normalizedEdits.length === 0) {
          return null;
        }
        return {
          textDocument: { uri, version: version2 },
          edits: normalizedEdits
        };
      }
      /**
       * Normalize command
       */
      normalizeCommand(cmd) {
        if (!cmd || typeof cmd !== "object") {
          return null;
        }
        const cmdObj = cmd;
        const title = typeof cmdObj["title"] === "string" ? cmdObj["title"] : "";
        const command2 = typeof cmdObj["command"] === "string" ? cmdObj["command"] : "";
        if (!command2) {
          return null;
        }
        const args = Array.isArray(cmdObj["arguments"]) ? cmdObj["arguments"] : void 0;
        return { title, command: command2, arguments: args };
      }
      // ============================================================================
      // Location and Symbol Normalization
      // ============================================================================
      /**
       * Normalize location result (definitions, references, implementations)
       */
      normalizeLocationResult(item, serverName) {
        if (!item || typeof item !== "object") {
          return null;
        }
        const itemObj = item;
        const uri = itemObj["uri"] ?? itemObj["targetUri"] ?? itemObj["target"]?.["uri"];
        const range = itemObj["range"] ?? itemObj["targetSelectionRange"] ?? itemObj["targetRange"] ?? itemObj["target"]?.["range"];
        if (!uri || !range?.start || !range?.end) {
          return null;
        }
        const start = range.start;
        const end = range.end;
        return {
          uri,
          range: {
            start: {
              line: Number(start?.line ?? 0),
              character: Number(start?.character ?? 0)
            },
            end: {
              line: Number(end?.line ?? 0),
              character: Number(end?.character ?? 0)
            }
          },
          serverName
        };
      }
      /**
       * Normalize symbol result (workspace symbols, document symbols)
       */
      normalizeSymbolResult(item, serverName) {
        if (!item || typeof item !== "object") {
          return null;
        }
        const itemObj = item;
        const location = itemObj["location"] ?? itemObj["target"] ?? item;
        if (!location || typeof location !== "object") {
          return null;
        }
        const locationObj = location;
        const range = locationObj["range"] ?? locationObj["targetRange"] ?? itemObj["range"] ?? void 0;
        if (!locationObj["uri"] || !range?.start || !range?.end) {
          return null;
        }
        const start = range.start;
        const end = range.end;
        return {
          name: itemObj["name"] ?? itemObj["label"] ?? "symbol",
          kind: this.normalizeSymbolKind(itemObj["kind"]),
          containerName: itemObj["containerName"] ?? itemObj["container"],
          location: {
            uri: locationObj["uri"],
            range: {
              start: {
                line: Number(start?.line ?? 0),
                character: Number(start?.character ?? 0)
              },
              end: {
                line: Number(end?.line ?? 0),
                character: Number(end?.character ?? 0)
              }
            }
          },
          serverName
        };
      }
      // ============================================================================
      // Range Normalization
      // ============================================================================
      /**
       * Normalize a single range
       */
      normalizeRange(range) {
        if (!range || typeof range !== "object") {
          return null;
        }
        const rangeObj = range;
        const start = rangeObj["start"];
        const end = rangeObj["end"];
        if (!start || typeof start !== "object" || !end || typeof end !== "object") {
          return null;
        }
        const startObj = start;
        const endObj = end;
        return {
          start: {
            line: Number(startObj["line"] ?? 0),
            character: Number(startObj["character"] ?? 0)
          },
          end: {
            line: Number(endObj["line"] ?? 0),
            character: Number(endObj["character"] ?? 0)
          }
        };
      }
      /**
       * Normalize an array of ranges
       */
      normalizeRanges(ranges2) {
        if (!Array.isArray(ranges2)) {
          return [];
        }
        const results = [];
        for (const range of ranges2) {
          const normalized2 = this.normalizeRange(range);
          if (normalized2) {
            results.push(normalized2);
          }
        }
        return results;
      }
      /**
       * Normalize symbol kind from number to string label
       */
      normalizeSymbolKind(kind2) {
        if (typeof kind2 === "number") {
          return SYMBOL_KIND_LABELS[kind2] ?? String(kind2);
        }
        if (typeof kind2 === "string") {
          const trimmed2 = kind2.trim();
          if (trimmed2 === "") {
            return void 0;
          }
          const numeric = Number(trimmed2);
          if (Number.isFinite(numeric) && SYMBOL_KIND_LABELS[numeric]) {
            return SYMBOL_KIND_LABELS[numeric];
          }
          return trimmed2;
        }
        return void 0;
      }
      // ============================================================================
      // Hover Normalization
      // ============================================================================
      /**
       * Normalize hover contents to string
       */
      normalizeHoverContents(contents) {
        if (!contents) {
          return "";
        }
        if (typeof contents === "string") {
          return contents;
        }
        if (Array.isArray(contents)) {
          const parts = contents.map((item) => this.normalizeHoverContents(item)).map((item) => item.trim()).filter((item) => item.length > 0);
          return parts.join("\n");
        }
        if (typeof contents === "object") {
          const contentsObj = contents;
          const value = contentsObj["value"];
          if (typeof value === "string") {
            const language = contentsObj["language"];
            if (typeof language === "string" && language.trim() !== "") {
              return `\`\`\`${language}
${value}
\`\`\``;
            }
            return value;
          }
        }
        return "";
      }
      /**
       * Normalize hover result
       */
      normalizeHoverResult(response, serverName) {
        if (!response) {
          return null;
        }
        if (typeof response !== "object") {
          const contents2 = this.normalizeHoverContents(response);
          if (!contents2.trim()) {
            return null;
          }
          return {
            contents: contents2,
            serverName
          };
        }
        const responseObj = response;
        const contents = this.normalizeHoverContents(responseObj["contents"]);
        if (!contents.trim()) {
          return null;
        }
        const range = this.normalizeRange(responseObj["range"]);
        return {
          contents,
          range: range ?? void 0,
          serverName
        };
      }
      // ============================================================================
      // Call Hierarchy Normalization
      // ============================================================================
      /**
       * Normalize call hierarchy item
       */
      normalizeCallHierarchyItem(item, serverName) {
        if (!item || typeof item !== "object") {
          return null;
        }
        const itemObj = item;
        const nameValue = itemObj["name"] ?? itemObj["label"] ?? "symbol";
        const name3 = typeof nameValue === "string" ? nameValue : String(nameValue ?? "");
        const uri = itemObj["uri"];
        if (!name3 || typeof uri !== "string") {
          return null;
        }
        const range = this.normalizeRange(itemObj["range"]);
        const selectionRange = this.normalizeRange(itemObj["selectionRange"]) ?? range;
        if (!range || !selectionRange) {
          return null;
        }
        const serverOverride = typeof itemObj["serverName"] === "string" ? itemObj["serverName"] : void 0;
        let rawKind;
        if (typeof itemObj["rawKind"] === "number") {
          rawKind = itemObj["rawKind"];
        } else if (typeof itemObj["kind"] === "number") {
          rawKind = itemObj["kind"];
        } else if (typeof itemObj["kind"] === "string") {
          const parsed = Number(itemObj["kind"]);
          if (Number.isFinite(parsed)) {
            rawKind = parsed;
          }
        }
        return {
          name: name3,
          kind: this.normalizeSymbolKind(itemObj["kind"]),
          rawKind,
          detail: typeof itemObj["detail"] === "string" ? itemObj["detail"] : void 0,
          uri,
          range,
          selectionRange,
          data: itemObj["data"],
          serverName: serverOverride ?? serverName
        };
      }
      /**
       * Normalize incoming call
       */
      normalizeIncomingCall(item, serverName) {
        if (!item || typeof item !== "object") {
          return null;
        }
        const itemObj = item;
        const from = this.normalizeCallHierarchyItem(itemObj["from"], serverName);
        if (!from) {
          return null;
        }
        return {
          from,
          fromRanges: this.normalizeRanges(itemObj["fromRanges"])
        };
      }
      /**
       * Normalize outgoing call
       */
      normalizeOutgoingCall(item, serverName) {
        if (!item || typeof item !== "object") {
          return null;
        }
        const itemObj = item;
        const to = this.normalizeCallHierarchyItem(itemObj["to"], serverName);
        if (!to) {
          return null;
        }
        return {
          to,
          fromRanges: this.normalizeRanges(itemObj["fromRanges"])
        };
      }
      /**
       * Convert call hierarchy item back to LSP params format
       */
      toCallHierarchyItemParams(item) {
        let numericKind = item.rawKind;
        if (numericKind === void 0 && item.kind !== void 0) {
          const parsed = Number(item.kind);
          if (Number.isFinite(parsed)) {
            numericKind = parsed;
          }
        }
        return {
          name: item.name,
          kind: numericKind,
          detail: item.detail,
          uri: item.uri,
          range: item.range,
          selectionRange: item.selectionRange,
          data: item.data
        };
      }
      // ============================================================================
      // Document Symbol Helpers
      // ============================================================================
      /**
       * Check if item is a DocumentSymbol (has range and selectionRange)
       */
      isDocumentSymbol(item) {
        const range = item["range"];
        const selectionRange = item["selectionRange"];
        return typeof range === "object" && range !== null && typeof selectionRange === "object" && selectionRange !== null;
      }
      /**
       * Recursively collect document symbols from a tree structure
       */
      collectDocumentSymbol(item, uri, serverName, results, limit2, containerName) {
        if (results.length >= limit2) {
          return;
        }
        const nameValue = item["name"] ?? item["label"] ?? "symbol";
        const name3 = typeof nameValue === "string" ? nameValue : String(nameValue);
        const selectionRange = this.normalizeRange(item["selectionRange"]) ?? this.normalizeRange(item["range"]);
        if (!selectionRange) {
          return;
        }
        results.push({
          name: name3,
          kind: this.normalizeSymbolKind(item["kind"]),
          containerName,
          location: {
            uri,
            range: selectionRange
          },
          serverName
        });
        if (results.length >= limit2) {
          return;
        }
        const children = item["children"];
        if (Array.isArray(children)) {
          for (const child of children) {
            if (results.length >= limit2) {
              break;
            }
            if (child && typeof child === "object") {
              this.collectDocumentSymbol(child, uri, serverName, results, limit2, name3);
            }
          }
        }
      }
    };
  }
});

// packages/core/dist/src/lsp/LspServerManager.js
import { spawn as spawn7 } from "node:child_process";
import * as fs72 from "node:fs";
import * as path76 from "path";
import { pathToFileURL as pathToFileURL4 } from "url";
var debugLogger68, LspServerManager;
var init_LspServerManager = __esm({
  "packages/core/dist/src/lsp/LspServerManager.js"() {
    "use strict";
    init_esbuild_shims();
    init_esm11();
    init_LspConnectionFactory();
    init_constants8();
    init_debugLogger();
    debugLogger68 = createDebugLogger("LSP");
    LspServerManager = class {
      static {
        __name(this, "LspServerManager");
      }
      config;
      workspaceContext;
      fileDiscoveryService;
      serverHandles = /* @__PURE__ */ new Map();
      requireTrustedWorkspace;
      workspaceRoot;
      constructor(config2, workspaceContext, fileDiscoveryService, options2) {
        this.config = config2;
        this.workspaceContext = workspaceContext;
        this.fileDiscoveryService = fileDiscoveryService;
        this.requireTrustedWorkspace = options2.requireTrustedWorkspace;
        this.workspaceRoot = options2.workspaceRoot;
      }
      setServerConfigs(configs) {
        this.serverHandles.clear();
        for (const config2 of configs) {
          this.serverHandles.set(config2.name, {
            config: config2,
            status: "NOT_STARTED"
          });
        }
      }
      clearServerHandles() {
        this.serverHandles.clear();
      }
      getHandles() {
        return this.serverHandles;
      }
      getStatus() {
        const statusMap = /* @__PURE__ */ new Map();
        for (const [name3, handle] of Array.from(this.serverHandles)) {
          statusMap.set(name3, handle.status);
        }
        return statusMap;
      }
      async startAll() {
        for (const [name3, handle] of Array.from(this.serverHandles)) {
          await this.startServer(name3, handle);
        }
      }
      async stopAll() {
        for (const [name3, handle] of Array.from(this.serverHandles)) {
          await this.stopServer(name3, handle);
        }
        this.serverHandles.clear();
      }
      /**
       * Ensure tsserver has at least one file open so navto/navtree requests succeed.
       * Sets warmedUp flag only after successful warm-up to allow retry on failure.
       */
      async warmupTypescriptServer(handle, force = false) {
        if (!handle.connection || !this.isTypescriptServer(handle)) {
          return;
        }
        if (handle.warmedUp && !force) {
          return;
        }
        const tsFile = this.findFirstTypescriptFile();
        if (!tsFile) {
          return;
        }
        const uri = pathToFileURL4(tsFile).toString();
        const languageId = tsFile.endsWith(".tsx") ? "typescriptreact" : tsFile.endsWith(".jsx") ? "javascriptreact" : tsFile.endsWith(".js") ? "javascript" : "typescript";
        try {
          const text = fs72.readFileSync(tsFile, "utf-8");
          handle.connection.send({
            jsonrpc: "2.0",
            method: "textDocument/didOpen",
            params: {
              textDocument: {
                uri,
                languageId,
                version: 1,
                text
              }
            }
          });
          await new Promise((resolve30) => setTimeout(resolve30, DEFAULT_LSP_WARMUP_DELAY_MS));
          handle.warmedUp = true;
        } catch (error2) {
          debugLogger68.warn("TypeScript server warm-up failed:", error2);
        }
      }
      /**
       * Check if the given handle is a TypeScript language server.
       *
       * @param handle - The LSP server handle
       * @returns true if it's a TypeScript server
       */
      isTypescriptServer(handle) {
        return handle.config.name.includes("typescript") || (handle.config.command?.includes("typescript") ?? false);
      }
      /**
       * Start individual LSP server with lock to prevent concurrent startup attempts.
       *
       * @param name - The name of the LSP server
       * @param handle - The LSP server handle
       */
      async startServer(name3, handle) {
        if (handle.startingPromise) {
          return handle.startingPromise;
        }
        if (handle.status === "IN_PROGRESS" || handle.status === "READY") {
          return;
        }
        handle.stopRequested = false;
        handle.startingPromise = this.doStartServer(name3, handle).finally(() => {
          handle.startingPromise = void 0;
        });
        return handle.startingPromise;
      }
      /**
       * Internal method that performs the actual server startup.
       *
       * @param name - The name of the LSP server
       * @param handle - The LSP server handle
       */
      async doStartServer(name3, handle) {
        const workspaceTrusted = this.config.isTrustedFolder();
        if ((this.requireTrustedWorkspace || handle.config.trustRequired) && !workspaceTrusted) {
          debugLogger68.warn(`LSP server ${name3} requires trusted workspace, skipping startup`);
          handle.status = "FAILED";
          return;
        }
        const consent = await this.requestUserConsent(name3, handle.config, workspaceTrusted);
        if (!consent) {
          debugLogger68.info(`User declined to start LSP server ${name3}`);
          handle.status = "FAILED";
          return;
        }
        if (handle.config.command) {
          const commandCwd = handle.config.workspaceFolder ?? this.workspaceRoot;
          if (!await this.commandExists(handle.config.command, handle.config.env, commandCwd)) {
            debugLogger68.warn(`LSP server ${name3} command not found: ${handle.config.command}`);
            handle.status = "FAILED";
            return;
          }
          if (!this.isPathSafe(handle.config.command, this.workspaceRoot, commandCwd)) {
            debugLogger68.warn(`LSP server ${name3} command path is unsafe: ${handle.config.command}`);
            handle.status = "FAILED";
            return;
          }
        }
        try {
          handle.error = void 0;
          handle.warmedUp = false;
          handle.status = "IN_PROGRESS";
          const connection = await this.createLspConnection(handle.config);
          handle.connection = connection.connection;
          handle.process = connection.process;
          await this.initializeLspServer(connection, handle.config);
          handle.status = "READY";
          this.attachRestartHandler(name3, handle);
          debugLogger68.info(`LSP server ${name3} started successfully`);
        } catch (error2) {
          handle.status = "FAILED";
          handle.error = error2;
          debugLogger68.error(`LSP server ${name3} failed to start:`, error2);
        }
      }
      /**
       * Stop individual LSP server
       */
      async stopServer(name3, handle) {
        handle.stopRequested = true;
        if (handle.connection) {
          try {
            await this.shutdownConnection(handle);
          } catch (error2) {
            debugLogger68.error(`Error closing LSP server ${name3}:`, error2);
          }
        } else if (handle.process && handle.process.exitCode === null) {
          handle.process.kill();
        }
        handle.connection = void 0;
        handle.process = void 0;
        handle.status = "NOT_STARTED";
        handle.warmedUp = false;
        handle.restartAttempts = 0;
      }
      async shutdownConnection(handle) {
        if (!handle.connection) {
          return;
        }
        try {
          const shutdownPromise = handle.connection.shutdown();
          if (typeof handle.config.shutdownTimeout === "number") {
            await Promise.race([
              shutdownPromise,
              new Promise((resolve30) => setTimeout(resolve30, handle.config.shutdownTimeout))
            ]);
          } else {
            await shutdownPromise;
          }
        } finally {
          handle.connection.end();
        }
      }
      attachRestartHandler(name3, handle) {
        if (!handle.process) {
          return;
        }
        handle.process.once("exit", (code2) => {
          if (handle.stopRequested) {
            return;
          }
          if (!handle.config.restartOnCrash) {
            handle.status = "FAILED";
            return;
          }
          const maxRestarts = handle.config.maxRestarts ?? DEFAULT_LSP_MAX_RESTARTS;
          if (maxRestarts <= 0) {
            handle.status = "FAILED";
            return;
          }
          const attempts = handle.restartAttempts ?? 0;
          if (attempts >= maxRestarts) {
            debugLogger68.warn(`LSP server ${name3} reached max restart attempts (${maxRestarts}), stopping restarts`);
            handle.status = "FAILED";
            return;
          }
          handle.restartAttempts = attempts + 1;
          debugLogger68.warn(`LSP server ${name3} exited (code ${code2 ?? "unknown"}), restarting (${handle.restartAttempts}/${maxRestarts})`);
          this.resetHandle(handle);
          void this.startServer(name3, handle);
        });
      }
      resetHandle(handle) {
        if (handle.connection) {
          handle.connection.end();
        }
        if (handle.process && handle.process.exitCode === null) {
          handle.process.kill();
        }
        handle.connection = void 0;
        handle.process = void 0;
        handle.status = "NOT_STARTED";
        handle.error = void 0;
        handle.warmedUp = false;
        handle.stopRequested = false;
      }
      buildProcessEnv(env7) {
        if (!env7 || Object.keys(env7).length === 0) {
          return void 0;
        }
        return { ...process.env, ...env7 };
      }
      async connectSocketWithRetry(socket, timeoutMs) {
        const deadline = Date.now() + timeoutMs;
        let attempt = 0;
        while (true) {
          const remaining = deadline - Date.now();
          if (remaining <= 0) {
            throw new Error("LSP server connection timeout");
          }
          try {
            return await LspConnectionFactory.createSocketConnection(socket, remaining);
          } catch (error2) {
            attempt += 1;
            if (Date.now() >= deadline) {
              throw error2;
            }
            const delay4 = Math.min(DEFAULT_LSP_SOCKET_RETRY_DELAY_MS * attempt, DEFAULT_LSP_SOCKET_MAX_RETRY_DELAY_MS);
            await new Promise((resolve30) => setTimeout(resolve30, delay4));
          }
        }
      }
      /**
       * Create LSP connection
       */
      async createLspConnection(config2) {
        const workspaceFolder = config2.workspaceFolder ?? this.workspaceRoot;
        const startupTimeout = config2.startupTimeout ?? DEFAULT_LSP_STARTUP_TIMEOUT_MS;
        const env7 = this.buildProcessEnv(config2.env);
        if (config2.transport === "stdio") {
          if (!config2.command) {
            throw new Error("LSP stdio transport requires a command");
          }
          const lspConnection = await LspConnectionFactory.createStdioConnection(config2.command, config2.args ?? [], { cwd: workspaceFolder, env: env7 }, startupTimeout);
          return {
            connection: lspConnection.connection,
            process: lspConnection.process,
            shutdown: /* @__PURE__ */ __name(async () => {
              await lspConnection.connection.shutdown();
            }, "shutdown"),
            exit: /* @__PURE__ */ __name(() => {
              if (lspConnection.process && !lspConnection.process.killed) {
                lspConnection.process.kill();
              }
              lspConnection.connection.end();
            }, "exit"),
            initialize: /* @__PURE__ */ __name(async (params) => lspConnection.connection.initialize(params), "initialize")
          };
        } else if (config2.transport === "tcp" || config2.transport === "socket") {
          if (!config2.socket) {
            throw new Error("LSP socket transport requires host/port or path");
          }
          let process50;
          if (config2.command) {
            process50 = spawn7(config2.command, config2.args ?? [], {
              cwd: workspaceFolder,
              env: env7,
              stdio: "ignore"
            });
            await new Promise((resolve30, reject) => {
              process50?.once("spawn", () => resolve30());
              process50?.once("error", (error2) => {
                reject(new Error(`Failed to spawn LSP server: ${error2.message}`));
              });
            });
          }
          try {
            const lspConnection = await this.connectSocketWithRetry(config2.socket, startupTimeout);
            return {
              connection: lspConnection.connection,
              process: process50,
              shutdown: /* @__PURE__ */ __name(async () => {
                await lspConnection.connection.shutdown();
              }, "shutdown"),
              exit: /* @__PURE__ */ __name(() => {
                lspConnection.connection.end();
              }, "exit"),
              initialize: /* @__PURE__ */ __name(async (params) => lspConnection.connection.initialize(params), "initialize")
            };
          } catch (error2) {
            if (process50 && process50.exitCode === null) {
              process50.kill();
            }
            throw error2;
          }
        } else {
          throw new Error(`Unsupported transport: ${config2.transport}`);
        }
      }
      /**
       * Initialize LSP server
       */
      async initializeLspServer(connection, config2) {
        const workspaceFolderPath = config2.workspaceFolder ?? this.workspaceRoot;
        const workspaceFolder = {
          name: path76.basename(workspaceFolderPath) || workspaceFolderPath,
          uri: config2.rootUri
        };
        const initializeParams = {
          processId: process.pid,
          rootUri: config2.rootUri,
          rootPath: workspaceFolderPath,
          workspaceFolders: [workspaceFolder],
          capabilities: {
            textDocument: {
              completion: { dynamicRegistration: true },
              hover: { dynamicRegistration: true },
              definition: { dynamicRegistration: true },
              references: { dynamicRegistration: true },
              documentSymbol: { dynamicRegistration: true },
              codeAction: { dynamicRegistration: true }
            },
            workspace: {
              workspaceFolders: true
            }
          },
          initializationOptions: config2.initializationOptions
        };
        await connection.initialize(initializeParams);
        connection.connection.send({
          jsonrpc: "2.0",
          method: "initialized",
          params: {}
        });
        connection.connection.send({
          jsonrpc: "2.0",
          method: "workspace/didChangeWorkspaceFolders",
          params: {
            event: {
              added: [workspaceFolder],
              removed: []
            }
          }
        });
        if (config2.settings && Object.keys(config2.settings).length > 0) {
          connection.connection.send({
            jsonrpc: "2.0",
            method: "workspace/didChangeConfiguration",
            params: {
              settings: config2.settings
            }
          });
        }
        if (config2.name.includes("typescript") || (config2.command?.includes("typescript") ?? false)) {
          try {
            const tsFile = this.findFirstTypescriptFile();
            if (tsFile) {
              const uri = pathToFileURL4(tsFile).toString();
              const languageId = tsFile.endsWith(".tsx") ? "typescriptreact" : "typescript";
              const text = fs72.readFileSync(tsFile, "utf-8");
              connection.connection.send({
                jsonrpc: "2.0",
                method: "textDocument/didOpen",
                params: {
                  textDocument: {
                    uri,
                    languageId,
                    version: 1,
                    text
                  }
                }
              });
            }
          } catch (error2) {
            debugLogger68.warn("TypeScript LSP warm-up failed:", error2);
          }
        }
      }
      /**
       * Check if command exists
       */
      async commandExists(command2, env7, cwd7) {
        return new Promise((resolve30) => {
          let settled = false;
          const child = spawn7(command2, ["--version"], {
            stdio: ["ignore", "ignore", "ignore"],
            cwd: cwd7 ?? this.workspaceRoot,
            env: this.buildProcessEnv(env7)
          });
          child.on("error", () => {
            settled = true;
            resolve30(false);
          });
          child.on("exit", (code2) => {
            if (settled) {
              return;
            }
            resolve30(code2 !== 127);
          });
          setTimeout(() => {
            settled = true;
            child.kill();
            resolve30(false);
          }, DEFAULT_LSP_COMMAND_CHECK_TIMEOUT_MS);
        });
      }
      /**
       * Check path safety
       */
      isPathSafe(command2, workspacePath, cwd7) {
        if (!command2.includes(path76.sep) && !command2.includes("/")) {
          return true;
        }
        const resolvedWorkspacePath = path76.resolve(workspacePath);
        const basePath = cwd7 ? path76.resolve(cwd7) : resolvedWorkspacePath;
        const resolvedPath = path76.isAbsolute(command2) ? path76.resolve(command2) : path76.resolve(basePath, command2);
        return resolvedPath.startsWith(resolvedWorkspacePath + path76.sep) || resolvedPath === resolvedWorkspacePath;
      }
      /**
       * 请求用户确认启动 LSP 服务器
       */
      async requestUserConsent(serverName, serverConfig, workspaceTrusted) {
        if (workspaceTrusted) {
          return true;
        }
        if (this.requireTrustedWorkspace || serverConfig.trustRequired) {
          debugLogger68.warn(`Workspace not trusted, skipping LSP server ${serverName} (${serverConfig.command ?? serverConfig.transport})`);
          return false;
        }
        debugLogger68.info(`Untrusted workspace, but LSP server ${serverName} has trustRequired=false, attempting cautious startup`);
        return true;
      }
      /**
       * Find a representative TypeScript/JavaScript file to warm up tsserver.
       */
      findFirstTypescriptFile() {
        const patterns = ["**/*.ts", "**/*.tsx", "**/*.js", "**/*.jsx"];
        const excludePatterns = [
          "**/node_modules/**",
          "**/.git/**",
          "**/dist/**",
          "**/build/**"
        ];
        for (const root of this.workspaceContext.getDirectories()) {
          for (const pattern of patterns) {
            try {
              const matches = globSync(pattern, {
                cwd: root,
                ignore: excludePatterns,
                absolute: true,
                nodir: true
              });
              for (const file of matches) {
                if (this.fileDiscoveryService.shouldIgnoreFile(file)) {
                  continue;
                }
                return file;
              }
            } catch (_error) {
            }
          }
        }
        return void 0;
      }
    };
  }
});

// packages/core/dist/src/lsp/NativeLspClient.js
var NativeLspClient;
var init_NativeLspClient = __esm({
  "packages/core/dist/src/lsp/NativeLspClient.js"() {
    "use strict";
    init_esbuild_shims();
    NativeLspClient = class {
      static {
        __name(this, "NativeLspClient");
      }
      service;
      /**
       * Creates a new NativeLspClient instance.
       *
       * @param service - The NativeLspService instance to delegate calls to
       */
      constructor(service) {
        this.service = service;
      }
      /**
       * Search for symbols across the workspace.
       *
       * @param query - The search query string
       * @param limit - Maximum number of results to return
       * @returns Promise resolving to array of symbol information
       */
      workspaceSymbols(query, limit2) {
        return this.service.workspaceSymbols(query, limit2);
      }
      /**
       * Find where a symbol is defined.
       *
       * @param location - The source location to find definitions for
       * @param serverName - Optional specific LSP server to query
       * @param limit - Maximum number of results to return
       * @returns Promise resolving to array of definition locations
       */
      definitions(location, serverName, limit2) {
        return this.service.definitions(location, serverName, limit2);
      }
      /**
       * Find all references to a symbol.
       *
       * @param location - The source location to find references for
       * @param serverName - Optional specific LSP server to query
       * @param includeDeclaration - Whether to include the declaration in results
       * @param limit - Maximum number of results to return
       * @returns Promise resolving to array of reference locations
       */
      references(location, serverName, includeDeclaration, limit2) {
        return this.service.references(location, serverName, includeDeclaration, limit2);
      }
      /**
       * Get hover information (documentation, type info) for a symbol.
       *
       * @param location - The source location to get hover info for
       * @param serverName - Optional specific LSP server to query
       * @returns Promise resolving to hover result or null if not available
       */
      hover(location, serverName) {
        return this.service.hover(location, serverName);
      }
      /**
       * Get all symbols in a document.
       *
       * @param uri - The document URI to get symbols for
       * @param serverName - Optional specific LSP server to query
       * @param limit - Maximum number of results to return
       * @returns Promise resolving to array of symbol information
       */
      documentSymbols(uri, serverName, limit2) {
        return this.service.documentSymbols(uri, serverName, limit2);
      }
      /**
       * Find implementations of an interface or abstract method.
       *
       * @param location - The source location to find implementations for
       * @param serverName - Optional specific LSP server to query
       * @param limit - Maximum number of results to return
       * @returns Promise resolving to array of implementation locations
       */
      implementations(location, serverName, limit2) {
        return this.service.implementations(location, serverName, limit2);
      }
      /**
       * Prepare call hierarchy item at a position (functions/methods).
       *
       * @param location - The source location to prepare call hierarchy for
       * @param serverName - Optional specific LSP server to query
       * @param limit - Maximum number of results to return
       * @returns Promise resolving to array of call hierarchy items
       */
      prepareCallHierarchy(location, serverName, limit2) {
        return this.service.prepareCallHierarchy(location, serverName, limit2);
      }
      /**
       * Find all functions/methods that call the given function.
       *
       * @param item - The call hierarchy item to find callers for
       * @param serverName - Optional specific LSP server to query
       * @param limit - Maximum number of results to return
       * @returns Promise resolving to array of incoming calls
       */
      incomingCalls(item, serverName, limit2) {
        return this.service.incomingCalls(item, serverName, limit2);
      }
      /**
       * Find all functions/methods called by the given function.
       *
       * @param item - The call hierarchy item to find callees for
       * @param serverName - Optional specific LSP server to query
       * @param limit - Maximum number of results to return
       * @returns Promise resolving to array of outgoing calls
       */
      outgoingCalls(item, serverName, limit2) {
        return this.service.outgoingCalls(item, serverName, limit2);
      }
      /**
       * Get diagnostics for a specific document.
       *
       * @param uri - The document URI to get diagnostics for
       * @param serverName - Optional specific LSP server to query
       * @returns Promise resolving to array of diagnostics
       */
      diagnostics(uri, serverName) {
        return this.service.diagnostics(uri, serverName);
      }
      /**
       * Get diagnostics for all open documents in the workspace.
       *
       * @param serverName - Optional specific LSP server to query
       * @param limit - Maximum number of file diagnostics to return
       * @returns Promise resolving to array of file diagnostics
       */
      workspaceDiagnostics(serverName, limit2) {
        return this.service.workspaceDiagnostics(serverName, limit2);
      }
      /**
       * Get code actions available at a specific location.
       *
       * @param uri - The document URI
       * @param range - The range to get code actions for
       * @param context - The code action context including diagnostics
       * @param serverName - Optional specific LSP server to query
       * @param limit - Maximum number of code actions to return
       * @returns Promise resolving to array of code actions
       */
      codeActions(uri, range, context2, serverName, limit2) {
        return this.service.codeActions(uri, range, context2, serverName, limit2);
      }
      /**
       * Apply a workspace edit (from code action or other sources).
       *
       * @param edit - The workspace edit to apply
       * @param serverName - Optional specific LSP server context
       * @returns Promise resolving to true if edit was applied successfully
       */
      applyWorkspaceEdit(edit2, serverName) {
        return this.service.applyWorkspaceEdit(edit2, serverName);
      }
    };
  }
});

// packages/core/dist/src/lsp/NativeLspService.js
import * as path77 from "path";
import { fileURLToPath as fileURLToPath7 } from "url";
import * as fs73 from "node:fs";
var debugLogger69, NativeLspService;
var init_NativeLspService = __esm({
  "packages/core/dist/src/lsp/NativeLspService.js"() {
    "use strict";
    init_esbuild_shims();
    init_LspConfigLoader();
    init_LspLanguageDetector();
    init_LspResponseNormalizer();
    init_LspServerManager();
    init_debugLogger();
    debugLogger69 = createDebugLogger("LSP");
    NativeLspService = class {
      static {
        __name(this, "NativeLspService");
      }
      config;
      workspaceContext;
      fileDiscoveryService;
      requireTrustedWorkspace;
      workspaceRoot;
      configLoader;
      serverManager;
      languageDetector;
      normalizer;
      constructor(config2, workspaceContext, _eventEmitter, fileDiscoveryService, _ideContextStore, options2 = {}) {
        this.config = config2;
        this.workspaceContext = workspaceContext;
        this.fileDiscoveryService = fileDiscoveryService;
        this.requireTrustedWorkspace = options2.requireTrustedWorkspace ?? true;
        this.workspaceRoot = options2.workspaceRoot ?? config2.getProjectRoot();
        this.configLoader = new LspConfigLoader(this.workspaceRoot);
        this.languageDetector = new LspLanguageDetector(this.workspaceContext, this.fileDiscoveryService);
        this.normalizer = new LspResponseNormalizer();
        this.serverManager = new LspServerManager(this.config, this.workspaceContext, this.fileDiscoveryService, {
          requireTrustedWorkspace: this.requireTrustedWorkspace,
          workspaceRoot: this.workspaceRoot
        });
      }
      /**
       * Discover and prepare LSP servers
       */
      async discoverAndPrepare() {
        const workspaceTrusted = this.config.isTrustedFolder();
        this.serverManager.clearServerHandles();
        if (this.requireTrustedWorkspace && !workspaceTrusted) {
          debugLogger69.warn("Workspace is not trusted, skipping LSP server discovery");
          return;
        }
        const userConfigs = await this.configLoader.loadUserConfigs();
        const extensionConfigs = await this.configLoader.loadExtensionConfigs(this.getActiveExtensions());
        const extensionOverrides = this.configLoader.collectExtensionToLanguageOverrides([
          ...extensionConfigs,
          ...userConfigs
        ]);
        const detectedLanguages = await this.languageDetector.detectLanguages(extensionOverrides);
        const serverConfigs = this.configLoader.mergeConfigs(detectedLanguages, extensionConfigs, userConfigs);
        this.serverManager.setServerConfigs(serverConfigs);
      }
      getActiveExtensions() {
        const configWithExtensions = this.config;
        return typeof configWithExtensions.getActiveExtensions === "function" ? configWithExtensions.getActiveExtensions() : [];
      }
      /**
       * Start all LSP servers
       */
      async start() {
        await this.serverManager.startAll();
      }
      /**
       * Stop all LSP servers
       */
      async stop() {
        await this.serverManager.stopAll();
      }
      /**
       * Get LSP server status
       */
      getStatus() {
        return this.serverManager.getStatus();
      }
      /**
       * Get ready server handles filtered by optional server name.
       * Each handle is guaranteed to have a valid connection.
       *
       * @param serverName - Optional server name to filter by
       * @returns Array of [serverName, handle] tuples with active connections
       */
      getReadyHandles(serverName) {
        return Array.from(this.serverManager.getHandles().entries()).filter((entry) => entry[1].status === "READY" && entry[1].connection !== void 0 && (!serverName || entry[0] === serverName));
      }
      /**
       * Workspace symbol search across all ready LSP servers.
       */
      async workspaceSymbols(query, limit2 = 50) {
        const results = [];
        for (const [serverName, handle] of Array.from(this.serverManager.getHandles())) {
          if (handle.status !== "READY" || !handle.connection) {
            continue;
          }
          try {
            await this.serverManager.warmupTypescriptServer(handle);
            let response = await handle.connection.request("workspace/symbol", {
              query
            });
            if (this.serverManager.isTypescriptServer(handle) && this.isNoProjectErrorResponse(response)) {
              await this.serverManager.warmupTypescriptServer(handle, true);
              response = await handle.connection.request("workspace/symbol", {
                query
              });
            }
            if (!Array.isArray(response)) {
              continue;
            }
            for (const item of response) {
              const symbol = this.normalizer.normalizeSymbolResult(item, serverName);
              if (symbol) {
                results.push(symbol);
              }
              if (results.length >= limit2) {
                return results.slice(0, limit2);
              }
            }
          } catch (error2) {
            debugLogger69.warn(`LSP workspace/symbol failed for ${serverName}:`, error2);
          }
        }
        return results.slice(0, limit2);
      }
      /**
       * Go to definition
       */
      async definitions(location, serverName, limit2 = 50) {
        const handles = this.getReadyHandles(serverName);
        for (const [name3, handle] of handles) {
          try {
            await this.serverManager.warmupTypescriptServer(handle);
            const response = await handle.connection.request("textDocument/definition", {
              textDocument: { uri: location.uri },
              position: location.range.start
            });
            const candidates = Array.isArray(response) ? response : response ? [response] : [];
            const definitions = [];
            for (const def2 of candidates) {
              const normalized2 = this.normalizer.normalizeLocationResult(def2, name3);
              if (normalized2) {
                definitions.push(normalized2);
                if (definitions.length >= limit2) {
                  return definitions.slice(0, limit2);
                }
              }
            }
            if (definitions.length > 0) {
              return definitions.slice(0, limit2);
            }
          } catch (error2) {
            debugLogger69.warn(`LSP textDocument/definition failed for ${name3}:`, error2);
          }
        }
        return [];
      }
      /**
       * Find references
       */
      async references(location, serverName, includeDeclaration = false, limit2 = 200) {
        const handles = this.getReadyHandles(serverName);
        for (const [name3, handle] of handles) {
          try {
            await this.serverManager.warmupTypescriptServer(handle);
            const response = await handle.connection.request("textDocument/references", {
              textDocument: { uri: location.uri },
              position: location.range.start,
              context: { includeDeclaration }
            });
            if (!Array.isArray(response)) {
              continue;
            }
            const refs = [];
            for (const ref of response) {
              const normalized2 = this.normalizer.normalizeLocationResult(ref, name3);
              if (normalized2) {
                refs.push(normalized2);
              }
              if (refs.length >= limit2) {
                return refs.slice(0, limit2);
              }
            }
            if (refs.length > 0) {
              return refs.slice(0, limit2);
            }
          } catch (error2) {
            debugLogger69.warn(`LSP textDocument/references failed for ${name3}:`, error2);
          }
        }
        return [];
      }
      /**
       * Get hover information
       */
      async hover(location, serverName) {
        const handles = this.getReadyHandles(serverName);
        for (const [name3, handle] of handles) {
          try {
            await this.serverManager.warmupTypescriptServer(handle);
            const response = await handle.connection.request("textDocument/hover", {
              textDocument: { uri: location.uri },
              position: location.range.start
            });
            const normalized2 = this.normalizer.normalizeHoverResult(response, name3);
            if (normalized2) {
              return normalized2;
            }
          } catch (error2) {
            debugLogger69.warn(`LSP textDocument/hover failed for ${name3}:`, error2);
          }
        }
        return null;
      }
      /**
       * Get document symbols
       */
      async documentSymbols(uri, serverName, limit2 = 200) {
        const handles = this.getReadyHandles(serverName);
        for (const [name3, handle] of handles) {
          try {
            await this.serverManager.warmupTypescriptServer(handle);
            const response = await handle.connection.request("textDocument/documentSymbol", {
              textDocument: { uri }
            });
            if (!Array.isArray(response)) {
              continue;
            }
            const symbols = [];
            for (const item of response) {
              if (!item || typeof item !== "object") {
                continue;
              }
              const itemObj = item;
              if (this.normalizer.isDocumentSymbol(itemObj)) {
                this.normalizer.collectDocumentSymbol(itemObj, uri, name3, symbols, limit2);
              } else {
                const normalized2 = this.normalizer.normalizeSymbolResult(itemObj, name3);
                if (normalized2) {
                  symbols.push(normalized2);
                }
              }
              if (symbols.length >= limit2) {
                return symbols.slice(0, limit2);
              }
            }
            if (symbols.length > 0) {
              return symbols.slice(0, limit2);
            }
          } catch (error2) {
            debugLogger69.warn(`LSP textDocument/documentSymbol failed for ${name3}:`, error2);
          }
        }
        return [];
      }
      /**
       * Find implementations
       */
      async implementations(location, serverName, limit2 = 50) {
        const handles = this.getReadyHandles(serverName);
        for (const [name3, handle] of handles) {
          try {
            await this.serverManager.warmupTypescriptServer(handle);
            const response = await handle.connection.request("textDocument/implementation", {
              textDocument: { uri: location.uri },
              position: location.range.start
            });
            const candidates = Array.isArray(response) ? response : response ? [response] : [];
            const implementations = [];
            for (const item of candidates) {
              const normalized2 = this.normalizer.normalizeLocationResult(item, name3);
              if (normalized2) {
                implementations.push(normalized2);
                if (implementations.length >= limit2) {
                  return implementations.slice(0, limit2);
                }
              }
            }
            if (implementations.length > 0) {
              return implementations.slice(0, limit2);
            }
          } catch (error2) {
            debugLogger69.warn(`LSP textDocument/implementation failed for ${name3}:`, error2);
          }
        }
        return [];
      }
      /**
       * Prepare call hierarchy
       */
      async prepareCallHierarchy(location, serverName, limit2 = 50) {
        const handles = this.getReadyHandles(serverName);
        for (const [name3, handle] of handles) {
          try {
            await this.serverManager.warmupTypescriptServer(handle);
            const response = await handle.connection.request("textDocument/prepareCallHierarchy", {
              textDocument: { uri: location.uri },
              position: location.range.start
            });
            const candidates = Array.isArray(response) ? response : response ? [response] : [];
            const items = [];
            for (const item of candidates) {
              const normalized2 = this.normalizer.normalizeCallHierarchyItem(item, name3);
              if (normalized2) {
                items.push(normalized2);
                if (items.length >= limit2) {
                  return items.slice(0, limit2);
                }
              }
            }
            if (items.length > 0) {
              return items.slice(0, limit2);
            }
          } catch (error2) {
            debugLogger69.warn(`LSP textDocument/prepareCallHierarchy failed for ${name3}:`, error2);
          }
        }
        return [];
      }
      /**
       * Find callers of the current function
       */
      async incomingCalls(item, serverName, limit2 = 50) {
        const targetServer = serverName ?? item.serverName;
        const handles = this.getReadyHandles(targetServer);
        for (const [name3, handle] of handles) {
          try {
            await this.serverManager.warmupTypescriptServer(handle);
            const response = await handle.connection.request("callHierarchy/incomingCalls", {
              item: this.normalizer.toCallHierarchyItemParams(item)
            });
            if (!Array.isArray(response)) {
              continue;
            }
            const calls = [];
            for (const call of response) {
              const normalized2 = this.normalizer.normalizeIncomingCall(call, name3);
              if (normalized2) {
                calls.push(normalized2);
                if (calls.length >= limit2) {
                  return calls.slice(0, limit2);
                }
              }
            }
            if (calls.length > 0) {
              return calls.slice(0, limit2);
            }
          } catch (error2) {
            debugLogger69.warn(`LSP callHierarchy/incomingCalls failed for ${name3}:`, error2);
          }
        }
        return [];
      }
      /**
       * Find functions called by the current function
       */
      async outgoingCalls(item, serverName, limit2 = 50) {
        const targetServer = serverName ?? item.serverName;
        const handles = this.getReadyHandles(targetServer);
        for (const [name3, handle] of handles) {
          try {
            await this.serverManager.warmupTypescriptServer(handle);
            const response = await handle.connection.request("callHierarchy/outgoingCalls", {
              item: this.normalizer.toCallHierarchyItemParams(item)
            });
            if (!Array.isArray(response)) {
              continue;
            }
            const calls = [];
            for (const call of response) {
              const normalized2 = this.normalizer.normalizeOutgoingCall(call, name3);
              if (normalized2) {
                calls.push(normalized2);
                if (calls.length >= limit2) {
                  return calls.slice(0, limit2);
                }
              }
            }
            if (calls.length > 0) {
              return calls.slice(0, limit2);
            }
          } catch (error2) {
            debugLogger69.warn(`LSP callHierarchy/outgoingCalls failed for ${name3}:`, error2);
          }
        }
        return [];
      }
      /**
       * Get diagnostics for a document
       */
      async diagnostics(uri, serverName) {
        const handles = this.getReadyHandles(serverName);
        const allDiagnostics = [];
        for (const [name3, handle] of handles) {
          try {
            await this.serverManager.warmupTypescriptServer(handle);
            const response = await handle.connection.request("textDocument/diagnostic", {
              textDocument: { uri }
            });
            if (response && typeof response === "object") {
              const responseObj = response;
              const items = responseObj["items"];
              if (Array.isArray(items)) {
                for (const item of items) {
                  const normalized2 = this.normalizer.normalizeDiagnostic(item, name3);
                  if (normalized2) {
                    allDiagnostics.push(normalized2);
                  }
                }
              }
            }
          } catch (error2) {
            debugLogger69.warn(`LSP textDocument/diagnostic failed for ${name3}:`, error2);
          }
        }
        return allDiagnostics;
      }
      /**
       * Get diagnostics for all documents in the workspace
       */
      async workspaceDiagnostics(serverName, limit2 = 100) {
        const handles = this.getReadyHandles(serverName);
        const results = [];
        for (const [name3, handle] of handles) {
          try {
            await this.serverManager.warmupTypescriptServer(handle);
            const response = await handle.connection.request("workspace/diagnostic", {
              previousResultIds: []
            });
            if (response && typeof response === "object") {
              const responseObj = response;
              const items = responseObj["items"];
              if (Array.isArray(items)) {
                for (const item of items) {
                  if (results.length >= limit2) {
                    break;
                  }
                  const normalized2 = this.normalizer.normalizeFileDiagnostics(item, name3);
                  if (normalized2 && normalized2.diagnostics.length > 0) {
                    results.push(normalized2);
                  }
                }
              }
            }
          } catch (error2) {
            debugLogger69.warn(`LSP workspace/diagnostic failed for ${name3}:`, error2);
          }
          if (results.length >= limit2) {
            break;
          }
        }
        return results.slice(0, limit2);
      }
      /**
       * Get code actions at the specified position
       */
      async codeActions(uri, range, context2, serverName, limit2 = 20) {
        const handles = this.getReadyHandles(serverName);
        for (const [name3, handle] of handles) {
          try {
            await this.serverManager.warmupTypescriptServer(handle);
            const lspDiagnostics = context2.diagnostics.map((d2) => this.normalizer.denormalizeDiagnostic(d2));
            const response = await handle.connection.request("textDocument/codeAction", {
              textDocument: { uri },
              range,
              context: {
                diagnostics: lspDiagnostics,
                only: context2.only,
                triggerKind: context2.triggerKind === "automatic" ? 2 : 1
                // CodeActionTriggerKind.Invoked
              }
            });
            if (!Array.isArray(response)) {
              continue;
            }
            const actions = [];
            for (const item of response) {
              const normalized2 = this.normalizer.normalizeCodeAction(item, name3);
              if (normalized2) {
                actions.push(normalized2);
                if (actions.length >= limit2) {
                  break;
                }
              }
            }
            if (actions.length > 0) {
              return actions.slice(0, limit2);
            }
          } catch (error2) {
            debugLogger69.warn(`LSP textDocument/codeAction failed for ${name3}:`, error2);
          }
        }
        return [];
      }
      /**
       * Apply workspace edit
       */
      async applyWorkspaceEdit(edit2, _serverName) {
        try {
          if (edit2.changes) {
            for (const [uri, edits] of Object.entries(edit2.changes)) {
              await this.applyTextEdits(uri, edits);
            }
          }
          if (edit2.documentChanges) {
            for (const docChange of edit2.documentChanges) {
              await this.applyTextEdits(docChange.textDocument.uri, docChange.edits);
            }
          }
          return true;
        } catch (error2) {
          debugLogger69.error("Failed to apply workspace edit:", error2);
          return false;
        }
      }
      /**
       * Apply text edits to a file
       */
      async applyTextEdits(uri, edits) {
        let filePath = uri.startsWith("file://") ? fileURLToPath7(uri) : uri;
        if (!path77.isAbsolute(filePath)) {
          filePath = path77.resolve(this.workspaceRoot, filePath);
        }
        if (!this.workspaceContext.isPathWithinWorkspace(filePath)) {
          throw new Error(`Refusing to apply edits outside workspace: ${filePath}`);
        }
        let content;
        try {
          content = fs73.readFileSync(filePath, "utf-8");
        } catch {
          content = "";
        }
        const sortedEdits = [...edits].sort((a2, b2) => {
          if (a2.range.start.line !== b2.range.start.line) {
            return b2.range.start.line - a2.range.start.line;
          }
          return b2.range.start.character - a2.range.start.character;
        });
        const lines = content.split("\n");
        for (const edit2 of sortedEdits) {
          const { range, newText } = edit2;
          const startLine = range.start.line;
          const endLine = range.end.line;
          const startChar = range.start.character;
          const endChar = range.end.character;
          const startLineText = lines[startLine] ?? "";
          const endLineText = lines[endLine] ?? "";
          const before = startLineText.slice(0, startChar);
          const after = endLineText.slice(endChar);
          const newLines = (before + newText + after).split("\n");
          lines.splice(startLine, endLine - startLine + 1, ...newLines);
        }
        fs73.writeFileSync(filePath, lines.join("\n"), "utf-8");
      }
      isNoProjectErrorResponse(response) {
        if (!response) {
          return false;
        }
        const message = typeof response === "string" ? response : typeof response["message"] === "string" ? response["message"] : "";
        return message.includes("No Project");
      }
    };
  }
});

// packages/core/dist/src/lsp/types.js
var init_types13 = __esm({
  "packages/core/dist/src/lsp/types.js"() {
    "use strict";
    init_esbuild_shims();
  }
});

// packages/core/dist/src/utils/pathReader.js
import { promises as fs74 } from "node:fs";
import path78 from "node:path";
async function readPathFromWorkspace(pathStr, config2) {
  const workspace = config2.getWorkspaceContext();
  const fileService = config2.getFileService();
  let absolutePath = null;
  if (path78.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 = path78.resolve(dir, pathStr);
      try {
        await fs74.access(potentialPath);
        absolutePath = potentialPath;
        break;
      } catch {
      }
    }
  }
  if (!absolutePath) {
    throw new Error(`Path not found in workspace: ${pathStr}`);
  }
  const stats = await fs74.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((p2) => path78.relative(config2.getTargetDir(), p2));
    const filteredFiles = fileService.filterFiles(relativeFiles, {
      respectGitIgnore: true,
      respectQwenIgnore: true
    });
    const finalFiles = filteredFiles.map((p2) => path78.resolve(config2.getTargetDir(), p2));
    for (const filePath of finalFiles) {
      const relativePathForDisplay = path78.relative(absolutePath, filePath);
      allParts.push({ text: `--- ${relativePathForDisplay} ---
` });
      const result = await processSingleFileContent(filePath, config2);
      allParts.push(result.llmContent);
      allParts.push({ text: "\n" });
    }
    allParts.push({ text: `--- End of content for directory: ${pathStr} ---` });
    return allParts;
  } else {
    const relativePath = path78.relative(config2.getTargetDir(), absolutePath);
    const filtered = fileService.filterFiles([relativePath], {
      respectGitIgnore: true,
      respectQwenIgnore: true
    });
    if (filtered.length === 0) {
      return [];
    }
    const result = await processSingleFileContent(absolutePath, config2);
    return [result.llmContent];
  }
}
var init_pathReader = __esm({
  "packages/core/dist/src/utils/pathReader.js"() {
    "use strict";
    init_esbuild_shims();
    init_esm11();
    init_fileUtils();
    __name(readPathFromWorkspace, "readPathFromWorkspace");
  }
});

// packages/core/dist/src/utils/readManyFiles.js
import * as fs75 from "node:fs";
import * as path79 from "node:path";
async function readManyFiles(config2, options2) {
  const { paths: inputPatterns } = options2;
  const seenFiles = /* @__PURE__ */ new Set();
  const contentParts = [];
  const files = [];
  try {
    const projectRoot = config2.getProjectRoot();
    for (const rawPattern of inputPatterns) {
      const normalizedPattern = rawPattern.replace(/\\/g, "/");
      const fullPath = path79.resolve(projectRoot, normalizedPattern);
      const stats = fs75.existsSync(fullPath) ? fs75.statSync(fullPath) : null;
      if (stats?.isDirectory()) {
        const { contentParts: dirParts, info } = await readDirectory(config2, fullPath);
        contentParts.push(...dirParts);
        files.push(info);
        continue;
      }
      if (stats?.isFile() && !seenFiles.has(fullPath)) {
        seenFiles.add(fullPath);
        const readResult = await readFileContent(config2, fullPath);
        if (readResult) {
          contentParts.push(...readResult.contentParts);
          files.push(readResult.info);
        }
      }
    }
  } catch (error2) {
    const errorMessage = `Error during file search: ${getErrorMessage(error2)}`;
    return {
      contentParts: [errorMessage],
      files: [],
      error: errorMessage
    };
  }
  if (contentParts.length > 0) {
    contentParts.unshift({ text: DEFAULT_OUTPUT_HEADER });
    contentParts.push({ text: DEFAULT_OUTPUT_TERMINATOR });
  } else {
    contentParts.push({
      text: "No files matching the criteria were found or all were skipped."
    });
  }
  return { contentParts, files };
}
async function readDirectory(config2, directoryPath) {
  const structure = await getFolderStructure(directoryPath, {
    fileService: config2.getFileService(),
    fileFilteringOptions: config2.getFileFilteringOptions()
  });
  const contentParts = [
    { text: `
Content from ${directoryPath}:
` },
    { text: structure }
  ];
  return {
    contentParts,
    info: {
      filePath: directoryPath,
      content: structure,
      isDirectory: true
    }
  };
}
async function readFileContent(config2, filePath) {
  try {
    const fileReadResult = await processSingleFileContent(filePath, config2);
    if (fileReadResult.error) {
      return null;
    }
    const prefixText = { text: `
Content from ${filePath}:
` };
    if (typeof fileReadResult.llmContent === "string") {
      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;
      }
      const contentParts2 = [prefixText, { text: fileContentForLlm }];
      return {
        contentParts: contentParts2,
        info: {
          filePath,
          content: fileContentForLlm,
          isDirectory: false
        }
      };
    }
    const contentParts = [prefixText, fileReadResult.llmContent];
    return {
      contentParts,
      info: {
        filePath,
        content: fileReadResult.llmContent,
        isDirectory: false
      }
    };
  } catch {
    return null;
  }
}
var DEFAULT_OUTPUT_HEADER, DEFAULT_OUTPUT_TERMINATOR;
var init_readManyFiles = __esm({
  "packages/core/dist/src/utils/readManyFiles.js"() {
    "use strict";
    init_esbuild_shims();
    init_errors();
    init_fileUtils();
    init_getFolderStructure();
    DEFAULT_OUTPUT_HEADER = "\n--- Content from referenced files ---";
    DEFAULT_OUTPUT_TERMINATOR = "\n--- End of content ---";
    __name(readManyFiles, "readManyFiles");
    __name(readDirectory, "readDirectory");
    __name(readFileContent, "readFileContent");
  }
});

// packages/core/dist/src/test-utils/config.js
var init_config4 = __esm({
  "packages/core/dist/src/test-utils/config.js"() {
    "use strict";
    init_esbuild_shims();
    init_config3();
  }
});

// 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_src2 = __esm({
  "packages/core/dist/src/index.js"() {
    "use strict";
    init_esbuild_shims();
    init_config3();
    init_storage();
    init_configResolver();
    init_models();
    init_models5();
    init_json_formatter();
    init_types10();
    init_client2();
    init_contentGenerator();
    init_coreToolScheduler();
    init_geminiChat();
    init_geminiRequest();
    init_logger();
    init_nonInteractiveToolExecutor();
    init_prompts();
    init_tokenLimits();
    init_turn();
    init_geminiRequest();
    init_coreToolScheduler();
    init_nonInteractiveToolExecutor();
    init_tool_names();
    init_paths();
    init_schemaValidator();
    init_errors();
    init_debugLogger();
    init_getFolderStructure();
    init_memoryDiscovery();
    init_gitIgnoreParser();
    init_gitUtils();
    init_editor();
    init_quotaErrorDetection();
    init_fileUtils();
    init_retry();
    init_shell_utils();
    init_tool_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_toml_to_markdown_converter();
    init_yaml_parser();
    init_configResolver();
    init_fileDiscoveryService();
    init_gitService();
    init_chatRecordingService();
    init_sessionService();
    init_fileSystemService();
    init_ide_client();
    init_ideContext();
    init_ide_installer();
    init_detect_ide();
    init_constants5();
    init_types7();
    init_shellExecutionService();
    init_tools();
    init_tool_error();
    init_tool_registry();
    init_subagents();
    init_skills();
    init_extension();
    init_mcp_prompts();
    init_read_file();
    init_ls();
    init_grep2();
    init_ripGrep();
    init_glob2();
    init_edit();
    init_exitPlanMode();
    init_glob2();
    init_grep2();
    init_ls();
    init_lsp();
    init_memoryTool();
    init_mcp_client();
    init_mcp_client_manager();
    init_mcp_tool();
    init_read_file();
    init_ripGrep();
    init_sdk_control_client_transport();
    init_shell();
    init_skill();
    init_task();
    init_todoWrite();
    init_tool_error();
    init_tool_registry();
    init_tools();
    init_web_fetch();
    init_web_search();
    init_write_file();
    init_chatRecordingService();
    init_fileDiscoveryService();
    init_fileSystemService();
    init_gitService();
    init_sessionService();
    init_shellExecutionService();
    init_constants8();
    init_LspConfigLoader();
    init_LspConnectionFactory();
    init_LspLanguageDetector();
    init_LspResponseNormalizer();
    init_LspServerManager();
    init_NativeLspClient();
    init_NativeLspService();
    init_types13();
    init_oauth_provider();
    init_oauth_token_storage();
    init_keychain_token_storage();
    init_oauth_utils();
    init_qwen_logger();
    init_telemetry();
    init_loggers();
    init_types();
    init_extension();
    init_mcp_prompts();
    init_skills();
    init_subagents();
    init_browser();
    init_editor();
    init_errorParsing();
    init_errors();
    init_fileUtils();
    init_fileSearch();
    init_formatters();
    init_generateContentResponseUtilities();
    init_getFolderStructure();
    init_gitIgnoreParser();
    init_gitUtils();
    init_ignorePatterns();
    init_memoryDiscovery();
    init_openaiLogger();
    init_partUtils();
    init_pathReader();
    init_paths();
    init_promptIdContext();
    init_projectSummary();
    init_quotaErrorDetection();
    init_readManyFiles();
    init_supportedImageFormats();
    init_retry();
    init_ripgrepUtils();
    init_schemaValidator();
    init_shell_utils();
    init_subagentGenerator();
    init_systemEncoding();
    init_terminalSerializer();
    init_textUtils();
    init_thoughtUtils();
    init_toml_to_markdown_converter();
    init_tool_utils();
    init_workspaceContext();
    init_yaml_parser();
    init_jsonl_utils();
    init_qwenOAuth2();
    init_config4();
    init_test_utils();
  }
});

// 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 REACT_ACTIVITY_TYPE = Symbol.for("react.activity");
    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;
    function noop8() {
    }
    __name(noop8, "noop");
    var ReactSharedInternals = { H: null, A: null, T: null, S: null };
    var hasOwnProperty2 = Object.prototype.hasOwnProperty;
    function ReactElement(type, key, props) {
      var refProp = props.ref;
      return {
        $$typeof: REACT_ELEMENT_TYPE,
        type,
        key,
        ref: void 0 !== refProp ? refProp : null,
        props
      };
    }
    __name(ReactElement, "ReactElement");
    function cloneAndReplaceKey(oldElement, newKey) {
      return ReactElement(oldElement.type, newKey, oldElement.props);
    }
    __name(cloneAndReplaceKey, "cloneAndReplaceKey");
    function isValidElement(object3) {
      return "object" === typeof object3 && null !== object3 && object3.$$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 resolveThenable(thenable) {
      switch (thenable.status) {
        case "fulfilled":
          return thenable.value;
        case "rejected":
          throw thenable.reason;
        default:
          switch ("string" === typeof thenable.status ? thenable.then(noop8, noop8) : (thenable.status = "pending", thenable.then(
            function(fulfilledValue) {
              "pending" === thenable.status && (thenable.status = "fulfilled", thenable.value = fulfilledValue);
            },
            function(error2) {
              "pending" === thenable.status && (thenable.status = "rejected", thenable.reason = error2);
            }
          )), thenable.status) {
            case "fulfilled":
              return thenable.value;
            case "rejected":
              throw thenable.reason;
          }
      }
      throw thenable;
    }
    __name(resolveThenable, "resolveThenable");
    function mapIntoArray(children, array2, 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),
                  array2,
                  escapedPrefix,
                  nameSoFar,
                  callback
                );
            }
        }
      if (invokeCallback)
        return callback = callback(children), invokeCallback = "" === nameSoFar ? "." + getElementKey(children, 0) : nameSoFar, isArrayImpl(callback) ? (escapedPrefix = "", null != invokeCallback && (escapedPrefix = invokeCallback.replace(userProvidedKeyEscapeRegex, "$&/") + "/"), mapIntoArray(callback, array2, escapedPrefix, "", function(c4) {
          return c4;
        })) : null != callback && (isValidElement(callback) && (callback = cloneAndReplaceKey(
          callback,
          escapedPrefix + (null == callback.key || children && children.key === callback.key ? "" : ("" + callback.key).replace(
            userProvidedKeyEscapeRegex,
            "$&/"
          ) + "/") + invokeCallback
        )), array2.push(callback)), 1;
      invokeCallback = 0;
      var nextNamePrefix = "" === nameSoFar ? "." : nameSoFar + ":";
      if (isArrayImpl(children))
        for (var i3 = 0; i3 < children.length; i3++)
          nameSoFar = children[i3], type = nextNamePrefix + getElementKey(nameSoFar, i3), invokeCallback += mapIntoArray(
            nameSoFar,
            array2,
            escapedPrefix,
            type,
            callback
          );
      else if (i3 = getIteratorFn(children), "function" === typeof i3)
        for (children = i3.call(children), i3 = 0; !(nameSoFar = children.next()).done; )
          nameSoFar = nameSoFar.value, type = nextNamePrefix + getElementKey(nameSoFar, i3++), invokeCallback += mapIntoArray(
            nameSoFar,
            array2,
            escapedPrefix,
            type,
            callback
          );
      else if ("object" === type) {
        if ("function" === typeof children.then)
          return mapIntoArray(
            resolveThenable(children),
            array2,
            escapedPrefix,
            nameSoFar,
            callback
          );
        array2 = String(children);
        throw Error(
          "Objects are not valid as a React child (found: " + ("[object Object]" === array2 ? "object with keys {" + Object.keys(children).join(", ") + "}" : array2) + "). If you meant to render a collection of children, use an array instead."
        );
      }
      return invokeCallback;
    }
    __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(error2) {
            if (0 === payload._status || -1 === payload._status)
              payload._status = 2, payload._result = error2;
          }
        );
        -1 === payload._status && (payload._status = 0, payload._result = ctor);
      }
      if (1 === payload._status) return payload._result.default;
      throw payload._result;
    }
    __name(lazyInitializer, "lazyInitializer");
    var reportGlobalError = "function" === typeof reportError ? reportError : function(error2) {
      if ("object" === typeof window && "function" === typeof window.ErrorEvent) {
        var event = new window.ErrorEvent("error", {
          bubbles: true,
          cancelable: true,
          message: "object" === typeof error2 && null !== error2 && "string" === typeof error2.message ? String(error2.message) : String(error2),
          error: error2
        });
        if (!window.dispatchEvent(event)) return;
      } else if ("object" === typeof process && "function" === typeof process.emit) {
        process.emit("uncaughtException", error2);
        return;
      }
      console.error(error2);
    };
    var 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 n3 = 0;
        mapChildren(children, function() {
          n3++;
        });
        return n3;
      }, "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.Activity = REACT_ACTIVITY_TYPE;
    exports2.Children = Children;
    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.cacheSignal = function() {
      return null;
    };
    exports2.cloneElement = function(element, config2, children) {
      if (null === element || void 0 === element)
        throw Error(
          "The argument must be a React element, but you passed " + element + "."
        );
      var props = assign({}, element.props), key = element.key;
      if (null != config2)
        for (propName in void 0 !== config2.key && (key = "" + config2.key), config2)
          !hasOwnProperty2.call(config2, propName) || "key" === propName || "__self" === propName || "__source" === propName || "ref" === propName && void 0 === config2.ref || (props[propName] = config2[propName]);
      var propName = arguments.length - 2;
      if (1 === propName) props.children = children;
      else if (1 < propName) {
        for (var childArray = Array(propName), i3 = 0; i3 < propName; i3++)
          childArray[i3] = arguments[i3 + 2];
        props.children = childArray;
      }
      return ReactElement(element.type, key, 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, config2, children) {
      var propName, props = {}, key = null;
      if (null != config2)
        for (propName in void 0 !== config2.key && (key = "" + config2.key), config2)
          hasOwnProperty2.call(config2, propName) && "key" !== propName && "__self" !== propName && "__source" !== propName && (props[propName] = config2[propName]);
      var childrenLength = arguments.length - 2;
      if (1 === childrenLength) props.children = children;
      else if (1 < childrenLength) {
        for (var childArray = Array(childrenLength), i3 = 0; i3 < childrenLength; i3++)
          childArray[i3] = arguments[i3 + 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, 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(noop8, reportGlobalError);
      } catch (error2) {
        reportGlobalError(error2);
      } finally {
        null !== prevTransition && null !== currentTransition.types && (prevTransition.types = currentTransition.types), 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, deps) {
      return ReactSharedInternals.H.useEffect(create3, deps);
    };
    exports2.useEffectEvent = function(callback) {
      return ReactSharedInternals.H.useEffectEvent(callback);
    };
    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.2.4";
  }
});

// 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 noop8() {
      }
      __name(noop8, "noop");
      function testStringCoercion(value) {
        return "" + value;
      }
      __name(testStringCoercion, "testStringCoercion");
      function checkKeyStringCoercion(value) {
        try {
          testStringCoercion(value);
          var JSCompiler_inline_result = false;
        } catch (e4) {
          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";
            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 (x3) {
              }
          }
        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 (x3) {
          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(config2) {
        if (hasOwnProperty2.call(config2, "key")) {
          var getter = Object.getOwnPropertyDescriptor(config2, "key").get;
          if (getter && getter.isReactWarning) return false;
        }
        return void 0 !== config2.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, props, owner, debugStack, debugTask) {
        var refProp = props.ref;
        type = {
          $$typeof: REACT_ELEMENT_TYPE,
          type,
          key,
          props,
          _owner: owner
        };
        null !== (void 0 !== refProp ? refProp : 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,
          oldElement.props,
          oldElement._owner,
          oldElement._debugStack,
          oldElement._debugTask
        );
        oldElement._store && (newKey._store.validated = oldElement._store.validated);
        return newKey;
      }
      __name(cloneAndReplaceKey, "cloneAndReplaceKey");
      function validateChildKeys(node) {
        isValidElement(node) ? node._store && (node._store.validated = 1) : "object" === typeof node && null !== node && node.$$typeof === REACT_LAZY_TYPE && ("fulfilled" === node._payload.status ? isValidElement(node._payload.value) && node._payload.value._store && (node._payload.value._store.validated = 1) : node._store && (node._store.validated = 1));
      }
      __name(validateChildKeys, "validateChildKeys");
      function isValidElement(object3) {
        return "object" === typeof object3 && null !== object3 && object3.$$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 resolveThenable(thenable) {
        switch (thenable.status) {
          case "fulfilled":
            return thenable.value;
          case "rejected":
            throw thenable.reason;
          default:
            switch ("string" === typeof thenable.status ? thenable.then(noop8, noop8) : (thenable.status = "pending", thenable.then(
              function(fulfilledValue) {
                "pending" === thenable.status && (thenable.status = "fulfilled", thenable.value = fulfilledValue);
              },
              function(error2) {
                "pending" === thenable.status && (thenable.status = "rejected", thenable.reason = error2);
              }
            )), thenable.status) {
              case "fulfilled":
                return thenable.value;
              case "rejected":
                throw thenable.reason;
            }
        }
        throw thenable;
      }
      __name(resolveThenable, "resolveThenable");
      function mapIntoArray(children, array2, 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),
                    array2,
                    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, array2, escapedPrefix, "", function(c4) {
            return c4;
          })) : 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), array2.push(callback));
          return 1;
        }
        invokeCallback = 0;
        childKey = "" === nameSoFar ? "." : nameSoFar + ":";
        if (isArrayImpl(children))
          for (var i3 = 0; i3 < children.length; i3++)
            nameSoFar = children[i3], type = childKey + getElementKey(nameSoFar, i3), invokeCallback += mapIntoArray(
              nameSoFar,
              array2,
              escapedPrefix,
              type,
              callback
            );
        else if (i3 = getIteratorFn(children), "function" === typeof i3)
          for (i3 === children.entries && (didWarnAboutMaps || console.warn(
            "Using Maps as children is not supported. Use an array of keyed ReactElements instead."
          ), didWarnAboutMaps = true), children = i3.call(children), i3 = 0; !(nameSoFar = children.next()).done; )
            nameSoFar = nameSoFar.value, type = childKey + getElementKey(nameSoFar, i3++), invokeCallback += mapIntoArray(
              nameSoFar,
              array2,
              escapedPrefix,
              type,
              callback
            );
        else if ("object" === type) {
          if ("function" === typeof children.then)
            return mapIntoArray(
              resolveThenable(children),
              array2,
              escapedPrefix,
              nameSoFar,
              callback
            );
          array2 = String(children);
          throw Error(
            "Objects are not valid as a React child (found: " + ("[object Object]" === array2 ? "object with keys {" + Object.keys(children).join(", ") + "}" : array2) + "). If you meant to render a collection of children, use an array instead."
          );
        }
        return invokeCallback;
      }
      __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 ioInfo = payload._ioInfo;
          null != ioInfo && (ioInfo.start = ioInfo.end = performance.now());
          ioInfo = payload._result;
          var thenable = ioInfo();
          thenable.then(
            function(moduleObject) {
              if (0 === payload._status || -1 === payload._status) {
                payload._status = 1;
                payload._result = moduleObject;
                var _ioInfo = payload._ioInfo;
                null != _ioInfo && (_ioInfo.end = performance.now());
                void 0 === thenable.status && (thenable.status = "fulfilled", thenable.value = moduleObject);
              }
            },
            function(error2) {
              if (0 === payload._status || -1 === payload._status) {
                payload._status = 2;
                payload._result = error2;
                var _ioInfo2 = payload._ioInfo;
                null != _ioInfo2 && (_ioInfo2.end = performance.now());
                void 0 === thenable.status && (thenable.status = "rejected", thenable.reason = error2);
              }
            }
          );
          ioInfo = payload._ioInfo;
          if (null != ioInfo) {
            ioInfo.value = thenable;
            var displayName = thenable.displayName;
            "string" === typeof displayName && (ioInfo.name = displayName);
          }
          -1 === payload._status && (payload._status = 0, payload._result = thenable);
        }
        if (1 === payload._status)
          return ioInfo = payload._result, void 0 === ioInfo && 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?",
            ioInfo
          ), "default" in ioInfo || 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'))",
            ioInfo
          ), ioInfo.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 releaseAsyncTransition() {
        ReactSharedInternals.asyncTransitions--;
      }
      __name(releaseAsyncTransition, "releaseAsyncTransition");
      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, resolve30, reject) {
        var queue = ReactSharedInternals.actQueue;
        if (null !== queue)
          if (0 !== queue.length)
            try {
              flushActQueue(queue);
              enqueueTask(function() {
                return recursivelyFlushAsyncActWork(returnValue, resolve30, reject);
              });
              return;
            } catch (error2) {
              ReactSharedInternals.thrownErrors.push(error2);
            }
          else ReactSharedInternals.actQueue = null;
        0 < ReactSharedInternals.thrownErrors.length ? (queue = aggregateErrors(ReactSharedInternals.thrownErrors), ReactSharedInternals.thrownErrors.length = 0, reject(queue)) : resolve30(returnValue);
      }
      __name(recursivelyFlushAsyncActWork, "recursivelyFlushAsyncActWork");
      function flushActQueue(queue) {
        if (!isFlushing) {
          isFlushing = true;
          var i3 = 0;
          try {
            for (; i3 < queue.length; i3++) {
              var callback = queue[i3];
              do {
                ReactSharedInternals.didUsePromise = false;
                var continuation = callback(false);
                if (null !== continuation) {
                  if (ReactSharedInternals.didUsePromise) {
                    queue[i3] = callback;
                    queue.splice(0, i3);
                    return;
                  }
                  callback = continuation;
                } else break;
              } while (1);
            }
            queue.length = 0;
          } catch (error2) {
            queue.splice(0, i3 + 1), ReactSharedInternals.thrownErrors.push(error2);
          } 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"), 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)."
        ]
      };
      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,
        actQueue: null,
        asyncTransitions: 0,
        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(error2) {
        if ("object" === typeof window && "function" === typeof window.ErrorEvent) {
          var event = new window.ErrorEvent("error", {
            bubbles: true,
            cancelable: true,
            message: "object" === typeof error2 && null !== error2 && "string" === typeof error2.message ? String(error2.message) : String(error2),
            error: error2
          });
          if (!window.dispatchEvent(event)) return;
        } else if ("object" === typeof process && "function" === typeof process.emit) {
          process.emit("uncaughtException", error2);
          return;
        }
        console.error(error2);
      }, 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")
      });
      var fnName = {
        map: mapChildren,
        forEach: /* @__PURE__ */ __name(function(children, forEachFunc, forEachContext) {
          mapChildren(
            children,
            function() {
              forEachFunc.apply(this, arguments);
            },
            forEachContext
          );
        }, "forEach"),
        count: /* @__PURE__ */ __name(function(children) {
          var n3 = 0;
          mapChildren(children, function() {
            n3++;
          });
          return n3;
        }, "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.Activity = REACT_ACTIVITY_TYPE;
      exports2.Children = fnName;
      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 (error2) {
          ReactSharedInternals.thrownErrors.push(error2);
        }
        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(resolve30, reject) {
              didAwaitActCall = true;
              thenable.then(
                function(returnValue) {
                  popActScope(prevActQueue, prevActScopeDepth);
                  if (0 === prevActScopeDepth) {
                    try {
                      flushActQueue(queue), enqueueTask(function() {
                        return recursivelyFlushAsyncActWork(
                          returnValue,
                          resolve30,
                          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 resolve30(returnValue);
                },
                function(error2) {
                  popActScope(prevActQueue, prevActScopeDepth);
                  0 < ReactSharedInternals.thrownErrors.length ? (error2 = aggregateErrors(
                    ReactSharedInternals.thrownErrors
                  ), ReactSharedInternals.thrownErrors.length = 0, reject(error2)) : reject(error2);
                }
              );
            }, "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(resolve30, reject) {
            didAwaitActCall = true;
            0 === prevActScopeDepth ? (ReactSharedInternals.actQueue = queue, enqueueTask(function() {
              return recursivelyFlushAsyncActWork(
                returnValue$jscomp$0,
                resolve30,
                reject
              );
            })) : resolve30(returnValue$jscomp$0);
          }, "then")
        };
      };
      exports2.cache = function(fn) {
        return function() {
          return fn.apply(null, arguments);
        };
      };
      exports2.cacheSignal = function() {
        return null;
      };
      exports2.captureOwnerStack = function() {
        var getCurrentStack = ReactSharedInternals.getCurrentStack;
        return null === getCurrentStack ? null : getCurrentStack();
      };
      exports2.cloneElement = function(element, config2, children) {
        if (null === element || void 0 === element)
          throw Error(
            "The argument must be a React element, but you passed " + element + "."
          );
        var props = assign({}, element.props), key = element.key, owner = element._owner;
        if (null != config2) {
          var JSCompiler_inline_result;
          a: {
            if (hasOwnProperty2.call(config2, "ref") && (JSCompiler_inline_result = Object.getOwnPropertyDescriptor(
              config2,
              "ref"
            ).get) && JSCompiler_inline_result.isReactWarning) {
              JSCompiler_inline_result = false;
              break a;
            }
            JSCompiler_inline_result = void 0 !== config2.ref;
          }
          JSCompiler_inline_result && (owner = getOwner());
          hasValidKey(config2) && (checkKeyStringCoercion(config2.key), key = "" + config2.key);
          for (propName in config2)
            !hasOwnProperty2.call(config2, propName) || "key" === propName || "__self" === propName || "__source" === propName || "ref" === propName && void 0 === config2.ref || (props[propName] = config2[propName]);
        }
        var propName = arguments.length - 2;
        if (1 === propName) props.children = children;
        else if (1 < propName) {
          JSCompiler_inline_result = Array(propName);
          for (var i3 = 0; i3 < propName; i3++)
            JSCompiler_inline_result[i3] = arguments[i3 + 2];
          props.children = JSCompiler_inline_result;
        }
        props = ReactElement(
          element.type,
          key,
          props,
          owner,
          element._debugStack,
          element._debugTask
        );
        for (key = 2; key < arguments.length; key++)
          validateChildKeys(arguments[key]);
        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, config2, children) {
        for (var i3 = 2; i3 < arguments.length; i3++)
          validateChildKeys(arguments[i3]);
        i3 = {};
        var key = null;
        if (null != config2)
          for (propName in didWarnAboutOldJSXRuntime || !("__self" in config2) || "key" in config2 || (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(config2) && (checkKeyStringCoercion(config2.key), key = "" + config2.key), config2)
            hasOwnProperty2.call(config2, propName) && "key" !== propName && "__self" !== propName && "__source" !== propName && (i3[propName] = config2[propName]);
        var childrenLength = arguments.length - 2;
        if (1 === childrenLength) i3.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);
          i3.children = childArray;
        }
        if (type && type.defaultProps)
          for (propName in childrenLength = type.defaultProps, childrenLength)
            void 0 === i3[propName] && (i3[propName] = childrenLength[propName]);
        key && defineKeyPropWarningGetter(
          i3,
          "function" === typeof type ? type.displayName || type.name || "Unknown" : type
        );
        var propName = 1e4 > ReactSharedInternals.recentlyCreatedOwnerStacks++;
        return ReactElement(
          type,
          key,
          i3,
          getOwner(),
          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) {
        ctor = { _status: -1, _result: ctor };
        var lazyType2 = {
          $$typeof: REACT_LAZY_TYPE,
          _payload: ctor,
          _init: lazyInitializer
        }, ioInfo = {
          name: "lazy",
          start: -1,
          end: -1,
          value: null,
          owner: null,
          debugStack: Error("react-stack-top-frame"),
          debugTask: console.createTask ? console.createTask("lazy()") : null
        };
        ctor._ioInfo = ioInfo;
        lazyType2._debugInfo = [{ awaited: ioInfo }];
        return lazyType2;
      };
      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 = {};
        currentTransition._updatedFibers = /* @__PURE__ */ new Set();
        ReactSharedInternals.T = currentTransition;
        try {
          var returnValue = scope(), onStartTransitionFinish = ReactSharedInternals.S;
          null !== onStartTransitionFinish && onStartTransitionFinish(currentTransition, returnValue);
          "object" === typeof returnValue && null !== returnValue && "function" === typeof returnValue.then && (ReactSharedInternals.asyncTransitions++, returnValue.then(releaseAsyncTransition, releaseAsyncTransition), returnValue.then(noop8, reportGlobalError));
        } catch (error2) {
          reportGlobalError(error2);
        } 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."
          )), null !== prevTransition && null !== currentTransition.types && (null !== prevTransition.types && prevTransition.types !== currentTransition.types && console.error(
            "We expected inner Transitions to have transferred the outer types set and that you cannot add to the outer Transition while inside the inner.This is a bug in React."
          ), prevTransition.types = currentTransition.types), 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, deps) {
        null == create3 && console.warn(
          "React Hook useEffect requires an effect callback. Did you forget to pass a callback to the hook?"
        );
        return resolveDispatcher().useEffect(create3, deps);
      };
      exports2.useEffectEvent = function(callback) {
        return resolveDispatcher().useEffectEvent(callback);
      };
      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.2.4";
      "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 process50 = globalThis.process;
    var processOk = /* @__PURE__ */ __name(function(process51) {
      return process51 && typeof process51 === "object" && typeof process51.removeListener === "function" && typeof process51.emit === "function" && typeof process51.reallyExit === "function" && typeof process51.listeners === "function" && typeof process51.kill === "function" && typeof process51.pid === "number" && typeof process51.on === "function";
    }, "processOk");
    if (!processOk(process50)) {
      module2.exports = function() {
        return function() {
        };
      };
    } else {
      assert4 = __require("assert");
      signals = require_signals();
      isWin = /^win/i.test(process50.platform);
      EE3 = __require("events");
      if (typeof EE3 !== "function") {
        EE3 = EE3.EventEmitter;
      }
      if (process50.__signal_exit_emitter__) {
        emitter = process50.__signal_exit_emitter__;
      } else {
        emitter = process50.__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() {
          };
        }
        assert4.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 {
            process50.removeListener(sig, sigListeners[sig]);
          } catch (er2) {
          }
        });
        process50.emit = originalProcessEmit;
        process50.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 = process50.listeners(sig);
          if (listeners.length === emitter.count) {
            unload();
            emit("exit", null, sig);
            emit("afterexit", null, sig);
            if (isWin && sig === "SIGHUP") {
              sig = "SIGINT";
            }
            process50.kill(process50.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 {
            process50.on(sig, sigListeners[sig]);
            return true;
          } catch (er2) {
            return false;
          }
        });
        process50.emit = processEmit;
        process50.reallyExit = processReallyExit;
      }, "load");
      module2.exports.load = load;
      originalProcessReallyExit = process50.reallyExit;
      processReallyExit = /* @__PURE__ */ __name(function processReallyExit2(code2) {
        if (!processOk(globalThis.process)) {
          return;
        }
        process50.exitCode = code2 || /* istanbul ignore next */
        0;
        emit("exit", process50.exitCode, null);
        emit("afterexit", process50.exitCode, null);
        originalProcessReallyExit.call(process50, process50.exitCode);
      }, "processReallyExit");
      originalProcessEmit = process50.emit;
      processEmit = /* @__PURE__ */ __name(function processEmit2(ev, arg) {
        if (ev === "exit" && processOk(globalThis.process)) {
          if (arg !== void 0) {
            process50.exitCode = arg;
          }
          var ret = originalProcessEmit.apply(this, arguments);
          emit("exit", process50.exitCode, null);
          emit("afterexit", process50.exitCode, null);
          return ret;
        } else {
          return originalProcessEmit.apply(this, arguments);
        }
      }, "processEmit");
    }
    var assert4;
    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_constants12 = __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/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(a2, b2) {
      var diff4 = a2.sortIndex - b2.sortIndex;
      return 0 !== diff4 ? diff4 : a2.id - b2.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(a2, b2) {
        var diff4 = a2.sortIndex - b2.sortIndex;
        return 0 !== diff4 ? diff4 : a2.id - b2.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 noop8() {
      }
      __name(noop8, "noop");
      function formatProdErrorMessage(code2) {
        var url2 = "https://react.dev/errors/" + code2;
        if (1 < arguments.length) {
          url2 += "?args[]=" + encodeURIComponent(arguments[1]);
          for (var i3 = 2; i3 < arguments.length; i3++)
            url2 += "&args[]=" + encodeURIComponent(arguments[i3]);
        }
        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 a2 = fiber, b2 = alternate; ; ) {
          var parentA = a2.return;
          if (null === parentA) break;
          var parentB = parentA.alternate;
          if (null === parentB) {
            b2 = parentA.return;
            if (null !== b2) {
              a2 = b2;
              continue;
            }
            break;
          }
          if (parentA.child === parentB.child) {
            for (parentB = parentA.child; parentB; ) {
              if (parentB === a2) return assertIsMounted(parentA), fiber;
              if (parentB === b2) return assertIsMounted(parentA), alternate;
              parentB = parentB.sibling;
            }
            throw Error(formatProdErrorMessage(188));
          }
          if (a2.return !== b2.return) a2 = parentA, b2 = parentB;
          else {
            for (var didFindChild = false, child$0 = parentA.child; child$0; ) {
              if (child$0 === a2) {
                didFindChild = true;
                a2 = parentA;
                b2 = parentB;
                break;
              }
              if (child$0 === b2) {
                didFindChild = true;
                b2 = parentA;
                a2 = parentB;
                break;
              }
              child$0 = child$0.sibling;
            }
            if (!didFindChild) {
              for (child$0 = parentB.child; child$0; ) {
                if (child$0 === a2) {
                  didFindChild = true;
                  a2 = parentB;
                  b2 = parentA;
                  break;
                }
                if (child$0 === b2) {
                  didFindChild = true;
                  b2 = parentB;
                  a2 = parentA;
                  break;
                }
                child$0 = child$0.sibling;
              }
              if (!didFindChild) throw Error(formatProdErrorMessage(189));
            }
          }
          if (a2.alternate !== b2) throw Error(formatProdErrorMessage(190));
        }
        if (3 !== a2.tag) throw Error(formatProdErrorMessage(188));
        return a2.stateNode.current === a2 ? 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 (x3) {
              }
          }
        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(x3) {
        x3 >>>= 0;
        return 0 === x3 ? 32 : 31 - (log$1(x3) / 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 = [], i3 = 0; 31 > i3; i3++) 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 (x3) {
            var match2 = x3.stack.trim().match(/\n( *(at )?)/);
            prefix = match2 && match2[1] || "";
            suffix = -1 < x3.stack.indexOf("\n    at") ? " (<anonymous>)" : -1 < x3.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 (x3) {
                      var control = x3;
                    }
                    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 (x3) {
          return "\nError generating stack: " + x3.message + "\n" + x3.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 error2 = Error(formatProdErrorMessage(418, ""));
        queueHydrationError(createCapturedValueAtFiber(error2, 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(error2) {
        null === hydrationErrors ? hydrationErrors = [error2] : hydrationErrors.push(error2);
      }
      __name(queueHydrationError, "queueHydrationError");
      function is(x3, y2) {
        return x3 === y2 && (0 !== x3 || 1 / x3 === 1 / y2) || x3 !== x3 && y2 !== y2;
      }
      __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 i3 = 0; i3 < contexts.length; i3++)
                if (dependency.context === contexts[i3]) {
                  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(resolve30) {
              entangledListeners.push(resolve30);
            }, "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 i3 = 0; i3 < listeners.length; i3++) (0, listeners[i3])();
        }
      }
      __name(pingEngtangledActionScope, "pingEngtangledActionScope");
      function chainThenableValue(thenable, result) {
        var listeners = [], thenableWithOverride = {
          status: "pending",
          value: null,
          reason: null,
          then: /* @__PURE__ */ __name(function(resolve30) {
            listeners.push(resolve30);
          }, "then")
        };
        thenable.then(
          function() {
            thenableWithOverride.status = "fulfilled";
            thenableWithOverride.value = result;
            for (var i3 = 0; i3 < listeners.length; i3++) (0, listeners[i3])(result);
          },
          function(error2) {
            thenableWithOverride.status = "rejected";
            thenableWithOverride.reason = error2;
            for (error2 = 0; error2 < listeners.length; error2++)
              (0, listeners[error2])(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(error2) {
                  if ("pending" === thenable.status) {
                    var rejectedThenable = thenable;
                    rejectedThenable.status = "rejected";
                    rejectedThenable.reason = error2;
                  }
                }
              );
            }
            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, i3 = concurrentlyUpdatedLanes = concurrentQueuesIndex = 0; i3 < endIndex; ) {
          var fiber = concurrentQueues[i3];
          concurrentQueues[i3++] = null;
          var queue = concurrentQueues[i3];
          concurrentQueues[i3++] = null;
          var update2 = concurrentQueues[i3];
          concurrentQueues[i3++] = null;
          var lane = concurrentQueues[i3];
          concurrentQueues[i3++] = 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 clone4 = {
                lane: queue.lane,
                tag: queue.tag,
                payload: queue.payload,
                callback: null,
                next: null
              };
              null === newLast ? newFirst = newLast = clone4 : newLast = newLast.next = clone4;
              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 i3 = 0; i3 < prevDeps.length && i3 < nextDeps.length; i3++)
          if (!objectIs(nextDeps[i3], prevDeps[i3])) 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(array2) {
              return array2.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 (error2) {
          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 (error2) {
            onActionError(actionQueue, node, error2);
          } 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(error2) {
            return onActionError(actionQueue, node, error2);
          }
        ) : 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, error2) {
        var last2 = actionQueue.pending;
        actionQueue.pending = null;
        if (null !== last2) {
          last2 = last2.next;
          do
            actionNode.status = "rejected", actionNode.reason = error2, notifyActionListeners(actionNode), actionNode = actionNode.next;
          while (actionNode !== last2);
        }
        actionQueue.action = null;
      }
      __name(onActionError, "onActionError");
      function notifyActionListeners(actionNode) {
        actionNode = actionNode.listeners;
        for (var i3 = 0; i3 < actionNode.length; i3++) (0, actionNode[i3])();
      }
      __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 (x3) {
            if (x3 === SuspenseException) throw SuspenseActionException;
            throw x3;
          }
        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 (error2) {
          dispatchSetStateInternal(
            fiber,
            queue,
            { then: /* @__PURE__ */ __name(function() {
            }, "then"), status: "rejected", reason: error2 },
            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 (error2) {
            } 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 (x3) {
            if (x3 === SuspenseException || x3 === SuspenseActionException) throw x3;
            var fiber = createFiber(29, x3, 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 (e4) {
          setTimeout(function() {
            throw e4;
          });
        }
      }
      __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 (e4) {
          setTimeout(function() {
            throw e4;
          });
        }
      }
      __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 error2 = errorInfo.value;
          update2.payload = function() {
            return getDerivedStateFromError(error2);
          };
          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 (error2) {
          captureCommitPhaseError(finishedWork, finishedWork.return, error2);
        }
      }
      __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 (error2) {
                    captureCommitPhaseError(
                      lastEffect,
                      nearestMountedAncestor,
                      error2
                    );
                  }
                }
              }
              updateQueue = updateQueue.next;
            } while (updateQueue !== firstEffect);
          }
        } catch (error2) {
          captureCommitPhaseError(finishedWork, finishedWork.return, error2);
        }
      }
      __name(commitHookEffectListUnmount, "commitHookEffectListUnmount");
      function commitClassCallbacks(finishedWork) {
        var updateQueue = finishedWork.updateQueue;
        if (null !== updateQueue) {
          var instance = finishedWork.stateNode;
          try {
            commitCallbacks(updateQueue, instance);
          } catch (error2) {
            captureCommitPhaseError(finishedWork, finishedWork.return, error2);
          }
        }
      }
      __name(commitClassCallbacks, "commitClassCallbacks");
      function safelyCallComponentWillUnmount(current, nearestMountedAncestor, instance) {
        instance.props = resolveClassComponentProps(
          current.type,
          current.memoizedProps
        );
        instance.state = current.memoizedState;
        try {
          instance.componentWillUnmount();
        } catch (error2) {
          captureCommitPhaseError(current, nearestMountedAncestor, error2);
        }
      }
      __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 (error2) {
          captureCommitPhaseError(current, nearestMountedAncestor, error2);
        }
      }
      __name(safelyAttachRef, "safelyAttachRef");
      function safelyDetachRef(current, nearestMountedAncestor) {
        var ref = current.ref, refCleanup = current.refCleanup;
        if (null !== ref)
          if ("function" === typeof refCleanup)
            try {
              refCleanup();
            } catch (error2) {
              captureCommitPhaseError(current, nearestMountedAncestor, error2);
            } 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 (error2) {
          captureCommitPhaseError(finishedWork, finishedWork.return, error2);
        }
      }
      __name(commitHostMount, "commitHostMount");
      function commitHostUpdate(finishedWork, newProps, oldProps) {
        try {
          commitUpdate(
            finishedWork.stateNode,
            finishedWork.type,
            oldProps,
            newProps,
            finishedWork
          );
        } catch (error2) {
          captureCommitPhaseError(finishedWork, finishedWork.return, error2);
        }
      }
      __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 (error2) {
          captureCommitPhaseError(finishedWork, finishedWork.return, error2);
        }
      }
      __name(commitHostPortalContainerChildren, "commitHostPortalContainerChildren");
      function commitHostSingletonAcquisition(finishedWork) {
        var singleton = finishedWork.stateNode, props = finishedWork.memoizedProps;
        try {
          acquireSingletonInstance(
            finishedWork.type,
            props,
            singleton,
            finishedWork
          );
        } catch (error2) {
          captureCommitPhaseError(finishedWork, finishedWork.return, error2);
        }
      }
      __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 (error2) {
                      captureCommitPhaseError(
                        finishedWork,
                        finishedWork.return,
                        error2
                      );
                    }
                  }
                  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 (error2) {
                  captureCommitPhaseError(finishedWork, finishedWork.return, error2);
                }
              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 (error2) {
                captureCommitPhaseError(finishedWork, finishedWork.return, error2);
              }
            }
            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 (error2) {
                    captureCommitPhaseError(
                      deletedFiber,
                      nearestMountedAncestor,
                      error2
                    );
                  }
                else
                  try {
                    removeChild(hostParent, deletedFiber.stateNode);
                  } catch (error2) {
                    captureCommitPhaseError(
                      deletedFiber,
                      nearestMountedAncestor,
                      error2
                    );
                  }
            } 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 (error2) {
            captureCommitPhaseError(finishedWork, finishedWork.return, error2);
          }
      }
      __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 i3 = 0; i3 < deletions.length; i3++) {
            var childToDelete = deletions[i3], 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 (error2) {
                  captureCommitPhaseError(finishedWork, finishedWork.return, error2);
                }
              }
              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 (error2) {
                captureCommitPhaseError(finishedWork, finishedWork.return, error2);
              }
            }
            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 (error2) {
                  captureCommitPhaseError(finishedWork, finishedWork.return, error2);
                }
              if (supportsPersistence) {
                flags = root.containerInfo;
                current = root.pendingChildren;
                try {
                  replaceContainerChildren(flags, current);
                } catch (error2) {
                  captureCommitPhaseError(finishedWork, finishedWork.return, error2);
                }
              }
            }
            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 (error2) {
                        captureCommitPhaseError(wasHidden, wasHidden.return, error2);
                      }
                    }
                  } else if (6 === root.tag) {
                    if (null === current) {
                      wasHidden = root;
                      try {
                        var instance = wasHidden.stateNode;
                        hoistableRoot ? hideTextInstance(instance) : unhideTextInstance(instance, wasHidden.memoizedProps);
                      } catch (error2) {
                        captureCommitPhaseError(wasHidden, wasHidden.return, error2);
                      }
                    }
                  } 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 (error2) {
            captureCommitPhaseError(finishedWork, finishedWork.return, error2);
          }
          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 (error2) {
                  captureCommitPhaseError(current, current.return, error2);
                }
              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 (error2) {
                  captureCommitPhaseError(current, current.return, error2);
                }
              }
              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 (error2) {
                captureCommitPhaseError(finishedWork, finishedWork.return, error2);
              }
            } 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 i3 = 0; i3 < deletions.length; i3++) {
              var childToDelete = deletions[i3];
              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 i3 = 0; i3 < deletions.length; i3++) {
              var childToDelete = deletions[i3];
              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:
              i3 = deletions.stateNode;
              i3._visibility & 2 && (i3._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 i3 = 0; i3 < tag2.length; i3++) {
              var check2 = tag2[i3], getSnapshot = check2.getSnapshot;
              check2 = check2.value;
              try {
                if (!objectIs(getSnapshot(), check2)) return false;
              } catch (error2) {
                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 (error2) {
          if (null !== returnFiber) throw workInProgress = returnFiber, error2;
          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, i3 = 0; i3 < recoverableErrors.length; i3++) {
                var recoverableError = recoverableErrors[i3];
                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, error2) {
        sourceFiber = createCapturedValueAtFiber(error2, 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, error2) {
        if (3 === sourceFiber.tag)
          captureCommitPhaseErrorOnRoot(sourceFiber, sourceFiber, error2);
        else
          for (; null !== nearestMountedAncestor; ) {
            if (3 === nearestMountedAncestor.tag) {
              captureCommitPhaseErrorOnRoot(
                nearestMountedAncestor,
                sourceFiber,
                error2
              );
              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(error2, sourceFiber);
                error2 = createClassErrorUpdate(2);
                instance = enqueueUpdate(nearestMountedAncestor, error2, 2);
                null !== instance && (initializeClassErrorUpdate(
                  error2,
                  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 a2 = fiber.retryLane;
          fiber.retryLane = 0 !== a2 && a2 < retryLane ? a2 : 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 React27 = 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 = React27.__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(error2) {
        if ("object" === typeof window && "function" === typeof window.ErrorEvent) {
          var event = new window.ErrorEvent("error", {
            bubbles: true,
            cancelable: true,
            message: "object" === typeof error2 && null !== error2 && "string" === typeof error2.message ? String(error2.message) : String(error2),
            error: error2
          });
          if (!window.dispatchEvent(event)) return;
        } else if ("object" === typeof process && "function" === typeof process.emit) {
          process.emit("uncaughtException", error2);
          return;
        }
        console.error(error2);
      }, 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, a2) {
        return fn(a2);
      };
      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(error2) {
        console.error(error2);
      };
      exports3.defaultOnRecoverableError = function(error2) {
        reportGlobalError(error2);
      };
      exports3.defaultOnUncaughtError = function(error2) {
        reportGlobalError(error2);
      };
      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, a2, b2, c4, d2) {
        var prevTransition = ReactSharedInternals.T, previousPriority = getCurrentUpdatePriority();
        try {
          return setCurrentUpdatePriority(2), ReactSharedInternals.T = null, fn(a2, b2, c4, d2);
        } 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 i3 = 0; i3 < selectors.length; i3++)
          hostRoot.push(getBoundingRect(selectors[i3]));
        for (selectors = hostRoot.length - 1; 0 < selectors; selectors--) {
          i3 = hostRoot[selectors];
          for (var targetLeft = i3.x, targetRight = targetLeft + i3.width, targetTop = i3.y, targetBottom = targetTop + i3.height, j2 = selectors - 1; 0 <= j2; j2--)
            if (selectors !== j2) {
              var otherRect = hostRoot[j2], 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 || i3.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 || i3.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 ? noop8 : 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, path125, index, value) {
        if (index >= path125.length) return value;
        var key = path125[index], updated = isArrayImpl(obj) ? obj.slice() : assign({}, obj);
        updated[key] = copyWithSetImpl(obj[key], path125, 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 i3 = 0; i3 < newPath.length - 1; i3++)
            if (oldPath[i3] !== newPath[i3]) {
              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, path125, index) {
        var key = path125[index], updated = isArrayImpl(obj) ? obj.slice() : assign({}, obj);
        if (index + 1 === path125.length)
          return isArrayImpl(updated) ? updated.splice(key, 1) : delete updated[key], updated;
        updated[key] = copyWithDeleteImpl(obj[key], path125, 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 noop8() {
      }
      __name(noop8, "noop");
      function setToSortedString(set) {
        var array2 = [];
        set.forEach(function(value) {
          array2.push(value);
        });
        return array2.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 a2 = fiber, b2 = alternate; ; ) {
          var parentA = a2.return;
          if (null === parentA) break;
          var parentB = parentA.alternate;
          if (null === parentB) {
            b2 = parentA.return;
            if (null !== b2) {
              a2 = b2;
              continue;
            }
            break;
          }
          if (parentA.child === parentB.child) {
            for (parentB = parentA.child; parentB; ) {
              if (parentB === a2) return assertIsMounted(parentA), fiber;
              if (parentB === b2) return assertIsMounted(parentA), alternate;
              parentB = parentB.sibling;
            }
            throw Error("Unable to find node on an unmounted component.");
          }
          if (a2.return !== b2.return) a2 = parentA, b2 = parentB;
          else {
            for (var didFindChild = false, _child = parentA.child; _child; ) {
              if (_child === a2) {
                didFindChild = true;
                a2 = parentA;
                b2 = parentB;
                break;
              }
              if (_child === b2) {
                didFindChild = true;
                b2 = parentA;
                a2 = parentB;
                break;
              }
              _child = _child.sibling;
            }
            if (!didFindChild) {
              for (_child = parentB.child; _child; ) {
                if (_child === a2) {
                  didFindChild = true;
                  a2 = parentB;
                  b2 = parentA;
                  break;
                }
                if (_child === b2) {
                  didFindChild = true;
                  b2 = parentB;
                  a2 = 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 (a2.alternate !== b2)
            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 !== a2.tag)
          throw Error("Unable to find node on an unmounted component.");
        return a2.stateNode.current === a2 ? 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 (x3) {
              }
          }
        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 i3 = type.length - 1; 0 <= i3; i3--)
                if ("string" === typeof type[i3].name) return type[i3].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(x3) {
        x3 >>>= 0;
        return 0 === x3 ? 32 : 31 - (log$1(x3) / 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 = [], i3 = 0; 31 > i3; i3++) 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 (x3) {
            var match2 = x3.stack.trim().match(/\n( *(at )?)/);
            prefix = match2 && match2[1] || "";
            suffix = -1 < x3.stack.indexOf("\n    at") ? " (<anonymous>)" : -1 < x3.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 (x3) {
                      var control = x3;
                    }
                    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(error2) {
        var prevPrepareStackTrace = Error.prepareStackTrace;
        Error.prepareStackTrace = void 0;
        error2 = error2.stack;
        Error.prepareStackTrace = prevPrepareStackTrace;
        error2.startsWith("Error: react-stack-top-frame\n") && (error2 = error2.slice(29));
        prevPrepareStackTrace = error2.indexOf("\n");
        -1 !== prevPrepareStackTrace && (error2 = error2.slice(prevPrepareStackTrace + 1));
        prevPrepareStackTrace = error2.indexOf("react-stack-bottom-frame");
        -1 !== prevPrepareStackTrace && (prevPrepareStackTrace = error2.lastIndexOf(
          "\n",
          prevPrepareStackTrace
        ));
        if (-1 !== prevPrepareStackTrace)
          error2 = error2.slice(0, prevPrepareStackTrace);
        else return "";
        return error2;
      }
      __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 i3 = debugInfo.length - 1; 0 <= i3; i3--) {
                var entry = debugInfo[i3];
                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 (x3) {
          return "\nError generating stack: " + x3.message + "\n" + x3.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(c4) {
        null === c4 && console.error(
          "Expected host context to exist. This error is likely caused by a bug in React. Please file an issue."
        );
        return c4;
      }
      __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(object3) {
        return Object.prototype.toString.call(object3).replace(/^\[object (.*)\]$/, function(m3, 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 i3 = 0; i3 < debugInfo.length; i3++) {
            var serverComponentName = debugInfo[i3].name;
            "string" === typeof serverComponentName && (skipToNode += indentation(indent) + "<" + serverComponentName + ">\n", indent++);
          }
        debugInfo = "";
        i3 = node.fiber.pendingProps;
        if (6 === node.fiber.tag)
          debugInfo = describeTextDiff(i3, 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 i3)
              if (i3.hasOwnProperty(propName) && "children" !== propName) {
                var propValue = describePropValue(i3[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,
              i3,
              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,
              i3,
              node.serverProps,
              indent
            ), indent++);
        var propName = "";
        i3 = node.fiber.child;
        for (serverComponentName = 0; i3 && serverComponentName < node.children.length; )
          maxLength = node.children[serverComponentName], maxLength.fiber === i3 ? (propName += describeNode(maxLength, indent), serverComponentName++) : propName += describeSiblingFiber(i3, indent), i3 = i3.sibling;
        i3 && 0 < node.children.length && (propName += indentation(indent) + "...\n");
        i3 = node.serverTail;
        null === node.serverProps && indent--;
        for (node = 0; node < i3.length; node++)
          serverComponentName = i3[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 (x3) {
          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 (x3) {
          JSCompiler_inline_result = "\nError generating stack: " + x3.message + "\n" + x3.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(error2) {
        null === hydrationErrors ? hydrationErrors = [error2] : hydrationErrors.push(error2);
      }
      __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(x3, y2) {
        return x3 === y2 && (0 !== x3 || 1 / x3 === 1 / y2) || x3 !== x3 && y2 !== y2;
      }
      __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 i3 = 0; i3 < contexts.length; i3++)
                if (dependency.context === contexts[i3]) {
                  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(resolve30) {
              entangledListeners.push(resolve30);
            }, "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 i3 = 0; i3 < listeners.length; i3++) (0, listeners[i3])();
        }
      }
      __name(pingEngtangledActionScope, "pingEngtangledActionScope");
      function chainThenableValue(thenable, result) {
        var listeners = [], thenableWithOverride = {
          status: "pending",
          value: null,
          reason: null,
          then: /* @__PURE__ */ __name(function(resolve30) {
            listeners.push(resolve30);
          }, "then")
        };
        thenable.then(
          function() {
            thenableWithOverride.status = "fulfilled";
            thenableWithOverride.value = result;
            for (var i3 = 0; i3 < listeners.length; i3++) (0, listeners[i3])(result);
          },
          function(error2) {
            thenableWithOverride.status = "rejected";
            thenableWithOverride.reason = error2;
            for (error2 = 0; error2 < listeners.length; error2++)
              (0, listeners[error2])(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(error2) {
                  if ("pending" === thenable.status) {
                    var rejectedThenable = thenable;
                    rejectedThenable.status = "rejected";
                    rejectedThenable.reason = error2;
                  }
                }
              );
            }
            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, i3 = concurrentlyUpdatedLanes = concurrentQueuesIndex = 0; i3 < endIndex; ) {
          var fiber = concurrentQueues[i3];
          concurrentQueues[i3++] = null;
          var queue = concurrentQueues[i3];
          concurrentQueues[i3++] = null;
          var update2 = concurrentQueues[i3];
          concurrentQueues[i3++] = null;
          var lane = concurrentQueues[i3];
          concurrentQueues[i3++] = 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 clone4 = {
                lane: queue.lane,
                tag: queue.tag,
                payload: queue.payload,
                callback: null,
                next: null
              };
              null === newLast ? newFirst = newLast = clone4 : newLast = newLast.next = clone4;
              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 = "", i3 = 0; i3 <= hookTypesUpdateIndexDev; i3++) {
              var oldHookName = hookTypesDev[i3], newHookName = i3 === hookTypesUpdateIndexDev ? hookName : oldHookName;
              for (oldHookName = i3 + 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 i3 = 0; i3 < prevDeps.length && i3 < nextDeps.length; i3++)
          if (!objectIs(nextDeps[i3], prevDeps[i3])) 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(array2) {
              return array2.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 (error2) {
          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 (error2) {
            onActionError(actionQueue, node, error2);
          } 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(error2) {
            return onActionError(actionQueue, node, error2);
          }
        ), 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, error2) {
        var last2 = actionQueue.pending;
        actionQueue.pending = null;
        if (null !== last2) {
          last2 = last2.next;
          do
            actionNode.status = "rejected", actionNode.reason = error2, notifyActionListeners(actionNode), actionNode = actionNode.next;
          while (actionNode !== last2);
        }
        actionQueue.action = null;
      }
      __name(onActionError, "onActionError");
      function notifyActionListeners(actionNode) {
        actionNode = actionNode.listeners;
        for (var i3 = 0; i3 < actionNode.length; i3++) (0, actionNode[i3])();
      }
      __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 (x3) {
            if (x3 === SuspenseException) throw SuspenseActionException;
            throw x3;
          }
        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 (error2) {
          dispatchSetStateInternal(
            fiber,
            queue,
            { then: /* @__PURE__ */ __name(function() {
            }, "then"), status: "rejected", reason: error2 },
            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 (error2) {
            } 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), i3 = 0; i3 < keys.length; i3++) {
          var key = keys[i3];
          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 (x3) {
            if (x3 === SuspenseException || x3 === SuspenseActionException) throw x3;
            var fiber = createFiber(29, x3, 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 i3 = debugInfo.length - 1; 0 <= i3; i3--)
                if ("string" === typeof debugInfo[i3].stack) {
                  fiber._debugOwner = debugInfo[i3];
                  fiber._debugTask = debugInfo[i3].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 error2 = errorInfo.value;
          if (null !== ReactSharedInternals.actQueue)
            ReactSharedInternals.thrownErrors.push(error2);
          else {
            var onUncaughtError = root.onUncaughtError;
            onUncaughtError(error2, { componentStack: errorInfo.stack });
          }
        } catch (e4) {
          setTimeout(function() {
            throw e4;
          });
        }
      }
      __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 (e4) {
          setTimeout(function() {
            throw e4;
          });
        }
      }
      __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 error2 = errorInfo.value;
          update2.payload = function() {
            return getDerivedStateFromError(error2);
          };
          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 error2 = 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 = [error2] : workInProgressRootConcurrentErrors.push(error2);
        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, error2 = sourceFiber.stateNode, 0 === (sourceFiber.flags & 128) && ("function" === typeof returnFiber.getDerivedStateFromError || null !== error2 && "function" === typeof error2.componentDidCatch && (null === legacyErrorBoundariesThatAlreadyFailed || !legacyErrorBoundariesThatAlreadyFailed.has(error2))))
                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 i3 = 0; i3 < nextProps.length; i3++) {
              if (!validateSuspenseListNestedChild(nextProps[i3], i3)) break a;
            }
          else if (i3 = getIteratorFn(nextProps), "function" === typeof i3) {
            if (i3 = i3.call(nextProps))
              for (var step = i3.next(), _i = 0; !step.done; step = i3.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(n3, a2) {
                    console.error(
                      "%s must not return anything besides a function, which is used for clean-up.%s",
                      n3,
                      a2
                    );
                  },
                  hookName,
                  addendum
                );
              }
              updateQueue = updateQueue.next;
            } while (updateQueue !== firstEffect);
          }
        } catch (error2) {
          captureCommitPhaseError(finishedWork, finishedWork.return, error2);
        }
      }
      __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 (error2) {
          captureCommitPhaseError(finishedWork, finishedWork.return, error2);
        }
      }
      __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 (error2) {
            captureCommitPhaseError(finishedWork, finishedWork.return, error2);
          }
        }
      }
      __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 (error2) {
          captureCommitPhaseError(finishedWork, finishedWork.return, error2);
        }
      }
      __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 (error2) {
          captureCommitPhaseError(current2, nearestMountedAncestor, error2);
        }
      }
      __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 (error2) {
              captureCommitPhaseError(current2, nearestMountedAncestor, error2);
            } 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 (error2) {
          captureCommitPhaseError(finishedWork, finishedWork.return, error2);
        }
      }
      __name(commitHostMount, "commitHostMount");
      function commitHostUpdate(finishedWork, newProps, oldProps) {
        try {
          runWithFiberInDEV(
            finishedWork,
            commitUpdate,
            finishedWork.stateNode,
            finishedWork.type,
            oldProps,
            newProps,
            finishedWork
          );
        } catch (error2) {
          captureCommitPhaseError(finishedWork, finishedWork.return, error2);
        }
      }
      __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 (error2) {
          captureCommitPhaseError(finishedWork, finishedWork.return, error2);
        }
      }
      __name(commitHostPortalContainerChildren, "commitHostPortalContainerChildren");
      function commitHostSingletonAcquisition(finishedWork) {
        var singleton = finishedWork.stateNode, props = finishedWork.memoizedProps;
        try {
          runWithFiberInDEV(
            finishedWork,
            acquireSingletonInstance,
            finishedWork.type,
            props,
            singleton,
            finishedWork
          );
        } catch (error2) {
          captureCommitPhaseError(finishedWork, finishedWork.return, error2);
        }
      }
      __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 (error2) {
                captureCommitPhaseError(finishedWork, finishedWork.return, error2);
              }
            }
            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 (error2) {
                captureCommitPhaseError(finishedWork, finishedWork.return, error2);
              }
            } 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 (error2) {
                    captureCommitPhaseError(
                      deletedFiber,
                      nearestMountedAncestor,
                      error2
                    );
                  }
                else
                  try {
                    runWithFiberInDEV(
                      deletedFiber,
                      removeChild,
                      hostParent,
                      deletedFiber.stateNode
                    );
                  } catch (error2) {
                    captureCommitPhaseError(
                      deletedFiber,
                      nearestMountedAncestor,
                      error2
                    );
                  }
            } 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 (error2) {
            captureCommitPhaseError(finishedWork, finishedWork.return, error2);
          }
      }
      __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 i3 = 0; i3 < deletions.length; i3++) {
            var root = root$jscomp$0, returnFiber = parentFiber, deletedFiber = deletions[i3];
            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 (error2) {
                  captureCommitPhaseError(
                    finishedWork,
                    finishedWork.return,
                    error2
                  );
                }
              }
              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 (error2) {
                captureCommitPhaseError(finishedWork, finishedWork.return, error2);
              }
            }
            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 (error2) {
                  captureCommitPhaseError(
                    finishedWork,
                    finishedWork.return,
                    error2
                  );
                }
              if (supportsPersistence) {
                flags = root.containerInfo;
                current2 = root.pendingChildren;
                try {
                  runWithFiberInDEV(
                    finishedWork,
                    replaceContainerChildren,
                    flags,
                    current2
                  );
                } catch (error2) {
                  captureCommitPhaseError(
                    finishedWork,
                    finishedWork.return,
                    error2
                  );
                }
              }
            }
            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 (error2) {
                        captureCommitPhaseError(
                          wasHidden,
                          wasHidden.return,
                          error2
                        );
                      }
                    }
                  } 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 (error2) {
                        captureCommitPhaseError(
                          wasHidden,
                          wasHidden.return,
                          error2
                        );
                      }
                    }
                  } 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 (error2) {
            captureCommitPhaseError(finishedWork, finishedWork.return, error2);
          }
          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 (error2) {
                captureCommitPhaseError(finishedWork, finishedWork.return, error2);
              }
            }
            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 (error2) {
                captureCommitPhaseError(finishedWork, finishedWork.return, error2);
              }
            } 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 (error2) {
                captureCommitPhaseError(finishedWork, finishedWork.return, error2);
              }
            } 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 i3 = 0; i3 < deletions.length; i3++) {
              var childToDelete = deletions[i3];
              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 i3 = 0; i3 < deletions.length; i3++) {
              var childToDelete = deletions[i3];
              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 i3 = 0; i3 < tag2.length; i3++) {
              var check2 = tag2[i3], getSnapshot = check2.getSnapshot;
              check2 = check2.value;
              try {
                if (!objectIs(getSnapshot(), check2)) return false;
              } catch (error2) {
                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 (error2) {
          if (null !== returnFiber) throw workInProgress = returnFiber, error2;
          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, error2) {
        sourceFiber = createCapturedValueAtFiber(error2, 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, error2) {
        isRunningInsertionEffect = false;
        if (3 === sourceFiber.tag)
          captureCommitPhaseErrorOnRoot(sourceFiber, sourceFiber, error2);
        else {
          for (; null !== nearestMountedAncestor; ) {
            if (3 === nearestMountedAncestor.tag) {
              captureCommitPhaseErrorOnRoot(
                nearestMountedAncestor,
                sourceFiber,
                error2
              );
              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(error2, sourceFiber);
                error2 = createClassErrorUpdate(2);
                instance = enqueueUpdate(nearestMountedAncestor, error2, 2);
                null !== instance && (initializeClassErrorUpdate(
                  error2,
                  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",
            error2
          );
        }
      }
      __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 a2 = fiber.retryLane;
          fiber.retryLane = 0 !== a2 && a2 < retryLane ? a2 : 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 React27 = 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 = React27.__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 (error2) {
            captureCommitPhaseError(finishedWork, finishedWork.return, error2);
          }
        }, "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 (error2) {
            captureCommitPhaseError(finishedWork, finishedWork.return, error2);
          }
        }, "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 (error2) {
            captureCommitPhaseError(current2, nearestMountedAncestor, error2);
          }
        }, "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 (error2) {
            captureCommitPhaseError(current2, nearestMountedAncestor, error2);
          }
        }, "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(error2) {
        if ("object" === typeof window && "function" === typeof window.ErrorEvent) {
          var event = new window.ErrorEvent("error", {
            bubbles: true,
            cancelable: true,
            message: "object" === typeof error2 && null !== error2 && "string" === typeof error2.message ? String(error2.message) : String(error2),
            error: error2
          });
          if (!window.dispatchEvent(event)) return;
        } else if ("object" === typeof process && "function" === typeof process.emit) {
          process.emit("uncaughtException", error2);
          return;
        }
        console.error(error2);
      }, 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 (e4) {
        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, path125, value) {
        id = findHook(fiber, id);
        null !== id && (path125 = copyWithSetImpl(id.memoizedState, path125, 0, value), id.memoizedState = path125, id.baseState = path125, fiber.memoizedProps = assign({}, fiber.memoizedProps), path125 = enqueueConcurrentRenderForLane(fiber, 2), null !== path125 && scheduleUpdateOnFiber(path125, fiber, 2));
      }, "overrideHookState");
      overrideHookStateDeletePath = /* @__PURE__ */ __name(function(fiber, id, path125) {
        id = findHook(fiber, id);
        null !== id && (path125 = copyWithDeleteImpl(id.memoizedState, path125, 0), id.memoizedState = path125, id.baseState = path125, fiber.memoizedProps = assign({}, fiber.memoizedProps), path125 = enqueueConcurrentRenderForLane(fiber, 2), null !== path125 && scheduleUpdateOnFiber(path125, 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, path125, value) {
        fiber.pendingProps = copyWithSetImpl(fiber.memoizedProps, path125, 0, value);
        fiber.alternate && (fiber.alternate.pendingProps = fiber.pendingProps);
        path125 = enqueueConcurrentRenderForLane(fiber, 2);
        null !== path125 && scheduleUpdateOnFiber(path125, fiber, 2);
      }, "overrideProps");
      overridePropsDeletePath = /* @__PURE__ */ __name(function(fiber, path125) {
        fiber.pendingProps = copyWithDeleteImpl(fiber.memoizedProps, path125, 0);
        fiber.alternate && (fiber.alternate.pendingProps = fiber.pendingProps);
        path125 = enqueueConcurrentRenderForLane(fiber, 2);
        null !== path125 && scheduleUpdateOnFiber(path125, 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, a2) {
        return fn(a2);
      };
      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(error2) {
        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 error2 && null !== error2 && "string" === typeof error2.environmentName ? bindToConsole(
          "error",
          ["%o\n\n%s\n\n%s\n", error2, componentNameMessage, recreateMessage],
          error2.environmentName
        )() : console.error(
          "%o\n\n%s\n\n%s\n",
          error2,
          componentNameMessage,
          recreateMessage
        );
      };
      exports3.defaultOnRecoverableError = function(error2) {
        reportGlobalError(error2);
      };
      exports3.defaultOnUncaughtError = function(error2) {
        reportGlobalError(error2);
        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, a2, b2, c4, d2) {
        var prevTransition = ReactSharedInternals.T, previousPriority = getCurrentUpdatePriority();
        try {
          return setCurrentUpdatePriority(2), ReactSharedInternals.T = null, fn(a2, b2, c4, d2);
        } 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 i3 = 0; i3 < selectors.length; i3++)
          hostRoot.push(getBoundingRect(selectors[i3]));
        for (selectors = hostRoot.length - 1; 0 < selectors; selectors--) {
          i3 = hostRoot[selectors];
          for (var targetLeft = i3.x, targetRight = targetLeft + i3.width, targetTop = i3.y, targetBottom = targetTop + i3.height, j2 = selectors - 1; 0 <= j2; j2--)
            if (selectors !== j2) {
              var otherRect = hostRoot[j2], 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 || i3.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 || i3.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 ? noop8 : 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/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 k2 = __webpack_require__2(206), p2 = __webpack_require__2(189), q2 = Object.assign, w2 = p2.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED, x3 = [], y2 = null;
                function z2() {
                  if (null === y2) {
                    var a2 = /* @__PURE__ */ new Map();
                    try {
                      A4.useContext({
                        _currentValue: null
                      }), A4.useState(null), A4.useReducer(function(c4) {
                        return c4;
                      }, null), A4.useRef(null), "function" === typeof A4.useCacheRefresh && A4.useCacheRefresh(), A4.useLayoutEffect(function() {
                      }), A4.useInsertionEffect(function() {
                      }), A4.useEffect(function() {
                      }), A4.useImperativeHandle(void 0, function() {
                        return null;
                      }), A4.useDebugValue(null), A4.useCallback(function() {
                      }), A4.useMemo(function() {
                        return null;
                      }), "function" === typeof A4.useMemoCache && A4.useMemoCache(0);
                    } finally {
                      var b2 = x3;
                      x3 = [];
                    }
                    for (var e4 = 0; e4 < b2.length; e4++) {
                      var g2 = b2[e4];
                      a2.set(g2.primitive, k2.parse(g2.stackError));
                    }
                    y2 = a2;
                  }
                  return y2;
                }
                __name(z2, "z");
                var B2 = null;
                function C2() {
                  var a2 = B2;
                  null !== a2 && (B2 = a2.next);
                  return a2;
                }
                __name(C2, "C");
                var A4 = {
                  use: /* @__PURE__ */ __name(function use2() {
                    throw Error("Support for `use` not yet implemented in react-debug-tools.");
                  }, "use"),
                  readContext: /* @__PURE__ */ __name(function readContext(a2) {
                    return a2._currentValue;
                  }, "readContext"),
                  useCacheRefresh: /* @__PURE__ */ __name(function useCacheRefresh() {
                    var a2 = C2();
                    x3.push({
                      primitive: "CacheRefresh",
                      stackError: Error(),
                      value: null !== a2 ? a2.memoizedState : function() {
                      }
                    });
                    return function() {
                    };
                  }, "useCacheRefresh"),
                  useCallback: /* @__PURE__ */ __name(function useCallback54(a2) {
                    var b2 = C2();
                    x3.push({
                      primitive: "Callback",
                      stackError: Error(),
                      value: null !== b2 ? b2.memoizedState[0] : a2
                    });
                    return a2;
                  }, "useCallback"),
                  useContext: /* @__PURE__ */ __name(function useContext22(a2) {
                    x3.push({
                      primitive: "Context",
                      stackError: Error(),
                      value: a2._currentValue
                    });
                    return a2._currentValue;
                  }, "useContext"),
                  useEffect: /* @__PURE__ */ __name(function useEffect56(a2) {
                    C2();
                    x3.push({
                      primitive: "Effect",
                      stackError: Error(),
                      value: a2
                    });
                  }, "useEffect"),
                  useImperativeHandle: /* @__PURE__ */ __name(function useImperativeHandle(a2) {
                    C2();
                    var b2 = void 0;
                    null !== a2 && "object" === _typeof2(a2) && (b2 = a2.current);
                    x3.push({
                      primitive: "ImperativeHandle",
                      stackError: Error(),
                      value: b2
                    });
                  }, "useImperativeHandle"),
                  useDebugValue: /* @__PURE__ */ __name(function useDebugValue(a2, b2) {
                    x3.push({
                      primitive: "DebugValue",
                      stackError: Error(),
                      value: "function" === typeof b2 ? b2(a2) : a2
                    });
                  }, "useDebugValue"),
                  useLayoutEffect: /* @__PURE__ */ __name(function useLayoutEffect3(a2) {
                    C2();
                    x3.push({
                      primitive: "LayoutEffect",
                      stackError: Error(),
                      value: a2
                    });
                  }, "useLayoutEffect"),
                  useInsertionEffect: /* @__PURE__ */ __name(function useInsertionEffect(a2) {
                    C2();
                    x3.push({
                      primitive: "InsertionEffect",
                      stackError: Error(),
                      value: a2
                    });
                  }, "useInsertionEffect"),
                  useMemo: /* @__PURE__ */ __name(function useMemo27(a2) {
                    var b2 = C2();
                    a2 = null !== b2 ? b2.memoizedState[0] : a2();
                    x3.push({
                      primitive: "Memo",
                      stackError: Error(),
                      value: a2
                    });
                    return a2;
                  }, "useMemo"),
                  useMemoCache: /* @__PURE__ */ __name(function useMemoCache() {
                    return [];
                  }, "useMemoCache"),
                  useReducer: /* @__PURE__ */ __name(function useReducer7(a2, b2, e4) {
                    a2 = C2();
                    b2 = null !== a2 ? a2.memoizedState : void 0 !== e4 ? e4(b2) : b2;
                    x3.push({
                      primitive: "Reducer",
                      stackError: Error(),
                      value: b2
                    });
                    return [b2, function() {
                    }];
                  }, "useReducer"),
                  useRef: /* @__PURE__ */ __name(function useRef19(a2) {
                    var b2 = C2();
                    a2 = null !== b2 ? b2.memoizedState : {
                      current: a2
                    };
                    x3.push({
                      primitive: "Ref",
                      stackError: Error(),
                      value: a2.current
                    });
                    return a2;
                  }, "useRef"),
                  useState: /* @__PURE__ */ __name(function useState69(a2) {
                    var b2 = C2();
                    a2 = null !== b2 ? b2.memoizedState : "function" === typeof a2 ? a2() : a2;
                    x3.push({
                      primitive: "State",
                      stackError: Error(),
                      value: a2
                    });
                    return [a2, function() {
                    }];
                  }, "useState"),
                  useTransition: /* @__PURE__ */ __name(function useTransition() {
                    C2();
                    C2();
                    x3.push({
                      primitive: "Transition",
                      stackError: Error(),
                      value: void 0
                    });
                    return [false, function() {
                    }];
                  }, "useTransition"),
                  useSyncExternalStore: /* @__PURE__ */ __name(function useSyncExternalStore2(a2, b2) {
                    C2();
                    C2();
                    a2 = b2();
                    x3.push({
                      primitive: "SyncExternalStore",
                      stackError: Error(),
                      value: a2
                    });
                    return a2;
                  }, "useSyncExternalStore"),
                  useDeferredValue: /* @__PURE__ */ __name(function useDeferredValue(a2) {
                    var b2 = C2();
                    x3.push({
                      primitive: "DeferredValue",
                      stackError: Error(),
                      value: null !== b2 ? b2.memoizedState : a2
                    });
                    return a2;
                  }, "useDeferredValue"),
                  useId: /* @__PURE__ */ __name(function useId2() {
                    var a2 = C2();
                    a2 = null !== a2 ? a2.memoizedState : "";
                    x3.push({
                      primitive: "Id",
                      stackError: Error(),
                      value: a2
                    });
                    return a2;
                  }, "useId")
                }, D2 = {
                  get: /* @__PURE__ */ __name(function get4(a2, b2) {
                    if (a2.hasOwnProperty(b2)) return a2[b2];
                    a2 = Error("Missing method in Dispatcher: " + b2);
                    a2.name = "ReactDebugToolsUnsupportedHookError";
                    throw a2;
                  }, "get")
                }, E2 = "undefined" === typeof Proxy ? A4 : new Proxy(A4, D2), F4 = 0;
                function G2(a2, b2, e4) {
                  var g2 = b2[e4].source, c4 = 0;
                  a: for (; c4 < a2.length; c4++) {
                    if (a2[c4].source === g2) {
                      for (var h3 = e4 + 1, r5 = c4 + 1; h3 < b2.length && r5 < a2.length; h3++, r5++) {
                        if (a2[r5].source !== b2[h3].source) continue a;
                      }
                      return c4;
                    }
                  }
                  return -1;
                }
                __name(G2, "G");
                function H2(a2, b2) {
                  if (!a2) return false;
                  b2 = "use" + b2;
                  return a2.length < b2.length ? false : a2.lastIndexOf(b2) === a2.length - b2.length;
                }
                __name(H2, "H");
                function I3(a2, b2, e4) {
                  for (var g2 = [], c4 = null, h3 = g2, r5 = 0, t5 = [], v2 = 0; v2 < b2.length; v2++) {
                    var u2 = b2[v2];
                    var d2 = a2;
                    var l3 = k2.parse(u2.stackError);
                    b: {
                      var m3 = l3, n3 = G2(m3, d2, F4);
                      if (-1 !== n3) d2 = n3;
                      else {
                        for (var f5 = 0; f5 < d2.length && 5 > f5; f5++) {
                          if (n3 = G2(m3, d2, f5), -1 !== n3) {
                            F4 = f5;
                            d2 = n3;
                            break b;
                          }
                        }
                        d2 = -1;
                      }
                    }
                    b: {
                      m3 = l3;
                      n3 = z2().get(u2.primitive);
                      if (void 0 !== n3) for (f5 = 0; f5 < n3.length && f5 < m3.length; f5++) {
                        if (n3[f5].source !== m3[f5].source) {
                          f5 < m3.length - 1 && H2(m3[f5].functionName, u2.primitive) && f5++;
                          f5 < m3.length - 1 && H2(m3[f5].functionName, u2.primitive) && f5++;
                          m3 = f5;
                          break b;
                        }
                      }
                      m3 = -1;
                    }
                    l3 = -1 === d2 || -1 === m3 || 2 > d2 - m3 ? null : l3.slice(m3, d2 - 1);
                    if (null !== l3) {
                      d2 = 0;
                      if (null !== c4) {
                        for (; d2 < l3.length && d2 < c4.length && l3[l3.length - d2 - 1].source === c4[c4.length - d2 - 1].source; ) {
                          d2++;
                        }
                        for (c4 = c4.length - 1; c4 > d2; c4--) {
                          h3 = t5.pop();
                        }
                      }
                      for (c4 = l3.length - d2 - 1; 1 <= c4; c4--) {
                        d2 = [], m3 = l3[c4], (n3 = l3[c4 - 1].functionName) ? (f5 = n3.lastIndexOf("."), -1 === f5 && (f5 = 0), "use" === n3.slice(f5, f5 + 3) && (f5 += 3), n3 = n3.slice(f5)) : n3 = "", n3 = {
                          id: null,
                          isStateEditable: false,
                          name: n3,
                          value: void 0,
                          subHooks: d2
                        }, e4 && (n3.hookSource = {
                          lineNumber: m3.lineNumber,
                          columnNumber: m3.columnNumber,
                          functionName: m3.functionName,
                          fileName: m3.fileName
                        }), h3.push(n3), t5.push(h3), h3 = d2;
                      }
                      c4 = l3;
                    }
                    d2 = u2.primitive;
                    u2 = {
                      id: "Context" === d2 || "DebugValue" === d2 ? null : r5++,
                      isStateEditable: "Reducer" === d2 || "State" === d2,
                      name: d2,
                      value: u2.value,
                      subHooks: []
                    };
                    e4 && (d2 = {
                      lineNumber: null,
                      functionName: null,
                      fileName: null,
                      columnNumber: null
                    }, l3 && 1 <= l3.length && (l3 = l3[0], d2.lineNumber = l3.lineNumber, d2.functionName = l3.functionName, d2.fileName = l3.fileName, d2.columnNumber = l3.columnNumber), u2.hookSource = d2);
                    h3.push(u2);
                  }
                  J2(g2, null);
                  return g2;
                }
                __name(I3, "I");
                function J2(a2, b2) {
                  for (var e4 = [], g2 = 0; g2 < a2.length; g2++) {
                    var c4 = a2[g2];
                    "DebugValue" === c4.name && 0 === c4.subHooks.length ? (a2.splice(g2, 1), g2--, e4.push(c4)) : J2(c4.subHooks, c4);
                  }
                  null !== b2 && (1 === e4.length ? b2.value = e4[0].value : 1 < e4.length && (b2.value = e4.map(function(h3) {
                    return h3.value;
                  })));
                }
                __name(J2, "J");
                function K2(a2) {
                  if (a2 instanceof Error && "ReactDebugToolsUnsupportedHookError" === a2.name) throw a2;
                  var b2 = Error("Error rendering inspected component", {
                    cause: a2
                  });
                  b2.name = "ReactDebugToolsRenderError";
                  b2.cause = a2;
                  throw b2;
                }
                __name(K2, "K");
                function L2(a2, b2, e4) {
                  var g2 = 3 < arguments.length && void 0 !== arguments[3] ? arguments[3] : false;
                  null == e4 && (e4 = w2.ReactCurrentDispatcher);
                  var c4 = e4.current;
                  e4.current = E2;
                  try {
                    var h3 = Error();
                    a2(b2);
                  } catch (t5) {
                    K2(t5);
                  } finally {
                    var r5 = x3;
                    x3 = [];
                    e4.current = c4;
                  }
                  c4 = k2.parse(h3);
                  return I3(c4, r5, g2);
                }
                __name(L2, "L");
                function M2(a2) {
                  a2.forEach(function(b2, e4) {
                    return e4._currentValue = b2;
                  });
                }
                __name(M2, "M");
                __webpack_unused_export__ = L2;
                exports3.inspectHooksOfFiber = function(a2, b2) {
                  var e4 = 2 < arguments.length && void 0 !== arguments[2] ? arguments[2] : false;
                  null == b2 && (b2 = w2.ReactCurrentDispatcher);
                  if (0 !== a2.tag && 15 !== a2.tag && 11 !== a2.tag) throw Error("Unknown Fiber. Needs to be a function component to inspect hooks.");
                  z2();
                  var g2 = a2.type, c4 = a2.memoizedProps;
                  if (g2 !== a2.elementType && g2 && g2.defaultProps) {
                    c4 = q2({}, c4);
                    var h3 = g2.defaultProps;
                    for (r5 in h3) {
                      void 0 === c4[r5] && (c4[r5] = h3[r5]);
                    }
                  }
                  B2 = a2.memoizedState;
                  var r5 = /* @__PURE__ */ new Map();
                  try {
                    for (h3 = a2; h3; ) {
                      if (10 === h3.tag) {
                        var t5 = h3.type._context;
                        r5.has(t5) || (r5.set(t5, t5._currentValue), t5._currentValue = h3.memoizedProps.value);
                      }
                      h3 = h3.return;
                    }
                    if (11 === a2.tag) {
                      var v2 = g2.render;
                      g2 = c4;
                      var u2 = a2.ref;
                      t5 = b2;
                      var d2 = t5.current;
                      t5.current = E2;
                      try {
                        var l3 = Error();
                        v2(g2, u2);
                      } catch (f5) {
                        K2(f5);
                      } finally {
                        var m3 = x3;
                        x3 = [];
                        t5.current = d2;
                      }
                      var n3 = k2.parse(l3);
                      return I3(n3, m3, e4);
                    }
                    return L2(g2, c4, b2, e4);
                  } finally {
                    B2 = null, M2(r5);
                  }
                };
              }
            ),
            /***/
            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 b2 = Symbol.for("react.element"), c4 = Symbol.for("react.portal"), d2 = Symbol.for("react.fragment"), e4 = Symbol.for("react.strict_mode"), f5 = Symbol.for("react.profiler"), g2 = Symbol.for("react.provider"), h3 = Symbol.for("react.context"), k2 = Symbol.for("react.server_context"), l3 = Symbol.for("react.forward_ref"), m3 = Symbol.for("react.suspense"), n3 = Symbol.for("react.suspense_list"), p2 = Symbol.for("react.memo"), q2 = Symbol.for("react.lazy"), t5 = Symbol.for("react.offscreen"), u2 = Symbol.for("react.cache"), v2 = Symbol.for("react.client.reference");
                function w2(a2) {
                  if ("object" === _typeof2(a2) && null !== a2) {
                    var r5 = a2.$$typeof;
                    switch (r5) {
                      case b2:
                        switch (a2 = a2.type, a2) {
                          case d2:
                          case f5:
                          case e4:
                          case m3:
                          case n3:
                            return a2;
                          default:
                            switch (a2 = a2 && a2.$$typeof, a2) {
                              case k2:
                              case h3:
                              case l3:
                              case q2:
                              case p2:
                              case g2:
                                return a2;
                              default:
                                return r5;
                            }
                        }
                      case c4:
                        return r5;
                    }
                  }
                }
                __name(w2, "w");
                exports3.ContextConsumer = h3;
                exports3.ContextProvider = g2;
                __webpack_unused_export__ = b2;
                exports3.ForwardRef = l3;
                exports3.Fragment = d2;
                exports3.Lazy = q2;
                exports3.Memo = p2;
                exports3.Portal = c4;
                exports3.Profiler = f5;
                exports3.StrictMode = e4;
                exports3.Suspense = m3;
                __webpack_unused_export__ = n3;
                __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(a2) {
                  return w2(a2) === h3;
                }, "__webpack_unused_export__");
                __webpack_unused_export__ = /* @__PURE__ */ __name(function(a2) {
                  return w2(a2) === g2;
                }, "__webpack_unused_export__");
                exports3.isElement = function(a2) {
                  return "object" === _typeof2(a2) && null !== a2 && a2.$$typeof === b2;
                };
                __webpack_unused_export__ = /* @__PURE__ */ __name(function(a2) {
                  return w2(a2) === l3;
                }, "__webpack_unused_export__");
                __webpack_unused_export__ = /* @__PURE__ */ __name(function(a2) {
                  return w2(a2) === d2;
                }, "__webpack_unused_export__");
                __webpack_unused_export__ = /* @__PURE__ */ __name(function(a2) {
                  return w2(a2) === q2;
                }, "__webpack_unused_export__");
                __webpack_unused_export__ = /* @__PURE__ */ __name(function(a2) {
                  return w2(a2) === p2;
                }, "__webpack_unused_export__");
                __webpack_unused_export__ = /* @__PURE__ */ __name(function(a2) {
                  return w2(a2) === c4;
                }, "__webpack_unused_export__");
                __webpack_unused_export__ = /* @__PURE__ */ __name(function(a2) {
                  return w2(a2) === f5;
                }, "__webpack_unused_export__");
                __webpack_unused_export__ = /* @__PURE__ */ __name(function(a2) {
                  return w2(a2) === e4;
                }, "__webpack_unused_export__");
                __webpack_unused_export__ = /* @__PURE__ */ __name(function(a2) {
                  return w2(a2) === m3;
                }, "__webpack_unused_export__");
                __webpack_unused_export__ = /* @__PURE__ */ __name(function(a2) {
                  return w2(a2) === n3;
                }, "__webpack_unused_export__");
                __webpack_unused_export__ = /* @__PURE__ */ __name(function(a2) {
                  return "string" === typeof a2 || "function" === typeof a2 || a2 === d2 || a2 === f5 || a2 === e4 || a2 === m3 || a2 === n3 || a2 === t5 || a2 === u2 || "object" === _typeof2(a2) && null !== a2 && (a2.$$typeof === q2 || a2.$$typeof === p2 || a2.$$typeof === g2 || a2.$$typeof === h3 || a2.$$typeof === l3 || a2.$$typeof === v2 || void 0 !== a2.getModuleId) ? true : false;
                }, "__webpack_unused_export__");
                exports3.typeOf = w2;
              }
            ),
            /***/
            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 l3 = Symbol.for("react.element"), n3 = Symbol.for("react.portal"), p2 = Symbol.for("react.fragment"), q2 = Symbol.for("react.strict_mode"), r5 = Symbol.for("react.profiler"), t5 = Symbol.for("react.provider"), u2 = Symbol.for("react.context"), v2 = Symbol.for("react.server_context"), w2 = Symbol.for("react.forward_ref"), x3 = Symbol.for("react.suspense"), y2 = Symbol.for("react.suspense_list"), z2 = Symbol.for("react.memo"), A4 = Symbol.for("react.lazy"), aa = Symbol.for("react.debug_trace_mode"), ba = Symbol.for("react.offscreen"), ca = Symbol.for("react.cache"), B2 = Symbol.for("react.default_value"), da = Symbol.for("react.postpone"), C2 = Symbol.iterator;
                function ea(a2) {
                  if (null === a2 || "object" !== _typeof2(a2)) return null;
                  a2 = C2 && a2[C2] || a2["@@iterator"];
                  return "function" === typeof a2 ? a2 : null;
                }
                __name(ea, "ea");
                var D2 = {
                  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")
                }, E2 = Object.assign, F4 = {};
                function G2(a2, b2, c4) {
                  this.props = a2;
                  this.context = b2;
                  this.refs = F4;
                  this.updater = c4 || D2;
                }
                __name(G2, "G");
                G2.prototype.isReactComponent = {};
                G2.prototype.setState = function(a2, b2) {
                  if ("object" !== _typeof2(a2) && "function" !== typeof a2 && null != a2) 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, a2, b2, "setState");
                };
                G2.prototype.forceUpdate = function(a2) {
                  this.updater.enqueueForceUpdate(this, a2, "forceUpdate");
                };
                function H2() {
                }
                __name(H2, "H");
                H2.prototype = G2.prototype;
                function I3(a2, b2, c4) {
                  this.props = a2;
                  this.context = b2;
                  this.refs = F4;
                  this.updater = c4 || D2;
                }
                __name(I3, "I");
                var J2 = I3.prototype = new H2();
                J2.constructor = I3;
                E2(J2, G2.prototype);
                J2.isPureReactComponent = true;
                var K2 = Array.isArray, L2 = Object.prototype.hasOwnProperty, M2 = {
                  current: null
                }, N2 = {
                  key: true,
                  ref: true,
                  __self: true,
                  __source: true
                };
                function O2(a2, b2, c4) {
                  var d2, e4 = {}, f5 = null, g2 = null;
                  if (null != b2) for (d2 in void 0 !== b2.ref && (g2 = b2.ref), void 0 !== b2.key && (f5 = "" + b2.key), b2) {
                    L2.call(b2, d2) && !N2.hasOwnProperty(d2) && (e4[d2] = b2[d2]);
                  }
                  var h3 = arguments.length - 2;
                  if (1 === h3) e4.children = c4;
                  else if (1 < h3) {
                    for (var k2 = Array(h3), m3 = 0; m3 < h3; m3++) {
                      k2[m3] = arguments[m3 + 2];
                    }
                    e4.children = k2;
                  }
                  if (a2 && a2.defaultProps) for (d2 in h3 = a2.defaultProps, h3) {
                    void 0 === e4[d2] && (e4[d2] = h3[d2]);
                  }
                  return {
                    $$typeof: l3,
                    type: a2,
                    key: f5,
                    ref: g2,
                    props: e4,
                    _owner: M2.current
                  };
                }
                __name(O2, "O");
                function fa(a2, b2) {
                  return {
                    $$typeof: l3,
                    type: a2.type,
                    key: b2,
                    ref: a2.ref,
                    props: a2.props,
                    _owner: a2._owner
                  };
                }
                __name(fa, "fa");
                function P2(a2) {
                  return "object" === _typeof2(a2) && null !== a2 && a2.$$typeof === l3;
                }
                __name(P2, "P");
                function escape7(a2) {
                  var b2 = {
                    "=": "=0",
                    ":": "=2"
                  };
                  return "$" + a2.replace(/[=:]/g, function(c4) {
                    return b2[c4];
                  });
                }
                __name(escape7, "escape");
                var Q2 = /\/+/g;
                function R2(a2, b2) {
                  return "object" === _typeof2(a2) && null !== a2 && null != a2.key ? escape7("" + a2.key) : b2.toString(36);
                }
                __name(R2, "R");
                function S4(a2, b2, c4, d2, e4) {
                  var f5 = _typeof2(a2);
                  if ("undefined" === f5 || "boolean" === f5) a2 = null;
                  var g2 = false;
                  if (null === a2) g2 = true;
                  else switch (f5) {
                    case "string":
                    case "number":
                      g2 = true;
                      break;
                    case "object":
                      switch (a2.$$typeof) {
                        case l3:
                        case n3:
                          g2 = true;
                      }
                  }
                  if (g2) return g2 = a2, e4 = e4(g2), a2 = "" === d2 ? "." + R2(g2, 0) : d2, K2(e4) ? (c4 = "", null != a2 && (c4 = a2.replace(Q2, "$&/") + "/"), S4(e4, b2, c4, "", function(m3) {
                    return m3;
                  })) : null != e4 && (P2(e4) && (e4 = fa(e4, c4 + (!e4.key || g2 && g2.key === e4.key ? "" : ("" + e4.key).replace(Q2, "$&/") + "/") + a2)), b2.push(e4)), 1;
                  g2 = 0;
                  d2 = "" === d2 ? "." : d2 + ":";
                  if (K2(a2)) for (var h3 = 0; h3 < a2.length; h3++) {
                    f5 = a2[h3];
                    var k2 = d2 + R2(f5, h3);
                    g2 += S4(f5, b2, c4, k2, e4);
                  }
                  else if (k2 = ea(a2), "function" === typeof k2) for (a2 = k2.call(a2), h3 = 0; !(f5 = a2.next()).done; ) {
                    f5 = f5.value, k2 = d2 + R2(f5, h3++), g2 += S4(f5, b2, c4, k2, e4);
                  }
                  else if ("object" === f5) throw b2 = String(a2), Error("Objects are not valid as a React child (found: " + ("[object Object]" === b2 ? "object with keys {" + Object.keys(a2).join(", ") + "}" : b2) + "). If you meant to render a collection of children, use an array instead.");
                  return g2;
                }
                __name(S4, "S");
                function T2(a2, b2, c4) {
                  if (null == a2) return a2;
                  var d2 = [], e4 = 0;
                  S4(a2, d2, "", "", function(f5) {
                    return b2.call(c4, f5, e4++);
                  });
                  return d2;
                }
                __name(T2, "T");
                function ha(a2) {
                  if (-1 === a2._status) {
                    var b2 = a2._result;
                    b2 = b2();
                    b2.then(function(c4) {
                      if (0 === a2._status || -1 === a2._status) a2._status = 1, a2._result = c4;
                    }, function(c4) {
                      if (0 === a2._status || -1 === a2._status) a2._status = 2, a2._result = c4;
                    });
                    -1 === a2._status && (a2._status = 0, a2._result = b2);
                  }
                  if (1 === a2._status) return a2._result.default;
                  throw a2._result;
                }
                __name(ha, "ha");
                var U2 = {
                  current: null
                };
                function ia() {
                  return /* @__PURE__ */ new WeakMap();
                }
                __name(ia, "ia");
                function V3() {
                  return {
                    s: 0,
                    v: void 0,
                    o: null,
                    p: null
                  };
                }
                __name(V3, "V");
                var W2 = {
                  current: null
                };
                function X2(a2, b2) {
                  return W2.current.useOptimistic(a2, b2);
                }
                __name(X2, "X");
                var Y2 = {
                  transition: null
                }, Z4 = {}, ja = {
                  ReactCurrentDispatcher: W2,
                  ReactCurrentCache: U2,
                  ReactCurrentBatchConfig: Y2,
                  ReactCurrentOwner: M2,
                  ContextRegistry: Z4
                };
                exports3.Children = {
                  map: T2,
                  forEach: /* @__PURE__ */ __name(function forEach2(a2, b2, c4) {
                    T2(a2, function() {
                      b2.apply(this, arguments);
                    }, c4);
                  }, "forEach"),
                  count: /* @__PURE__ */ __name(function count(a2) {
                    var b2 = 0;
                    T2(a2, function() {
                      b2++;
                    });
                    return b2;
                  }, "count"),
                  toArray: /* @__PURE__ */ __name(function toArray(a2) {
                    return T2(a2, function(b2) {
                      return b2;
                    }) || [];
                  }, "toArray"),
                  only: /* @__PURE__ */ __name(function only(a2) {
                    if (!P2(a2)) throw Error("React.Children.only expected to receive a single React element child.");
                    return a2;
                  }, "only")
                };
                exports3.Component = G2;
                exports3.Fragment = p2;
                exports3.Profiler = r5;
                exports3.PureComponent = I3;
                exports3.StrictMode = q2;
                exports3.Suspense = x3;
                exports3.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED = ja;
                exports3.cache = function(a2) {
                  return function() {
                    var b2 = U2.current;
                    if (!b2) return a2.apply(null, arguments);
                    var c4 = b2.getCacheForType(ia);
                    b2 = c4.get(a2);
                    void 0 === b2 && (b2 = V3(), c4.set(a2, b2));
                    c4 = 0;
                    for (var d2 = arguments.length; c4 < d2; c4++) {
                      var e4 = arguments[c4];
                      if ("function" === typeof e4 || "object" === _typeof2(e4) && null !== e4) {
                        var f5 = b2.o;
                        null === f5 && (b2.o = f5 = /* @__PURE__ */ new WeakMap());
                        b2 = f5.get(e4);
                        void 0 === b2 && (b2 = V3(), f5.set(e4, b2));
                      } else f5 = b2.p, null === f5 && (b2.p = f5 = /* @__PURE__ */ new Map()), b2 = f5.get(e4), void 0 === b2 && (b2 = V3(), f5.set(e4, b2));
                    }
                    if (1 === b2.s) return b2.v;
                    if (2 === b2.s) throw b2.v;
                    try {
                      var g2 = a2.apply(null, arguments);
                      c4 = b2;
                      c4.s = 1;
                      return c4.v = g2;
                    } catch (h3) {
                      throw g2 = b2, g2.s = 2, g2.v = h3, h3;
                    }
                  };
                };
                exports3.cloneElement = function(a2, b2, c4) {
                  if (null === a2 || void 0 === a2) throw Error("React.cloneElement(...): The argument must be a React element, but you passed " + a2 + ".");
                  var d2 = E2({}, a2.props), e4 = a2.key, f5 = a2.ref, g2 = a2._owner;
                  if (null != b2) {
                    void 0 !== b2.ref && (f5 = b2.ref, g2 = M2.current);
                    void 0 !== b2.key && (e4 = "" + b2.key);
                    if (a2.type && a2.type.defaultProps) var h3 = a2.type.defaultProps;
                    for (k2 in b2) {
                      L2.call(b2, k2) && !N2.hasOwnProperty(k2) && (d2[k2] = void 0 === b2[k2] && void 0 !== h3 ? h3[k2] : b2[k2]);
                    }
                  }
                  var k2 = arguments.length - 2;
                  if (1 === k2) d2.children = c4;
                  else if (1 < k2) {
                    h3 = Array(k2);
                    for (var m3 = 0; m3 < k2; m3++) {
                      h3[m3] = arguments[m3 + 2];
                    }
                    d2.children = h3;
                  }
                  return {
                    $$typeof: l3,
                    type: a2.type,
                    key: e4,
                    ref: f5,
                    props: d2,
                    _owner: g2
                  };
                };
                exports3.createContext = function(a2) {
                  a2 = {
                    $$typeof: u2,
                    _currentValue: a2,
                    _currentValue2: a2,
                    _threadCount: 0,
                    Provider: null,
                    Consumer: null,
                    _defaultValue: null,
                    _globalName: null
                  };
                  a2.Provider = {
                    $$typeof: t5,
                    _context: a2
                  };
                  return a2.Consumer = a2;
                };
                exports3.createElement = O2;
                exports3.createFactory = function(a2) {
                  var b2 = O2.bind(null, a2);
                  b2.type = a2;
                  return b2;
                };
                exports3.createRef = function() {
                  return {
                    current: null
                  };
                };
                exports3.createServerContext = function(a2, b2) {
                  var c4 = true;
                  if (!Z4[a2]) {
                    c4 = false;
                    var d2 = {
                      $$typeof: v2,
                      _currentValue: b2,
                      _currentValue2: b2,
                      _defaultValue: b2,
                      _threadCount: 0,
                      Provider: null,
                      Consumer: null,
                      _globalName: a2
                    };
                    d2.Provider = {
                      $$typeof: t5,
                      _context: d2
                    };
                    Z4[a2] = d2;
                  }
                  d2 = Z4[a2];
                  if (d2._defaultValue === B2) d2._defaultValue = b2, d2._currentValue === B2 && (d2._currentValue = b2), d2._currentValue2 === B2 && (d2._currentValue2 = b2);
                  else if (c4) throw Error("ServerContext: " + a2 + " already defined");
                  return d2;
                };
                exports3.experimental_useEffectEvent = function(a2) {
                  return W2.current.useEffectEvent(a2);
                };
                exports3.experimental_useOptimistic = function(a2, b2) {
                  return X2(a2, b2);
                };
                exports3.forwardRef = function(a2) {
                  return {
                    $$typeof: w2,
                    render: a2
                  };
                };
                exports3.isValidElement = P2;
                exports3.lazy = function(a2) {
                  return {
                    $$typeof: A4,
                    _payload: {
                      _status: -1,
                      _result: a2
                    },
                    _init: ha
                  };
                };
                exports3.memo = function(a2, b2) {
                  return {
                    $$typeof: z2,
                    type: a2,
                    compare: void 0 === b2 ? null : b2
                  };
                };
                exports3.startTransition = function(a2) {
                  var b2 = Y2.transition;
                  Y2.transition = {};
                  try {
                    a2();
                  } finally {
                    Y2.transition = b2;
                  }
                };
                exports3.unstable_Cache = ca;
                exports3.unstable_DebugTracingMode = aa;
                exports3.unstable_Offscreen = ba;
                exports3.unstable_SuspenseList = y2;
                exports3.unstable_act = function() {
                  throw Error("act(...) is not supported in production builds of React.");
                };
                exports3.unstable_getCacheForType = function(a2) {
                  var b2 = U2.current;
                  return b2 ? b2.getCacheForType(a2) : a2();
                };
                exports3.unstable_getCacheSignal = function() {
                  var a2 = U2.current;
                  return a2 ? a2.getCacheSignal() : (a2 = new AbortController(), a2.abort(Error("This CacheSignal was requested outside React which means that it is immediately aborted.")), a2.signal);
                };
                exports3.unstable_postpone = function(a2) {
                  a2 = Error(a2);
                  a2.$$typeof = da;
                  throw a2;
                };
                exports3.unstable_useCacheRefresh = function() {
                  return W2.current.useCacheRefresh();
                };
                exports3.unstable_useMemoCache = function(a2) {
                  return W2.current.useMemoCache(a2);
                };
                exports3.use = function(a2) {
                  return W2.current.use(a2);
                };
                exports3.useCallback = function(a2, b2) {
                  return W2.current.useCallback(a2, b2);
                };
                exports3.useContext = function(a2) {
                  return W2.current.useContext(a2);
                };
                exports3.useDebugValue = function() {
                };
                exports3.useDeferredValue = function(a2, b2) {
                  return W2.current.useDeferredValue(a2, b2);
                };
                exports3.useEffect = function(a2, b2) {
                  return W2.current.useEffect(a2, b2);
                };
                exports3.useId = function() {
                  return W2.current.useId();
                };
                exports3.useImperativeHandle = function(a2, b2, c4) {
                  return W2.current.useImperativeHandle(a2, b2, c4);
                };
                exports3.useInsertionEffect = function(a2, b2) {
                  return W2.current.useInsertionEffect(a2, b2);
                };
                exports3.useLayoutEffect = function(a2, b2) {
                  return W2.current.useLayoutEffect(a2, b2);
                };
                exports3.useMemo = function(a2, b2) {
                  return W2.current.useMemo(a2, b2);
                };
                exports3.useOptimistic = X2;
                exports3.useReducer = function(a2, b2, c4) {
                  return W2.current.useReducer(a2, b2, c4);
                };
                exports3.useRef = function(a2) {
                  return W2.current.useRef(a2);
                };
                exports3.useState = function(a2) {
                  return W2.current.useState(a2);
                };
                exports3.useSyncExternalStore = function(a2, b2, c4) {
                  return W2.current.useSyncExternalStore(a2, b2, c4);
                };
                exports3.useTransition = function() {
                  return W2.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(error2) {
                      if (typeof error2.stacktrace !== "undefined" || typeof error2["opera#sourceloc"] !== "undefined") {
                        return this.parseOpera(error2);
                      } else if (error2.stack && error2.stack.match(CHROME_IE_STACK_REGEXP)) {
                        return this.parseV8OrIE(error2);
                      } else if (error2.stack) {
                        return this.parseFFOrSafari(error2);
                      } 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(error2) {
                      var filtered = error2.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(error2) {
                      var filtered = error2.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(e4) {
                      if (!e4.stacktrace || e4.message.indexOf("\n") > -1 && e4.message.split("\n").length > e4.stacktrace.split("\n").length) {
                        return this.parseOpera9(e4);
                      } else if (!e4.stack) {
                        return this.parseOpera10(e4);
                      } else {
                        return this.parseOpera11(e4);
                      }
                    }, "ErrorStackParser$$parseOpera"),
                    parseOpera9: /* @__PURE__ */ __name(function ErrorStackParser$$parseOpera9(e4) {
                      var lineRE = /Line (\d+).*script (?:in )?(\S+)/i;
                      var lines = e4.message.split("\n");
                      var result = [];
                      for (var i3 = 2, len = lines.length; i3 < len; i3 += 2) {
                        var match2 = lineRE.exec(lines[i3]);
                        if (match2) {
                          result.push(new StackFrame({
                            fileName: match2[2],
                            lineNumber: match2[1],
                            source: lines[i3]
                          }));
                        }
                      }
                      return result;
                    }, "ErrorStackParser$$parseOpera9"),
                    parseOpera10: /* @__PURE__ */ __name(function ErrorStackParser$$parseOpera10(e4) {
                      var lineRE = /Line (\d+).*script (?:in )?(\S+)(?:: In function (\S+))?$/i;
                      var lines = e4.stacktrace.split("\n");
                      var result = [];
                      for (var i3 = 0, len = lines.length; i3 < len; i3 += 2) {
                        var match2 = lineRE.exec(lines[i3]);
                        if (match2) {
                          result.push(new StackFrame({
                            functionName: match2[3] || void 0,
                            fileName: match2[2],
                            lineNumber: match2[1],
                            source: lines[i3]
                          }));
                        }
                      }
                      return result;
                    }, "ErrorStackParser$$parseOpera10"),
                    // Opera 10.65+ Error.stack very similar to FF/Safari
                    parseOpera11: /* @__PURE__ */ __name(function ErrorStackParser$$parseOpera11(error2) {
                      var filtered = error2.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 (isObject4(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(time3) {
                    var args = lastArgs, thisArg = lastThis;
                    lastArgs = lastThis = void 0;
                    lastInvokeTime = time3;
                    result = func.apply(thisArg, args);
                    return result;
                  }
                  __name(invokeFunc, "invokeFunc");
                  function leadingEdge(time3) {
                    lastInvokeTime = time3;
                    timerId = setTimeout(timerExpired, wait);
                    return leading ? invokeFunc(time3) : result;
                  }
                  __name(leadingEdge, "leadingEdge");
                  function remainingWait(time3) {
                    var timeSinceLastCall = time3 - lastCallTime, timeSinceLastInvoke = time3 - lastInvokeTime, result2 = wait - timeSinceLastCall;
                    return maxing ? nativeMin(result2, maxWait - timeSinceLastInvoke) : result2;
                  }
                  __name(remainingWait, "remainingWait");
                  function shouldInvoke(time3) {
                    var timeSinceLastCall = time3 - lastCallTime, timeSinceLastInvoke = time3 - lastInvokeTime;
                    return lastCallTime === void 0 || timeSinceLastCall >= wait || timeSinceLastCall < 0 || maxing && timeSinceLastInvoke >= maxWait;
                  }
                  __name(shouldInvoke, "shouldInvoke");
                  function timerExpired() {
                    var time3 = now();
                    if (shouldInvoke(time3)) {
                      return trailingEdge(time3);
                    }
                    timerId = setTimeout(timerExpired, remainingWait(time3));
                  }
                  __name(timerExpired, "timerExpired");
                  function trailingEdge(time3) {
                    timerId = void 0;
                    if (trailing && lastArgs) {
                      return invokeFunc(time3);
                    }
                    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 time3 = now(), isInvoking = shouldInvoke(time3);
                    lastArgs = arguments;
                    lastThis = this;
                    lastCallTime = time3;
                    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 (isObject4(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 isObject4(value) {
                  var type = _typeof2(value);
                  return !!value && (type == "object" || type == "function");
                }
                __name(isObject4, "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 (isObject4(value)) {
                    var other2 = typeof value.valueOf == "function" ? value.valueOf() : value;
                    value = isObject4(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 process50 = __webpack_require__2(169);
                module3.exports = LRUCache2;
                var Map2 = __webpack_require__2(307);
                var util3 = __webpack_require__2(82);
                var Yallist2 = __webpack_require__2(695);
                var hasSymbol = typeof Symbol === "function" && process50.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 get5() {
                    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 get5() {
                    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 get5() {
                    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 get5() {
                    return this[LENGTH_CALCULATOR];
                  }, "get"),
                  enumerable: true
                });
                Object.defineProperty(LRUCache2.prototype, "length", {
                  get: /* @__PURE__ */ __name(function get5() {
                    return this[LENGTH];
                  }, "get"),
                  enumerable: true
                });
                Object.defineProperty(LRUCache2.prototype, "itemCount", {
                  get: /* @__PURE__ */ __name(function get5() {
                    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(k2) {
                    return k2.key;
                  }, this);
                };
                LRUCache2.prototype.values = function() {
                  return this[LRU_LIST].toArray().map(function(k2) {
                    return k2.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(h3) {
                    return h3;
                  });
                };
                LRUCache2.prototype.dumpLru = function() {
                  return this[LRU_LIST];
                };
                LRUCache2.prototype.inspect = function(n3, 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: " + util3.inspect(max, opts);
                    extras = true;
                  }
                  var maxAge = this[MAX_AGE];
                  if (maxAge) {
                    if (extras) {
                      str2 += ",";
                    }
                    str2 += "\n  maxAge: " + util3.inspect(maxAge, opts);
                    extras = true;
                  }
                  var lc = this[LENGTH_CALCULATOR];
                  if (lc && lc !== naiveLength) {
                    if (extras) {
                      str2 += ",";
                    }
                    str2 += "\n  length: " + util3.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 = util3.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 = util3.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 get4(this, key, true);
                };
                LRUCache2.prototype.peek = function(key) {
                  return get4(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 l3 = arr.length - 1; l3 >= 0; l3--) {
                    var hit = arr[l3];
                    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) {
                    get4(self2, key, false);
                  });
                };
                function get4(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(get4, "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 process50 = 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 (e4) {
                    cachedSetTimeout = defaultSetTimout;
                  }
                  try {
                    if (typeof clearTimeout === "function") {
                      cachedClearTimeout = clearTimeout;
                    } else {
                      cachedClearTimeout = defaultClearTimeout;
                    }
                  } catch (e4) {
                    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 (e4) {
                    try {
                      return cachedSetTimeout.call(null, fun, 0);
                    } catch (e5) {
                      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 (e4) {
                    try {
                      return cachedClearTimeout.call(null, marker);
                    } catch (e5) {
                      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");
                process50.nextTick = function(fun) {
                  var args = new Array(arguments.length - 1);
                  if (arguments.length > 1) {
                    for (var i3 = 1; i3 < arguments.length; i3++) {
                      args[i3 - 1] = arguments[i3];
                    }
                  }
                  queue.push(new Item(fun, args));
                  if (queue.length === 1 && !draining) {
                    runTimeout(drainQueue);
                  }
                };
                function Item(fun, array2) {
                  this.fun = fun;
                  this.array = array2;
                }
                __name(Item, "Item");
                Item.prototype.run = function() {
                  this.fun.apply(null, this.array);
                };
                process50.title = "browser";
                process50.browser = true;
                process50.env = {};
                process50.argv = [];
                process50.version = "";
                process50.versions = {};
                function noop8() {
                }
                __name(noop8, "noop");
                process50.on = noop8;
                process50.addListener = noop8;
                process50.once = noop8;
                process50.off = noop8;
                process50.removeListener = noop8;
                process50.removeAllListeners = noop8;
                process50.emit = noop8;
                process50.prependListener = noop8;
                process50.prependOnceListener = noop8;
                process50.listeners = function(name3) {
                  return [];
                };
                process50.binding = function(name3) {
                  throw new Error("process.binding is not supported");
                };
                process50.cwd = function() {
                  return "/";
                };
                process50.chdir = function(dir) {
                  throw new Error("process.chdir is not supported");
                };
                process50.umask = function() {
                  return 0;
                };
              }
            ),
            /***/
            307: (
              /***/
              (module3, __unused_webpack_exports, __webpack_require__2) => {
                var process50 = __webpack_require__2(169);
                if (process50.env.npm_package_name === "pseudomap" && process50.env.npm_lifecycle_script === "test") process50.env.TEST_PSEUDOMAP = "true";
                if (typeof Map === "function" && !process50.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(k2) {
                    if (k2 !== "size") fn.call(thisp, this._data[k2].value, this._data[k2].key);
                  }, this);
                };
                PseudoMap.prototype.has = function(k2) {
                  return !!find(this._data, k2);
                };
                PseudoMap.prototype.get = function(k2) {
                  var res = find(this._data, k2);
                  return res && res.value;
                };
                PseudoMap.prototype.set = function(k2, v2) {
                  set(this._data, k2, v2);
                };
                PseudoMap.prototype.delete = function(k2) {
                  var res = find(this._data, k2);
                  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 get4() {
                    return this._data.size;
                  }, "get"),
                  set: /* @__PURE__ */ __name(function set2(n3) {
                  }, "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(a2, b2) {
                  return a2 === b2 || a2 !== a2 && b2 !== b2;
                }
                __name(same, "same");
                function Entry(k2, v2, i3) {
                  this.key = k2;
                  this.value = v2;
                  this._index = i3;
                }
                __name(Entry, "Entry");
                function find(data, k2) {
                  for (var i3 = 0, s5 = "_" + k2, key = s5; hasOwnProperty2.call(data, key); key = s5 + i3++) {
                    if (same(data[key].key, k2)) return data[key];
                  }
                }
                __name(find, "find");
                function set(data, k2, v2) {
                  for (var i3 = 0, s5 = "_" + k2, key = s5; hasOwnProperty2.call(data, key); key = s5 + i3++) {
                    if (same(data[key].key, k2)) {
                      data[key].value = v2;
                      return;
                    }
                  }
                  data.size++;
                  data[key] = new Entry(k2, v2, 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(n3) {
                    return !isNaN(parseFloat(n3)) && isFinite(n3);
                  }
                  __name(_isNumber, "_isNumber");
                  function _capitalize(str2) {
                    return str2.charAt(0).toUpperCase() + str2.substring(1);
                  }
                  __name(_capitalize, "_capitalize");
                  function _getter(p2) {
                    return function() {
                      return this[p2];
                    };
                  }
                  __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 i4 = 0; i4 < props.length; i4++) {
                      if (obj[props[i4]] !== void 0) {
                        this["set" + _capitalize(props[i4])](obj[props[i4]]);
                      }
                    }
                  }
                  __name(StackFrame, "StackFrame");
                  StackFrame.prototype = {
                    getArgs: /* @__PURE__ */ __name(function getArgs() {
                      return this.args;
                    }, "getArgs"),
                    setArgs: /* @__PURE__ */ __name(function setArgs(v2) {
                      if (Object.prototype.toString.call(v2) !== "[object Array]") {
                        throw new TypeError("Args must be an Array");
                      }
                      this.args = v2;
                    }, "setArgs"),
                    getEvalOrigin: /* @__PURE__ */ __name(function getEvalOrigin() {
                      return this.evalOrigin;
                    }, "getEvalOrigin"),
                    setEvalOrigin: /* @__PURE__ */ __name(function setEvalOrigin(v2) {
                      if (v2 instanceof StackFrame) {
                        this.evalOrigin = v2;
                      } else if (v2 instanceof Object) {
                        this.evalOrigin = new StackFrame(v2);
                      } 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 i3 = 0; i3 < booleanProps.length; i3++) {
                    StackFrame.prototype["get" + _capitalize(booleanProps[i3])] = _getter(booleanProps[i3]);
                    StackFrame.prototype["set" + _capitalize(booleanProps[i3])] = /* @__PURE__ */ function(p2) {
                      return function(v2) {
                        this[p2] = Boolean(v2);
                      };
                    }(booleanProps[i3]);
                  }
                  for (var j2 = 0; j2 < numericProps.length; j2++) {
                    StackFrame.prototype["get" + _capitalize(numericProps[j2])] = _getter(numericProps[j2]);
                    StackFrame.prototype["set" + _capitalize(numericProps[j2])] = /* @__PURE__ */ function(p2) {
                      return function(v2) {
                        if (!_isNumber(v2)) {
                          throw new TypeError(p2 + " must be a Number");
                        }
                        this[p2] = Number(v2);
                      };
                    }(numericProps[j2]);
                  }
                  for (var k2 = 0; k2 < stringProps.length; k2++) {
                    StackFrame.prototype["get" + _capitalize(stringProps[k2])] = _getter(stringProps[k2]);
                    StackFrame.prototype["set" + _capitalize(stringProps[k2])] = /* @__PURE__ */ function(p2) {
                      return function(v2) {
                        this[p2] = String(v2);
                      };
                    }(stringProps[k2]);
                  }
                  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 process50 = __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(f5) {
                  if (!isString2(f5)) {
                    var objects = [];
                    for (var i3 = 0; i3 < arguments.length; i3++) {
                      objects.push(inspect3(arguments[i3]));
                    }
                    return objects.join(" ");
                  }
                  var i3 = 1;
                  var args = arguments;
                  var len = args.length;
                  var str2 = String(f5).replace(formatRegExp, function(x4) {
                    if (x4 === "%%") return "%";
                    if (i3 >= len) return x4;
                    switch (x4) {
                      case "%s":
                        return String(args[i3++]);
                      case "%d":
                        return Number(args[i3++]);
                      case "%j":
                        try {
                          return JSON.stringify(args[i3++]);
                        } catch (_2) {
                          return "[Circular]";
                        }
                      default:
                        return x4;
                    }
                  });
                  for (var x3 = args[i3]; i3 < len; x3 = args[++i3]) {
                    if (isNull(x3) || !isObject4(x3)) {
                      str2 += " " + x3;
                    } else {
                      str2 += " " + inspect3(x3);
                    }
                  }
                  return str2;
                };
                exports3.deprecate = function(fn, msg) {
                  if (isUndefined2(globalThis.process)) {
                    return function() {
                      return exports3.deprecate(fn, msg).apply(this, arguments);
                    };
                  }
                  if (process50.noDeprecation === true) {
                    return fn;
                  }
                  var warned2 = false;
                  function deprecated() {
                    if (!warned2) {
                      if (process50.throwDeprecation) {
                        throw new Error(msg);
                      } else if (process50.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 = process50.env.NODE_DEBUG || "";
                  set = set.toUpperCase();
                  if (!debugs[set]) {
                    if (new RegExp("\\b" + set + "\\b", "i").test(debugEnviron)) {
                      var pid = process50.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 inspect3(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(inspect3, "inspect");
                exports3.inspect = inspect3;
                inspect3.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]
                };
                inspect3.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 = inspect3.styles[styleType];
                  if (style) {
                    return "\x1B[" + inspect3.colors[style][0] + "m" + str2 + "\x1B[" + inspect3.colors[style][1] + "m";
                  } else {
                    return str2;
                  }
                }
                __name(stylizeWithColor, "stylizeWithColor");
                function stylizeNoColor(str2, styleType) {
                  return str2;
                }
                __name(stylizeNoColor, "stylizeNoColor");
                function arrayToHash(array2) {
                  var hash = {};
                  array2.forEach(function(val, idx) {
                    hash[val] = true;
                  });
                  return hash;
                }
                __name(arrayToHash, "arrayToHash");
                function formatValue2(ctx, value, recurseTimes) {
                  if (ctx.customInspect && value && isFunction5(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 formatError2(value);
                  }
                  if (keys.length === 0) {
                    if (isFunction5(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 formatError2(value);
                    }
                  }
                  var base = "", array2 = false, braces = ["{", "}"];
                  if (isArray2(value)) {
                    array2 = true;
                    braces = ["[", "]"];
                  }
                  if (isFunction5(value)) {
                    var n3 = value.name ? ": " + value.name : "";
                    base = " [Function" + n3 + "]";
                  }
                  if (isRegExp(value)) {
                    base = " " + RegExp.prototype.toString.call(value);
                  }
                  if (isDate(value)) {
                    base = " " + Date.prototype.toUTCString.call(value);
                  }
                  if (isError(value)) {
                    base = " " + formatError2(value);
                  }
                  if (keys.length === 0 && (!array2 || 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 (array2) {
                    output = formatArray(ctx, value, recurseTimes, visibleKeys, keys);
                  } else {
                    output = keys.map(function(key) {
                      return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array2);
                    });
                  }
                  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 formatError2(value) {
                  return "[" + Error.prototype.toString.call(value) + "]";
                }
                __name(formatError2, "formatError");
                function formatArray(ctx, value, recurseTimes, visibleKeys, keys) {
                  var output = [];
                  for (var i3 = 0, l3 = value.length; i3 < l3; ++i3) {
                    if (hasOwnProperty2(value, String(i3))) {
                      output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, String(i3), 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, array2) {
                  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 (array2) {
                          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 (array2 && 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(ar2) {
                  return Array.isArray(ar2);
                }
                __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(re3) {
                  return isObject4(re3) && objectToString2(re3) === "[object RegExp]";
                }
                __name(isRegExp, "isRegExp");
                exports3.isRegExp = isRegExp;
                function isObject4(arg) {
                  return _typeof2(arg) === "object" && arg !== null;
                }
                __name(isObject4, "isObject");
                exports3.isObject = isObject4;
                function isDate(d2) {
                  return isObject4(d2) && objectToString2(d2) === "[object Date]";
                }
                __name(isDate, "isDate");
                exports3.isDate = isDate;
                function isError(e4) {
                  return isObject4(e4) && (objectToString2(e4) === "[object Error]" || e4 instanceof Error);
                }
                __name(isError, "isError");
                exports3.isError = isError;
                function isFunction5(arg) {
                  return typeof arg === "function";
                }
                __name(isFunction5, "isFunction");
                exports3.isFunction = isFunction5;
                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(o3) {
                  return Object.prototype.toString.call(o3);
                }
                __name(objectToString2, "objectToString");
                function pad(n3) {
                  return n3 < 10 ? "0" + n3.toString(10) : n3.toString(10);
                }
                __name(pad, "pad");
                var months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
                function timestamp() {
                  var d2 = /* @__PURE__ */ new Date();
                  var time3 = [pad(d2.getHours()), pad(d2.getMinutes()), pad(d2.getSeconds())].join(":");
                  return [d2.getDate(), months[d2.getMonth()], time3].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 || !isObject4(add)) return origin;
                  var keys = Object.keys(add);
                  var i3 = keys.length;
                  while (i3--) {
                    origin[keys[i3]] = add[keys[i3]];
                  }
                  return origin;
                };
                function hasOwnProperty2(obj, prop) {
                  return Object.prototype.hasOwnProperty.call(obj, prop);
                }
                __name(hasOwnProperty2, "hasOwnProperty");
              }
            ),
            /***/
            695: (
              /***/
              (module3) => {
                module3.exports = Yallist2;
                Yallist2.Node = Node5;
                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 i3 = 0, l3 = arguments.length; i3 < l3; i3++) {
                      self2.push(arguments[i3]);
                    }
                  }
                  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 i3 = 0, l3 = arguments.length; i3 < l3; i3++) {
                    push2(this, arguments[i3]);
                  }
                  return this.length;
                };
                Yallist2.prototype.unshift = function() {
                  for (var i3 = 0, l3 = arguments.length; i3 < l3; i3++) {
                    unshift2(this, arguments[i3]);
                  }
                  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, i3 = 0; walker !== null; i3++) {
                    fn.call(thisp, walker.value, i3, this);
                    walker = walker.next;
                  }
                };
                Yallist2.prototype.forEachReverse = function(fn, thisp) {
                  thisp = thisp || this;
                  for (var walker = this.tail, i3 = this.length - 1; walker !== null; i3--) {
                    fn.call(thisp, walker.value, i3, this);
                    walker = walker.prev;
                  }
                };
                Yallist2.prototype.get = function(n3) {
                  for (var i3 = 0, walker = this.head; walker !== null && i3 < n3; i3++) {
                    walker = walker.next;
                  }
                  if (i3 === n3 && walker !== null) {
                    return walker.value;
                  }
                };
                Yallist2.prototype.getReverse = function(n3) {
                  for (var i3 = 0, walker = this.tail; walker !== null && i3 < n3; i3++) {
                    walker = walker.prev;
                  }
                  if (i3 === n3 && 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 i3 = 0; walker !== null; i3++) {
                    acc = fn(acc, walker.value, i3);
                    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 i3 = this.length - 1; walker !== null; i3--) {
                    acc = fn(acc, walker.value, i3);
                    walker = walker.prev;
                  }
                  return acc;
                };
                Yallist2.prototype.toArray = function() {
                  var arr = new Array(this.length);
                  for (var i3 = 0, walker = this.head; walker !== null; i3++) {
                    arr[i3] = walker.value;
                    walker = walker.next;
                  }
                  return arr;
                };
                Yallist2.prototype.toArrayReverse = function() {
                  var arr = new Array(this.length);
                  for (var i3 = 0, walker = this.tail; walker !== null; i3++) {
                    arr[i3] = 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 i3 = 0, walker = this.head; walker !== null && i3 < from; i3++) {
                    walker = walker.next;
                  }
                  for (; walker !== null && i3 < to; i3++, 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 i3 = this.length, walker = this.tail; walker !== null && i3 > to; i3--) {
                    walker = walker.prev;
                  }
                  for (; walker !== null && i3 > from; i3--, 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 p2 = walker.prev;
                    walker.prev = walker.next;
                    walker.next = p2;
                  }
                  this.head = tail;
                  this.tail = head;
                  return this;
                };
                function push2(self2, item) {
                  self2.tail = new Node5(item, self2.tail, null, self2);
                  if (!self2.head) {
                    self2.head = self2.tail;
                  }
                  self2.length++;
                }
                __name(push2, "push");
                function unshift2(self2, item) {
                  self2.head = new Node5(item, null, self2.head, self2);
                  if (!self2.tail) {
                    self2.tail = self2.head;
                  }
                  self2.length++;
                }
                __name(unshift2, "unshift");
                function Node5(value, prev, next, list3) {
                  if (!(this instanceof Node5)) {
                    return new Node5(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(Node5, "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 i3 = 0; i3 < props.length; i3++) {
                var descriptor2 = props[i3];
                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 EventEmitter11 = /* @__PURE__ */ function() {
              function EventEmitter12() {
                _classCallCheck(this, EventEmitter12);
                _defineProperty2(this, "listenersMap", /* @__PURE__ */ new Map());
              }
              __name(EventEmitter12, "EventEmitter");
              _createClass(EventEmitter12, [{
                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 i3 = 0; i3 < clonedListeners.length; i3++) {
                        var _listener = clonedListeners[i3];
                        try {
                          _listener.apply(null, args);
                        } catch (error2) {
                          if (caughtError === null) {
                            didThrow = true;
                            caughtError = error2;
                          }
                        }
                      }
                      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 EventEmitter12;
            }();
            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 (error2) {
                return null;
              }
            }
            __name(storage_localStorageGetItem, "storage_localStorageGetItem");
            function localStorageRemoveItem(key) {
              try {
                localStorage.removeItem(key);
              } catch (error2) {
              }
            }
            __name(localStorageRemoveItem, "localStorageRemoveItem");
            function storage_localStorageSetItem(key, value) {
              try {
                return localStorage.setItem(key, value);
              } catch (error2) {
              }
            }
            __name(storage_localStorageSetItem, "storage_localStorageSetItem");
            function sessionStorageGetItem(key) {
              try {
                return sessionStorage.getItem(key);
              } catch (error2) {
                return null;
              }
            }
            __name(sessionStorageGetItem, "sessionStorageGetItem");
            function sessionStorageRemoveItem(key) {
              try {
                sessionStorage.removeItem(key);
              } catch (error2) {
              }
            }
            __name(sessionStorageRemoveItem, "sessionStorageRemoveItem");
            function sessionStorageSetItem(key, value) {
              try {
                return sessionStorage.setItem(key, value);
              } catch (error2) {
              }
            }
            __name(sessionStorageSetItem, "sessionStorageSetItem");
            ;
            var simpleIsEqual = /* @__PURE__ */ __name(function simpleIsEqual2(a2, b2) {
              return a2 === b2;
            }, "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 i3 = 0; i3 < props.length; i3++) {
                var descriptor2 = props[i3];
                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 inspect3(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 (error2) {
                  }
                });
                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 (error2) {
                  }
                }
                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(_2, 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, i3) {
              return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i3) || _unsupportedIterableToArray2(arr, i3) || _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(o3, minLen) {
              if (!o3) return;
              if (typeof o3 === "string") return _arrayLikeToArray2(o3, minLen);
              var n3 = Object.prototype.toString.call(o3).slice(8, -1);
              if (n3 === "Object" && o3.constructor) n3 = o3.constructor.name;
              if (n3 === "Map" || n3 === "Set") return Array.from(o3);
              if (n3 === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n3)) return _arrayLikeToArray2(o3, minLen);
            }
            __name(_unsupportedIterableToArray2, "_unsupportedIterableToArray");
            function _arrayLikeToArray2(arr, len) {
              if (len == null || len > arr.length) len = arr.length;
              for (var i3 = 0, arr2 = new Array(len); i3 < len; i3++) {
                arr2[i3] = arr[i3];
              }
              return arr2;
            }
            __name(_arrayLikeToArray2, "_arrayLikeToArray");
            function _iterableToArrayLimit(arr, i3) {
              if (typeof Symbol === "undefined" || !(Symbol.iterator in Object(arr))) return;
              var _arr = [];
              var _n = true;
              var _d = false;
              var _e2 = void 0;
              try {
                for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) {
                  _arr.push(_s.value);
                  if (i3 && _arr.length === i3) break;
                }
              } catch (err) {
                _d = true;
                _e2 = err;
              } finally {
                try {
                  if (!_n && _i["return"] != null) _i["return"]();
                } finally {
                  if (_d) throw _e2;
                }
              }
              return _arr;
            }
            __name(_iterableToArrayLimit, "_iterableToArrayLimit");
            function _arrayWithHoles(arr) {
              if (Array.isArray(arr)) return arr;
            }
            __name(_arrayWithHoles, "_arrayWithHoles");
            var compareVersions = /* @__PURE__ */ __name(function compareVersions2(v1, v2) {
              var n1 = validateAndParse(v1);
              var n22 = validateAndParse(v2);
              var p1 = n1.pop();
              var p2 = n22.pop();
              var r5 = compareSegments(n1, n22);
              if (r5 !== 0) return r5;
              if (p1 && p2) {
                return compareSegments(p1.split("."), p2.split("."));
              } else if (p1 || p2) {
                return p1 ? -1 : 1;
              }
              return 0;
            }, "compareVersions");
            var validate3 = /* @__PURE__ */ __name(function validate4(version2) {
              return typeof version2 === "string" && /^[v\d]/.test(version2) && semver3.test(version2);
            }, "validate");
            var compare = /* @__PURE__ */ __name(function compare2(v1, v2, operator2) {
              assertValidOperator(operator2);
              var res = compareVersions(v1, v2);
              return operatorResMap[operator2].includes(res);
            }, "compare");
            var satisfies = /* @__PURE__ */ __name(function satisfies2(version2, range) {
              var m3 = range.match(/^([<>=~^]+)/);
              var op = m3 ? m3[1] : "=";
              if (op !== "^" && op !== "~") return compare(version2, range, op);
              var _validateAndParse = validateAndParse(version2), _validateAndParse2 = _slicedToArray(_validateAndParse, 5), v1 = _validateAndParse2[0], v2 = _validateAndParse2[1], v3 = _validateAndParse2[2], vp = _validateAndParse2[4];
              var _validateAndParse3 = validateAndParse(range), _validateAndParse4 = _slicedToArray(_validateAndParse3, 5), r1 = _validateAndParse4[0], r22 = _validateAndParse4[1], r32 = _validateAndParse4[2], rp = _validateAndParse4[4];
              var v5 = [v1, v2, v3];
              var r5 = [r1, r22 !== null && r22 !== void 0 ? r22 : "x", r32 !== null && r32 !== void 0 ? r32 : "x"];
              if (rp) {
                if (!vp) return false;
                if (compareSegments(v5, r5) !== 0) return false;
                if (compareSegments(vp.split("."), rp.split(".")) === -1) return false;
              }
              var nonZero = r5.findIndex(function(v6) {
                return v6 !== "0";
              }) + 1;
              var i3 = op === "~" ? 2 : nonZero > 1 ? nonZero : 1;
              if (compareSegments(v5.slice(0, i3), r5.slice(0, i3)) !== 0) return false;
              if (compareSegments(v5.slice(i3), r5.slice(i3)) === -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(s5) {
              return s5 === "*" || s5 === "x" || s5 === "X";
            }, "isWildcard");
            var tryParse = /* @__PURE__ */ __name(function tryParse2(v2) {
              var n3 = parseInt(v2, 10);
              return isNaN(n3) ? v2 : n3;
            }, "tryParse");
            var forceType = /* @__PURE__ */ __name(function forceType2(a2, b2) {
              return esm_typeof(a2) !== esm_typeof(b2) ? [String(a2), String(b2)] : [a2, b2];
            }, "forceType");
            var compareStrings = /* @__PURE__ */ __name(function compareStrings2(a2, b2) {
              if (isWildcard(a2) || isWildcard(b2)) return 0;
              var _forceType = forceType(tryParse(a2), tryParse(b2)), _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(a2, b2) {
              for (var i3 = 0; i3 < Math.max(a2.length, b2.length); i3++) {
                var r5 = compareStrings(a2[i3] || "0", b2[i3] || "0");
                if (r5 !== 0) return r5;
              }
              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 process50 = __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(o3, minLen) {
              if (!o3) return;
              if (typeof o3 === "string") return utils_arrayLikeToArray(o3, minLen);
              var n3 = Object.prototype.toString.call(o3).slice(8, -1);
              if (n3 === "Object" && o3.constructor) n3 = o3.constructor.name;
              if (n3 === "Map" || n3 === "Set") return Array.from(o3);
              if (n3 === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n3)) return utils_arrayLikeToArray(o3, 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 i3 = 0, arr2 = new Array(len); i3 < len; i3++) {
                arr2[i3] = arr[i3];
              }
              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(a2, b2) {
              if (a2.toString() > b2.toString()) {
                return 1;
              } else if (b2.toString() > a2.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(array2) {
              var string4 = "";
              for (var i3 = 0; i3 < array2.length; i3++) {
                var char = array2[i3];
                string4 += String.fromCodePoint(char);
              }
              return string4;
            }
            __name(utfDecodeString, "utfDecodeString");
            function surrogatePairToCodePoint(charCode1, charCode2) {
              return ((charCode1 & 1023) << 10) + (charCode2 & 1023) + 65536;
            }
            __name(surrogatePairToCodePoint, "surrogatePairToCodePoint");
            function utfEncodeString(string4) {
              var cached2 = encodedStringCache.get(string4);
              if (cached2 !== void 0) {
                return cached2;
              }
              var encoded = [];
              var i3 = 0;
              var charCode;
              while (i3 < string4.length) {
                charCode = string4.charCodeAt(i3);
                if ((charCode & 63488) === 55296) {
                  encoded.push(surrogatePairToCodePoint(charCode, string4.charCodeAt(++i3)));
                } else {
                  encoded.push(charCode);
                }
                ++i3;
              }
              encodedStringCache.set(string4, 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 i3 = 2;
              var stringTable = [
                null
                // ID = 0 corresponds to the null string.
              ];
              var stringTableSize = operations[i3++];
              var stringTableEnd = i3 + stringTableSize;
              while (i3 < stringTableEnd) {
                var nextLength = operations[i3++];
                var nextString = utfDecodeString(operations.slice(i3, i3 + nextLength));
                stringTable.push(nextString);
                i3 += nextLength;
              }
              while (i3 < operations.length) {
                var operation = operations[i3];
                switch (operation) {
                  case TREE_OPERATION_ADD: {
                    var _id = operations[i3 + 1];
                    var type = operations[i3 + 2];
                    i3 += 3;
                    if (type === ElementTypeRoot) {
                      logs2.push("Add new root node ".concat(_id));
                      i3++;
                      i3++;
                      i3++;
                      i3++;
                    } else {
                      var parentID = operations[i3];
                      i3++;
                      i3++;
                      var displayNameStringID = operations[i3];
                      var displayName = stringTable[displayNameStringID];
                      i3++;
                      i3++;
                      logs2.push("Add node ".concat(_id, " (").concat(displayName || "null", ") as child of ").concat(parentID));
                    }
                    break;
                  }
                  case TREE_OPERATION_REMOVE: {
                    var removeLength = operations[i3 + 1];
                    i3 += 2;
                    for (var removeIndex = 0; removeIndex < removeLength; removeIndex++) {
                      var _id2 = operations[i3];
                      i3 += 1;
                      logs2.push("Remove node ".concat(_id2));
                    }
                    break;
                  }
                  case TREE_OPERATION_REMOVE_ROOT: {
                    i3 += 1;
                    logs2.push("Remove root ".concat(rootID));
                    break;
                  }
                  case TREE_OPERATION_SET_SUBTREE_MODE: {
                    var _id3 = operations[i3 + 1];
                    var mode = operations[i3 + 1];
                    i3 += 3;
                    logs2.push("Mode ".concat(mode, " set for subtree with root ").concat(_id3));
                    break;
                  }
                  case TREE_OPERATION_REORDER_CHILDREN: {
                    var _id4 = operations[i3 + 1];
                    var numChildren = operations[i3 + 2];
                    i3 += 3;
                    var children = operations.slice(i3, i3 + numChildren);
                    i3 += numChildren;
                    logs2.push("Re-order node ".concat(_id4, " children ").concat(children.join(",")));
                    break;
                  }
                  case TREE_OPERATION_UPDATE_TREE_BASE_DURATION:
                    i3 += 3;
                    break;
                  case TREE_OPERATION_UPDATE_ERRORS_OR_WARNINGS:
                    var id = operations[i3 + 1];
                    var numErrors = operations[i3 + 2];
                    var numWarnings = operations[i3 + 3];
                    i3 += 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 (error2) {
              }
              return getDefaultComponentFilters();
            }
            __name(getSavedComponentFilters, "getSavedComponentFilters");
            function setSavedComponentFilters(componentFilters) {
              localStorageSetItem(LOCAL_STORAGE_COMPONENT_FILTER_PREFERENCES_KEY, JSON.stringify(componentFilters));
            }
            __name(setSavedComponentFilters, "setSavedComponentFilters");
            function parseBool(s5) {
              if (s5 === "true") {
                return true;
              }
              if (s5 === "false") {
                return false;
              }
            }
            __name(parseBool, "parseBool");
            function castBool(v2) {
              if (v2 === true || v2 === false) {
                return v2;
              }
            }
            __name(castBool, "castBool");
            function castBrowserTheme(v2) {
              if (v2 === "light" || v2 === "dark" || v2 === "auto") {
                return v2;
              }
            }
            __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 process50.env.EDITOR_URL === "string" ? process50.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 (error2) {
              }
              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(object3, path125) {
              return path125.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;
              }, object3);
            }
            __name(utils_getInObject, "utils_getInObject");
            function deletePathInObject(object3, path125) {
              var length = path125.length;
              var last2 = path125[length - 1];
              if (object3 != null) {
                var parent = utils_getInObject(object3, path125.slice(0, length - 1));
                if (parent) {
                  if (src_isArray(parent)) {
                    parent.splice(last2, 1);
                  } else {
                    delete parent[last2];
                  }
                }
              }
            }
            __name(deletePathInObject, "deletePathInObject");
            function renamePathInObject(object3, oldPath, newPath) {
              var length = oldPath.length;
              if (object3 != null) {
                var parent = utils_getInObject(object3, 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(object3, path125, value) {
              var length = path125.length;
              var last2 = path125[length - 1];
              if (object3 != null) {
                var parent = utils_getInObject(object3, path125.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 (!isPlainObject7(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(string4) {
              var length = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : MAX_PREVIEW_STRING_LENGTH;
              if (string4.length > length) {
                return string4.slice(0, length) + "\u2026";
              } else {
                return string4;
              }
            }
            __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 i3 = 0; i3 < data.length; i3++) {
                      if (i3 > 0) {
                        formatted += ", ";
                      }
                      formatted += formatDataForPreview(data[i3], 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 array2 = Array.from(data);
                    var _formatted2 = "";
                    for (var _i2 = 0; _i2 < array2.length; _i2++) {
                      var entryOrEntries = array2[_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 (error2) {
                    return "unserializable";
                  }
              }
            }
            __name(formatDataForPreview, "formatDataForPreview");
            var isPlainObject7 = /* @__PURE__ */ __name(function isPlainObject8(object3) {
              var objectPrototype = Object.getPrototypeOf(object3);
              if (!objectPrototype) return true;
              var objectParentPrototype = Object.getPrototypeOf(objectPrototype);
              return !objectParentPrototype;
            }, "isPlainObject");
            ;
            function ownKeys2(object3, enumerableOnly) {
              var keys = Object.keys(object3);
              if (Object.getOwnPropertySymbols) {
                var symbols = Object.getOwnPropertySymbols(object3);
                if (enumerableOnly) symbols = symbols.filter(function(sym) {
                  return Object.getOwnPropertyDescriptor(object3, sym).enumerable;
                });
                keys.push.apply(keys, symbols);
              }
              return keys;
            }
            __name(ownKeys2, "ownKeys");
            function _objectSpread(target) {
              for (var i3 = 1; i3 < arguments.length; i3++) {
                var source2 = arguments[i3] != null ? arguments[i3] : {};
                if (i3 % 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, path125) {
              cleaned.push(path125);
              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, path125, 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(path125);
                  return {
                    inspectable: false,
                    preview_short: formatDataForPreview(data, false),
                    preview_long: formatDataForPreview(data, true),
                    name: data.tagName,
                    type
                  };
                case "function":
                  cleaned.push(path125);
                  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(path125);
                  if (isPathAllowedCheck) {
                    return data;
                  } else {
                    return data.length <= 500 ? data : data.slice(0, 500) + "...";
                  }
                case "bigint":
                  cleaned.push(path125);
                  return {
                    inspectable: false,
                    preview_short: formatDataForPreview(data, false),
                    preview_long: formatDataForPreview(data, true),
                    name: data.toString(),
                    type
                  };
                case "symbol":
                  cleaned.push(path125);
                  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(path125);
                  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(path125);
                  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(path125);
                  if (level >= LEVEL_THRESHOLD && !isPathAllowedCheck) {
                    return createDehydrated(type, true, data, cleaned, path125);
                  }
                  return data.map(function(item, i3) {
                    return dehydrate(item, cleaned, unserializable, path125.concat([i3]), isPathAllowed, isPathAllowedCheck ? 1 : level + 1);
                  });
                case "html_all_collection":
                case "typed_array":
                case "iterator":
                  isPathAllowedCheck = isPathAllowed(path125);
                  if (level >= LEVEL_THRESHOLD && !isPathAllowedCheck) {
                    return createDehydrated(type, true, data, cleaned, path125);
                  } 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, i3) {
                      return unserializableValue[i3] = dehydrate(item, cleaned, unserializable, path125.concat([i3]), isPathAllowed, isPathAllowedCheck ? 1 : level + 1);
                    });
                    unserializable.push(path125);
                    return unserializableValue;
                  }
                case "opaque_iterator":
                  cleaned.push(path125);
                  return {
                    inspectable: false,
                    preview_short: formatDataForPreview(data, false),
                    preview_long: formatDataForPreview(data, true),
                    name: data[Symbol.toStringTag],
                    type
                  };
                case "date":
                  cleaned.push(path125);
                  return {
                    inspectable: false,
                    preview_short: formatDataForPreview(data, false),
                    preview_long: formatDataForPreview(data, true),
                    name: data.toString(),
                    type
                  };
                case "regexp":
                  cleaned.push(path125);
                  return {
                    inspectable: false,
                    preview_short: formatDataForPreview(data, false),
                    preview_long: formatDataForPreview(data, true),
                    name: data.toString(),
                    type
                  };
                case "object":
                  isPathAllowedCheck = isPathAllowed(path125);
                  if (level >= LEVEL_THRESHOLD && !isPathAllowedCheck) {
                    return createDehydrated(type, true, data, cleaned, path125);
                  } else {
                    var object3 = {};
                    getAllEnumerableKeys(data).forEach(function(key) {
                      var name3 = key.toString();
                      object3[name3] = dehydrate(data[key], cleaned, unserializable, path125.concat([name3]), isPathAllowed, isPathAllowedCheck ? 1 : level + 1);
                    });
                    return object3;
                  }
                case "class_instance":
                  isPathAllowedCheck = isPathAllowed(path125);
                  if (level >= LEVEL_THRESHOLD && !isPathAllowedCheck) {
                    return createDehydrated(type, true, data, cleaned, path125);
                  }
                  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, path125.concat([keyAsString]), isPathAllowed, isPathAllowedCheck ? 1 : level + 1);
                  });
                  unserializable.push(path125);
                  return value;
                case "infinity":
                case "nan":
                case "undefined":
                  cleaned.push(path125);
                  return {
                    type
                  };
                default:
                  return data;
              }
            }
            __name(dehydrate, "dehydrate");
            function fillInPath(object3, data, path125, value) {
              var target = getInObject(object3, path125);
              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 === path125.length;
                for (var i3 = 0; i3 < path125.length; i3++) {
                  if (path125[i3] !== unserializablePath[i3]) {
                    isMatch = false;
                    break;
                  }
                }
                if (isMatch) {
                  upgradeUnserializable(value, value);
                }
              }
              setInObject(object3, path125, value);
            }
            __name(fillInPath, "fillInPath");
            function hydrate(object3, cleaned, unserializable) {
              cleaned.forEach(function(path125) {
                var length = path125.length;
                var last2 = path125[length - 1];
                var parent = getInObject(object3, path125.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(path125) {
                var length = path125.length;
                var last2 = path125[length - 1];
                var parent = getInObject(object3, path125.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 object3;
            }
            __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(a2) {
              return isArrayImpl(a2);
            }
            __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(o3, minLen) {
              if (!o3) return;
              if (typeof o3 === "string") return backend_utils_arrayLikeToArray(o3, minLen);
              var n3 = Object.prototype.toString.call(o3).slice(8, -1);
              if (n3 === "Object" && o3.constructor) n3 = o3.constructor.name;
              if (n3 === "Map" || n3 === "Set") return Array.from(o3);
              if (n3 === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n3)) return backend_utils_arrayLikeToArray(o3, 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 i3 = 0, arr2 = new Array(len); i3 < len; i3++) {
                arr2[i3] = arr[i3];
              }
              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(object3, enumerableOnly) {
              var keys = Object.keys(object3);
              if (Object.getOwnPropertySymbols) {
                var symbols = Object.getOwnPropertySymbols(object3);
                if (enumerableOnly) symbols = symbols.filter(function(sym) {
                  return Object.getOwnPropertyDescriptor(object3, sym).enumerable;
                });
                keys.push.apply(keys, symbols);
              }
              return keys;
            }
            __name(utils_ownKeys, "utils_ownKeys");
            function utils_objectSpread(target) {
              for (var i3 = 1; i3 < arguments.length; i3++) {
                var source2 = arguments[i3] != null ? arguments[i3] : {};
                if (i3 % 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 path125 = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : [];
              if (data !== null) {
                var cleanedPaths = [];
                var unserializablePaths = [];
                var cleanedData = dehydrate(data, cleanedPaths, unserializablePaths, path125, isPathAllowed);
                return {
                  data: cleanedData,
                  cleaned: cleanedPaths,
                  unserializable: unserializablePaths
                };
              } else {
                return null;
              }
            }
            __name(cleanForBridge, "cleanForBridge");
            function copyWithDelete(obj, path125) {
              var index = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : 0;
              var key = path125[index];
              var updated = shared_isArray(obj) ? obj.slice() : utils_objectSpread({}, obj);
              if (index + 1 === path125.length) {
                if (shared_isArray(updated)) {
                  updated.splice(key, 1);
                } else {
                  delete updated[key];
                }
              } else {
                updated[key] = copyWithDelete(obj[key], path125, 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, path125, value) {
              var index = arguments.length > 3 && arguments[3] !== void 0 ? arguments[3] : 0;
              if (index >= path125.length) {
                return value;
              }
              var key = path125[index];
              var updated = shared_isArray(obj) ? obj.slice() : utils_objectSpread({}, obj);
              updated[key] = copyWithSet(obj[key], path125, 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, i3) {
                  if (i3 > 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 i3 = 0; i3 < args.length; i3++) {
                  formatted += " " + String(args[i3]);
                }
              }
              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 gt2() {
              var a2 = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : "";
              var b2 = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : "";
              return compareVersions(a2, b2) === 1;
            }
            __name(gt2, "gt");
            function gte() {
              var a2 = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : "";
              var b2 = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : "";
              return compareVersions(a2, b2) > -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(x3, y2) {
              return x3 === y2 && (x3 !== 0 || 1 / x3 === 1 / y2) || x3 !== x3 && y2 !== y2;
            }
            __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 (_e2) {
                  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(object3, enumerableOnly) {
              var keys = Object.keys(object3);
              if (Object.getOwnPropertySymbols) {
                var symbols = Object.getOwnPropertySymbols(object3);
                if (enumerableOnly) symbols = symbols.filter(function(sym) {
                  return Object.getOwnPropertyDescriptor(object3, sym).enumerable;
                });
                keys.push.apply(keys, symbols);
              }
              return keys;
            }
            __name(DevToolsConsolePatching_ownKeys, "DevToolsConsolePatching_ownKeys");
            function DevToolsConsolePatching_objectSpread(target) {
              for (var i3 = 1; i3 < arguments.length; i3++) {
                var source2 = arguments[i3] != null ? arguments[i3] : {};
                if (i3 % 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 (x3) {
                  var match2 = x3.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 (x3) {
                      control = x3;
                    }
                    Reflect.construct(fn, [], Fake);
                  } else {
                    try {
                      Fake.call();
                    } catch (x3) {
                      control = x3;
                    }
                    fn.call(Fake.prototype);
                  }
                } else {
                  try {
                    throw Error();
                  } catch (x3) {
                    control = x3;
                  }
                  fn();
                }
              } catch (sample) {
                if (sample && control && typeof sample.stack === "string") {
                  var sampleLines = sample.stack.split("\n");
                  var controlLines = control.stack.split("\n");
                  var s5 = sampleLines.length - 1;
                  var c4 = controlLines.length - 1;
                  while (s5 >= 1 && c4 >= 0 && sampleLines[s5] !== controlLines[c4]) {
                    c4--;
                  }
                  for (; s5 >= 1 && c4 >= 0; s5--, c4--) {
                    if (sampleLines[s5] !== controlLines[c4]) {
                      if (s5 !== 1 || c4 !== 1) {
                        do {
                          s5--;
                          c4--;
                          if (c4 < 0 || sampleLines[s5] !== controlLines[c4]) {
                            var _frame = "\n" + sampleLines[s5].replace(" at new ", " at ");
                            if (false) {
                            }
                            return _frame;
                          }
                        } while (s5 >= 1 && c4 >= 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 (x3) {
                    }
                  }
                }
              }
              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 (x3) {
                return "\nError generating stack: " + x3.message + "\n" + x3.stack;
              }
            }
            __name(getStackByFiberInDevAndProd, "getStackByFiberInDevAndProd");
            ;
            function profilingHooks_slicedToArray(arr, i3) {
              return profilingHooks_arrayWithHoles(arr) || profilingHooks_iterableToArrayLimit(arr, i3) || profilingHooks_unsupportedIterableToArray(arr, i3) || 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(o3, minLen) {
              if (!o3) return;
              if (typeof o3 === "string") return profilingHooks_arrayLikeToArray(o3, minLen);
              var n3 = Object.prototype.toString.call(o3).slice(8, -1);
              if (n3 === "Object" && o3.constructor) n3 = o3.constructor.name;
              if (n3 === "Map" || n3 === "Set") return Array.from(o3);
              if (n3 === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n3)) return profilingHooks_arrayLikeToArray(o3, minLen);
            }
            __name(profilingHooks_unsupportedIterableToArray, "profilingHooks_unsupportedIterableToArray");
            function profilingHooks_arrayLikeToArray(arr, len) {
              if (len == null || len > arr.length) len = arr.length;
              for (var i3 = 0, arr2 = new Array(len); i3 < len; i3++) {
                arr2[i3] = arr[i3];
              }
              return arr2;
            }
            __name(profilingHooks_arrayLikeToArray, "profilingHooks_arrayLikeToArray");
            function profilingHooks_iterableToArrayLimit(arr, i3) {
              if (typeof Symbol === "undefined" || !(Symbol.iterator in Object(arr))) return;
              var _arr = [];
              var _n = true;
              var _d = false;
              var _e2 = void 0;
              try {
                for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) {
                  _arr.push(_s.value);
                  if (i3 && _arr.length === i3) break;
                }
              } catch (err) {
                _d = true;
                _e2 = err;
              } finally {
                try {
                  if (!_n && _i["return"] != null) _i["return"]();
                } finally {
                  if (_d) throw _e2;
                }
              }
              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 get4() {
                  supportsUserTimingV3 = true;
                  return 0;
                }, "get"),
                set: /* @__PURE__ */ __name(function set() {
                }, "set")
              });
              try {
                performance.mark(CHECK_V3_MARK, markOptions);
              } catch (error2) {
              } 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 i3 = 0; i3 < ranges2.length; i3++) {
                    var range = ranges2[i3];
                    if (shared_isArray(range) && range.length === 2) {
                      var _ranges$i = profilingHooks_slicedToArray(ranges2[i3], 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 i3 = 0; i3 < ranges2.length; i3++) {
                          var range = ranges2[i3];
                          if (shared_isArray(range) && range.length === 2) {
                            var _ranges$i2 = profilingHooks_slicedToArray(ranges2[i3], 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, i3;
              if (Object.getOwnPropertySymbols) {
                var sourceSymbolKeys = Object.getOwnPropertySymbols(source2);
                for (i3 = 0; i3 < sourceSymbolKeys.length; i3++) {
                  key = sourceSymbolKeys[i3];
                  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, i3;
              for (i3 = 0; i3 < sourceKeys.length; i3++) {
                key = sourceKeys[i3];
                if (excluded.indexOf(key) >= 0) continue;
                target[key] = source2[key];
              }
              return target;
            }
            __name(_objectWithoutPropertiesLoose, "_objectWithoutPropertiesLoose");
            function renderer_ownKeys(object3, enumerableOnly) {
              var keys = Object.keys(object3);
              if (Object.getOwnPropertySymbols) {
                var symbols = Object.getOwnPropertySymbols(object3);
                if (enumerableOnly) symbols = symbols.filter(function(sym) {
                  return Object.getOwnPropertyDescriptor(object3, sym).enumerable;
                });
                keys.push.apply(keys, symbols);
              }
              return keys;
            }
            __name(renderer_ownKeys, "renderer_ownKeys");
            function renderer_objectSpread(target) {
              for (var i3 = 1; i3 < arguments.length; i3++) {
                var source2 = arguments[i3] != null ? arguments[i3] : {};
                if (i3 % 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, i3) {
              return renderer_arrayWithHoles(arr) || renderer_iterableToArrayLimit(arr, i3) || renderer_unsupportedIterableToArray(arr, i3) || 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, i3) {
              if (typeof Symbol === "undefined" || !(Symbol.iterator in Object(arr))) return;
              var _arr = [];
              var _n = true;
              var _d = false;
              var _e2 = void 0;
              try {
                for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) {
                  _arr.push(_s.value);
                  if (i3 && _arr.length === i3) break;
                }
              } catch (err) {
                _d = true;
                _e2 = err;
              } finally {
                try {
                  if (!_n && _i["return"] != null) _i["return"]();
                } finally {
                  if (_d) throw _e2;
                }
              }
              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(o3, allowArrayLike) {
              var it2;
              if (typeof Symbol === "undefined" || o3[Symbol.iterator] == null) {
                if (Array.isArray(o3) || (it2 = renderer_unsupportedIterableToArray(o3)) || allowArrayLike && o3 && typeof o3.length === "number") {
                  if (it2) o3 = it2;
                  var i3 = 0;
                  var F4 = /* @__PURE__ */ __name(function F5() {
                  }, "F");
                  return { s: F4, n: /* @__PURE__ */ __name(function n3() {
                    if (i3 >= o3.length) return { done: true };
                    return { done: false, value: o3[i3++] };
                  }, "n"), e: /* @__PURE__ */ __name(function e4(_e2) {
                    throw _e2;
                  }, "e"), f: F4 };
                }
                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 s5() {
                it2 = o3[Symbol.iterator]();
              }, "s"), n: /* @__PURE__ */ __name(function n3() {
                var step = it2.next();
                normalCompletion = step.done;
                return step;
              }, "n"), e: /* @__PURE__ */ __name(function e4(_e3) {
                didErr = true;
                err = _e3;
              }, "e"), f: /* @__PURE__ */ __name(function f5() {
                try {
                  if (!normalCompletion && it2.return != null) it2.return();
                } finally {
                  if (didErr) throw err;
                }
              }, "f") };
            }
            __name(_createForOfIteratorHelper, "_createForOfIteratorHelper");
            function renderer_unsupportedIterableToArray(o3, minLen) {
              if (!o3) return;
              if (typeof o3 === "string") return renderer_arrayLikeToArray(o3, minLen);
              var n3 = Object.prototype.toString.call(o3).slice(8, -1);
              if (n3 === "Object" && o3.constructor) n3 = o3.constructor.name;
              if (n3 === "Map" || n3 === "Set") return Array.from(o3);
              if (n3 === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n3)) return renderer_arrayLikeToArray(o3, minLen);
            }
            __name(renderer_unsupportedIterableToArray, "renderer_unsupportedIterableToArray");
            function renderer_arrayLikeToArray(arr, len) {
              if (len == null || len > arr.length) len = arr.length;
              for (var i3 = 0, arr2 = new Array(len); i3 < len; i3++) {
                arr2[i3] = arr[i3];
              }
              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 (gt2(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 (gt2(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, Fragment16 = _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 Fragment16:
                    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, Fragment16 = 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__) {
                  debug4("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 debug4 = /* @__PURE__ */ __name(function debug5(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 Fragment16:
                    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 Fragment16:
                    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) {
                    debug4("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__) {
                  debug4("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 j2 = 0; j2 < pendingOperations.length; j2++) {
                    operations[3 + j2] = pendingOperations[j2];
                  }
                  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 i3 = 0;
                operations[i3++] = rendererID;
                operations[i3++] = currentRootID;
                operations[i3++] = pendingStringTableLength;
                pendingStringTable.forEach(function(entry, stringKey) {
                  var encodedString = entry.encodedString;
                  var length = encodedString.length;
                  operations[i3++] = length;
                  for (var j3 = 0; j3 < length; j3++) {
                    operations[i3 + j3] = encodedString[j3];
                  }
                  i3 += length;
                });
                if (numUnmountIDs > 0) {
                  operations[i3++] = TREE_OPERATION_REMOVE;
                  operations[i3++] = numUnmountIDs;
                  for (var j2 = pendingRealUnmountedIDs.length - 1; j2 >= 0; j2--) {
                    operations[i3++] = pendingRealUnmountedIDs[j2];
                  }
                  for (var _j = 0; _j < pendingSimulatedUnmountedIDs.length; _j++) {
                    operations[i3 + _j] = pendingSimulatedUnmountedIDs[_j];
                  }
                  i3 += pendingSimulatedUnmountedIDs.length;
                  if (pendingUnmountedRootID !== null) {
                    operations[i3] = pendingUnmountedRootID;
                    i3++;
                  }
                }
                for (var _j2 = 0; _j2 < pendingOperations.length; _j2++) {
                  operations[i3 + _j2] = pendingOperations[_j2];
                }
                i3 += pendingOperations.length;
                flushOrQueueOperations(operations);
                pendingOperations.length = 0;
                pendingRealUnmountedIDs.length = 0;
                pendingSimulatedUnmountedIDs.length = 0;
                pendingUnmountedRootID = null;
                pendingStringTable.clear();
                pendingStringTableLength = 0;
              }
              __name(flushPendingEvents, "flushPendingEvents");
              function getStringID(string4) {
                if (string4 === null) {
                  return 0;
                }
                var existingEntry = pendingStringTable.get(string4);
                if (existingEntry !== void 0) {
                  return existingEntry.id;
                }
                var id = pendingStringTable.size + 1;
                var encodedString = utfEncodeString(string4);
                pendingStringTable.set(string4, {
                  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__) {
                  debug4("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__) {
                  debug4("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__) {
                    debug4("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__) {
                  debug4("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__) {
                  debug4("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 i3 = 0; i3 < nextChildren.length; i3++) {
                  pushOperation(nextChildren[i3]);
                }
              }
              __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__) {
                  debug4("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 a2 = fiber;
                var b2 = alternate;
                while (true) {
                  var parentA = a2.return;
                  if (parentA === null) {
                    break;
                  }
                  var parentB = parentA.alternate;
                  if (parentB === null) {
                    var nextParent = parentA.return;
                    if (nextParent !== null) {
                      a2 = b2 = nextParent;
                      continue;
                    }
                    break;
                  }
                  if (parentA.child === parentB.child) {
                    var child = parentA.child;
                    while (child) {
                      if (child === a2) {
                        assertIsMounted(parentA);
                        return fiber;
                      }
                      if (child === b2) {
                        assertIsMounted(parentA);
                        return alternate;
                      }
                      child = child.sibling;
                    }
                    throw new Error("Unable to find node on an unmounted component.");
                  }
                  if (a2.return !== b2.return) {
                    a2 = parentA;
                    b2 = parentB;
                  } else {
                    var didFindChild = false;
                    var _child = parentA.child;
                    while (_child) {
                      if (_child === a2) {
                        didFindChild = true;
                        a2 = parentA;
                        b2 = parentB;
                        break;
                      }
                      if (_child === b2) {
                        didFindChild = true;
                        b2 = parentA;
                        a2 = parentB;
                        break;
                      }
                      _child = _child.sibling;
                    }
                    if (!didFindChild) {
                      _child = parentB.child;
                      while (_child) {
                        if (_child === a2) {
                          didFindChild = true;
                          a2 = parentB;
                          b2 = parentA;
                          break;
                        }
                        if (_child === b2) {
                          didFindChild = true;
                          b2 = parentB;
                          a2 = 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 (a2.alternate !== b2) {
                    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 (a2.tag !== HostRoot) {
                  throw new Error("Unable to find node on an unmounted component.");
                }
                if (a2.stateNode.current === a2) {
                  return fiber;
                }
                return alternate;
              }
              __name(findCurrentFiberUsingSlowPathById, "findCurrentFiberUsingSlowPathById");
              function prepareViewAttributeSource(id, path125) {
                if (isMostRecentlyInspectedElement(id)) {
                  window.$attribute = utils_getInObject(mostRecentlyInspectedElement, path125);
                }
              }
              __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 (error2) {
                    }
                  }
                  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 (error2) {
                      }
                    }
                  }
                }
                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(path125) {
                var current = currentlyInspectedPaths;
                path125.forEach(function(key) {
                  if (!current[key]) {
                    current[key] = {};
                  }
                  current = current[key];
                });
              }
              __name(mergeInspectedPaths, "mergeInspectedPaths");
              function createIsPathAllowed(key, secondaryCategory) {
                return /* @__PURE__ */ __name(function isPathAllowed(path125) {
                  switch (secondaryCategory) {
                    case "hooks":
                      if (path125.length === 1) {
                        return true;
                      }
                      if (path125[path125.length - 2] === "hookSource" && path125[path125.length - 1] === "fileName") {
                        return true;
                      }
                      if (path125[path125.length - 1] === "subHooks" || path125[path125.length - 2] === "subHooks") {
                        return true;
                      }
                      break;
                    default:
                      break;
                  }
                  var current = key === null ? currentlyInspectedPaths : currentlyInspectedPaths[key];
                  if (!current) {
                    return false;
                  }
                  for (var i3 = 0; i3 < path125.length; i3++) {
                    current = current[path125[i3]];
                    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, path125, count) {
                if (isMostRecentlyInspectedElement(id)) {
                  var value = utils_getInObject(mostRecentlyInspectedElement, path125);
                  var key = "$reactTemp".concat(count);
                  window[key] = value;
                  console.log(key);
                  console.log(value);
                }
              }
              __name(storeAsGlobal, "storeAsGlobal");
              function getSerializedElementValueByPath(id, path125) {
                if (isMostRecentlyInspectedElement(id)) {
                  var valueToCopy = utils_getInObject(mostRecentlyInspectedElement, path125);
                  return serializeToString(valueToCopy);
                }
              }
              __name(getSerializedElementValueByPath, "getSerializedElementValueByPath");
              function inspectElement(requestID, id, path125, forceFullData) {
                if (path125 !== null) {
                  mergeInspectedPaths(path125);
                }
                if (isMostRecentlyInspectedElement(id) && !forceFullData) {
                  if (!hasElementUpdatedSinceLastInspected) {
                    if (path125 !== null) {
                      var secondaryCategory = null;
                      if (path125[0] === "hooks") {
                        secondaryCategory = "hooks";
                      }
                      return {
                        id,
                        responseID: requestID,
                        type: "hydrated-path",
                        path: path125,
                        value: cleanForBridge(utils_getInObject(mostRecentlyInspectedElement, path125), createIsPathAllowed(null, secondaryCategory), path125)
                      };
                    } else {
                      return {
                        id,
                        responseID: requestID,
                        type: "no-change"
                      };
                    }
                  }
                } else {
                  currentlyInspectedPaths = {};
                }
                hasElementUpdatedSinceLastInspected = false;
                try {
                  mostRecentlyInspectedElement = inspectElementRaw(id);
                } catch (error2) {
                  if (error2.name === "ReactDebugToolsRenderError") {
                    var message = "Error rendering inspected element.";
                    var stack;
                    console.error(message + "\n\n", error2);
                    if (error2.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", error2.cause);
                      if (error2.cause instanceof Error) {
                        message = error2.cause.message || message;
                        stack = error2.cause.stack;
                      }
                    }
                    return {
                      type: "error",
                      errorType: "user",
                      id,
                      responseID: requestID,
                      message,
                      stack
                    };
                  }
                  if (error2.name === "ReactDebugToolsUnsupportedHookError") {
                    return {
                      type: "error",
                      errorType: "unknown-hook",
                      id,
                      responseID: requestID,
                      message: "Unsupported hook in the react-debug-tools package: " + error2.message
                    };
                  }
                  console.error("Error inspecting element.\n\n", error2);
                  return {
                    type: "error",
                    errorType: "uncaught",
                    id,
                    responseID: requestID,
                    message: error2.message,
                    stack: error2.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, path125) {
                var fiber = findCurrentFiberUsingSlowPathById(id);
                if (fiber !== null) {
                  var instance = fiber.stateNode;
                  switch (type) {
                    case "context":
                      path125 = path125.slice(1);
                      switch (fiber.tag) {
                        case ClassComponent:
                          if (path125.length === 0) {
                          } else {
                            deletePathInObject(instance.context, path125);
                          }
                          instance.forceUpdate();
                          break;
                        case FunctionComponent:
                          break;
                      }
                      break;
                    case "hooks":
                      if (typeof overrideHookStateDeletePath === "function") {
                        overrideHookStateDeletePath(fiber, hookID, path125);
                      }
                      break;
                    case "props":
                      if (instance === null) {
                        if (typeof overridePropsDeletePath === "function") {
                          overridePropsDeletePath(fiber, path125);
                        }
                      } else {
                        fiber.pendingProps = copyWithDelete(instance.props, path125);
                        instance.forceUpdate();
                      }
                      break;
                    case "state":
                      deletePathInObject(instance.state, path125);
                      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, path125, value) {
                var fiber = findCurrentFiberUsingSlowPathById(id);
                if (fiber !== null) {
                  var instance = fiber.stateNode;
                  switch (type) {
                    case "context":
                      path125 = path125.slice(1);
                      switch (fiber.tag) {
                        case ClassComponent:
                          if (path125.length === 0) {
                            instance.context = value;
                          } else {
                            utils_setInObject(instance.context, path125, value);
                          }
                          instance.forceUpdate();
                          break;
                        case FunctionComponent:
                          break;
                      }
                      break;
                    case "hooks":
                      if (typeof overrideHookState === "function") {
                        overrideHookState(fiber, hookID, path125, value);
                      }
                      break;
                    case "props":
                      switch (fiber.tag) {
                        case ClassComponent:
                          fiber.pendingProps = copyWithSet(instance.props, path125, value);
                          instance.forceUpdate();
                          break;
                        default:
                          if (typeof overrideProps === "function") {
                            overrideProps(fiber, path125, value);
                          }
                          break;
                      }
                      break;
                    case "state":
                      switch (fiber.tag) {
                        case ClassComponent:
                          utils_setInObject(instance.state, path125, 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 i3 = 0; i3 < durations.length; i3 += 3) {
                      var fiberID = durations[i3];
                      fiberActualDurations.push([fiberID, durations[i3 + 1]]);
                      fiberSelfDurations.push([fiberID, durations[i3 + 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(path125) {
                if (path125 === null) {
                  trackedPathMatchFiber = null;
                  trackedPathMatchDepth = -1;
                  mightBeOnTrackedPath = false;
                }
                trackedPath = path125;
              }
              __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 i3 = 0; i3 < 3; i3++) {
                  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(o3, allowArrayLike) {
              var it2;
              if (typeof Symbol === "undefined" || o3[Symbol.iterator] == null) {
                if (Array.isArray(o3) || (it2 = console_unsupportedIterableToArray(o3)) || allowArrayLike && o3 && typeof o3.length === "number") {
                  if (it2) o3 = it2;
                  var i3 = 0;
                  var F4 = /* @__PURE__ */ __name(function F5() {
                  }, "F");
                  return { s: F4, n: /* @__PURE__ */ __name(function n3() {
                    if (i3 >= o3.length) return { done: true };
                    return { done: false, value: o3[i3++] };
                  }, "n"), e: /* @__PURE__ */ __name(function e4(_e2) {
                    throw _e2;
                  }, "e"), f: F4 };
                }
                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 s5() {
                it2 = o3[Symbol.iterator]();
              }, "s"), n: /* @__PURE__ */ __name(function n3() {
                var step = it2.next();
                normalCompletion = step.done;
                return step;
              }, "n"), e: /* @__PURE__ */ __name(function e4(_e2) {
                didErr = true;
                err = _e2;
              }, "e"), f: /* @__PURE__ */ __name(function f5() {
                try {
                  if (!normalCompletion && it2.return != null) it2.return();
                } finally {
                  if (didErr) throw err;
                }
              }, "f") };
            }
            __name(console_createForOfIteratorHelper, "console_createForOfIteratorHelper");
            function console_unsupportedIterableToArray(o3, minLen) {
              if (!o3) return;
              if (typeof o3 === "string") return console_arrayLikeToArray(o3, minLen);
              var n3 = Object.prototype.toString.call(o3).slice(8, -1);
              if (n3 === "Object" && o3.constructor) n3 = o3.constructor.name;
              if (n3 === "Map" || n3 === "Set") return Array.from(o3);
              if (n3 === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n3)) return console_arrayLikeToArray(o3, minLen);
            }
            __name(console_unsupportedIterableToArray, "console_unsupportedIterableToArray");
            function console_arrayLikeToArray(arr, len) {
              if (len == null || len > arr.length) len = arr.length;
              for (var i3 = 0, arr2 = new Array(len); i3 < len; i3++) {
                arr2[i3] = arr[i3];
              }
              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 (error2) {
            }
            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 (error2) {
                    }
                  }
                }, "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 (error2) {
                              setTimeout(function() {
                                throw error2;
                              }, 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 (error2) {
                  }
                });
              } 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 (error2) {
                    }
                  }
                }, "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 (error2) {
                  }
                });
              }
            }
            __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(o3, minLen) {
              if (!o3) return;
              if (typeof o3 === "string") return bridge_arrayLikeToArray(o3, minLen);
              var n3 = Object.prototype.toString.call(o3).slice(8, -1);
              if (n3 === "Object" && o3.constructor) n3 = o3.constructor.name;
              if (n3 === "Map" || n3 === "Set") return Array.from(o3);
              if (n3 === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n3)) return bridge_arrayLikeToArray(o3, 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 i3 = 0, arr2 = new Array(len); i3 < len; i3++) {
                arr2[i3] = arr[i3];
              }
              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 i3 = 0; i3 < props.length; i3++) {
                var descriptor2 = props[i3];
                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(o3, p2) {
              _setPrototypeOf = Object.setPrototypeOf || /* @__PURE__ */ __name(function _setPrototypeOf2(o4, p3) {
                o4.__proto__ = p3;
                return o4;
              }, "_setPrototypeOf");
              return _setPrototypeOf(o3, p2);
            }
            __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 (e4) {
                return false;
              }
            }
            __name(_isNativeReflectConstruct, "_isNativeReflectConstruct");
            function _getPrototypeOf(o3) {
              _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : /* @__PURE__ */ __name(function _getPrototypeOf2(o4) {
                return o4.__proto__ || Object.getPrototypeOf(o4);
              }, "_getPrototypeOf");
              return _getPrototypeOf(o3);
            }
            __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 i3 = 0; i3 < _this._messageQueue.length; i3 += 2) {
                      var _this$_wall;
                      (_this$_wall = _this._wall).send.apply(_this$_wall, [_this._messageQueue[i3]].concat(bridge_toConsumableArray(_this._messageQueue[i3 + 1])));
                    }
                    _this._messageQueue.length = 0;
                    _this._timeoutID = setTimeout(_this._flush, BATCH_DURATION);
                  }
                });
                bridge_defineProperty(_assertThisInitialized(_this), "overrideValueAtPath", function(_ref) {
                  var id = _ref.id, path125 = _ref.path, rendererID = _ref.rendererID, type = _ref.type, value = _ref.value;
                  switch (type) {
                    case "context":
                      _this.send("overrideContext", {
                        id,
                        path: path125,
                        rendererID,
                        wasForwarded: true,
                        value
                      });
                      break;
                    case "hooks":
                      _this.send("overrideHookState", {
                        id,
                        path: path125,
                        rendererID,
                        wasForwarded: true,
                        value
                      });
                      break;
                    case "props":
                      _this.send("overrideProps", {
                        id,
                        path: path125,
                        rendererID,
                        wasForwarded: true,
                        value
                      });
                      break;
                    case "state":
                      _this.send("overrideState", {
                        id,
                        path: path125,
                        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 get4() {
                  return this._wall;
                }, "get")
              }]);
              return Bridge2;
            }(EventEmitter11);
            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 i3 = 0; i3 < props.length; i3++) {
                var descriptor2 = props[i3];
                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(o3, p2) {
              agent_setPrototypeOf = Object.setPrototypeOf || /* @__PURE__ */ __name(function _setPrototypeOf2(o4, p3) {
                o4.__proto__ = p3;
                return o4;
              }, "_setPrototypeOf");
              return agent_setPrototypeOf(o3, p2);
            }
            __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 (e4) {
                return false;
              }
            }
            __name(agent_isNativeReflectConstruct, "agent_isNativeReflectConstruct");
            function agent_getPrototypeOf(o3) {
              agent_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : /* @__PURE__ */ __name(function _getPrototypeOf2(o4) {
                return o4.__proto__ || Object.getPrototypeOf(o4);
              }, "_getPrototypeOf");
              return agent_getPrototypeOf(o3);
            }
            __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 debug3 = /* @__PURE__ */ __name(function debug4(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 Agent4 = /* @__PURE__ */ function(_EventEmitter) {
              agent_inherits(Agent5, _EventEmitter);
              var _super = agent_createSuper(Agent5);
              function Agent5(bridge) {
                var _this;
                agent_classCallCheck(this, Agent5);
                _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, path125 = _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, path125);
                    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, path125 = _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, path125);
                  }
                });
                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, path125 = _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, path125, 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, path125 = _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, path125, value);
                  }
                });
                agent_defineProperty(agent_assertThisInitialized(_this), "overrideContext", function(_ref13) {
                  var id = _ref13.id, path125 = _ref13.path, rendererID = _ref13.rendererID, wasForwarded = _ref13.wasForwarded, value = _ref13.value;
                  if (!wasForwarded) {
                    _this.overrideValueAtPath({
                      id,
                      path: path125,
                      rendererID,
                      type: "context",
                      value
                    });
                  }
                });
                agent_defineProperty(agent_assertThisInitialized(_this), "overrideHookState", function(_ref14) {
                  var id = _ref14.id, hookID = _ref14.hookID, path125 = _ref14.path, rendererID = _ref14.rendererID, wasForwarded = _ref14.wasForwarded, value = _ref14.value;
                  if (!wasForwarded) {
                    _this.overrideValueAtPath({
                      id,
                      path: path125,
                      rendererID,
                      type: "hooks",
                      value
                    });
                  }
                });
                agent_defineProperty(agent_assertThisInitialized(_this), "overrideProps", function(_ref15) {
                  var id = _ref15.id, path125 = _ref15.path, rendererID = _ref15.rendererID, wasForwarded = _ref15.wasForwarded, value = _ref15.value;
                  if (!wasForwarded) {
                    _this.overrideValueAtPath({
                      id,
                      path: path125,
                      rendererID,
                      type: "props",
                      value
                    });
                  }
                });
                agent_defineProperty(agent_assertThisInitialized(_this), "overrideState", function(_ref16) {
                  var id = _ref16.id, path125 = _ref16.path, rendererID = _ref16.rendererID, wasForwarded = _ref16.wasForwarded, value = _ref16.value;
                  if (!wasForwarded) {
                    _this.overrideValueAtPath({
                      id,
                      path: path125,
                      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, path125 = _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, path125, 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, path125 = _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, path125);
                  }
                });
                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__) {
                    debug3("onFastRefreshScheduled");
                  }
                  _this._bridge.send("fastRefreshScheduled");
                });
                agent_defineProperty(agent_assertThisInitialized(_this), "onHookOperations", function(operations) {
                  if (__DEBUG__) {
                    debug3("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 path125 = renderer2 != null ? renderer2.getPathForElement(id) : null;
                  if (path125 !== null) {
                    sessionStorageSetItem(SESSION_STORAGE_LAST_SELECTION_KEY, JSON.stringify({
                      rendererID,
                      path: path125
                    }));
                  } 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 (error2) {
                }
                bridge.send("isBackendStorageAPISupported", isBackendStorageAPISupported);
                bridge.send("isSynchronousXHRSupported", isSynchronousXHRSupported());
                setupHighlighter(bridge, agent_assertThisInitialized(_this));
                TraceUpdates_initialize(agent_assertThisInitialized(_this));
                return _this;
              }
              __name(Agent5, "Agent");
              agent_createClass(Agent5, [{
                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 (error2) {
                    }
                  }
                  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 get4() {
                  return this._rendererInterfaces;
                }, "get")
              }]);
              return Agent5;
            }(EventEmitter11);
            ;
            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(o3, minLen) {
              if (!o3) return;
              if (typeof o3 === "string") return hook_arrayLikeToArray(o3, minLen);
              var n3 = Object.prototype.toString.call(o3).slice(8, -1);
              if (n3 === "Object" && o3.constructor) n3 = o3.constructor.name;
              if (n3 === "Map" || n3 === "Set") return Array.from(o3);
              if (n3 === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n3)) return hook_arrayLikeToArray(o3, 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 i3 = 0, arr2 = new Array(len); i3 < len; i3++) {
                arr2[i3] = arr[i3];
              }
              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, i3) {
                    if (i3 > 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 (error2) {
                    }
                  }
                }, "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 (error2) {
                  }
                });
              }
              __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(error2) {
                var frames = error2.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(error2) {
                var startStackFrame = getTopStackFrameString(error2);
                if (startStackFrame !== null) {
                  openModuleRangesStack.push(startStackFrame);
                }
              }
              __name(registerInternalModuleStart, "registerInternalModuleStart");
              function registerInternalModuleStop(error2) {
                if (openModuleRangesStack.length > 0) {
                  var startStackFrame = openModuleRangesStack.pop();
                  var stopStackFrame = getTopStackFrameString(error2);
                  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 get4() {
                  return hook2;
                }, "get")
              });
              return hook2;
            }
            __name(installHook, "installHook");
            ;
            function decorate(object3, attr, fn) {
              var old = object3[attr];
              object3[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(object3, enumerableOnly) {
              var keys = Object.keys(object3);
              if (Object.getOwnPropertySymbols) {
                var symbols = Object.getOwnPropertySymbols(object3);
                if (enumerableOnly) symbols = symbols.filter(function(sym) {
                  return Object.getOwnPropertyDescriptor(object3, sym).enumerable;
                });
                keys.push.apply(keys, symbols);
              }
              return keys;
            }
            __name(legacy_renderer_ownKeys, "legacy_renderer_ownKeys");
            function legacy_renderer_objectSpread(target) {
              for (var i3 = 1; i3 < arguments.length; i3++) {
                var source2 = arguments[i3] != null ? arguments[i3] : {};
                if (i3 % 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(a2, b2) {
                if (a2.length !== b2.length) {
                  return false;
                }
                for (var i3 = 0; i3 < a2.length; i3++) {
                  if (a2[i3] !== b2[i3]) {
                    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 i3 = 0; i3 < nextChildIDs.length; i3++) {
                  pushOperation(nextChildIDs[i3]);
                }
              }
              __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 i3 = 0;
                operations[i3++] = rendererID;
                operations[i3++] = rootID;
                operations[i3++] = pendingStringTableLength;
                pendingStringTable.forEach(function(value, key) {
                  operations[i3++] = key.length;
                  var encodedKey = utfEncodeString(key);
                  for (var j3 = 0; j3 < encodedKey.length; j3++) {
                    operations[i3 + j3] = encodedKey[j3];
                  }
                  i3 += key.length;
                });
                if (numUnmountIDs > 0) {
                  operations[i3++] = TREE_OPERATION_REMOVE;
                  operations[i3++] = numUnmountIDs;
                  for (var j2 = 0; j2 < pendingUnmountedIDs.length; j2++) {
                    operations[i3++] = pendingUnmountedIDs[j2];
                  }
                  if (pendingUnmountedRootID !== null) {
                    operations[i3] = pendingUnmountedRootID;
                    i3++;
                  }
                }
                for (var _j = 0; _j < pendingOperations.length; _j++) {
                  operations[i3 + _j] = pendingOperations[_j];
                }
                i3 += 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(path125) {
                var current = currentlyInspectedPaths;
                path125.forEach(function(key) {
                  if (!current[key]) {
                    current[key] = {};
                  }
                  current = current[key];
                });
              }
              __name(mergeInspectedPaths, "mergeInspectedPaths");
              function createIsPathAllowed(key) {
                return /* @__PURE__ */ __name(function isPathAllowed(path125) {
                  var current = currentlyInspectedPaths[key];
                  if (!current) {
                    return false;
                  }
                  for (var i3 = 0; i3 < path125.length; i3++) {
                    current = current[path125[i3]];
                    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, path125, count) {
                var inspectedElement = inspectElementRaw(id);
                if (inspectedElement !== null) {
                  var value = utils_getInObject(inspectedElement, path125);
                  var key = "$reactTemp".concat(count);
                  window[key] = value;
                  console.log(key);
                  console.log(value);
                }
              }
              __name(storeAsGlobal, "storeAsGlobal");
              function getSerializedElementValueByPath(id, path125) {
                var inspectedElement = inspectElementRaw(id);
                if (inspectedElement !== null) {
                  var valueToCopy = utils_getInObject(inspectedElement, path125);
                  return serializeToString(valueToCopy);
                }
              }
              __name(getSerializedElementValueByPath, "getSerializedElementValueByPath");
              function inspectElement(requestID, id, path125, forceFullData) {
                if (forceFullData || currentlyInspectedElementID !== id) {
                  currentlyInspectedElementID = id;
                  currentlyInspectedPaths = {};
                }
                var inspectedElement = inspectElementRaw(id);
                if (inspectedElement === null) {
                  return {
                    id,
                    responseID: requestID,
                    type: "not-found"
                  };
                }
                if (path125 !== null) {
                  mergeInspectedPaths(path125);
                }
                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, path125) {
                var inspectedElement = inspectElementRaw(id);
                if (inspectedElement !== null) {
                  window.$attribute = utils_getInObject(inspectedElement, path125);
                }
              }
              __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, path125) {
                var internalInstance = idToInternalInstanceMap.get(id);
                if (internalInstance != null) {
                  var publicInstance = internalInstance._instance;
                  if (publicInstance != null) {
                    switch (type) {
                      case "context":
                        deletePathInObject(publicInstance.context, path125);
                        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, path125)
                        });
                        forceUpdate(publicInstance);
                        break;
                      case "state":
                        deletePathInObject(publicInstance.state, path125);
                        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, path125, value) {
                var internalInstance = idToInternalInstanceMap.get(id);
                if (internalInstance != null) {
                  var publicInstance = internalInstance._instance;
                  if (publicInstance != null) {
                    switch (type) {
                      case "context":
                        utils_setInObject(publicInstance.context, path125, 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, path125, value)
                        });
                        forceUpdate(publicInstance);
                        break;
                      case "state":
                        utils_setInObject(publicInstance.state, path125, 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(path125) {
              }
              __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(x3, y2, width, height, left3, top2) {
                if (typeof x3 !== "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: x3,
                    y: y2,
                    width,
                    height,
                    left: left3,
                    top: top2,
                    margin,
                    padding
                  },
                  style: resolvedStyle || null
                });
              });
            }
            __name(measureStyle, "measureStyle");
            function shallowClone(object3) {
              var cloned = {};
              for (var n3 in object3) {
                cloned[n3] = object3[n3];
              }
              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 (e4) {
                  console.error(e4);
                }
              }
              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 Agent4(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 get4() {
                        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 get4() {
                        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 (e4) {
                  console.error("[React DevTools] Failed to parse JSON: " + event.data);
                  return;
                }
                messageListeners.forEach(function(fn) {
                  try {
                    fn(data);
                  } catch (error2) {
                    console.log("[React DevTools] Error calling listener", data);
                    console.log("error:", error2);
                    throw error2;
                  }
                });
              }
              __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 process50 = globalThis.process;
    var processOk = /* @__PURE__ */ __name(function(process51) {
      return process51 && typeof process51 === "object" && typeof process51.removeListener === "function" && typeof process51.emit === "function" && typeof process51.reallyExit === "function" && typeof process51.listeners === "function" && typeof process51.kill === "function" && typeof process51.pid === "number" && typeof process51.on === "function";
    }, "processOk");
    if (!processOk(process50)) {
      module2.exports = function() {
        return function() {
        };
      };
    } else {
      assert4 = __require("assert");
      signals = require_signals2();
      isWin = /^win/i.test(process50.platform);
      EE3 = __require("events");
      if (typeof EE3 !== "function") {
        EE3 = EE3.EventEmitter;
      }
      if (process50.__signal_exit_emitter__) {
        emitter = process50.__signal_exit_emitter__;
      } else {
        emitter = process50.__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() {
          };
        }
        assert4.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 {
            process50.removeListener(sig, sigListeners[sig]);
          } catch (er2) {
          }
        });
        process50.emit = originalProcessEmit;
        process50.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 = process50.listeners(sig);
          if (listeners.length === emitter.count) {
            unload();
            emit("exit", null, sig);
            emit("afterexit", null, sig);
            if (isWin && sig === "SIGHUP") {
              sig = "SIGINT";
            }
            process50.kill(process50.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 {
            process50.on(sig, sigListeners[sig]);
            return true;
          } catch (er2) {
            return false;
          }
        });
        process50.emit = processEmit;
        process50.reallyExit = processReallyExit;
      }, "load");
      module2.exports.load = load;
      originalProcessReallyExit = process50.reallyExit;
      processReallyExit = /* @__PURE__ */ __name(function processReallyExit2(code2) {
        if (!processOk(globalThis.process)) {
          return;
        }
        process50.exitCode = code2 || /* istanbul ignore next */
        0;
        emit("exit", process50.exitCode, null);
        emit("afterexit", process50.exitCode, null);
        originalProcessReallyExit.call(process50, process50.exitCode);
      }, "processReallyExit");
      originalProcessEmit = process50.emit;
      processEmit = /* @__PURE__ */ __name(function processEmit2(ev, arg) {
        if (ev === "exit" && processOk(globalThis.process)) {
          if (arg !== void 0) {
            process50.exitCode = arg;
          }
          var ret = originalProcessEmit.apply(this, arguments);
          emit("exit", process50.exitCode, null);
          emit("afterexit", process50.exitCode, null);
          return ret;
        } else {
          return originalProcessEmit.apply(this, arguments);
        }
      }, "processEmit");
    }
    var assert4;
    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 = (string4) => {
      if (typeof string4 !== "string") {
        throw new TypeError("Expected a string");
      }
      return string4.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((n3) => new RegExp(`(?:\\((?:node:)?${n3}(?:\\.js)?:\\d+:\\d+\\)$|^\\s*at (?:node:)?${n3}(?:\\.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((st2) => {
          st2 = st2.replace(/\\/g, "/");
          if (this._internals.some((internal) => internal.test(st2))) {
            return;
          }
          const isAtLine = /^\s*at /.test(st2);
          if (outdent) {
            st2 = st2.trimEnd().replace(/^(\s+)at /, "$1");
          } else {
            st2 = st2.trim();
            if (isAtLine) {
              st2 = st2.slice(3);
            }
          }
          st2 = st2.replace(`${this._cwd}/`, "");
          if (st2) {
            if (isAtLine) {
              if (lastNonAtLine) {
                result.push(lastNonAtLine);
                lastNonAtLine = null;
              }
              result.push(st2);
            } else {
              outdent = true;
              lastNonAtLine = st2;
            }
          }
        });
        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 (_2) {
        }
        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(re3);
        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 i3 = file.length - 1; i3 > 0; i3--) {
            if (file.charAt(i3) === ")") {
              closes++;
            } else if (file.charAt(i3) === "(" && file.charAt(i3 - 1) === " ") {
              closes--;
              if (closes === -1 && file.charAt(i3 - 1) === " ") {
                const before = file.slice(0, i3 - 1);
                const after = file.slice(i3 + 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 re3 = new RegExp(
      "^(?:\\s*at )?(?:(new) )?(?:(.*?) \\()?(?:eval at ([^ ]+) \\((.+?):(\\d+):(\\d+)\\), )?(?:(.+?):(\\d+):(\\d+)|(native))(\\)?)$"
    );
    var methodRe = /^(.*?) \[as (.*?)\]$/;
    module2.exports = StackUtils2;
  }
});

// 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((string4, start, end) => string4.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 strip2 = options2.whitespace === false ? stripWithoutWhitespace : stripWithWhitespace;
      let insideString = false;
      let insideComment = false;
      let offset = 0;
      let result = "";
      for (let i3 = 0; i3 < jsonString.length; i3++) {
        const currentCharacter = jsonString[i3];
        const nextCharacter = jsonString[i3 + 1];
        if (!insideComment && currentCharacter === '"') {
          const escaped = isEscaped(jsonString, i3);
          if (!escaped) {
            insideString = !insideString;
          }
        }
        if (insideString) {
          continue;
        }
        if (!insideComment && currentCharacter + nextCharacter === "//") {
          result += jsonString.slice(offset, i3);
          offset = i3;
          insideComment = singleComment;
          i3++;
        } else if (insideComment === singleComment && currentCharacter + nextCharacter === "\r\n") {
          i3++;
          insideComment = false;
          result += strip2(jsonString, offset, i3);
          offset = i3;
          continue;
        } else if (insideComment === singleComment && currentCharacter === "\n") {
          insideComment = false;
          result += strip2(jsonString, offset, i3);
          offset = i3;
        } else if (!insideComment && currentCharacter + nextCharacter === "/*") {
          result += jsonString.slice(offset, i3);
          offset = i3;
          insideComment = multiComment;
          i3++;
          continue;
        } else if (insideComment === multiComment && currentCharacter + nextCharacter === "*/") {
          i3++;
          insideComment = false;
          result += strip2(jsonString, offset, i3 + 1);
          offset = i3 + 1;
          continue;
        }
      }
      return result + (insideComment ? strip2(jsonString.slice(offset)) : jsonString.slice(offset));
    };
  }
});

// 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 parse14(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(parse14, "parse");
            exports3.parse = parse14;
            function parseModule(code2, options2, delegate) {
              var parsingOptions = options2 || {};
              parsingOptions.sourceType = "module";
              return parse14(code2, parsingOptions, delegate);
            }
            __name(parseModule, "parseModule");
            exports3.parseModule = parseModule;
            function parseScript(code2, options2, delegate) {
              var parsingOptions = options2 || {};
              parsingOptions.sourceType = "script";
              return parse14(code2, parsingOptions, delegate);
            }
            __name(parseScript, "parseScript");
            exports3.parseScript = parseScript;
            function tokenize5(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 (e4) {
                tokenizer.errorHandler.tolerate(e4);
              }
              if (tokenizer.errorHandler.tolerant) {
                tokens.errors = tokenizer.errors();
              }
              return tokens;
            }
            __name(tokenize5, "tokenize");
            exports3.tokenize = tokenize5;
            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 i3 = this.leading.length - 1; i3 >= 0; --i3) {
                    var entry = this.leading[i3];
                    if (metadata.end.offset >= entry.start) {
                      innerComments.unshift(entry.comment);
                      this.leading.splice(i3, 1);
                      this.trailing.splice(i3, 1);
                    }
                  }
                  if (innerComments.length) {
                    node.innerComments = innerComments;
                  }
                }
              };
              CommentHandler2.prototype.findTrailingComments = function(metadata) {
                var trailingComments = [];
                if (this.trailing.length > 0) {
                  for (var i3 = this.trailing.length - 1; i3 >= 0; --i3) {
                    var entry_1 = this.trailing[i3];
                    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 i3 = count - 1; i3 >= 0; --i3) {
                    var comment = target.leadingComments[i3];
                    if (comment.range[1] <= metadata.start.offset) {
                      leadingComments.unshift(comment);
                      target.leadingComments.splice(i3, 1);
                    }
                  }
                  if (target.leadingComments && target.leadingComments.length === 0) {
                    delete target.leadingComments;
                  }
                  return leadingComments;
                }
                for (var i3 = this.leading.length - 1; i3 >= 0; --i3) {
                  var entry = this.leading[i3];
                  if (entry.start <= metadata.start.offset) {
                    leadingComments.unshift(entry.comment);
                    this.leading.splice(i3, 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(d2, b2) {
                d2.__proto__ = b2;
              } || function(d2, b2) {
                for (var p2 in b2) if (b2.hasOwnProperty(p2)) d2[p2] = b2[p2];
              };
              return function(d2, b2) {
                extendStatics(d2, b2);
                function __() {
                  this.constructor = d2;
                }
                __name(__, "__");
                d2.prototype = b2 === null ? Object.create(b2) : (__.prototype = b2.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 Node5 = __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 cp3 = this.scanner.source.charCodeAt(this.scanner.index);
                if (cp3 === 60 || cp3 === 62 || cp3 === 47 || cp3 === 58 || cp3 === 61 || cp3 === 123 || cp3 === 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 (cp3 === 34 || cp3 === 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 (cp3 === 46) {
                  var n1 = this.scanner.source.charCodeAt(this.scanner.index + 1);
                  var n22 = this.scanner.source.charCodeAt(this.scanner.index + 2);
                  var value = n1 === 46 && n22 === 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 (cp3 === 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(cp3) && cp3 !== 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 object3 = elementName;
                    this.expectJSX(".");
                    var property = this.parseJSXIdentifier();
                    elementName = this.finalize(node, new JSXNode.JSXMemberExpression(object3, 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 Node5.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(cp3) {
                return cp3 < 65536 ? String.fromCharCode(cp3) : String.fromCharCode(55296 + (cp3 - 65536 >> 10)) + String.fromCharCode(56320 + (cp3 - 65536 & 1023));
              }, "fromCodePoint"),
              // https://tc39.github.io/ecma262/#sec-white-space
              isWhiteSpace: /* @__PURE__ */ __name(function(cp3) {
                return cp3 === 32 || cp3 === 9 || cp3 === 11 || cp3 === 12 || cp3 === 160 || cp3 >= 5760 && [5760, 8192, 8193, 8194, 8195, 8196, 8197, 8198, 8199, 8200, 8201, 8202, 8239, 8287, 12288, 65279].indexOf(cp3) >= 0;
              }, "isWhiteSpace"),
              // https://tc39.github.io/ecma262/#sec-line-terminators
              isLineTerminator: /* @__PURE__ */ __name(function(cp3) {
                return cp3 === 10 || cp3 === 13 || cp3 === 8232 || cp3 === 8233;
              }, "isLineTerminator"),
              // https://tc39.github.io/ecma262/#sec-names-and-keywords
              isIdentifierStart: /* @__PURE__ */ __name(function(cp3) {
                return cp3 === 36 || cp3 === 95 || cp3 >= 65 && cp3 <= 90 || cp3 >= 97 && cp3 <= 122 || cp3 === 92 || cp3 >= 128 && Regex.NonAsciiIdentifierStart.test(exports3.Character.fromCodePoint(cp3));
              }, "isIdentifierStart"),
              isIdentifierPart: /* @__PURE__ */ __name(function(cp3) {
                return cp3 === 36 || cp3 === 95 || cp3 >= 65 && cp3 <= 90 || cp3 >= 97 && cp3 <= 122 || cp3 >= 48 && cp3 <= 57 || cp3 === 92 || cp3 >= 128 && Regex.NonAsciiIdentifierPart.test(exports3.Character.fromCodePoint(cp3));
              }, "isIdentifierPart"),
              // https://tc39.github.io/ecma262/#sec-literals-numeric-literals
              isDecimalDigit: /* @__PURE__ */ __name(function(cp3) {
                return cp3 >= 48 && cp3 <= 57;
              }, "isDecimalDigit"),
              isHexDigit: /* @__PURE__ */ __name(function(cp3) {
                return cp3 >= 48 && cp3 <= 57 || cp3 >= 65 && cp3 <= 70 || cp3 >= 97 && cp3 <= 102;
              }, "isHexDigit"),
              isOctalDigit: /* @__PURE__ */ __name(function(cp3) {
                return cp3 >= 48 && cp3 <= 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(object3, property) {
                this.type = jsx_syntax_1.JSXSyntax.JSXMemberExpression;
                this.object = object3;
                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(object3, property) {
                this.type = syntax_1.Syntax.MemberExpression;
                this.computed = true;
                this.object = object3;
                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, kind2, isStatic) {
                this.type = syntax_1.Syntax.MethodDefinition;
                this.key = key;
                this.computed = computed;
                this.value = value;
                this.kind = kind2;
                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(kind2, key, computed, value, method, shorthand) {
                this.type = syntax_1.Syntax.Property;
                this.key = key;
                this.computed = computed;
                this.value = value;
                this.kind = kind2;
                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(object3, property) {
                this.type = syntax_1.Syntax.MemberExpression;
                this.computed = false;
                this.object = object3;
                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, kind2) {
                this.type = syntax_1.Syntax.VariableDeclaration;
                this.declarations = declarations;
                this.kind = kind2;
              }
              __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(object3, body) {
                this.type = syntax_1.Syntax.WithStatement;
                this.object = object3;
                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 Node5 = __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 i3 = 0; i3 < comments.length; ++i3) {
                      var e4 = comments[i3];
                      var node = void 0;
                      node = {
                        type: e4.multiLine ? "BlockComment" : "LineComment",
                        value: this.scanner.source.slice(e4.slice[0], e4.slice[1])
                      };
                      if (this.config.range) {
                        node.range = e4.range;
                      }
                      if (this.config.loc) {
                        node.loc = e4.loc;
                      }
                      var metadata = {
                        start: {
                          line: e4.loc.start.line,
                          column: e4.loc.start.column,
                          offset: e4.range[0]
                        },
                        end: {
                          line: e4.loc.end.line,
                          column: e4.loc.end.column,
                          offset: e4.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 t5 = {
                  type: token_1.TokenName[token2.type],
                  value: this.getTokenRaw(token2)
                };
                if (this.config.range) {
                  t5.range = [token2.start, token2.end];
                }
                if (this.config.loc) {
                  t5.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;
                  t5.regex = { pattern, flags };
                }
                return t5;
              };
              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 Node5.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 Node5.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 Node5.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 Node5.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 Node5.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 Node5.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 Node5.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 Node5.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 Node5.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 Node5.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 Node5.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 Node5.Literal(token2.value, raw2));
                    break;
                  case 3:
                  case 1:
                  case 5:
                  case 4:
                    key = this.finalize(node, new Node5.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 kind2;
                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 Node5.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) {
                  kind2 = "get";
                  computed = this.match("[");
                  key = this.parseObjectPropertyKey();
                  this.context.allowYield = false;
                  value = this.parseGetterMethod();
                } else if (token2.type === 3 && !isAsync2 && token2.value === "set" && lookaheadPropertyKey) {
                  kind2 = "set";
                  computed = this.match("[");
                  key = this.parseObjectPropertyKey();
                  value = this.parseSetterMethod();
                } else if (token2.type === 7 && token2.value === "*" && lookaheadPropertyKey) {
                  kind2 = "init";
                  computed = this.match("[");
                  key = this.parseObjectPropertyKey();
                  value = this.parseGeneratorMethod();
                  method = true;
                } else {
                  if (!key) {
                    this.throwUnexpectedToken(this.lookahead);
                  }
                  kind2 = "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 Node5.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 Node5.AssignmentPattern(id, init));
                    } else {
                      shorthand = true;
                      value = id;
                    }
                  } else {
                    this.throwUnexpectedToken(this.nextToken());
                  }
                }
                return this.finalize(node, new Node5.Property(kind2, 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 Node5.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 Node5.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 Node5.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 Node5.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 i3 = 0; i3 < expr.elements.length; i3++) {
                      if (expr.elements[i3] !== null) {
                        this.reinterpretExpressionAsPattern(expr.elements[i3]);
                      }
                    }
                    break;
                  case syntax_1.Syntax.ObjectExpression:
                    expr.type = syntax_1.Syntax.ObjectPattern;
                    for (var i3 = 0; i3 < expr.properties.length; i3++) {
                      this.reinterpretExpressionAsPattern(expr.properties[i3].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 i3 = 0; i3 < expressions.length; i3++) {
                            this.reinterpretExpressionAsPattern(expressions[i3]);
                          }
                          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 i3 = 0; i3 < expressions.length; i3++) {
                            this.reinterpretExpressionAsPattern(expressions[i3]);
                          }
                          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 Node5.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 i3 = 0; i3 < expr.expressions.length; i3++) {
                              this.reinterpretExpressionAsPattern(expr.expressions[i3]);
                            }
                          } 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 Node5.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 Node5.MetaProperty(id, property);
                  } else {
                    this.throwUnexpectedToken(this.lookahead);
                  }
                } else {
                  var callee = this.isolateCoverGrammar(this.parseLeftHandSideExpression);
                  var args = this.match("(") ? this.parseArguments() : [];
                  expr = new Node5.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 Node5.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 Node5.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 Node5.CallExpression(expr, args));
                    if (asyncArrow && this.match("=>")) {
                      for (var i3 = 0; i3 < args.length; ++i3) {
                        this.reinterpretExpressionAsPattern(args[i3]);
                      }
                      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 Node5.ComputedMemberExpression(expr, property));
                  } else if (this.lookahead.type === 10 && this.lookahead.head) {
                    var quasi = this.parseTemplateLiteral();
                    expr = this.finalize(this.startNode(startToken), new Node5.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 Node5.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 Node5.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 Node5.StaticMemberExpression(expr, property));
                  } else if (this.lookahead.type === 10 && this.lookahead.head) {
                    var quasi = this.parseTemplateLiteral();
                    expr = this.finalize(node, new Node5.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 Node5.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 Node5.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 Node5.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 Node5.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 Node5.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 Node5.BinaryExpression(operator2, left3, right3)));
                    }
                    stack.push(this.nextToken().value);
                    precedences.push(prec);
                    markers.push(this.lookahead);
                    stack.push(this.isolateCoverGrammar(this.parseExponentiationExpression));
                  }
                  var i3 = stack.length - 1;
                  expr = stack[i3];
                  var lastMarker = markers.pop();
                  while (i3 > 1) {
                    var marker = markers.pop();
                    var lastLineStart = lastMarker && lastMarker.lineStart;
                    var node = this.startNode(marker, lastLineStart);
                    var operator2 = stack[i3 - 1];
                    expr = this.finalize(node, new Node5.BinaryExpression(operator2, stack[i3 - 2], expr));
                    i3 -= 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 Node5.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 i3 = 0; i3 < param.elements.length; i3++) {
                      if (param.elements[i3] !== null) {
                        this.checkPatternParam(options2, param.elements[i3]);
                      }
                    }
                    break;
                  case syntax_1.Syntax.ObjectPattern:
                    for (var i3 = 0; i3 < param.properties.length; i3++) {
                      this.checkPatternParam(options2, param.properties[i3].value);
                    }
                    break;
                  default:
                    break;
                }
                options2.simple = options2.simple && param instanceof Node5.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 i3 = 0; i3 < params.length; ++i3) {
                  var param = params[i3];
                  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[i3] = param;
                }
                if (this.context.strict || !this.context.allowYield) {
                  for (var i3 = 0; i3 < params.length; ++i3) {
                    var param = params[i3];
                    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 Node5.AsyncArrowFunctionExpression(list3.params, body, expression)) : this.finalize(node, new Node5.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 Node5.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 Node5.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 Node5.BlockStatement(block2));
              };
              Parser5.prototype.parseLexicalBinding = function(kind2, options2) {
                var node = this.createNode();
                var params = [];
                var id = this.parsePattern(params, kind2);
                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 (kind2 === "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 Node5.VariableDeclarator(id, init));
              };
              Parser5.prototype.parseBindingList = function(kind2, options2) {
                var list3 = [this.parseLexicalBinding(kind2, options2)];
                while (this.match(",")) {
                  this.nextToken();
                  list3.push(this.parseLexicalBinding(kind2, 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 kind2 = this.nextToken().value;
                assert_1.assert(kind2 === "let" || kind2 === "const", "Lexical declaration must be either let or const");
                var declarations = this.parseBindingList(kind2, options2);
                this.consumeSemicolon();
                return this.finalize(node, new Node5.VariableDeclaration(declarations, kind2));
              };
              Parser5.prototype.parseBindingRestElement = function(params, kind2) {
                var node = this.createNode();
                this.expect("...");
                var arg = this.parsePattern(params, kind2);
                return this.finalize(node, new Node5.RestElement(arg));
              };
              Parser5.prototype.parseArrayPattern = function(params, kind2) {
                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, kind2));
                      break;
                    } else {
                      elements.push(this.parsePatternWithDefault(params, kind2));
                    }
                    if (!this.match("]")) {
                      this.expect(",");
                    }
                  }
                }
                this.expect("]");
                return this.finalize(node, new Node5.ArrayPattern(elements));
              };
              Parser5.prototype.parsePropertyPattern = function(params, kind2) {
                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 Node5.Identifier(keyToken.value));
                  if (this.match("=")) {
                    params.push(keyToken);
                    shorthand = true;
                    this.nextToken();
                    var expr = this.parseAssignmentExpression();
                    value = this.finalize(this.startNode(keyToken), new Node5.AssignmentPattern(init, expr));
                  } else if (!this.match(":")) {
                    params.push(keyToken);
                    shorthand = true;
                    value = init;
                  } else {
                    this.expect(":");
                    value = this.parsePatternWithDefault(params, kind2);
                  }
                } else {
                  computed = this.match("[");
                  key = this.parseObjectPropertyKey();
                  this.expect(":");
                  value = this.parsePatternWithDefault(params, kind2);
                }
                return this.finalize(node, new Node5.Property("init", key, computed, value, method, shorthand));
              };
              Parser5.prototype.parseObjectPattern = function(params, kind2) {
                var node = this.createNode();
                var properties = [];
                this.expect("{");
                while (!this.match("}")) {
                  properties.push(this.parsePropertyPattern(params, kind2));
                  if (!this.match("}")) {
                    this.expect(",");
                  }
                }
                this.expect("}");
                return this.finalize(node, new Node5.ObjectPattern(properties));
              };
              Parser5.prototype.parsePattern = function(params, kind2) {
                var pattern;
                if (this.match("[")) {
                  pattern = this.parseArrayPattern(params, kind2);
                } else if (this.match("{")) {
                  pattern = this.parseObjectPattern(params, kind2);
                } else {
                  if (this.matchKeyword("let") && (kind2 === "const" || kind2 === "let")) {
                    this.tolerateUnexpectedToken(this.lookahead, messages_1.Messages.LetInLexicalBinding);
                  }
                  params.push(this.lookahead);
                  pattern = this.parseVariableIdentifier(kind2);
                }
                return pattern;
              };
              Parser5.prototype.parsePatternWithDefault = function(params, kind2) {
                var startToken = this.lookahead;
                var pattern = this.parsePattern(params, kind2);
                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 Node5.AssignmentPattern(pattern, right3));
                }
                return pattern;
              };
              Parser5.prototype.parseVariableIdentifier = function(kind2) {
                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" || kind2 !== "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 Node5.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 Node5.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 Node5.VariableDeclaration(declarations, "var"));
              };
              Parser5.prototype.parseEmptyStatement = function() {
                var node = this.createNode();
                this.expect(";");
                return this.finalize(node, new Node5.EmptyStatement());
              };
              Parser5.prototype.parseExpressionStatement = function() {
                var node = this.createNode();
                var expr = this.parseExpression();
                this.consumeSemicolon();
                return this.finalize(node, new Node5.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 Node5.EmptyStatement());
                } else {
                  this.expect(")");
                  consequent = this.parseIfClause();
                  if (this.matchKeyword("else")) {
                    this.nextToken();
                    alternate = this.parseIfClause();
                  }
                }
                return this.finalize(node, new Node5.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 Node5.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 Node5.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 Node5.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 Node5.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 Node5.VariableDeclaration(declarations, "var"));
                      this.nextToken();
                      left3 = init;
                      right3 = this.parseAssignmentExpression();
                      init = null;
                      forIn = false;
                    } else {
                      init = this.finalize(init, new Node5.VariableDeclaration(declarations, "var"));
                      this.expect(";");
                    }
                  } else if (this.matchKeyword("const") || this.matchKeyword("let")) {
                    init = this.createNode();
                    var kind2 = this.nextToken().value;
                    if (!this.context.strict && this.lookahead.value === "in") {
                      init = this.finalize(init, new Node5.Identifier(kind2));
                      this.nextToken();
                      left3 = init;
                      right3 = this.parseExpression();
                      init = null;
                    } else {
                      var previousAllowIn = this.context.allowIn;
                      this.context.allowIn = false;
                      var declarations = this.parseBindingList(kind2, { inFor: true });
                      this.context.allowIn = previousAllowIn;
                      if (declarations.length === 1 && declarations[0].init === null && this.matchKeyword("in")) {
                        init = this.finalize(init, new Node5.VariableDeclaration(declarations, kind2));
                        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 Node5.VariableDeclaration(declarations, kind2));
                        this.nextToken();
                        left3 = init;
                        right3 = this.parseAssignmentExpression();
                        init = null;
                        forIn = false;
                      } else {
                        this.consumeSemicolon();
                        init = this.finalize(init, new Node5.VariableDeclaration(declarations, kind2));
                      }
                    }
                  } 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 Node5.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 Node5.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 Node5.ForStatement(init, test, update2, body)) : forIn ? this.finalize(node, new Node5.ForInStatement(left3, right3, body)) : this.finalize(node, new Node5.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 Node5.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 Node5.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 Node5.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 object3 = this.parseExpression();
                if (!this.match(")") && this.config.tolerant) {
                  this.tolerateUnexpectedToken(this.nextToken());
                  body = this.finalize(this.createNode(), new Node5.EmptyStatement());
                } else {
                  this.expect(")");
                  body = this.parseStatement();
                }
                return this.finalize(node, new Node5.WithStatement(object3, 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 Node5.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 Node5.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 Node5.LabeledStatement(id, body);
                } else {
                  this.consumeSemicolon();
                  statement = new Node5.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 Node5.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 i3 = 0; i3 < params.length; i3++) {
                  var key = "$" + params[i3].value;
                  if (Object.prototype.hasOwnProperty.call(paramMap, key)) {
                    this.tolerateError(messages_1.Messages.DuplicateBinding, params[i3].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 Node5.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 Node5.TryStatement(block2, handler, finalizer));
              };
              Parser5.prototype.parseDebuggerStatement = function() {
                var node = this.createNode();
                this.expectKeyword("debugger");
                this.consumeSemicolon();
                return this.finalize(node, new Node5.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 Node5.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 Node5.RestElement(arg));
              };
              Parser5.prototype.parseFormalParameter = function(options2) {
                var params = [];
                var param = this.match("...") ? this.parseRestElement(params) : this.parsePatternWithDefault(params);
                for (var i3 = 0; i3 < params.length; i3++) {
                  this.validateParam(options2, params[i3], params[i3].value);
                }
                options2.simple = options2.simple && param instanceof Node5.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 Node5.AsyncFunctionDeclaration(id, params, body)) : this.finalize(node, new Node5.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 Node5.AsyncFunctionExpression(id, params, body)) : this.finalize(node, new Node5.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 Node5.Directive(expr, directive) : new Node5.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 Node5.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 Node5.RestElement) {
                  this.tolerateError(messages_1.Messages.BadSetterRestParameter);
                }
                var method = this.parsePropertyMethod(formalParameters);
                this.context.allowYield = previousAllowYield;
                return this.finalize(node, new Node5.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 Node5.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 Node5.YieldExpression(argument, delegate));
              };
              Parser5.prototype.parseClassElement = function(hasConstructor) {
                var token2 = this.lookahead;
                var node = this.createNode();
                var kind2 = "";
                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) {
                    kind2 = "get";
                    computed = this.match("[");
                    key = this.parseObjectPropertyKey();
                    this.context.allowYield = false;
                    value = this.parseGetterMethod();
                  } else if (token2.value === "set" && lookaheadPropertyKey) {
                    kind2 = "set";
                    computed = this.match("[");
                    key = this.parseObjectPropertyKey();
                    value = this.parseSetterMethod();
                  }
                } else if (token2.type === 7 && token2.value === "*" && lookaheadPropertyKey) {
                  kind2 = "init";
                  computed = this.match("[");
                  key = this.parseObjectPropertyKey();
                  value = this.parseGeneratorMethod();
                  method = true;
                }
                if (!kind2 && key && this.match("(")) {
                  kind2 = "init";
                  value = isAsync2 ? this.parsePropertyMethodAsyncFunction() : this.parsePropertyMethodFunction();
                  method = true;
                }
                if (!kind2) {
                  this.throwUnexpectedToken(this.lookahead);
                }
                if (kind2 === "init") {
                  kind2 = "method";
                }
                if (!computed) {
                  if (isStatic && this.isPropertyKey(key, "prototype")) {
                    this.throwUnexpectedToken(token2, messages_1.Messages.StaticPrototype);
                  }
                  if (!isStatic && this.isPropertyKey(key, "constructor")) {
                    if (kind2 !== "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;
                    }
                    kind2 = "constructor";
                  }
                }
                return this.finalize(node, new Node5.MethodDefinition(key, computed, value, kind2, 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 Node5.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 Node5.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 Node5.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 Node5.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 Node5.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 Node5.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 Node5.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 Node5.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 Node5.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 Node5.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 Node5.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 Node5.ExportDefaultDeclaration(declaration));
                  } else if (this.matchKeyword("class")) {
                    var declaration = this.parseClassDeclaration(true);
                    exportDeclaration = this.finalize(node, new Node5.ExportDefaultDeclaration(declaration));
                  } else if (this.matchContextualKeyword("async")) {
                    var declaration = this.matchAsyncFunction() ? this.parseFunctionDeclaration(true) : this.parseAssignmentExpression();
                    exportDeclaration = this.finalize(node, new Node5.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 Node5.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 Node5.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 Node5.ExportNamedDeclaration(declaration, [], null));
                } else if (this.matchAsyncFunction()) {
                  var declaration = this.parseFunctionDeclaration();
                  exportDeclaration = this.finalize(node, new Node5.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 Node5.ExportNamedDeclaration(null, specifiers, source2));
                }
                return exportDeclaration;
              };
              return Parser5;
            }();
            exports3.Parser = Parser4;
          },
          /* 9 */
          /***/
          function(module3, exports3) {
            "use strict";
            Object.defineProperty(exports3, "__esModule", { value: true });
            function assert4(condition, message) {
              if (!condition) {
                throw new Error("ASSERT: " + message);
              }
            }
            __name(assert4, "assert");
            exports3.assert = assert4;
          },
          /* 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(error2) {
                this.errors.push(error2);
              };
              ErrorHandler2.prototype.tolerate = function(error2) {
                if (this.tolerant) {
                  this.recordError(error2);
                } else {
                  throw error2;
                }
              };
              ErrorHandler2.prototype.constructError = function(msg, column) {
                var error2 = new Error(msg);
                try {
                  throw error2;
                } catch (base) {
                  if (Object.create && Object.defineProperty) {
                    error2 = Object.create(base);
                    Object.defineProperty(error2, "column", { value: column });
                  }
                }
                return error2;
              };
              ErrorHandler2.prototype.createError = function(index, line, col, description) {
                var msg = "Line " + line + ": " + description;
                var error2 = this.constructError(msg, col);
                error2.index = index;
                error2.lineNumber = line;
                error2.description = description;
                return error2;
              };
              ErrorHandler2.prototype.throwError = function(index, line, col, description) {
                throw this.createError(index, line, col, description);
              };
              ErrorHandler2.prototype.tolerateError = function(index, line, col, description) {
                var error2 = this.createError(index, line, col, description);
                if (this.tolerant) {
                  this.recordError(error2);
                } else {
                  throw error2;
                }
              };
              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(i3) {
                var cp3 = this.source.charCodeAt(i3);
                if (cp3 >= 55296 && cp3 <= 56319) {
                  var second = this.source.charCodeAt(i3 + 1);
                  if (second >= 56320 && second <= 57343) {
                    var first2 = cp3;
                    cp3 = (first2 - 55296) * 1024 + second - 56320 + 65536;
                  }
                }
                return cp3;
              };
              Scanner2.prototype.scanHexEscape = function(prefix) {
                var len = prefix === "u" ? 4 : 2;
                var code2 = 0;
                for (var i3 = 0; i3 < len; ++i3) {
                  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 cp3 = this.codePointAt(this.index);
                var id = character_1.Character.fromCodePoint(cp3);
                this.index += id.length;
                var ch;
                if (cp3 === 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()) {
                  cp3 = this.codePointAt(this.index);
                  if (!character_1.Character.isIdentifierPart(cp3)) {
                    break;
                  }
                  ch = character_1.Character.fromCodePoint(cp3);
                  id += ch;
                  this.index += ch.length;
                  if (cp3 === 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 i3 = this.index + 1; i3 < this.length; ++i3) {
                  var ch = this.source[i3];
                  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 (e4) {
                  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 cp3 = this.source.charCodeAt(this.index);
                if (character_1.Character.isIdentifierStart(cp3)) {
                  return this.scanIdentifier();
                }
                if (cp3 === 40 || cp3 === 41 || cp3 === 59) {
                  return this.scanPunctuator();
                }
                if (cp3 === 39 || cp3 === 34) {
                  return this.scanStringLiteral();
                }
                if (cp3 === 46) {
                  if (character_1.Character.isDecimalDigit(this.source.charCodeAt(this.index + 1))) {
                    return this.scanNumericLiteral();
                  }
                  return this.scanPunctuator();
                }
                if (character_1.Character.isDecimalDigit(cp3)) {
                  return this.scanNumericLiteral();
                }
                if (cp3 === 96 || cp3 === 125 && this.curlyStack[this.curlyStack.length - 1] === "${") {
                  return this.scanTemplate();
                }
                if (cp3 >= 55296 && cp3 < 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(t5) {
                return [
                  "(",
                  "{",
                  "[",
                  "in",
                  "typeof",
                  "instanceof",
                  "new",
                  "return",
                  "case",
                  "delete",
                  "throw",
                  "void",
                  // assignment operators
                  "=",
                  "+=",
                  "-=",
                  "*=",
                  "**=",
                  "/=",
                  "%=",
                  "<<=",
                  ">>=",
                  ">>>=",
                  "&=",
                  "|=",
                  "^=",
                  ",",
                  // binary/unary operators
                  "+",
                  "-",
                  "*",
                  "**",
                  "/",
                  "%",
                  "++",
                  "--",
                  "<<",
                  ">>",
                  ">>>",
                  "&",
                  "|",
                  "^",
                  "!",
                  "~",
                  "&&",
                  "||",
                  "?",
                  ":",
                  "===",
                  "==",
                  ">=",
                  "<=",
                  "<",
                  ">",
                  "!=",
                  "!=="
                ].indexOf(t5) >= 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 check2 = this.values[this.curly - 4];
                      regex3 = check2 ? !this.beforeFunctionExpression(check2) : false;
                    } else if (this.values[this.curly - 4] === "function") {
                      var check2 = this.values[this.curly - 5];
                      regex3 = check2 ? !this.beforeFunctionExpression(check2) : 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, config2) {
                this.errorHandler = new error_handler_1.ErrorHandler();
                this.errorHandler.tolerant = config2 ? typeof config2.tolerant === "boolean" && config2.tolerant : false;
                this.scanner = new scanner_1.Scanner(code2, this.errorHandler);
                this.scanner.trackComment = config2 ? typeof config2.comment === "boolean" && config2.comment : false;
                this.trackRange = config2 ? typeof config2.range === "boolean" && config2.range : false;
                this.trackLoc = config2 ? typeof config2.loc === "boolean" && config2.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 i3 = 0; i3 < comments.length; ++i3) {
                      var e4 = comments[i3];
                      var value = this.scanner.source.slice(e4.slice[0], e4.slice[1]);
                      var comment = {
                        type: e4.multiLine ? "BlockComment" : "LineComment",
                        value
                      };
                      if (this.trackRange) {
                        comment.range = e4.range;
                      }
                      if (this.trackLoc) {
                        comment.loc = e4.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_util19 = __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(re3) {
      return objectToString2(re3) === "[object RegExp]";
    }
    __name(isRegExp, "isRegExp");
    exports2.isRegExp = isRegExp;
    function isObject4(arg) {
      return typeof arg === "object" && arg !== null;
    }
    __name(isObject4, "isObject");
    exports2.isObject = isObject4;
    function isDate(d2) {
      return objectToString2(d2) === "[object Date]";
    }
    __name(isDate, "isDate");
    exports2.isDate = isDate;
    function isError(e4) {
      return objectToString2(e4) === "[object Error]" || e4 instanceof Error;
    }
    __name(isError, "isError");
    exports2.isError = isError;
    function isFunction5(arg) {
      return typeof arg === "function";
    }
    __name(isFunction5, "isFunction");
    exports2.isFunction = isFunction5;
    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(o3) {
      return Object.prototype.toString.call(o3);
    }
    __name(objectToString2, "objectToString");
  }
});

// node_modules/array-timsort/src/index.js
var require_src38 = __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((x3) => x3 < 1e5 ? x3 < 100 ? x3 < 10 ? 0 : 1 : x3 < 1e4 ? x3 < 1e3 ? 2 : 3 : 4 : x3 < 1e7 ? x3 < 1e6 ? 5 : 6 : x3 < 1e9 ? x3 < 1e8 ? 7 : 8 : 9, "log10");
    function alphabeticalCompare(a2, b2) {
      if (a2 === b2) {
        return 0;
      }
      if (~~a2 === a2 && ~~b2 === b2) {
        if (a2 === 0 || b2 === 0) {
          return a2 < b2 ? -1 : 1;
        }
        if (a2 < 0 || b2 < 0) {
          if (b2 >= 0) {
            return -1;
          }
          if (a2 >= 0) {
            return 1;
          }
          a2 = -a2;
          b2 = -b2;
        }
        const al = log10(a2);
        const bl = log10(b2);
        let t5 = 0;
        if (al < bl) {
          a2 *= POWERS_OF_TEN[bl - al - 1];
          b2 /= 10;
          t5 = -1;
        } else if (al > bl) {
          b2 *= POWERS_OF_TEN[al - bl - 1];
          a2 /= 10;
          t5 = 1;
        }
        if (a2 === b2) {
          return t5;
        }
        return a2 < b2 ? -1 : 1;
      }
      const aStr = String(a2);
      const bStr = String(b2);
      if (aStr === bStr) {
        return 0;
      }
      return aStr < bStr ? -1 : 1;
    }
    __name(alphabeticalCompare, "alphabeticalCompare");
    function minRunLength(n3) {
      let r5 = 0;
      while (n3 >= DEFAULT_MIN_MERGE) {
        r5 |= n3 & 1;
        n3 >>= 1;
      }
      return n3 + r5;
    }
    __name(minRunLength, "minRunLength");
    function makeAscendingRun(array2, lo, hi, compare) {
      let runHi = lo + 1;
      if (runHi === hi) {
        return 1;
      }
      if (compare(array2[runHi++], array2[lo]) < 0) {
        while (runHi < hi && compare(array2[runHi], array2[runHi - 1]) < 0) {
          runHi++;
        }
        reverseRun(array2, lo, runHi);
        reverseRun(results, lo, runHi);
      } else {
        while (runHi < hi && compare(array2[runHi], array2[runHi - 1]) >= 0) {
          runHi++;
        }
      }
      return runHi - lo;
    }
    __name(makeAscendingRun, "makeAscendingRun");
    function reverseRun(array2, lo, hi) {
      hi--;
      while (lo < hi) {
        const t5 = array2[lo];
        array2[lo++] = array2[hi];
        array2[hi--] = t5;
      }
    }
    __name(reverseRun, "reverseRun");
    function binaryInsertionSort(array2, lo, hi, start, compare) {
      if (start === lo) {
        start++;
      }
      for (; start < hi; start++) {
        const pivot = array2[start];
        const pivotIndex = results[start];
        let left3 = lo;
        let right3 = start;
        while (left3 < right3) {
          const mid = left3 + right3 >>> 1;
          if (compare(pivot, array2[mid]) < 0) {
            right3 = mid;
          } else {
            left3 = mid + 1;
          }
        }
        let n3 = start - left3;
        switch (n3) {
          case 3:
            array2[left3 + 3] = array2[left3 + 2];
            results[left3 + 3] = results[left3 + 2];
          /* falls through */
          case 2:
            array2[left3 + 2] = array2[left3 + 1];
            results[left3 + 2] = results[left3 + 1];
          /* falls through */
          case 1:
            array2[left3 + 1] = array2[left3];
            results[left3 + 1] = results[left3];
            break;
          default:
            while (n3 > 0) {
              array2[left3 + n3] = array2[left3 + n3 - 1];
              results[left3 + n3] = results[left3 + n3 - 1];
              n3--;
            }
        }
        array2[left3] = pivot;
        results[left3] = pivotIndex;
      }
    }
    __name(binaryInsertionSort, "binaryInsertionSort");
    function gallopLeft(value, array2, start, length, hint, compare) {
      let lastOffset = 0;
      let maxOffset = 0;
      let offset = 1;
      if (compare(value, array2[start + hint]) > 0) {
        maxOffset = length - hint;
        while (offset < maxOffset && compare(value, array2[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, array2[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 m3 = lastOffset + (offset - lastOffset >>> 1);
        if (compare(value, array2[start + m3]) > 0) {
          lastOffset = m3 + 1;
        } else {
          offset = m3;
        }
      }
      return offset;
    }
    __name(gallopLeft, "gallopLeft");
    function gallopRight(value, array2, start, length, hint, compare) {
      let lastOffset = 0;
      let maxOffset = 0;
      let offset = 1;
      if (compare(value, array2[start + hint]) < 0) {
        maxOffset = hint + 1;
        while (offset < maxOffset && compare(value, array2[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, array2[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 m3 = lastOffset + (offset - lastOffset >>> 1);
        if (compare(value, array2[start + m3]) < 0) {
          offset = m3;
        } else {
          lastOffset = m3 + 1;
        }
      }
      return offset;
    }
    __name(gallopRight, "gallopRight");
    var TimSort = class {
      static {
        __name(this, "TimSort");
      }
      constructor(array2, compare) {
        this.array = array2;
        this.compare = compare;
        const { length } = array2;
        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 n3 = this.stackSize - 2;
          if (n3 >= 1 && this.runLength[n3 - 1] <= this.runLength[n3] + this.runLength[n3 + 1] || n3 >= 2 && this.runLength[n3 - 2] <= this.runLength[n3] + this.runLength[n3 - 1]) {
            if (this.runLength[n3 - 1] < this.runLength[n3 + 1]) {
              n3--;
            }
          } else if (this.runLength[n3] > this.runLength[n3 + 1]) {
            break;
          }
          this.mergeAt(n3);
        }
      }
      /**
       * Merge all runs on TimSort's stack until only one remains.
       */
      forceMergeRuns() {
        while (this.stackSize > 1) {
          let n3 = this.stackSize - 2;
          if (n3 > 0 && this.runLength[n3 - 1] < this.runLength[n3 + 1]) {
            n3--;
          }
          this.mergeAt(n3);
        }
      }
      /**
       * 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(i3) {
        const { compare } = this;
        const { array: array2 } = this;
        let start1 = this.runStart[i3];
        let length1 = this.runLength[i3];
        const start2 = this.runStart[i3 + 1];
        let length2 = this.runLength[i3 + 1];
        this.runLength[i3] = length1 + length2;
        if (i3 === this.stackSize - 3) {
          this.runStart[i3 + 1] = this.runStart[i3 + 2];
          this.runLength[i3 + 1] = this.runLength[i3 + 2];
        }
        this.stackSize--;
        const k2 = gallopRight(array2[start2], array2, start1, length1, 0, compare);
        start1 += k2;
        length1 -= k2;
        if (length1 === 0) {
          return;
        }
        length2 = gallopLeft(
          array2[start1 + length1 - 1],
          array2,
          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: array2 } = this;
        const { tmp } = this;
        const { tmpIndex } = this;
        let i3 = 0;
        for (i3 = 0; i3 < length1; i3++) {
          tmp[i3] = array2[start1 + i3];
          tmpIndex[i3] = results[start1 + i3];
        }
        let cursor1 = 0;
        let cursor2 = start2;
        let dest = start1;
        array2[dest] = array2[cursor2];
        results[dest] = results[cursor2];
        dest++;
        cursor2++;
        if (--length2 === 0) {
          for (i3 = 0; i3 < length1; i3++) {
            array2[dest + i3] = tmp[cursor1 + i3];
            results[dest + i3] = tmpIndex[cursor1 + i3];
          }
          return;
        }
        if (length1 === 1) {
          for (i3 = 0; i3 < length2; i3++) {
            array2[dest + i3] = array2[cursor2 + i3];
            results[dest + i3] = results[cursor2 + i3];
          }
          array2[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(array2[cursor2], tmp[cursor1]) < 0) {
              array2[dest] = array2[cursor2];
              results[dest] = results[cursor2];
              dest++;
              cursor2++;
              count2++;
              count1 = 0;
              if (--length2 === 0) {
                exit = true;
                break;
              }
            } else {
              array2[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(array2[cursor2], tmp, cursor1, length1, 0, compare);
            if (count1 !== 0) {
              for (i3 = 0; i3 < count1; i3++) {
                array2[dest + i3] = tmp[cursor1 + i3];
                results[dest + i3] = tmpIndex[cursor1 + i3];
              }
              dest += count1;
              cursor1 += count1;
              length1 -= count1;
              if (length1 <= 1) {
                exit = true;
                break;
              }
            }
            array2[dest] = array2[cursor2];
            results[dest] = results[cursor2];
            dest++;
            cursor2++;
            if (--length2 === 0) {
              exit = true;
              break;
            }
            count2 = gallopLeft(tmp[cursor1], array2, cursor2, length2, 0, compare);
            if (count2 !== 0) {
              for (i3 = 0; i3 < count2; i3++) {
                array2[dest + i3] = array2[cursor2 + i3];
                results[dest + i3] = results[cursor2 + i3];
              }
              dest += count2;
              cursor2 += count2;
              length2 -= count2;
              if (length2 === 0) {
                exit = true;
                break;
              }
            }
            array2[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 (i3 = 0; i3 < length2; i3++) {
            array2[dest + i3] = array2[cursor2 + i3];
            results[dest + i3] = results[cursor2 + i3];
          }
          array2[dest + length2] = tmp[cursor1];
          results[dest + length2] = tmpIndex[cursor1];
        } else if (length1 === 0) {
          throw new Error("mergeLow preconditions were not respected");
        } else {
          for (i3 = 0; i3 < length1; i3++) {
            array2[dest + i3] = tmp[cursor1 + i3];
            results[dest + i3] = tmpIndex[cursor1 + i3];
          }
        }
      }
      /**
       * 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: array2 } = this;
        const { tmp } = this;
        const { tmpIndex } = this;
        let i3 = 0;
        for (i3 = 0; i3 < length2; i3++) {
          tmp[i3] = array2[start2 + i3];
          tmpIndex[i3] = results[start2 + i3];
        }
        let cursor1 = start1 + length1 - 1;
        let cursor2 = length2 - 1;
        let dest = start2 + length2 - 1;
        let customCursor = 0;
        let customDest = 0;
        array2[dest] = array2[cursor1];
        results[dest] = results[cursor1];
        dest--;
        cursor1--;
        if (--length1 === 0) {
          customCursor = dest - (length2 - 1);
          for (i3 = 0; i3 < length2; i3++) {
            array2[customCursor + i3] = tmp[i3];
            results[customCursor + i3] = tmpIndex[i3];
          }
          return;
        }
        if (length2 === 1) {
          dest -= length1;
          cursor1 -= length1;
          customDest = dest + 1;
          customCursor = cursor1 + 1;
          for (i3 = length1 - 1; i3 >= 0; i3--) {
            array2[customDest + i3] = array2[customCursor + i3];
            results[customDest + i3] = results[customCursor + i3];
          }
          array2[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], array2[cursor1]) < 0) {
              array2[dest] = array2[cursor1];
              results[dest] = results[cursor1];
              dest--;
              cursor1--;
              count1++;
              count2 = 0;
              if (--length1 === 0) {
                exit = true;
                break;
              }
            } else {
              array2[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],
              array2,
              start1,
              length1,
              length1 - 1,
              compare
            );
            if (count1 !== 0) {
              dest -= count1;
              cursor1 -= count1;
              length1 -= count1;
              customDest = dest + 1;
              customCursor = cursor1 + 1;
              for (i3 = count1 - 1; i3 >= 0; i3--) {
                array2[customDest + i3] = array2[customCursor + i3];
                results[customDest + i3] = results[customCursor + i3];
              }
              if (length1 === 0) {
                exit = true;
                break;
              }
            }
            array2[dest] = tmp[cursor2];
            results[dest] = tmpIndex[cursor2];
            dest--;
            cursor2--;
            if (--length2 === 1) {
              exit = true;
              break;
            }
            count2 = length2 - gallopLeft(
              array2[cursor1],
              tmp,
              0,
              length2,
              length2 - 1,
              compare
            );
            if (count2 !== 0) {
              dest -= count2;
              cursor2 -= count2;
              length2 -= count2;
              customDest = dest + 1;
              customCursor = cursor2 + 1;
              for (i3 = 0; i3 < count2; i3++) {
                array2[customDest + i3] = tmp[customCursor + i3];
                results[customDest + i3] = tmpIndex[customCursor + i3];
              }
              if (length2 <= 1) {
                exit = true;
                break;
              }
            }
            array2[dest] = array2[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 (i3 = length1 - 1; i3 >= 0; i3--) {
            array2[customDest + i3] = array2[customCursor + i3];
            results[customDest + i3] = results[customCursor + i3];
          }
          array2[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 (i3 = 0; i3 < length2; i3++) {
            array2[customCursor + i3] = tmp[i3];
            results[customCursor + i3] = tmpIndex[i3];
          }
        }
      }
    };
    function sort(array2, compare, lo, hi) {
      if (!Array.isArray(array2)) {
        throw new TypeError(
          `The "array" argument must be an array. Received ${array2}`
        );
      }
      results = [];
      const { length } = array2;
      let i3 = 0;
      while (i3 < length) {
        results[i3] = i3++;
      }
      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(array2, lo, hi, compare);
        binaryInsertionSort(array2, lo, hi, lo + runLength, compare);
        return results;
      }
      const ts = new TimSort(array2, compare);
      const minRun = minRunLength(remaining);
      do {
        runLength = makeAscendingRun(array2, lo, hi, compare);
        if (runLength < minRun) {
          let force = remaining;
          if (force > minRun) {
            force = minRun;
          }
          binaryInsertionSort(array2, 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 = (object3, property) => hasOwnProp.call(object3, 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: isObject4,
      isArray: isArray2,
      isString: isString2,
      isNumber: isNumber3
    } = require_util19();
    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 COLON3 = ":";
    var UNDEFINED = void 0;
    var symbol = /* @__PURE__ */ __name((prefix, key) => Symbol.for(prefix + COLON3 + 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((array2, from, to) => {
      if (from === to) {
        return;
      }
      SYMBOL_PREFIXES.forEach((prefix) => {
        const target_prop = symbol(prefix, to);
        if (!hasOwnProperty2(array2, target_prop)) {
          copy_comments_by_kind(array2, array2, to, from, prefix, true);
          return;
        }
        const comments = array2[target_prop];
        delete array2[target_prop];
        copy_comments_by_kind(array2, array2, to, from, prefix, true);
        define2(array2, 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: COLON3,
      COMMA,
      MINUS,
      EMPTY: EMPTY2,
      UNDEFINED,
      symbol,
      define: define2,
      copy_comments,
      swap_comments,
      assign_non_prop_comments,
      assign(target, source2, keys) {
        if (!isObject4(target)) {
          throw new TypeError("Cannot convert undefined or null to object");
        }
        if (!isObject4(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_util19();
    var { sort } = require_src38();
    var {
      SYMBOL_PREFIXES,
      UNDEFINED,
      symbol,
      copy_comments,
      swap_comments
    } = require_common5();
    var reverse_comments = /* @__PURE__ */ __name((array2) => {
      const { length } = array2;
      let i3 = 0;
      const max = length / 2;
      for (; i3 < max; i3++) {
        swap_comments(array2, i3, length - i3 - 1);
      }
    }, "reverse_comments");
    var move_comment = /* @__PURE__ */ __name((target, source2, i3, offset, remove2) => {
      copy_comments(target, source2, i3 + offset, i3, remove2);
    }, "move_comment");
    var move_comments = /* @__PURE__ */ __name((target, source2, start, count, offset, remove2) => {
      if (offset > 0) {
        let i4 = count;
        while (i4-- > 0) {
          move_comment(target, source2, start + i4, offset, remove2);
        }
        return;
      }
      let i3 = 0;
      while (i3 < count) {
        const ii = i3++;
        move_comment(target, source2, start + ii, offset, remove2);
      }
    }, "move_comments");
    var remove_comments = /* @__PURE__ */ __name((array2, key) => {
      SYMBOL_PREFIXES.forEach((prefix) => {
        const prop = symbol(prefix, key);
        delete array2[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 array2 = super.slice(...args);
        if (!array2.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(array2, this, begin, before - begin, -begin);
        return array2;
      }
      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_parse8 = __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: COLON3,
      COMMA,
      MINUS,
      EMPTY: EMPTY2,
      UNDEFINED,
      define: define2,
      assign_non_prop_comments
    } = require_common5();
    var tokenize5 = /* @__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 + COLON3 + last_prop : prefix
    ), "symbolFor");
    var transform2 = /* @__PURE__ */ __name((k2, v2) => reviver ? reviver(k2, v2) : v2, "transform");
    var unexpected = /* @__PURE__ */ __name(() => {
      const error2 = new SyntaxError(`Unexpected token ${current.value.slice(0, 1)}`);
      Object.assign(error2, current.loc.start);
      throw error2;
    }, "unexpected");
    var unexpected_end = /* @__PURE__ */ __name(() => {
      const error2 = new SyntaxError("Unexpected end of JSON input");
      Object.assign(error2, last2 ? last2.loc.end : {
        line: 1,
        column: 0
      });
      throw error2;
    }, "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((t5) => type() === t5, "is");
    var expect = /* @__PURE__ */ __name((a2) => {
      if (!is(a2)) {
        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(COLON3);
        next();
        parse_comments(PREFIX_AFTER_COLON);
        obj[name3] = transform2(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 array2 = new CommentArray();
      set_comments_host(array2);
      set_prop(UNDEFINED, true);
      let started = false;
      let i3 = 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(i3);
        assign_comments(PREFIX_BEFORE);
        array2[i3] = transform2(i3, walk());
        i3++;
        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 array2;
    }, "parse_array");
    function walk() {
      let tt2 = type();
      if (tt2 === CURLY_BRACKET_OPEN) {
        next();
        return parse_object();
      }
      if (tt2 === BRACKET_OPEN) {
        next();
        return parse_array();
      }
      let negative = EMPTY2;
      if (tt2 === MINUS) {
        next();
        tt2 = type();
        negative = MINUS;
      }
      let v2;
      switch (tt2) {
        case "String":
        case "Boolean":
        case "Null":
        case "Numeric":
          v2 = current.value;
          next();
          return JSON.parse(negative + v2);
        default:
      }
    }
    __name(walk, "walk");
    var isObject4 = /* @__PURE__ */ __name((subject) => Object(subject) === subject, "isObject");
    var parse14 = /* @__PURE__ */ __name((code2, rev, no_comments) => {
      clean();
      tokens = tokenize5(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 (!isObject4(result)) {
          result = new Object(result);
        }
        assign_non_prop_comments(result, comments_host);
      }
      restore_comments_host();
      result = transform2("", result);
      free();
      return result;
    }, "parse");
    module2.exports = {
      parse: parse14,
      tokenize: tokenize5
    };
  }
});

// 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_stringify3 = __commonJS({
  "node_modules/comment-json/src/stringify.js"(exports2, module2) {
    init_esbuild_shims();
    var {
      isArray: isArray2,
      isObject: isObject4,
      isFunction: isFunction5,
      isNumber: isNumber3,
      isString: isString2
    } = require_util19();
    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: COLON3,
      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 SPACE3 = " ";
    var LF3 = "\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((string4) => {
      ESCAPABLE.lastIndex = 0;
      if (!ESCAPABLE.test(string4)) {
        return string4;
      }
      return string4.replace(ESCAPABLE, (a2) => {
        const c4 = meta[a2];
        return typeof c4 === "string" ? c4 : a2;
      });
    }, "escape");
    var quote3 = /* @__PURE__ */ __name((string4) => `"${escape7(string4)}"`, "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 ? SPACE3 : LF3 + deeper_gap;
        is_line_comment = type === "LineComment";
        return prev + delimiter2 + comment_stringify(value, is_line_comment);
      }, EMPTY2);
      return display_block || is_line_comment ? str2 + LF3 + deeper_gap : str2;
    }, "process_comments");
    var replacer = null;
    var indent = EMPTY2;
    var clean = /* @__PURE__ */ __name(() => {
      replacer = null;
      indent = EMPTY2;
    }, "clean");
    var join45 = /* @__PURE__ */ __name((one, two, gap) => one ? two ? one + two.trim() + LF3 + gap : one.trimRight() + LF3 + gap : two ? two.trimRight() + LF3 + gap : EMPTY2, "join");
    var join_content = /* @__PURE__ */ __name((inside, value, gap) => {
      const comment = process_comments(value, PREFIX_BEFORE, gap + indent, true);
      return join45(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 i3 = 0; i3 < length; i3++) {
        if (i3 !== 0) {
          inside += COMMA;
        }
        const before = join45(
          after_comma,
          process_comments(value, BEFORE(i3), deeper_gap),
          deeper_gap
        );
        inside += before || LF3 + deeper_gap;
        inside += stringify4(i3, value, deeper_gap) || STR_NULL;
        inside += process_comments(value, AFTER_VALUE(i3), deeper_gap);
        after_comma = process_comments(value, AFTER(i3), deeper_gap);
      }
      inside += join45(
        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 = stringify4(key, value, deeper_gap);
        if (sv === UNDEFINED) {
          return;
        }
        if (!first2) {
          inside += COMMA;
        }
        first2 = false;
        const before = join45(
          after_comma,
          process_comments(value, BEFORE(key), deeper_gap),
          deeper_gap
        );
        inside += before || LF3 + deeper_gap;
        inside += quote3(key) + process_comments(value, AFTER_PROP(key), deeper_gap) + COLON3 + process_comments(value, AFTER_COLON(key), deeper_gap) + SPACE3 + sv + process_comments(value, AFTER_VALUE(key), deeper_gap);
        after_comma = process_comments(value, AFTER(key), deeper_gap);
      }, "iteratee");
      keys.forEach(iteratee);
      inside += join45(
        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 stringify4(key, holder, gap) {
      let value = holder[key];
      if (isObject4(value) && isFunction5(value.toJSON)) {
        value = value.toJSON(key);
      }
      if (isFunction5(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(stringify4, "stringify");
    var get_indent = /* @__PURE__ */ __name((space) => isString2(space) ? space : isNumber3(space) ? repeat(SPACE3, 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 (!isFunction5(replacer_) && !isArray2(replacer_)) {
        replacer_ = null;
      }
      replacer = replacer_;
      indent = indent_;
      const str2 = is_primitive_object(value) ? JSON.stringify(value) : stringify4("", { "": value }, EMPTY2);
      clean();
      return isObject4(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_src39 = __commonJS({
  "node_modules/comment-json/src/index.js"(exports2, module2) {
    init_esbuild_shims();
    var { parse: parse14, tokenize: tokenize5 } = require_parse8();
    var stringify4 = require_stringify3();
    var { CommentArray } = require_array();
    var { assign } = require_common5();
    module2.exports = {
      parse: parse14,
      stringify: stringify4,
      tokenize: tokenize5,
      CommentArray,
      assign
    };
  }
});

// packages/cli/src/i18n/locales/de.js
var de_exports = {};
__export(de_exports, {
  default: () => de_default
});
var de_default;
var init_de = __esm({
  "packages/cli/src/i18n/locales/de.js"() {
    "use strict";
    init_esbuild_shims();
    de_default = {
      // ============================================================================
      // Help / UI Components
      // ============================================================================
      // Attachment hints
      "\u2191 to manage attachments": "\u2191 Anh\xE4nge verwalten",
      "\u2190 \u2192 select, Delete to remove, \u2193 to exit": "\u2190 \u2192 ausw\xE4hlen, Entf zum L\xF6schen, \u2193 beenden",
      "Attachments: ": "Anh\xE4nge: ",
      "Basics:": "Grundlagen:",
      "Add context": "Kontext hinzuf\xFCgen",
      "Use {{symbol}} to specify files for context (e.g., {{example}}) to target specific files or folders.": "Verwenden Sie {{symbol}}, um Dateien als Kontext anzugeben (z.B. {{example}}), um bestimmte Dateien oder Ordner auszuw\xE4hlen.",
      "@": "@",
      "@src/myFile.ts": "@src/myFile.ts",
      "Shell mode": "Shell-Modus",
      "YOLO mode": "YOLO-Modus",
      "plan mode": "Planungsmodus",
      "auto-accept edits": "\xC4nderungen automatisch akzeptieren",
      "Accepting edits": "\xC4nderungen werden akzeptiert",
      "(shift + tab to cycle)": "(Umschalt + Tab zum Wechseln)",
      "(tab to cycle)": "(Tab zum Wechseln)",
      "Execute shell commands via {{symbol}} (e.g., {{example1}}) or use natural language (e.g., {{example2}}).": "Shell-Befehle \xFCber {{symbol}} ausf\xFChren (z.B. {{example1}}) oder nat\xFCrliche Sprache verwenden (z.B. {{example2}}).",
      "!": "!",
      "!npm run start": "!npm run start",
      "start server": "Server starten",
      "Commands:": "Befehle:",
      "shell command": "Shell-Befehl",
      "Model Context Protocol command (from external servers)": "Model Context Protocol Befehl (von externen Servern)",
      "Keyboard Shortcuts:": "Tastenk\xFCrzel:",
      "Jump through words in the input": "W\xF6rter in der Eingabe \xFCberspringen",
      "Close dialogs, cancel requests, or quit application": "Dialoge schlie\xDFen, Anfragen abbrechen oder Anwendung beenden",
      "New line": "Neue Zeile",
      "New line (Alt+Enter works for certain linux distros)": "Neue Zeile (Alt+Enter funktioniert bei bestimmten Linux-Distributionen)",
      "Clear the screen": "Bildschirm l\xF6schen",
      "Open input in external editor": "Eingabe in externem Editor \xF6ffnen",
      "Send message": "Nachricht senden",
      "Initializing...": "Initialisierung...",
      "Connecting to MCP servers... ({{connected}}/{{total}})": "Verbindung zu MCP-Servern wird hergestellt... ({{connected}}/{{total}})",
      "Type your message or @path/to/file": "Nachricht eingeben oder @Pfad/zur/Datei",
      "Press 'i' for INSERT mode and 'Esc' for NORMAL mode.": "Dr\xFCcken Sie 'i' f\xFCr den EINF\xDCGE-Modus und 'Esc' f\xFCr den NORMAL-Modus.",
      "Cancel operation / Clear input (double press)": "Vorgang abbrechen / Eingabe l\xF6schen (doppelt dr\xFCcken)",
      "Cycle approval modes": "Genehmigungsmodi durchschalten",
      "Cycle through your prompt history": "Eingabeverlauf durchbl\xE4ttern",
      "For a full list of shortcuts, see {{docPath}}": "Eine vollst\xE4ndige Liste der Tastenk\xFCrzel finden Sie unter {{docPath}}",
      "docs/keyboard-shortcuts.md": "docs/keyboard-shortcuts.md",
      "for help on Qwen Code": "f\xFCr Hilfe zu Qwen Code",
      "show version info": "Versionsinformationen anzeigen",
      "submit a bug report": "Fehlerbericht einreichen",
      "About Qwen Code": "\xDCber Qwen Code",
      Status: "Status",
      // ============================================================================
      // System Information Fields
      // ============================================================================
      "Qwen Code": "Qwen Code",
      Runtime: "Laufzeit",
      OS: "Betriebssystem",
      Auth: "Authentifizierung",
      "CLI Version": "CLI-Version",
      "Git Commit": "Git-Commit",
      Model: "Modell",
      Sandbox: "Sandbox",
      "OS Platform": "Betriebssystem",
      "OS Arch": "OS-Architektur",
      "OS Release": "OS-Version",
      "Node.js Version": "Node.js-Version",
      "NPM Version": "NPM-Version",
      "Session ID": "Sitzungs-ID",
      "Auth Method": "Authentifizierungsmethode",
      "Base URL": "Basis-URL",
      Proxy: "Proxy",
      "Memory Usage": "Speichernutzung",
      "IDE Client": "IDE-Client",
      // ============================================================================
      // Commands - General
      // ============================================================================
      "Analyzes the project and creates a tailored QWEN.md file.": "Analysiert das Projekt und erstellt eine ma\xDFgeschneiderte QWEN.md-Datei.",
      "list available Qwen Code tools. Usage: /tools [desc]": "Verf\xFCgbare Qwen Code Werkzeuge auflisten. Verwendung: /tools [desc]",
      "Available Qwen Code CLI tools:": "Verf\xFCgbare Qwen Code CLI-Werkzeuge:",
      "No tools available": "Keine Werkzeuge verf\xFCgbar",
      "View or change the approval mode for tool usage": "Genehmigungsmodus f\xFCr Werkzeugnutzung anzeigen oder \xE4ndern",
      "View or change the language setting": "Spracheinstellung anzeigen oder \xE4ndern",
      "change the theme": "Design \xE4ndern",
      "Select Theme": "Design ausw\xE4hlen",
      Preview: "Vorschau",
      "(Use Enter to select, Tab to configure scope)": "(Enter zum Ausw\xE4hlen, Tab zum Konfigurieren des Bereichs)",
      "(Use Enter to apply scope, Tab to go back)": "(Enter zum Anwenden des Bereichs, Tab zum Zur\xFCckgehen)",
      "Theme configuration unavailable due to NO_COLOR env variable.": "Design-Konfiguration aufgrund der NO_COLOR-Umgebungsvariable nicht verf\xFCgbar.",
      'Theme "{{themeName}}" not found.': 'Design "{{themeName}}" nicht gefunden.',
      'Theme "{{themeName}}" not found in selected scope.': 'Design "{{themeName}}" im ausgew\xE4hlten Bereich nicht gefunden.',
      "Clear conversation history and free up context": "Gespr\xE4chsverlauf l\xF6schen und Kontext freigeben",
      "Compresses the context by replacing it with a summary.": "Komprimiert den Kontext durch Ersetzen mit einer Zusammenfassung.",
      "open full Qwen Code documentation in your browser": "Vollst\xE4ndige Qwen Code Dokumentation im Browser \xF6ffnen",
      "Configuration not available.": "Konfiguration nicht verf\xFCgbar.",
      "change the auth method": "Authentifizierungsmethode \xE4ndern",
      "Configure authentication information for login": "Authentifizierungsinformationen f\xFCr die Anmeldung konfigurieren",
      "Copy the last result or code snippet to clipboard": "Letztes Ergebnis oder Codeausschnitt in die Zwischenablage kopieren",
      // ============================================================================
      // Commands - Agents
      // ============================================================================
      "Manage subagents for specialized task delegation.": "Unteragenten f\xFCr spezialisierte Aufgabendelegation verwalten.",
      "Manage existing subagents (view, edit, delete).": "Bestehende Unteragenten verwalten (anzeigen, bearbeiten, l\xF6schen).",
      "Create a new subagent with guided setup.": "Neuen Unteragenten mit gef\xFChrter Einrichtung erstellen.",
      // ============================================================================
      // Agents - Management Dialog
      // ============================================================================
      Agents: "Agenten",
      "Choose Action": "Aktion w\xE4hlen",
      "Edit {{name}}": "{{name}} bearbeiten",
      "Edit Tools: {{name}}": "Werkzeuge bearbeiten: {{name}}",
      "Edit Color: {{name}}": "Farbe bearbeiten: {{name}}",
      "Delete {{name}}": "{{name}} l\xF6schen",
      "Unknown Step": "Unbekannter Schritt",
      "Esc to close": "Esc zum Schlie\xDFen",
      "Enter to select, \u2191\u2193 to navigate, Esc to close": "Enter zum Ausw\xE4hlen, \u2191\u2193 zum Navigieren, Esc zum Schlie\xDFen",
      "Esc to go back": "Esc zum Zur\xFCckgehen",
      "Enter to confirm, Esc to cancel": "Enter zum Best\xE4tigen, Esc zum Abbrechen",
      "Enter to select, \u2191\u2193 to navigate, Esc to go back": "Enter zum Ausw\xE4hlen, \u2191\u2193 zum Navigieren, Esc zum Zur\xFCckgehen",
      "Invalid step: {{step}}": "Ung\xFCltiger Schritt: {{step}}",
      "No subagents found.": "Keine Unteragenten gefunden.",
      "Use '/agents create' to create your first subagent.": "Verwenden Sie '/agents create', um Ihren ersten Unteragenten zu erstellen.",
      "(built-in)": "(integriert)",
      "(overridden by project level agent)": "(\xFCberschrieben durch Projektagent)",
      "Project Level ({{path}})": "Projektebene ({{path}})",
      "User Level ({{path}})": "Benutzerebene ({{path}})",
      "Built-in Agents": "Integrierte Agenten",
      "Extension Agents": "Erweiterungs-Agenten",
      "Using: {{count}} agents": "Verwendet: {{count}} Agenten",
      "View Agent": "Agent anzeigen",
      "Edit Agent": "Agent bearbeiten",
      "Delete Agent": "Agent l\xF6schen",
      Back: "Zur\xFCck",
      "No agent selected": "Kein Agent ausgew\xE4hlt",
      "File Path: ": "Dateipfad: ",
      "Tools: ": "Werkzeuge: ",
      "Color: ": "Farbe: ",
      "Description:": "Beschreibung:",
      "System Prompt:": "System-Prompt:",
      "Open in editor": "Im Editor \xF6ffnen",
      "Edit tools": "Werkzeuge bearbeiten",
      "Edit color": "Farbe bearbeiten",
      "\u274C Error:": "\u274C Fehler:",
      'Are you sure you want to delete agent "{{name}}"?': 'Sind Sie sicher, dass Sie den Agenten "{{name}}" l\xF6schen m\xF6chten?',
      // ============================================================================
      // Agents - Creation Wizard
      // ============================================================================
      "Project Level (.qwen/agents/)": "Projektebene (.qwen/agents/)",
      "User Level (~/.qwen/agents/)": "Benutzerebene (~/.qwen/agents/)",
      "\u2705 Subagent Created Successfully!": "\u2705 Unteragent erfolgreich erstellt!",
      'Subagent "{{name}}" has been saved to {{level}} level.': 'Unteragent "{{name}}" wurde auf {{level}}-Ebene gespeichert.',
      "Name: ": "Name: ",
      "Location: ": "Speicherort: ",
      "\u274C Error saving subagent:": "\u274C Fehler beim Speichern des Unteragenten:",
      "Warnings:": "Warnungen:",
      'Name "{{name}}" already exists at {{level}} level - will overwrite existing subagent': 'Name "{{name}}" existiert bereits auf {{level}}-Ebene - bestehender Unteragent wird \xFCberschrieben',
      'Name "{{name}}" exists at user level - project level will take precedence': 'Name "{{name}}" existiert auf Benutzerebene - Projektebene hat Vorrang',
      'Name "{{name}}" exists at project level - existing subagent will take precedence': 'Name "{{name}}" existiert auf Projektebene - bestehender Unteragent hat Vorrang',
      "Description is over {{length}} characters": "Beschreibung ist \xFCber {{length}} Zeichen",
      "System prompt is over {{length}} characters": "System-Prompt ist \xFCber {{length}} Zeichen",
      // Agents - Creation Wizard Steps
      "Step {{n}}: Choose Location": "Schritt {{n}}: Speicherort w\xE4hlen",
      "Step {{n}}: Choose Generation Method": "Schritt {{n}}: Generierungsmethode w\xE4hlen",
      "Generate with Qwen Code (Recommended)": "Mit Qwen Code generieren (Empfohlen)",
      "Manual Creation": "Manuelle Erstellung",
      "Describe what this subagent should do and when it should be used. (Be comprehensive for best results)": "Beschreiben Sie, was dieser Unteragent tun soll und wann er verwendet werden soll. (Ausf\xFChrliche Beschreibung f\xFCr beste Ergebnisse)",
      "e.g., Expert code reviewer that reviews code based on best practices...": "z.B. Experte f\xFCr Code-Reviews, der Code nach Best Practices \xFCberpr\xFCft...",
      "Generating subagent configuration...": "Unteragent-Konfiguration wird generiert...",
      "Failed to generate subagent: {{error}}": "Fehler beim Generieren des Unteragenten: {{error}}",
      "Step {{n}}: Describe Your Subagent": "Schritt {{n}}: Unteragent beschreiben",
      "Step {{n}}: Enter Subagent Name": "Schritt {{n}}: Unteragent-Name eingeben",
      "Step {{n}}: Enter System Prompt": "Schritt {{n}}: System-Prompt eingeben",
      "Step {{n}}: Enter Description": "Schritt {{n}}: Beschreibung eingeben",
      // Agents - Tool Selection
      "Step {{n}}: Select Tools": "Schritt {{n}}: Werkzeuge ausw\xE4hlen",
      "All Tools (Default)": "Alle Werkzeuge (Standard)",
      "All Tools": "Alle Werkzeuge",
      "Read-only Tools": "Nur-Lese-Werkzeuge",
      "Read & Edit Tools": "Lese- und Bearbeitungswerkzeuge",
      "Read & Edit & Execution Tools": "Lese-, Bearbeitungs- und Ausf\xFChrungswerkzeuge",
      "All tools selected, including MCP tools": "Alle Werkzeuge ausgew\xE4hlt, einschlie\xDFlich MCP-Werkzeuge",
      "Selected tools:": "Ausgew\xE4hlte Werkzeuge:",
      "Read-only tools:": "Nur-Lese-Werkzeuge:",
      "Edit tools:": "Bearbeitungswerkzeuge:",
      "Execution tools:": "Ausf\xFChrungswerkzeuge:",
      "Step {{n}}: Choose Background Color": "Schritt {{n}}: Hintergrundfarbe w\xE4hlen",
      "Step {{n}}: Confirm and Save": "Schritt {{n}}: Best\xE4tigen und Speichern",
      // Agents - Navigation & Instructions
      "Esc to cancel": "Esc zum Abbrechen",
      "Press Enter to save, e to save and edit, Esc to go back": "Enter zum Speichern, e zum Speichern und Bearbeiten, Esc zum Zur\xFCckgehen",
      "Press Enter to continue, {{navigation}}Esc to {{action}}": "Enter zum Fortfahren, {{navigation}}Esc zum {{action}}",
      cancel: "Abbrechen",
      "go back": "Zur\xFCckgehen",
      "\u2191\u2193 to navigate, ": "\u2191\u2193 zum Navigieren, ",
      "Enter a clear, unique name for this subagent.": "Geben Sie einen eindeutigen Namen f\xFCr diesen Unteragenten ein.",
      "e.g., Code Reviewer": "z.B. Code-Reviewer",
      "Name cannot be empty.": "Name darf nicht leer sein.",
      "Write the system prompt that defines this subagent's behavior. Be comprehensive for best results.": "Schreiben Sie den System-Prompt, der das Verhalten dieses Unteragenten definiert. Ausf\xFChrlich f\xFCr beste Ergebnisse.",
      "e.g., You are an expert code reviewer...": "z.B. Sie sind ein Experte f\xFCr Code-Reviews...",
      "System prompt cannot be empty.": "System-Prompt darf nicht leer sein.",
      "Describe when and how this subagent should be used.": "Beschreiben Sie, wann und wie dieser Unteragent verwendet werden soll.",
      "e.g., Reviews code for best practices and potential bugs.": "z.B. \xDCberpr\xFCft Code auf Best Practices und m\xF6gliche Fehler.",
      "Description cannot be empty.": "Beschreibung darf nicht leer sein.",
      "Failed to launch editor: {{error}}": "Fehler beim Starten des Editors: {{error}}",
      "Failed to save and edit subagent: {{error}}": "Fehler beim Speichern und Bearbeiten des Unteragenten: {{error}}",
      // ============================================================================
      // Commands - General (continued)
      // ============================================================================
      "View and edit Qwen Code settings": "Qwen Code Einstellungen anzeigen und bearbeiten",
      Settings: "Einstellungen",
      "To see changes, Qwen Code must be restarted. Press r to exit and apply changes now.": "Um \xC4nderungen zu sehen, muss Qwen Code neu gestartet werden. Dr\xFCcken Sie r, um jetzt zu beenden und \xC4nderungen anzuwenden.",
      'The command "/{{command}}" is not supported in non-interactive mode.': 'Der Befehl "/{{command}}" wird im nicht-interaktiven Modus nicht unterst\xFCtzt.',
      // ============================================================================
      // Settings Labels
      // ============================================================================
      "Vim Mode": "Vim-Modus",
      "Disable Auto Update": "Automatische Updates deaktivieren",
      "Attribution: commit": "Attribution: Commit",
      "Terminal Bell Notification": "Terminal-Signalton",
      "Enable Usage Statistics": "Nutzungsstatistiken aktivieren",
      Theme: "Farbschema",
      "Preferred Editor": "Bevorzugter Editor",
      "Auto-connect to IDE": "Automatische Verbindung zur IDE",
      "Enable Prompt Completion": "Eingabevervollst\xE4ndigung aktivieren",
      "Debug Keystroke Logging": "Debug-Protokollierung von Tastatureingaben",
      "Language: UI": "Sprache: Benutzeroberfl\xE4che",
      "Language: Model": "Sprache: Modell",
      "Output Format": "Ausgabeformat",
      "Hide Window Title": "Fenstertitel ausblenden",
      "Show Status in Title": "Status im Titel anzeigen",
      "Hide Tips": "Tipps ausblenden",
      "Show Line Numbers in Code": "Zeilennummern im Code anzeigen",
      "Show Citations": "Quellenangaben anzeigen",
      "Custom Witty Phrases": "Benutzerdefinierte Witzige Spr\xFCche",
      "Show Welcome Back Dialog": "Willkommen-zur\xFCck-Dialog anzeigen",
      "Enable User Feedback": "Benutzerfeedback aktivieren",
      "How is Qwen doing this session? (optional)": "Wie macht sich Qwen in dieser Sitzung? (optional)",
      Bad: "Schlecht",
      Fine: "In Ordnung",
      Good: "Gut",
      Dismiss: "Ignorieren",
      "Not Sure Yet": "Noch nicht sicher",
      "Any other key": "Beliebige andere Taste",
      "Disable Loading Phrases": "Ladespr\xFCche deaktivieren",
      "Screen Reader Mode": "Bildschirmleser-Modus",
      "IDE Mode": "IDE-Modus",
      "Max Session Turns": "Maximale Sitzungsrunden",
      "Skip Next Speaker Check": "N\xE4chste-Sprecher-Pr\xFCfung \xFCberspringen",
      "Skip Loop Detection": "Schleifenerkennung \xFCberspringen",
      "Skip Startup Context": "Startkontext \xFCberspringen",
      "Enable OpenAI Logging": "OpenAI-Protokollierung aktivieren",
      "OpenAI Logging Directory": "OpenAI-Protokollierungsverzeichnis",
      Timeout: "Zeitlimit",
      "Max Retries": "Maximale Wiederholungen",
      "Disable Cache Control": "Cache-Steuerung deaktivieren",
      "Memory Discovery Max Dirs": "Maximale Verzeichnisse f\xFCr Speichererkennung",
      "Load Memory From Include Directories": "Speicher aus Include-Verzeichnissen laden",
      "Respect .gitignore": ".gitignore beachten",
      "Respect .qwenignore": ".qwenignore beachten",
      "Enable Recursive File Search": "Rekursive Dateisuche aktivieren",
      "Disable Fuzzy Search": "Unscharfe Suche deaktivieren",
      "Interactive Shell (PTY)": "Interaktive Shell (PTY)",
      "Show Color": "Farbe anzeigen",
      "Auto Accept": "Automatisch akzeptieren",
      "Use Ripgrep": "Ripgrep verwenden",
      "Use Builtin Ripgrep": "Integriertes Ripgrep verwenden",
      "Enable Tool Output Truncation": "Werkzeugausgabe-K\xFCrzung aktivieren",
      "Tool Output Truncation Threshold": "Schwellenwert f\xFCr Werkzeugausgabe-K\xFCrzung",
      "Tool Output Truncation Lines": "Zeilen f\xFCr Werkzeugausgabe-K\xFCrzung",
      "Folder Trust": "Ordnervertrauen",
      "Vision Model Preview": "Vision-Modell-Vorschau",
      "Tool Schema Compliance": "Werkzeug-Schema-Konformit\xE4t",
      // Settings enum options
      "Auto (detect from system)": "Automatisch (vom System erkennen)",
      Text: "Text",
      JSON: "JSON",
      Plan: "Plan",
      Default: "Standard",
      "Auto Edit": "Automatisch bearbeiten",
      YOLO: "YOLO",
      "toggle vim mode on/off": "Vim-Modus ein-/ausschalten",
      "check session stats. Usage: /stats [model|tools]": "Sitzungsstatistiken pr\xFCfen. Verwendung: /stats [model|tools]",
      "Show model-specific usage statistics.": "Modellspezifische Nutzungsstatistiken anzeigen.",
      "Show tool-specific usage statistics.": "Werkzeugspezifische Nutzungsstatistiken anzeigen.",
      "exit the cli": "CLI beenden",
      "list configured MCP servers and tools, or authenticate with OAuth-enabled servers": "Konfigurierte MCP-Server und Werkzeuge auflisten oder mit OAuth-f\xE4higen Servern authentifizieren",
      "Manage workspace directories": "Arbeitsbereichsverzeichnisse verwalten",
      "Add directories to the workspace. Use comma to separate multiple paths": "Verzeichnisse zum Arbeitsbereich hinzuf\xFCgen. Komma zum Trennen mehrerer Pfade verwenden",
      "Show all directories in the workspace": "Alle Verzeichnisse im Arbeitsbereich anzeigen",
      "set external editor preference": "Externen Editor festlegen",
      "Select Editor": "Editor ausw\xE4hlen",
      "Editor Preference": "Editor-Einstellung",
      "These editors are currently supported. Please note that some editors cannot be used in sandbox mode.": "Diese Editoren werden derzeit unterst\xFCtzt. Bitte beachten Sie, dass einige Editoren nicht im Sandbox-Modus verwendet werden k\xF6nnen.",
      "Your preferred editor is:": "Ihr bevorzugter Editor ist:",
      "Manage extensions": "Erweiterungen verwalten",
      "List active extensions": "Aktive Erweiterungen auflisten",
      "Update extensions. Usage: update <extension-names>|--all": "Erweiterungen aktualisieren. Verwendung: update <Erweiterungsnamen>|--all",
      "Disable an extension": "Erweiterung deaktivieren",
      "Enable an extension": "Erweiterung aktivieren",
      "Install an extension from a git repo or local path": "Erweiterung aus Git-Repository oder lokalem Pfad installieren",
      "Uninstall an extension": "Erweiterung deinstallieren",
      "No extensions installed.": "Keine Erweiterungen installiert.",
      "Usage: /extensions update <extension-names>|--all": "Verwendung: /extensions update <Erweiterungsnamen>|--all",
      'Extension "{{name}}" not found.': 'Erweiterung "{{name}}" nicht gefunden.',
      "No extensions to update.": "Keine Erweiterungen zum Aktualisieren.",
      "Usage: /extensions install <source>": "Verwendung: /extensions install <Quelle>",
      'Installing extension from "{{source}}"...': 'Installiere Erweiterung von "{{source}}"...',
      'Extension "{{name}}" installed successfully.': 'Erweiterung "{{name}}" erfolgreich installiert.',
      'Failed to install extension from "{{source}}": {{error}}': 'Fehler beim Installieren der Erweiterung von "{{source}}": {{error}}',
      "Usage: /extensions uninstall <extension-name>": "Verwendung: /extensions uninstall <Erweiterungsname>",
      'Uninstalling extension "{{name}}"...': 'Deinstalliere Erweiterung "{{name}}"...',
      'Extension "{{name}}" uninstalled successfully.': 'Erweiterung "{{name}}" erfolgreich deinstalliert.',
      'Failed to uninstall extension "{{name}}": {{error}}': 'Fehler beim Deinstallieren der Erweiterung "{{name}}": {{error}}',
      "Usage: /extensions {{command}} <extension> [--scope=<user|workspace>]": "Verwendung: /extensions {{command}} <Erweiterung> [--scope=<user|workspace>]",
      'Unsupported scope "{{scope}}", should be one of "user" or "workspace"': 'Nicht unterst\xFCtzter Bereich "{{scope}}", sollte "user" oder "workspace" sein',
      'Extension "{{name}}" disabled for scope "{{scope}}"': 'Erweiterung "{{name}}" f\xFCr Bereich "{{scope}}" deaktiviert',
      'Extension "{{name}}" enabled for scope "{{scope}}"': 'Erweiterung "{{name}}" f\xFCr Bereich "{{scope}}" aktiviert',
      "Do you want to continue? [Y/n]: ": "M\xF6chten Sie fortfahren? [Y/n]: ",
      "Do you want to continue?": "M\xF6chten Sie fortfahren?",
      'Installing extension "{{name}}".': 'Erweiterung "{{name}}" wird installiert.',
      "**Extensions may introduce unexpected behavior. Ensure you have investigated the extension source and trust the author.**": "**Erweiterungen k\xF6nnen unerwartetes Verhalten verursachen. Stellen Sie sicher, dass Sie die Erweiterungsquelle untersucht haben und dem Autor vertrauen.**",
      "This extension will run the following MCP servers:": "Diese Erweiterung wird folgende MCP-Server ausf\xFChren:",
      local: "lokal",
      remote: "remote",
      "This extension will add the following commands: {{commands}}.": "Diese Erweiterung wird folgende Befehle hinzuf\xFCgen: {{commands}}.",
      "This extension will append info to your QWEN.md context using {{fileName}}": "Diese Erweiterung wird Informationen zu Ihrem QWEN.md-Kontext mit {{fileName}} hinzuf\xFCgen",
      "This extension will exclude the following core tools: {{tools}}": "Diese Erweiterung wird folgende Kernwerkzeuge ausschlie\xDFen: {{tools}}",
      "This extension will install the following skills:": "Diese Erweiterung wird folgende F\xE4higkeiten installieren:",
      "This extension will install the following subagents:": "Diese Erweiterung wird folgende Unteragenten installieren:",
      'Installation cancelled for "{{name}}".': 'Installation von "{{name}}" abgebrochen.',
      "You are installing an extension from {{originSource}}. Some features may not work perfectly with Qwen Code.": "Sie installieren eine Erweiterung von {{originSource}}. Einige Funktionen funktionieren m\xF6glicherweise nicht perfekt mit Qwen Code.",
      "--ref and --auto-update are not applicable for marketplace extensions.": "--ref und --auto-update sind nicht anwendbar f\xFCr Marketplace-Erweiterungen.",
      'Extension "{{name}}" installed successfully and enabled.': 'Erweiterung "{{name}}" erfolgreich installiert und aktiviert.',
      "Installs an extension from a git repository URL, local path, or claude marketplace (marketplace-url:plugin-name).": "Installiert eine Erweiterung von einer Git-Repository-URL, einem lokalen Pfad oder dem Claude-Marketplace (marketplace-url:plugin-name).",
      "The github URL, local path, or marketplace source (marketplace-url:plugin-name) of the extension to install.": "Die GitHub-URL, der lokale Pfad oder die Marketplace-Quelle (marketplace-url:plugin-name) der zu installierenden Erweiterung.",
      "The git ref to install from.": "Die Git-Referenz f\xFCr die Installation.",
      "Enable auto-update for this extension.": "Automatisches Update f\xFCr diese Erweiterung aktivieren.",
      "Enable pre-release versions for this extension.": "Pre-Release-Versionen f\xFCr diese Erweiterung aktivieren.",
      "Acknowledge the security risks of installing an extension and skip the confirmation prompt.": "Sicherheitsrisiken der Erweiterungsinstallation best\xE4tigen und Best\xE4tigungsaufforderung \xFCberspringen.",
      "The source argument must be provided.": "Das Quellargument muss angegeben werden.",
      'Extension "{{name}}" successfully uninstalled.': 'Erweiterung "{{name}}" erfolgreich deinstalliert.',
      "Uninstalls an extension.": "Deinstalliert eine Erweiterung.",
      "The name or source path of the extension to uninstall.": "Der Name oder Quellpfad der zu deinstallierenden Erweiterung.",
      "Please include the name of the extension to uninstall as a positional argument.": "Bitte geben Sie den Namen der zu deinstallierenden Erweiterung als Positionsargument an.",
      "Enables an extension.": "Aktiviert eine Erweiterung.",
      "The name of the extension to enable.": "Der Name der zu aktivierenden Erweiterung.",
      "The scope to enable the extenison in. If not set, will be enabled in all scopes.": "Der Bereich, in dem die Erweiterung aktiviert werden soll. Wenn nicht gesetzt, wird sie in allen Bereichen aktiviert.",
      'Extension "{{name}}" successfully enabled for scope "{{scope}}".': 'Erweiterung "{{name}}" erfolgreich f\xFCr Bereich "{{scope}}" aktiviert.',
      'Extension "{{name}}" successfully enabled in all scopes.': 'Erweiterung "{{name}}" erfolgreich in allen Bereichen aktiviert.',
      "Invalid scope: {{scope}}. Please use one of {{scopes}}.": "Ung\xFCltiger Bereich: {{scope}}. Bitte verwenden Sie einen von {{scopes}}.",
      "Disables an extension.": "Deaktiviert eine Erweiterung.",
      "The name of the extension to disable.": "Der Name der zu deaktivierenden Erweiterung.",
      "The scope to disable the extenison in.": "Der Bereich, in dem die Erweiterung deaktiviert werden soll.",
      'Extension "{{name}}" successfully disabled for scope "{{scope}}".': 'Erweiterung "{{name}}" erfolgreich f\xFCr Bereich "{{scope}}" deaktiviert.',
      'Extension "{{name}}" successfully updated: {{oldVersion}} \u2192 {{newVersion}}.': 'Erweiterung "{{name}}" erfolgreich aktualisiert: {{oldVersion}} \u2192 {{newVersion}}.',
      'Unable to install extension "{{name}}" due to missing install metadata': 'Erweiterung "{{name}}" kann aufgrund fehlender Installationsmetadaten nicht installiert werden',
      'Extension "{{name}}" is already up to date.': 'Erweiterung "{{name}}" ist bereits aktuell.',
      "Updates all extensions or a named extension to the latest version.": "Aktualisiert alle Erweiterungen oder eine benannte Erweiterung auf die neueste Version.",
      "The name of the extension to update.": "Der Name der zu aktualisierenden Erweiterung.",
      "Update all extensions.": "Alle Erweiterungen aktualisieren.",
      "Either an extension name or --all must be provided": "Entweder ein Erweiterungsname oder --all muss angegeben werden",
      "Lists installed extensions.": "Listet installierte Erweiterungen auf.",
      "Path:": "Pfad:",
      "Source:": "Quelle:",
      "Type:": "Typ:",
      "Ref:": "Ref:",
      "Release tag:": "Release-Tag:",
      "Enabled (User):": "Aktiviert (Benutzer):",
      "Enabled (Workspace):": "Aktiviert (Arbeitsbereich):",
      "Context files:": "Kontextdateien:",
      "Skills:": "Skills:",
      "Agents:": "Agents:",
      "MCP servers:": "MCP-Server:",
      "Link extension failed to install.": "Verkn\xFCpfte Erweiterung konnte nicht installiert werden.",
      'Extension "{{name}}" linked successfully and enabled.': 'Erweiterung "{{name}}" erfolgreich verkn\xFCpft und aktiviert.',
      "Links an extension from a local path. Updates made to the local path will always be reflected.": "Verkn\xFCpft eine Erweiterung von einem lokalen Pfad. \xC4nderungen am lokalen Pfad werden immer widergespiegelt.",
      "The name of the extension to link.": "Der Name der zu verkn\xFCpfenden Erweiterung.",
      "Set a specific setting for an extension.": "Legt eine bestimmte Einstellung f\xFCr eine Erweiterung fest.",
      "Name of the extension to configure.": "Name der zu konfigurierenden Erweiterung.",
      "The setting to configure (name or env var).": "Die zu konfigurierende Einstellung (Name oder Umgebungsvariable).",
      "The scope to set the setting in.": "Der Bereich, in dem die Einstellung gesetzt werden soll.",
      "List all settings for an extension.": "Listet alle Einstellungen einer Erweiterung auf.",
      "Name of the extension.": "Name der Erweiterung.",
      'Extension "{{name}}" has no settings to configure.': 'Erweiterung "{{name}}" hat keine zu konfigurierenden Einstellungen.',
      'Settings for "{{name}}":': 'Einstellungen f\xFCr "{{name}}":',
      "(workspace)": "(Arbeitsbereich)",
      "(user)": "(Benutzer)",
      "[not set]": "[nicht gesetzt]",
      "[value stored in keychain]": "[Wert in Schl\xFCsselbund gespeichert]",
      "Manage extension settings.": "Erweiterungseinstellungen verwalten.",
      "You need to specify a command (set or list).": "Sie m\xFCssen einen Befehl angeben (set oder list).",
      // ============================================================================
      // Plugin Choice / Marketplace
      // ============================================================================
      "No plugins available in this marketplace.": "In diesem Marktplatz sind keine Plugins verf\xFCgbar.",
      'Select a plugin to install from marketplace "{{name}}":': 'W\xE4hlen Sie ein Plugin zur Installation aus Marktplatz "{{name}}":',
      "Plugin selection cancelled.": "Plugin-Auswahl abgebrochen.",
      'Select a plugin from "{{name}}"': 'Plugin aus "{{name}}" ausw\xE4hlen',
      "Use \u2191\u2193 or j/k to navigate, Enter to select, Escape to cancel": "Verwenden Sie \u2191\u2193 oder j/k zum Navigieren, Enter zum Ausw\xE4hlen, Escape zum Abbrechen",
      "{{count}} more above": "{{count}} weitere oben",
      "{{count}} more below": "{{count}} weitere unten",
      "manage IDE integration": "IDE-Integration verwalten",
      "check status of IDE integration": "Status der IDE-Integration pr\xFCfen",
      "install required IDE companion for {{ideName}}": "Erforderlichen IDE-Begleiter f\xFCr {{ideName}} installieren",
      "enable IDE integration": "IDE-Integration aktivieren",
      "disable IDE integration": "IDE-Integration deaktivieren",
      "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.": "IDE-Integration wird in Ihrer aktuellen Umgebung nicht unterst\xFCtzt. Um diese Funktion zu nutzen, f\xFChren Sie Qwen Code in einer dieser unterst\xFCtzten IDEs aus: VS Code oder VS Code-Forks.",
      "Set up GitHub Actions": "GitHub Actions einrichten",
      "Configure terminal keybindings for multiline input (VS Code, Cursor, Windsurf, Trae)": "Terminal-Tastenbelegungen f\xFCr mehrzeilige Eingabe konfigurieren (VS Code, Cursor, Windsurf, Trae)",
      "Please restart your terminal for the changes to take effect.": "Bitte starten Sie Ihr Terminal neu, damit die \xC4nderungen wirksam werden.",
      "Failed to configure terminal: {{error}}": "Fehler beim Konfigurieren des Terminals: {{error}}",
      "Could not determine {{terminalName}} config path on Windows: APPDATA environment variable is not set.": "Konnte {{terminalName}}-Konfigurationspfad unter Windows nicht ermitteln: APPDATA-Umgebungsvariable ist nicht gesetzt.",
      "{{terminalName}} keybindings.json exists but is not a valid JSON array. Please fix the file manually or delete it to allow automatic configuration.": "{{terminalName}} keybindings.json existiert, ist aber kein g\xFCltiges JSON-Array. Bitte korrigieren Sie die Datei manuell oder l\xF6schen Sie sie, um automatische Konfiguration zu erm\xF6glichen.",
      "File: {{file}}": "Datei: {{file}}",
      "Failed to parse {{terminalName}} keybindings.json. The file contains invalid JSON. Please fix the file manually or delete it to allow automatic configuration.": "Fehler beim Parsen von {{terminalName}} keybindings.json. Die Datei enth\xE4lt ung\xFCltiges JSON. Bitte korrigieren Sie die Datei manuell oder l\xF6schen Sie sie, um automatische Konfiguration zu erm\xF6glichen.",
      "Error: {{error}}": "Fehler: {{error}}",
      "Shift+Enter binding already exists": "Umschalt+Enter-Belegung existiert bereits",
      "Ctrl+Enter binding already exists": "Strg+Enter-Belegung existiert bereits",
      "Existing keybindings detected. Will not modify to avoid conflicts.": "Bestehende Tastenbelegungen erkannt. Keine \xC4nderungen, um Konflikte zu vermeiden.",
      "Please check and modify manually if needed: {{file}}": "Bitte pr\xFCfen und bei Bedarf manuell \xE4ndern: {{file}}",
      "Added Shift+Enter and Ctrl+Enter keybindings to {{terminalName}}.": "Umschalt+Enter und Strg+Enter Tastenbelegungen zu {{terminalName}} hinzugef\xFCgt.",
      "Modified: {{file}}": "Ge\xE4ndert: {{file}}",
      "{{terminalName}} keybindings already configured.": "{{terminalName}}-Tastenbelegungen bereits konfiguriert.",
      "Failed to configure {{terminalName}}.": "Fehler beim Konfigurieren von {{terminalName}}.",
      "Your terminal is already configured for an optimal experience with multiline input (Shift+Enter and Ctrl+Enter).": "Ihr Terminal ist bereits f\xFCr optimale Erfahrung mit mehrzeiliger Eingabe konfiguriert (Umschalt+Enter und Strg+Enter).",
      "Could not detect terminal type. Supported terminals: VS Code, Cursor, Windsurf, and Trae.": "Terminal-Typ konnte nicht erkannt werden. Unterst\xFCtzte Terminals: VS Code, Cursor, Windsurf und Trae.",
      'Terminal "{{terminal}}" is not supported yet.': 'Terminal "{{terminal}}" wird noch nicht unterst\xFCtzt.',
      // ============================================================================
      // Commands - Language
      // ============================================================================
      "Invalid language. Available: {{options}}": "Ung\xFCltige Sprache. Verf\xFCgbar: {{options}}",
      "Language subcommands do not accept additional arguments.": "Sprach-Unterbefehle akzeptieren keine zus\xE4tzlichen Argumente.",
      "Current UI language: {{lang}}": "Aktuelle UI-Sprache: {{lang}}",
      "Current LLM output language: {{lang}}": "Aktuelle LLM-Ausgabesprache: {{lang}}",
      "LLM output language not set": "LLM-Ausgabesprache nicht festgelegt",
      "Set UI language": "UI-Sprache festlegen",
      "Set LLM output language": "LLM-Ausgabesprache festlegen",
      "Usage: /language ui [{{options}}]": "Verwendung: /language ui [{{options}}]",
      "Usage: /language output <language>": "Verwendung: /language output <Sprache>",
      "Example: /language output \u4E2D\u6587": "Beispiel: /language output Deutsch",
      "Example: /language output English": "Beispiel: /language output Englisch",
      "Example: /language output \u65E5\u672C\u8A9E": "Beispiel: /language output Japanisch",
      "Example: /language output Portugu\xEAs": "Beispiel: /language output Portugiesisch",
      "UI language changed to {{lang}}": "UI-Sprache ge\xE4ndert zu {{lang}}",
      "LLM output language set to {{lang}}": "LLM-Ausgabesprache auf {{lang}} gesetzt",
      "LLM output language rule file generated at {{path}}": "LLM-Ausgabesprach-Regeldatei generiert unter {{path}}",
      "Please restart the application for the changes to take effect.": "Bitte starten Sie die Anwendung neu, damit die \xC4nderungen wirksam werden.",
      "Failed to generate LLM output language rule file: {{error}}": "Fehler beim Generieren der LLM-Ausgabesprach-Regeldatei: {{error}}",
      "Invalid command. Available subcommands:": "Ung\xFCltiger Befehl. Verf\xFCgbare Unterbefehle:",
      "Available subcommands:": "Verf\xFCgbare Unterbefehle:",
      "To request additional UI language packs, please open an issue on GitHub.": "Um zus\xE4tzliche UI-Sprachpakete anzufordern, \xF6ffnen Sie bitte ein Issue auf GitHub.",
      "Available options:": "Verf\xFCgbare Optionen:",
      "Set UI language to {{name}}": "UI-Sprache auf {{name}} setzen",
      // ============================================================================
      // Commands - Approval Mode
      // ============================================================================
      "Tool Approval Mode": "Werkzeug-Genehmigungsmodus",
      "Current approval mode: {{mode}}": "Aktueller Genehmigungsmodus: {{mode}}",
      "Available approval modes:": "Verf\xFCgbare Genehmigungsmodi:",
      "Approval mode changed to: {{mode}}": "Genehmigungsmodus ge\xE4ndert zu: {{mode}}",
      "Approval mode changed to: {{mode}} (saved to {{scope}} settings{{location}})": "Genehmigungsmodus ge\xE4ndert zu: {{mode}} (gespeichert in {{scope}} Einstellungen{{location}})",
      "Usage: /approval-mode <mode> [--session|--user|--project]": "Verwendung: /approval-mode <Modus> [--session|--user|--project]",
      "Scope subcommands do not accept additional arguments.": "Bereichs-Unterbefehle akzeptieren keine zus\xE4tzlichen Argumente.",
      "Plan mode - Analyze only, do not modify files or execute commands": "Planungsmodus - Nur analysieren, keine Dateien \xE4ndern oder Befehle ausf\xFChren",
      "Default mode - Require approval for file edits or shell commands": "Standardmodus - Genehmigung f\xFCr Dateibearbeitungen oder Shell-Befehle erforderlich",
      "Auto-edit mode - Automatically approve file edits": "Automatischer Bearbeitungsmodus - Dateibearbeitungen automatisch genehmigen",
      "YOLO mode - Automatically approve all tools": "YOLO-Modus - Alle Werkzeuge automatisch genehmigen",
      "{{mode}} mode": "{{mode}}-Modus",
      "Settings service is not available; unable to persist the approval mode.": "Einstellungsdienst nicht verf\xFCgbar; Genehmigungsmodus kann nicht gespeichert werden.",
      "Failed to save approval mode: {{error}}": "Fehler beim Speichern des Genehmigungsmodus: {{error}}",
      "Failed to change approval mode: {{error}}": "Fehler beim \xC4ndern des Genehmigungsmodus: {{error}}",
      "Apply to current session only (temporary)": "Nur auf aktuelle Sitzung anwenden (tempor\xE4r)",
      "Persist for this project/workspace": "F\xFCr dieses Projekt/Arbeitsbereich speichern",
      "Persist for this user on this machine": "F\xFCr diesen Benutzer auf diesem Computer speichern",
      "Analyze only, do not modify files or execute commands": "Nur analysieren, keine Dateien \xE4ndern oder Befehle ausf\xFChren",
      "Require approval for file edits or shell commands": "Genehmigung f\xFCr Dateibearbeitungen oder Shell-Befehle erforderlich",
      "Automatically approve file edits": "Dateibearbeitungen automatisch genehmigen",
      "Automatically approve all tools": "Alle Werkzeuge automatisch genehmigen",
      "Workspace approval mode exists and takes priority. User-level change will have no effect.": "Arbeitsbereich-Genehmigungsmodus existiert und hat Vorrang. Benutzerebene-\xC4nderung hat keine Wirkung.",
      "Apply To": "Anwenden auf",
      "User Settings": "Benutzereinstellungen",
      "Workspace Settings": "Arbeitsbereich-Einstellungen",
      // ============================================================================
      // Commands - Memory
      // ============================================================================
      "Commands for interacting with memory.": "Befehle f\xFCr die Interaktion mit dem Speicher.",
      "Show the current memory contents.": "Aktuellen Speicherinhalt anzeigen.",
      "Show project-level memory contents.": "Projektebene-Speicherinhalt anzeigen.",
      "Show global memory contents.": "Globalen Speicherinhalt anzeigen.",
      "Add content to project-level memory.": "Inhalt zum Projektebene-Speicher hinzuf\xFCgen.",
      "Add content to global memory.": "Inhalt zum globalen Speicher hinzuf\xFCgen.",
      "Refresh the memory from the source.": "Speicher aus der Quelle aktualisieren.",
      "Usage: /memory add --project <text to remember>": "Verwendung: /memory add --project <zu merkender Text>",
      "Usage: /memory add --global <text to remember>": "Verwendung: /memory add --global <zu merkender Text>",
      'Attempting to save to project memory: "{{text}}"': 'Versuche im Projektspeicher zu speichern: "{{text}}"',
      'Attempting to save to global memory: "{{text}}"': 'Versuche im globalen Speicher zu speichern: "{{text}}"',
      "Current memory content from {{count}} file(s):": "Aktueller Speicherinhalt aus {{count}} Datei(en):",
      "Memory is currently empty.": "Speicher ist derzeit leer.",
      "Project memory file not found or is currently empty.": "Projektspeicherdatei nicht gefunden oder derzeit leer.",
      "Global memory file not found or is currently empty.": "Globale Speicherdatei nicht gefunden oder derzeit leer.",
      "Global memory is currently empty.": "Globaler Speicher ist derzeit leer.",
      "Global memory content:\n\n---\n{{content}}\n---": "Globaler Speicherinhalt:\n\n---\n{{content}}\n---",
      "Project memory content from {{path}}:\n\n---\n{{content}}\n---": "Projektspeicherinhalt von {{path}}:\n\n---\n{{content}}\n---",
      "Project memory is currently empty.": "Projektspeicher ist derzeit leer.",
      "Refreshing memory from source files...": "Speicher wird aus Quelldateien aktualisiert...",
      "Add content to the memory. Use --global for global memory or --project for project memory.": "Inhalt zum Speicher hinzuf\xFCgen. --global f\xFCr globalen Speicher oder --project f\xFCr Projektspeicher verwenden.",
      "Usage: /memory add [--global|--project] <text to remember>": "Verwendung: /memory add [--global|--project] <zu merkender Text>",
      'Attempting to save to memory {{scope}}: "{{fact}}"': 'Versuche im Speicher {{scope}} zu speichern: "{{fact}}"',
      // ============================================================================
      // Commands - MCP
      // ============================================================================
      "Authenticate with an OAuth-enabled MCP server": "Mit einem OAuth-f\xE4higen MCP-Server authentifizieren",
      "List configured MCP servers and tools": "Konfigurierte MCP-Server und Werkzeuge auflisten",
      "Restarts MCP servers.": "MCP-Server neu starten.",
      "Config not loaded.": "Konfiguration nicht geladen.",
      "Could not retrieve tool registry.": "Werkzeugregister konnte nicht abgerufen werden.",
      "No MCP servers configured with OAuth authentication.": "Keine MCP-Server mit OAuth-Authentifizierung konfiguriert.",
      "MCP servers with OAuth authentication:": "MCP-Server mit OAuth-Authentifizierung:",
      "Use /mcp auth <server-name> to authenticate.": "Verwenden Sie /mcp auth <Servername> zur Authentifizierung.",
      "MCP server '{{name}}' not found.": "MCP-Server '{{name}}' nicht gefunden.",
      "Successfully authenticated and refreshed tools for '{{name}}'.": "Erfolgreich authentifiziert und Werkzeuge f\xFCr '{{name}}' aktualisiert.",
      "Failed to authenticate with MCP server '{{name}}': {{error}}": "Authentifizierung mit MCP-Server '{{name}}' fehlgeschlagen: {{error}}",
      "Re-discovering tools from '{{name}}'...": "Werkzeuge von '{{name}}' werden neu erkannt...",
      // ============================================================================
      // Commands - Chat
      // ============================================================================
      "Manage conversation history.": "Gespr\xE4chsverlauf verwalten.",
      "List saved conversation checkpoints": "Gespeicherte Gespr\xE4chspr\xFCfpunkte auflisten",
      "No saved conversation checkpoints found.": "Keine gespeicherten Gespr\xE4chspr\xFCfpunkte gefunden.",
      "List of saved conversations:": "Liste gespeicherter Gespr\xE4che:",
      "Note: Newest last, oldest first": "Hinweis: Neueste zuletzt, \xE4lteste zuerst",
      "Save the current conversation as a checkpoint. Usage: /chat save <tag>": "Aktuelles Gespr\xE4ch als Pr\xFCfpunkt speichern. Verwendung: /chat save <Tag>",
      "Missing tag. Usage: /chat save <tag>": "Tag fehlt. Verwendung: /chat save <Tag>",
      "Delete a conversation checkpoint. Usage: /chat delete <tag>": "Gespr\xE4chspr\xFCfpunkt l\xF6schen. Verwendung: /chat delete <Tag>",
      "Missing tag. Usage: /chat delete <tag>": "Tag fehlt. Verwendung: /chat delete <Tag>",
      "Conversation checkpoint '{{tag}}' has been deleted.": "Gespr\xE4chspr\xFCfpunkt '{{tag}}' wurde gel\xF6scht.",
      "Error: No checkpoint found with tag '{{tag}}'.": "Fehler: Kein Pr\xFCfpunkt mit Tag '{{tag}}' gefunden.",
      "Resume a conversation from a checkpoint. Usage: /chat resume <tag>": "Gespr\xE4ch von einem Pr\xFCfpunkt fortsetzen. Verwendung: /chat resume <Tag>",
      "Missing tag. Usage: /chat resume <tag>": "Tag fehlt. Verwendung: /chat resume <Tag>",
      "No saved checkpoint found with tag: {{tag}}.": "Kein gespeicherter Pr\xFCfpunkt mit Tag gefunden: {{tag}}.",
      "A checkpoint with the tag {{tag}} already exists. Do you want to overwrite it?": "Ein Pr\xFCfpunkt mit dem Tag {{tag}} existiert bereits. M\xF6chten Sie ihn \xFCberschreiben?",
      "No chat client available to save conversation.": "Kein Chat-Client verf\xFCgbar, um Gespr\xE4ch zu speichern.",
      "Conversation checkpoint saved with tag: {{tag}}.": "Gespr\xE4chspr\xFCfpunkt gespeichert mit Tag: {{tag}}.",
      "No conversation found to save.": "Kein Gespr\xE4ch zum Speichern gefunden.",
      "No chat client available to share conversation.": "Kein Chat-Client verf\xFCgbar, um Gespr\xE4ch zu teilen.",
      "Invalid file format. Only .md and .json are supported.": "Ung\xFCltiges Dateiformat. Nur .md und .json werden unterst\xFCtzt.",
      "Error sharing conversation: {{error}}": "Fehler beim Teilen des Gespr\xE4chs: {{error}}",
      "Conversation shared to {{filePath}}": "Gespr\xE4ch geteilt nach {{filePath}}",
      "No conversation found to share.": "Kein Gespr\xE4ch zum Teilen gefunden.",
      "Share the current conversation to a markdown or json file. Usage: /chat share <file>": "Aktuelles Gespr\xE4ch in eine Markdown- oder JSON-Datei teilen. Verwendung: /chat share <Datei>",
      // ============================================================================
      // Commands - Summary
      // ============================================================================
      "Generate a project summary and save it to .qwen/PROJECT_SUMMARY.md": "Projektzusammenfassung generieren und in .qwen/PROJECT_SUMMARY.md speichern",
      "No chat client available to generate summary.": "Kein Chat-Client verf\xFCgbar, um Zusammenfassung zu generieren.",
      "Already generating summary, wait for previous request to complete": "Zusammenfassung wird bereits generiert, warten Sie auf Abschluss der vorherigen Anfrage",
      "No conversation found to summarize.": "Kein Gespr\xE4ch zum Zusammenfassen gefunden.",
      "Failed to generate project context summary: {{error}}": "Fehler beim Generieren der Projektkontextzusammenfassung: {{error}}",
      "Saved project summary to {{filePathForDisplay}}.": "Projektzusammenfassung gespeichert unter {{filePathForDisplay}}.",
      "Saving project summary...": "Projektzusammenfassung wird gespeichert...",
      "Generating project summary...": "Projektzusammenfassung wird generiert...",
      "Failed to generate summary - no text content received from LLM response": "Fehler beim Generieren der Zusammenfassung - kein Textinhalt von LLM-Antwort erhalten",
      // ============================================================================
      // Commands - Model
      // ============================================================================
      "Switch the model for this session": "Modell f\xFCr diese Sitzung wechseln",
      "Content generator configuration not available.": "Inhaltsgenerator-Konfiguration nicht verf\xFCgbar.",
      "Authentication type not available.": "Authentifizierungstyp nicht verf\xFCgbar.",
      "No models available for the current authentication type ({{authType}}).": "Keine Modelle f\xFCr den aktuellen Authentifizierungstyp ({{authType}}) verf\xFCgbar.",
      // ============================================================================
      // Commands - Clear
      // ============================================================================
      "Starting a new session, resetting chat, and clearing terminal.": "Neue Sitzung wird gestartet, Chat wird zur\xFCckgesetzt und Terminal wird gel\xF6scht.",
      "Starting a new session and clearing.": "Neue Sitzung wird gestartet und gel\xF6scht.",
      // ============================================================================
      // Commands - Compress
      // ============================================================================
      "Already compressing, wait for previous request to complete": "Komprimierung l\xE4uft bereits, warten Sie auf Abschluss der vorherigen Anfrage",
      "Failed to compress chat history.": "Fehler beim Komprimieren des Chatverlaufs.",
      "Failed to compress chat history: {{error}}": "Fehler beim Komprimieren des Chatverlaufs: {{error}}",
      "Compressing chat history": "Chatverlauf wird komprimiert",
      "Chat history compressed from {{originalTokens}} to {{newTokens}} tokens.": "Chatverlauf komprimiert von {{originalTokens}} auf {{newTokens}} Token.",
      "Compression was not beneficial for this history size.": "Komprimierung war f\xFCr diese Verlaufsgr\xF6\xDFe nicht vorteilhaft.",
      "Chat history compression did not reduce size. This may indicate issues with the compression prompt.": "Chatverlauf-Komprimierung hat die Gr\xF6\xDFe nicht reduziert. Dies kann auf Probleme mit dem Komprimierungs-Prompt hindeuten.",
      "Could not compress chat history due to a token counting error.": "Chatverlauf konnte aufgrund eines Token-Z\xE4hlfehlers nicht komprimiert werden.",
      "Chat history is already compressed.": "Chatverlauf ist bereits komprimiert.",
      // ============================================================================
      // Commands - Directory
      // ============================================================================
      "Configuration is not available.": "Konfiguration ist nicht verf\xFCgbar.",
      "Please provide at least one path to add.": "Bitte geben Sie mindestens einen Pfad zum Hinzuf\xFCgen an.",
      "The /directory add command is not supported in restrictive sandbox profiles. Please use --include-directories when starting the session instead.": "Der Befehl /directory add wird in restriktiven Sandbox-Profilen nicht unterst\xFCtzt. Bitte verwenden Sie --include-directories beim Starten der Sitzung.",
      "Error adding '{{path}}': {{error}}": "Fehler beim Hinzuf\xFCgen von '{{path}}': {{error}}",
      "Successfully added QWEN.md files from the following directories if there are:\n- {{directories}}": "QWEN.md-Dateien aus folgenden Verzeichnissen erfolgreich hinzugef\xFCgt, falls vorhanden:\n- {{directories}}",
      "Error refreshing memory: {{error}}": "Fehler beim Aktualisieren des Speichers: {{error}}",
      "Successfully added directories:\n- {{directories}}": "Verzeichnisse erfolgreich hinzugef\xFCgt:\n- {{directories}}",
      "Current workspace directories:\n{{directories}}": "Aktuelle Arbeitsbereichsverzeichnisse:\n{{directories}}",
      // ============================================================================
      // Commands - Docs
      // ============================================================================
      "Please open the following URL in your browser to view the documentation:\n{{url}}": "Bitte \xF6ffnen Sie folgende URL in Ihrem Browser, um die Dokumentation anzusehen:\n{{url}}",
      "Opening documentation in your browser: {{url}}": "Dokumentation wird in Ihrem Browser ge\xF6ffnet: {{url}}",
      // ============================================================================
      // Dialogs - Tool Confirmation
      // ============================================================================
      "Do you want to proceed?": "M\xF6chten Sie fortfahren?",
      "Yes, allow once": "Ja, einmal erlauben",
      "Allow always": "Immer erlauben",
      No: "Nein",
      "No (esc)": "Nein (Esc)",
      "Yes, allow always for this session": "Ja, f\xFCr diese Sitzung immer erlauben",
      "Modify in progress:": "\xC4nderung in Bearbeitung:",
      "Save and close external editor to continue": "Speichern und externen Editor schlie\xDFen, um fortzufahren",
      "Apply this change?": "Diese \xC4nderung anwenden?",
      "Yes, allow always": "Ja, immer erlauben",
      "Modify with external editor": "Mit externem Editor bearbeiten",
      "No, suggest changes (esc)": "Nein, \xC4nderungen vorschlagen (Esc)",
      "Allow execution of: '{{command}}'?": "Ausf\xFChrung erlauben von: '{{command}}'?",
      "Yes, allow always ...": "Ja, immer erlauben ...",
      "Yes, and auto-accept edits": "Ja, und \xC4nderungen automatisch akzeptieren",
      "Yes, and manually approve edits": "Ja, und \xC4nderungen manuell genehmigen",
      "No, keep planning (esc)": "Nein, weiter planen (Esc)",
      "URLs to fetch:": "Abzurufende URLs:",
      "MCP Server: {{server}}": "MCP-Server: {{server}}",
      "Tool: {{tool}}": "Werkzeug: {{tool}}",
      'Allow execution of MCP tool "{{tool}}" from server "{{server}}"?': 'Ausf\xFChrung des MCP-Werkzeugs "{{tool}}" von Server "{{server}}" erlauben?',
      'Yes, always allow tool "{{tool}}" from server "{{server}}"': 'Ja, Werkzeug "{{tool}}" von Server "{{server}}" immer erlauben',
      'Yes, always allow all tools from server "{{server}}"': 'Ja, alle Werkzeuge von Server "{{server}}" immer erlauben',
      // ============================================================================
      // Dialogs - Shell Confirmation
      // ============================================================================
      "Shell Command Execution": "Shell-Befehlsausf\xFChrung",
      "A custom command wants to run the following shell commands:": "Ein benutzerdefinierter Befehl m\xF6chte folgende Shell-Befehle ausf\xFChren:",
      // ============================================================================
      // Dialogs - Pro Quota
      // ============================================================================
      "Pro quota limit reached for {{model}}.": "Pro-Kontingentlimit f\xFCr {{model}} erreicht.",
      "Change auth (executes the /auth command)": "Authentifizierung \xE4ndern (f\xFChrt den /auth-Befehl aus)",
      "Continue with {{model}}": "Mit {{model}} fortfahren",
      // ============================================================================
      // Dialogs - Welcome Back
      // ============================================================================
      "Current Plan:": "Aktueller Plan:",
      "Progress: {{done}}/{{total}} tasks completed": "Fortschritt: {{done}}/{{total}} Aufgaben abgeschlossen",
      ", {{inProgress}} in progress": ", {{inProgress}} in Bearbeitung",
      "Pending Tasks:": "Ausstehende Aufgaben:",
      "What would you like to do?": "Was m\xF6chten Sie tun?",
      "Choose how to proceed with your session:": "W\xE4hlen Sie, wie Sie mit Ihrer Sitzung fortfahren m\xF6chten:",
      "Start new chat session": "Neue Chat-Sitzung starten",
      "Continue previous conversation": "Vorheriges Gespr\xE4ch fortsetzen",
      "\u{1F44B} Welcome back! (Last updated: {{timeAgo}})": "\u{1F44B} Willkommen zur\xFCck! (Zuletzt aktualisiert: {{timeAgo}})",
      "\u{1F3AF} Overall Goal:": "\u{1F3AF} Gesamtziel:",
      // ============================================================================
      // Dialogs - Auth
      // ============================================================================
      "Get started": "Loslegen",
      "How would you like to authenticate for this project?": "Wie m\xF6chten Sie sich f\xFCr dieses Projekt authentifizieren?",
      "OpenAI API key is required to use OpenAI authentication.": "OpenAI API-Schl\xFCssel ist f\xFCr die OpenAI-Authentifizierung erforderlich.",
      "You must select an auth method to proceed. Press Ctrl+C again to exit.": "Sie m\xFCssen eine Authentifizierungsmethode w\xE4hlen, um fortzufahren. Dr\xFCcken Sie erneut Strg+C zum Beenden.",
      "(Use Enter to Set Auth)": "(Enter zum Festlegen der Authentifizierung)",
      "Terms of Services and Privacy Notice for Qwen Code": "Nutzungsbedingungen und Datenschutzhinweis f\xFCr Qwen Code",
      "Qwen OAuth": "Qwen OAuth",
      "Login with QwenChat account to use daily free quota.": "Melden Sie sich mit Ihrem QwenChat-Konto an, um das t\xE4gliche kostenlose Kontingent zu nutzen.",
      "API-KEY": "API-KEY",
      "Use coding plan credentials or your own api-keys/providers.": "Verwenden Sie Coding Plan-Anmeldedaten oder Ihre eigenen API-Schl\xFCssel/Anbieter.",
      OpenAI: "OpenAI",
      "Failed to login. Message: {{message}}": "Anmeldung fehlgeschlagen. Meldung: {{message}}",
      "Authentication is enforced to be {{enforcedType}}, but you are currently using {{currentType}}.": "Authentifizierung ist auf {{enforcedType}} festgelegt, aber Sie verwenden derzeit {{currentType}}.",
      "Qwen OAuth authentication timed out. Please try again.": "Qwen OAuth-Authentifizierung abgelaufen. Bitte versuchen Sie es erneut.",
      "Qwen OAuth authentication cancelled.": "Qwen OAuth-Authentifizierung abgebrochen.",
      "Qwen OAuth Authentication": "Qwen OAuth-Authentifizierung",
      "Please visit this URL to authorize:": "Bitte besuchen Sie diese URL zur Autorisierung:",
      "Or scan the QR code below:": "Oder scannen Sie den QR-Code unten:",
      "Waiting for authorization": "Warten auf Autorisierung",
      "Time remaining:": "Verbleibende Zeit:",
      "(Press ESC or CTRL+C to cancel)": "(ESC oder STRG+C zum Abbrechen dr\xFCcken)",
      "Qwen OAuth Authentication Timeout": "Qwen OAuth-Authentifizierung abgelaufen",
      "OAuth token expired (over {{seconds}} seconds). Please select authentication method again.": "OAuth-Token abgelaufen (\xFCber {{seconds}} Sekunden). Bitte w\xE4hlen Sie erneut eine Authentifizierungsmethode.",
      "Press any key to return to authentication type selection.": "Dr\xFCcken Sie eine beliebige Taste, um zur Authentifizierungstypauswahl zur\xFCckzukehren.",
      "Waiting for Qwen OAuth authentication...": "Warten auf Qwen OAuth-Authentifizierung...",
      "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.": "Hinweis: Ihr bestehender API-Schl\xFCssel in settings.json wird bei Verwendung von Qwen OAuth nicht gel\xF6scht. Sie k\xF6nnen sp\xE4ter bei Bedarf zur OpenAI-Authentifizierung zur\xFCckwechseln.",
      "Authentication timed out. Please try again.": "Authentifizierung abgelaufen. Bitte versuchen Sie es erneut.",
      "Waiting for auth... (Press ESC or CTRL+C to cancel)": "Warten auf Authentifizierung... (ESC oder STRG+C zum Abbrechen dr\xFCcken)",
      "Missing API key for OpenAI-compatible auth. Set settings.security.auth.apiKey, or set the {{envKeyHint}} environment variable.": "API-Schl\xFCssel f\xFCr OpenAI-kompatible Authentifizierung fehlt. Setzen Sie settings.security.auth.apiKey oder die Umgebungsvariable {{envKeyHint}}.",
      "{{envKeyHint}} environment variable not found.": "Umgebungsvariable {{envKeyHint}} wurde nicht gefunden.",
      "{{envKeyHint}} environment variable not found. Please set it in your .env file or environment variables.": "Umgebungsvariable {{envKeyHint}} wurde nicht gefunden. Bitte legen Sie sie in Ihrer .env-Datei oder den Systemumgebungsvariablen fest.",
      "{{envKeyHint}} environment variable not found (or set settings.security.auth.apiKey). Please set it in your .env file or environment variables.": "Umgebungsvariable {{envKeyHint}} wurde nicht gefunden (oder setzen Sie settings.security.auth.apiKey). Bitte legen Sie sie in Ihrer .env-Datei oder den Systemumgebungsvariablen fest.",
      "Missing API key for OpenAI-compatible auth. Set the {{envKeyHint}} environment variable.": "API-Schl\xFCssel f\xFCr OpenAI-kompatible Authentifizierung fehlt. Setzen Sie die Umgebungsvariable {{envKeyHint}}.",
      "Anthropic provider missing required baseUrl in modelProviders[].baseUrl.": "Anthropic-Anbieter fehlt erforderliche baseUrl in modelProviders[].baseUrl.",
      "ANTHROPIC_BASE_URL environment variable not found.": "Umgebungsvariable ANTHROPIC_BASE_URL wurde nicht gefunden.",
      "Invalid auth method selected.": "Ung\xFCltige Authentifizierungsmethode ausgew\xE4hlt.",
      "Failed to authenticate. Message: {{message}}": "Authentifizierung fehlgeschlagen. Meldung: {{message}}",
      "Authenticated successfully with {{authType}} credentials.": "Erfolgreich mit {{authType}}-Anmeldedaten authentifiziert.",
      'Invalid QWEN_DEFAULT_AUTH_TYPE value: "{{value}}". Valid values are: {{validValues}}': 'Ung\xFCltiger QWEN_DEFAULT_AUTH_TYPE-Wert: "{{value}}". G\xFCltige Werte sind: {{validValues}}',
      "OpenAI Configuration Required": "OpenAI-Konfiguration erforderlich",
      "Please enter your OpenAI configuration. You can get an API key from": "Bitte geben Sie Ihre OpenAI-Konfiguration ein. Sie k\xF6nnen einen API-Schl\xFCssel erhalten von",
      "API Key:": "API-Schl\xFCssel:",
      "Invalid credentials: {{errorMessage}}": "Ung\xFCltige Anmeldedaten: {{errorMessage}}",
      "Failed to validate credentials": "Anmeldedaten konnten nicht validiert werden",
      "Press Enter to continue, Tab/\u2191\u2193 to navigate, Esc to cancel": "Enter zum Fortfahren, Tab/\u2191\u2193 zum Navigieren, Esc zum Abbrechen",
      // ============================================================================
      // Dialogs - Model
      // ============================================================================
      "Select Model": "Modell ausw\xE4hlen",
      "(Press Esc to close)": "(Esc zum Schlie\xDFen dr\xFCcken)",
      "Current (effective) configuration": "Aktuelle (wirksame) Konfiguration",
      AuthType: "Authentifizierungstyp",
      "API Key": "API-Schl\xFCssel",
      unset: "nicht gesetzt",
      "(default)": "(Standard)",
      "(set)": "(gesetzt)",
      "(not set)": "(nicht gesetzt)",
      "Failed to switch model to '{{modelId}}'.\n\n{{error}}": "Modell konnte nicht auf '{{modelId}}' umgestellt werden.\n\n{{error}}",
      "Qwen 3.5 Plus \u2014 efficient hybrid model with leading coding performance": "Qwen 3.5 Plus \u2014 effizientes Hybridmodell mit f\xFChrender Programmierleistung",
      "The latest Qwen Vision model from Alibaba Cloud ModelStudio (version: qwen3-vl-plus-2025-09-23)": "Das neueste Qwen Vision Modell von Alibaba Cloud ModelStudio (Version: qwen3-vl-plus-2025-09-23)",
      // ============================================================================
      // Dialogs - Permissions
      // ============================================================================
      "Manage folder trust settings": "Ordnervertrauenseinstellungen verwalten",
      // ============================================================================
      // Status Bar
      // ============================================================================
      "Using:": "Verwendet:",
      "{{count}} open file": "{{count}} ge\xF6ffnete Datei",
      "{{count}} open files": "{{count}} ge\xF6ffnete Dateien",
      "(ctrl+g to view)": "(Strg+G zum Anzeigen)",
      "{{count}} {{name}} file": "{{count}} {{name}}-Datei",
      "{{count}} {{name}} files": "{{count}} {{name}}-Dateien",
      "{{count}} MCP server": "{{count}} MCP-Server",
      "{{count}} MCP servers": "{{count}} MCP-Server",
      "{{count}} Blocked": "{{count}} blockiert",
      "(ctrl+t to view)": "(Strg+T zum Anzeigen)",
      "(ctrl+t to toggle)": "(Strg+T zum Umschalten)",
      "Press Ctrl+C again to exit.": "Dr\xFCcken Sie erneut Strg+C zum Beenden.",
      "Press Ctrl+D again to exit.": "Dr\xFCcken Sie erneut Strg+D zum Beenden.",
      "Press Esc again to clear.": "Dr\xFCcken Sie erneut Esc zum L\xF6schen.",
      // ============================================================================
      // MCP Status
      // ============================================================================
      "No MCP servers configured.": "Keine MCP-Server konfiguriert.",
      "\u23F3 MCP servers are starting up ({{count}} initializing)...": "\u23F3 MCP-Server werden gestartet ({{count}} werden initialisiert)...",
      "Note: First startup may take longer. Tool availability will update automatically.": "Hinweis: Der erste Start kann l\xE4nger dauern. Werkzeugverf\xFCgbarkeit wird automatisch aktualisiert.",
      "Configured MCP servers:": "Konfigurierte MCP-Server:",
      Ready: "Bereit",
      "Starting... (first startup may take longer)": "Wird gestartet... (erster Start kann l\xE4nger dauern)",
      Disconnected: "Getrennt",
      "{{count}} tool": "{{count}} Werkzeug",
      "{{count}} tools": "{{count}} Werkzeuge",
      "{{count}} prompt": "{{count}} Prompt",
      "{{count}} prompts": "{{count}} Prompts",
      "(from {{extensionName}})": "(von {{extensionName}})",
      OAuth: "OAuth",
      "OAuth expired": "OAuth abgelaufen",
      "OAuth not authenticated": "OAuth nicht authentifiziert",
      "tools and prompts will appear when ready": "Werkzeuge und Prompts werden angezeigt, wenn bereit",
      "{{count}} tools cached": "{{count}} Werkzeuge zwischengespeichert",
      "Tools:": "Werkzeuge:",
      "Parameters:": "Parameter:",
      "Prompts:": "Prompts:",
      Blocked: "Blockiert",
      "\u{1F4A1} Tips:": "\u{1F4A1} Tipps:",
      Use: "Verwenden",
      "to show server and tool descriptions": "um Server- und Werkzeugbeschreibungen anzuzeigen",
      "to show tool parameter schemas": "um Werkzeug-Parameter-Schemas anzuzeigen",
      "to hide descriptions": "um Beschreibungen auszublenden",
      "to authenticate with OAuth-enabled servers": "um sich bei OAuth-f\xE4higen Servern zu authentifizieren",
      Press: "Dr\xFCcken Sie",
      "to toggle tool descriptions on/off": "um Werkzeugbeschreibungen ein-/auszuschalten",
      "Starting OAuth authentication for MCP server '{{name}}'...": "OAuth-Authentifizierung f\xFCr MCP-Server '{{name}}' wird gestartet...",
      "Restarting MCP servers...": "MCP-Server werden neu gestartet...",
      // ============================================================================
      // Startup Tips
      // ============================================================================
      "Tips for getting started:": "Tipps zum Einstieg:",
      "1. Ask questions, edit files, or run commands.": "1. Stellen Sie Fragen, bearbeiten Sie Dateien oder f\xFChren Sie Befehle aus.",
      "2. Be specific for the best results.": "2. Seien Sie spezifisch f\xFCr die besten Ergebnisse.",
      "files to customize your interactions with Qwen Code.": "Dateien, um Ihre Interaktionen mit Qwen Code anzupassen.",
      "for more information.": "f\xFCr weitere Informationen.",
      // ============================================================================
      // Exit Screen / Stats
      // ============================================================================
      "Agent powering down. Goodbye!": "Agent wird heruntergefahren. Auf Wiedersehen!",
      "To continue this session, run": "Um diese Sitzung fortzusetzen, f\xFChren Sie aus",
      "Interaction Summary": "Interaktionszusammenfassung",
      "Session ID:": "Sitzungs-ID:",
      "Tool Calls:": "Werkzeugaufrufe:",
      "Success Rate:": "Erfolgsrate:",
      "User Agreement:": "Benutzerzustimmung:",
      reviewed: "\xFCberpr\xFCft",
      "Code Changes:": "Code\xE4nderungen:",
      Performance: "Leistung",
      "Wall Time:": "Gesamtzeit:",
      "Agent Active:": "Agent aktiv:",
      "API Time:": "API-Zeit:",
      "Tool Time:": "Werkzeugzeit:",
      "Session Stats": "Sitzungsstatistiken",
      "Model Usage": "Modellnutzung",
      Reqs: "Anfragen",
      "Input Tokens": "Eingabe-Token",
      "Output Tokens": "Ausgabe-Token",
      "Savings Highlight:": "Einsparungen:",
      "of input tokens were served from the cache, reducing costs.": "der Eingabe-Token wurden aus dem Cache bedient, was die Kosten reduziert.",
      "Tip: For a full token breakdown, run `/stats model`.": "Tipp: F\xFCr eine vollst\xE4ndige Token-Aufschl\xFCsselung f\xFChren Sie `/stats model` aus.",
      "Model Stats For Nerds": "Modellstatistiken f\xFCr Nerds",
      "Tool Stats For Nerds": "Werkzeugstatistiken f\xFCr Nerds",
      Metric: "Metrik",
      API: "API",
      Requests: "Anfragen",
      Errors: "Fehler",
      "Avg Latency": "Durchschn. Latenz",
      Tokens: "Token",
      Total: "Gesamt",
      Prompt: "Prompt",
      Cached: "Zwischengespeichert",
      Thoughts: "Gedanken",
      Tool: "Werkzeug",
      Output: "Ausgabe",
      "No API calls have been made in this session.": "In dieser Sitzung wurden keine API-Aufrufe gemacht.",
      "Tool Name": "Werkzeugname",
      Calls: "Aufrufe",
      "Success Rate": "Erfolgsrate",
      "Avg Duration": "Durchschn. Dauer",
      "User Decision Summary": "Benutzerentscheidungs-Zusammenfassung",
      "Total Reviewed Suggestions:": "Insgesamt \xFCberpr\xFCfter Vorschl\xE4ge:",
      " \xBB Accepted:": " \xBB Akzeptiert:",
      " \xBB Rejected:": " \xBB Abgelehnt:",
      " \xBB Modified:": " \xBB Ge\xE4ndert:",
      " Overall Agreement Rate:": " Gesamtzustimmungsrate:",
      "No tool calls have been made in this session.": "In dieser Sitzung wurden keine Werkzeugaufrufe gemacht.",
      "Session start time is unavailable, cannot calculate stats.": "Sitzungsstartzeit nicht verf\xFCgbar, Statistiken k\xF6nnen nicht berechnet werden.",
      // ============================================================================
      // Command Format Migration
      // ============================================================================
      "Command Format Migration": "Befehlsformat-Migration",
      "Found {{count}} TOML command file:": "{{count}} TOML-Befehlsdatei gefunden:",
      "Found {{count}} TOML command files:": "{{count}} TOML-Befehlsdateien gefunden:",
      "... and {{count}} more": "... und {{count}} weitere",
      "The TOML format is deprecated. Would you like to migrate them to Markdown format?": "Das TOML-Format ist veraltet. M\xF6chten Sie sie ins Markdown-Format migrieren?",
      "(Backups will be created and original files will be preserved)": "(Backups werden erstellt und Originaldateien werden beibehalten)",
      // ============================================================================
      // Loading Phrases
      // ============================================================================
      "Waiting for user confirmation...": "Warten auf Benutzerbest\xE4tigung...",
      "(esc to cancel, {{time}})": "(Esc zum Abbrechen, {{time}})",
      // ============================================================================
      // Loading Phrases
      // ============================================================================
      WITTY_LOADING_PHRASES: [
        "Auf gut Gl\xFCck!",
        "Genialit\xE4t wird ausgeliefert...",
        "Die Serifen werden aufgemalt...",
        "Durch den Schleimpilz navigieren...",
        "Die digitalen Geister werden befragt...",
        "Splines werden retikuliert...",
        "Die KI-Hamster werden aufgew\xE4rmt...",
        "Die Zaubermuschel wird befragt...",
        "Witzige Erwiderung wird generiert...",
        "Die Algorithmen werden poliert...",
        "Perfektion braucht Zeit (mein Code auch)...",
        "Frische Bytes werden gebr\xFCht...",
        "Elektronen werden gez\xE4hlt...",
        "Kognitive Prozessoren werden aktiviert...",
        "Auf Syntaxfehler im Universum wird gepr\xFCft...",
        "Einen Moment, Humor wird optimiert...",
        "Pointen werden gemischt...",
        "Neuronale Netze werden entwirrt...",
        "Brillanz wird kompiliert...",
        "wit.exe wird geladen...",
        "Die Wolke der Weisheit wird beschworen...",
        "Eine witzige Antwort wird vorbereitet...",
        "Einen Moment, ich debugge die Realit\xE4t...",
        "Die Optionen werden verwirrt...",
        "Kosmische Frequenzen werden eingestellt...",
        "Eine Antwort wird erstellt, die Ihrer Geduld w\xFCrdig ist...",
        "Die Einsen und Nullen werden kompiliert...",
        "Abh\xE4ngigkeiten werden aufgel\xF6st... und existenzielle Krisen...",
        "Erinnerungen werden defragmentiert... sowohl RAM als auch pers\xF6nliche...",
        "Das Humor-Modul wird neu gestartet...",
        "Das Wesentliche wird zwischengespeichert (haupts\xE4chlich Katzen-Memes)...",
        "F\xFCr l\xE4cherliche Geschwindigkeit wird optimiert",
        "Bits werden getauscht... sagen Sie es nicht den Bytes...",
        "Garbage Collection l\xE4uft... bin gleich zur\xFCck...",
        "Das Internet wird zusammengebaut...",
        "Kaffee wird in Code umgewandelt...",
        "Die Syntax der Realit\xE4t wird aktualisiert...",
        "Die Synapsen werden neu verdrahtet...",
        "Ein verlegtes Semikolon wird gesucht...",
        "Die Zahnr\xE4der werden geschmiert...",
        "Die Server werden vorgeheizt...",
        "Der Fluxkompensator wird kalibriert...",
        "Der Unwahrscheinlichkeitsantrieb wird aktiviert...",
        "Die Macht wird kanalisiert...",
        "Die Sterne werden f\xFCr optimale Antwort ausgerichtet...",
        "So sagen wir alle...",
        "Die n\xE4chste gro\xDFe Idee wird geladen...",
        "Einen Moment, ich bin in der Zone...",
        "Bereite mich vor, Sie mit Brillanz zu blenden...",
        "Einen Augenblick, ich poliere meinen Witz...",
        "Halten Sie durch, ich erschaffe ein Meisterwerk...",
        "Einen Moment, ich debugge das Universum...",
        "Einen Moment, ich richte die Pixel aus...",
        "Einen Moment, ich optimiere den Humor...",
        "Einen Moment, ich tune die Algorithmen...",
        "Warp-Geschwindigkeit aktiviert...",
        "Mehr Dilithium-Kristalle werden gesucht...",
        "Keine Panik...",
        "Dem wei\xDFen Kaninchen wird gefolgt...",
        "Die Wahrheit ist hier drin... irgendwo...",
        "Auf die Kassette wird gepustet...",
        "Ladevorgang... Machen Sie eine Fassrolle!",
        "Auf den Respawn wird gewartet...",
        "Der Kessel-Flug wird in weniger als 12 Parsec beendet...",
        "Der Kuchen ist keine L\xFCge, er l\xE4dt nur noch...",
        "Am Charaktererstellungsbildschirm wird herumgefummelt...",
        "Einen Moment, ich suche das richtige Meme...",
        "'A' wird zum Fortfahren gedr\xFCckt...",
        "Digitale Katzen werden geh\xFCtet...",
        "Die Pixel werden poliert...",
        "Ein passender Ladebildschirm-Witz wird gesucht...",
        "Ich lenke Sie mit diesem witzigen Spruch ab...",
        "Fast da... wahrscheinlich...",
        "Unsere Hamster arbeiten so schnell sie k\xF6nnen...",
        "Cloudy wird am Kopf gestreichelt...",
        "Die Katze wird gestreichelt...",
        "Meinen Chef rickrollen...",
        "Never gonna give you up, never gonna let you down...",
        "Auf den Bass wird geschlagen...",
        "Die Schnozbeeren werden probiert...",
        "I'm going the distance, I'm going for speed...",
        "Ist dies das wahre Leben? Ist dies nur Fantasie?...",
        "Ich habe ein gutes Gef\xFChl dabei...",
        "Den B\xE4ren wird gestupst...",
        "Recherche zu den neuesten Memes...",
        "\xDCberlege, wie ich das witziger machen kann...",
        "Hmmm... lassen Sie mich nachdenken...",
        "Wie nennt man einen Fisch ohne Augen? Ein Fsh...",
        "Warum ging der Computer zur Therapie? Er hatte zu viele Bytes...",
        "Warum m\xF6gen Programmierer keine Natur? Sie hat zu viele Bugs...",
        "Warum bevorzugen Programmierer den Dunkelmodus? Weil Licht Bugs anzieht...",
        "Warum ging der Entwickler pleite? Er hat seinen ganzen Cache aufgebraucht...",
        "Was kann man mit einem kaputten Bleistift machen? Nichts, er ist sinnlos...",
        "Perkussive Wartung wird angewendet...",
        "Die richtige USB-Ausrichtung wird gesucht...",
        "Es wird sichergestellt, dass der magische Rauch in den Kabeln bleibt...",
        "Versuche Vim zu beenden...",
        "Das Hamsterrad wird angeworfen...",
        "Das ist kein Bug, das ist ein undokumentiertes Feature...",
        "Engage.",
        "Ich komme wieder... mit einer Antwort.",
        "Mein anderer Prozess ist eine TARDIS...",
        "Mit dem Maschinengeist wird kommuniziert...",
        "Die Gedanken marinieren lassen...",
        "Gerade erinnert, wo ich meine Schl\xFCssel hingelegt habe...",
        "\xDCber die Kugel wird nachgedacht...",
        "Ich habe Dinge gesehen, die Sie nicht glauben w\xFCrden... wie einen Benutzer, der Lademeldungen liest.",
        "Nachdenklicher Blick wird initiiert...",
        "Was ist der Lieblingssnack eines Computers? Mikrochips.",
        "Warum tragen Java-Entwickler Brillen? Weil sie nicht C#.",
        "Der Laser wird aufgeladen... pew pew!",
        "Durch Null wird geteilt... nur Spa\xDF!",
        "Suche nach einem erwachsenen Aufseh... ich meine, Verarbeitung.",
        "Es piept und boopt.",
        "Pufferung... weil auch KIs einen Moment brauchen.",
        "Quantenteilchen werden f\xFCr schnellere Antwort verschr\xE4nkt...",
        "Das Chrom wird poliert... an den Algorithmen.",
        "Sind Sie nicht unterhalten? (Arbeite daran!)",
        "Die Code-Gremlins werden beschworen... zum Helfen, nat\xFCrlich.",
        "Warte nur auf das Einwahlton-Ende...",
        "Das Humor-O-Meter wird neu kalibriert.",
        "Mein anderer Ladebildschirm ist noch lustiger.",
        "Ziemlich sicher, dass irgendwo eine Katze \xFCber die Tastatur l\xE4uft...",
        "Verbessern... Verbessern... L\xE4dt noch.",
        "Das ist kein Bug, das ist ein Feature... dieses Ladebildschirms.",
        "Haben Sie versucht, es aus- und wieder einzuschalten? (Den Ladebildschirm, nicht mich.)",
        "Zus\xE4tzliche Pylonen werden gebaut..."
      ],
      // ============================================================================
      // Extension Settings Input
      // ============================================================================
      "Enter value...": "Wert eingeben...",
      "Enter sensitive value...": "Sensiblen Wert eingeben...",
      "Press Enter to submit, Escape to cancel": "Enter zum Absenden, Escape zum Abbrechen dr\xFCcken",
      // ============================================================================
      // Command Migration Tool
      // ============================================================================
      "Markdown file already exists: {{filename}}": "Markdown-Datei existiert bereits: {{filename}}",
      "TOML Command Format Deprecation Notice": "TOML-Befehlsformat Veraltet-Hinweis",
      "Found {{count}} command file(s) in TOML format:": "{{count}} Befehlsdatei(en) im TOML-Format gefunden:",
      "The TOML format for commands is being deprecated in favor of Markdown format.": "Das TOML-Format f\xFCr Befehle wird zugunsten des Markdown-Formats eingestellt.",
      "Markdown format is more readable and easier to edit.": "Das Markdown-Format ist lesbarer und einfacher zu bearbeiten.",
      "You can migrate these files automatically using:": "Sie k\xF6nnen diese Dateien automatisch migrieren mit:",
      "Or manually convert each file:": "Oder jede Datei manuell konvertieren:",
      'TOML: prompt = "..." / description = "..."': 'TOML: prompt = "..." / description = "..."',
      "Markdown: YAML frontmatter + content": "Markdown: YAML-Frontmatter + Inhalt",
      "The migration tool will:": "Das Migrationstool wird:",
      "Convert TOML files to Markdown": "TOML-Dateien in Markdown konvertieren",
      "Create backups of original files": "Sicherungen der Originaldateien erstellen",
      "Preserve all command functionality": "Alle Befehlsfunktionen beibehalten",
      "TOML format will continue to work for now, but migration is recommended.": "Das TOML-Format funktioniert vorerst weiter, aber eine Migration wird empfohlen.",
      // ============================================================================
      // Extensions - Explore Command
      // ============================================================================
      "Open extensions page in your browser": "Erweiterungsseite im Browser \xF6ffnen",
      "Unknown extensions source: {{source}}.": "Unbekannte Erweiterungsquelle: {{source}}.",
      "Would open extensions page in your browser: {{url}} (skipped in test environment)": "W\xFCrde Erweiterungsseite im Browser \xF6ffnen: {{url}} (\xFCbersprungen in Testumgebung)",
      "View available extensions at {{url}}": "Verf\xFCgbare Erweiterungen ansehen unter {{url}}",
      "Opening extensions page in your browser: {{url}}": "Erweiterungsseite wird im Browser ge\xF6ffnet: {{url}}",
      "Failed to open browser. Check out the extensions gallery at {{url}}": "Browser konnte nicht ge\xF6ffnet werden. Besuchen Sie die Erweiterungsgalerie unter {{url}}",
      "Use /compress when the conversation gets long to summarize history and free up context.": "Verwenden Sie /compress, wenn die Unterhaltung lang wird, um den Verlauf zusammenzufassen und Kontext freizugeben.",
      "Start a fresh idea with /clear or /new; the previous session stays available in history.": "Starten Sie eine neue Idee mit /clear oder /new; die vorherige Sitzung bleibt im Verlauf verf\xFCgbar.",
      "Use /bug to submit issues to the maintainers when something goes off.": "Verwenden Sie /bug, um Probleme an die Betreuer zu melden, wenn etwas schiefgeht.",
      "Switch auth type quickly with /auth.": "Wechseln Sie den Authentifizierungstyp schnell mit /auth.",
      "You can run any shell commands from Qwen Code using ! (e.g. !ls).": "Sie k\xF6nnen beliebige Shell-Befehle in Qwen Code mit ! ausf\xFChren (z. B. !ls).",
      "Type / to open the command popup; Tab autocompletes slash commands and saved prompts.": "Geben Sie / ein, um das Befehlsmen\xFC zu \xF6ffnen; Tab vervollst\xE4ndigt Slash-Befehle und gespeicherte Prompts.",
      "You can resume a previous conversation by running qwen --continue or qwen --resume.": "Sie k\xF6nnen eine fr\xFChere Unterhaltung mit qwen --continue oder qwen --resume fortsetzen.",
      "You can switch permission mode quickly with Shift+Tab or /approval-mode.": "Sie k\xF6nnen den Berechtigungsmodus schnell mit Shift+Tab oder /approval-mode wechseln.",
      "You can switch permission mode quickly with Tab or /approval-mode.": "Sie k\xF6nnen den Berechtigungsmodus schnell mit Tab oder /approval-mode wechseln.",
      "Try /insight to generate personalized insights from your chat history.": "Probieren Sie /insight, um personalisierte Erkenntnisse aus Ihrem Chatverlauf zu erstellen.",
      // ============================================================================
      // Custom API-KEY Configuration
      // ============================================================================
      "For advanced users who want to configure models manually.": "F\xFCr fortgeschrittene Benutzer, die Modelle manuell konfigurieren m\xF6chten.",
      "Please configure your models in settings.json:": "Bitte konfigurieren Sie Ihre Modelle in settings.json:",
      "Set API key via environment variable (e.g., OPENAI_API_KEY)": "API-Schl\xFCssel \xFCber Umgebungsvariable setzen (z.B. OPENAI_API_KEY)",
      "Add model configuration to modelProviders['openai'] (or other auth types)": "Modellkonfiguration zu modelProviders['openai'] (oder anderen Authentifizierungstypen) hinzuf\xFCgen",
      "Each provider needs: id, envKey (required), plus optional baseUrl, generationConfig": "Jeder Anbieter ben\xF6tigt: id, envKey (erforderlich), plus optionale baseUrl, generationConfig",
      "Use /model command to select your preferred model from the configured list": "Verwenden Sie den /model-Befehl, um Ihr bevorzugtes Modell aus der konfigurierten Liste auszuw\xE4hlen",
      "Supported auth types: openai, anthropic, gemini, vertex-ai, etc.": "Unterst\xFCtzte Authentifizierungstypen: openai, anthropic, gemini, vertex-ai, usw.",
      // ============================================================================
      // Coding Plan Authentication
      // ============================================================================
      "Please enter your API key:": "Bitte geben Sie Ihren API-Schl\xFCssel ein:",
      "API key cannot be empty.": "API-Schl\xFCssel darf nicht leer sein.",
      "You can get your exclusive Coding Plan API-KEY here:": "Hier k\xF6nnen Sie Ihren exklusiven Coding Plan API-KEY erhalten:",
      "New model configurations are available for Bailian Coding Plan. Update now?": "Neue Modellkonfigurationen sind f\xFCr Bailian Coding Plan verf\xFCgbar. Jetzt aktualisieren?",
      "Coding Plan configuration updated successfully. New models are now available.": "Coding Plan-Konfiguration erfolgreich aktualisiert. Neue Modelle sind jetzt verf\xFCgbar.",
      "Coding Plan API key not found. Please re-authenticate with Coding Plan.": "Coding Plan API-Schl\xFCssel nicht gefunden. Bitte authentifizieren Sie sich erneut mit Coding Plan.",
      "Failed to update Coding Plan configuration: {{message}}": "Fehler beim Aktualisieren der Coding Plan-Konfiguration: {{message}}",
      // ============================================================================
      // Auth Dialog - View Titles and Labels
      // ============================================================================
      "Coding Plan": "Coding Plan",
      "Coding Plan (Bailian, China)": "Coding Plan (Bailian, China)",
      "Coding Plan (Bailian, Global/Intl)": "Coding Plan (Bailian, Global/Intl)",
      "Paste your api key of Bailian Coding Plan and you're all set!": "F\xFCgen Sie Ihren Bailian Coding Plan API-Schl\xFCssel ein und Sie sind bereit!",
      "Paste your api key of Coding Plan (Bailian, Global/Intl) and you're all set!": "F\xFCgen Sie Ihren Coding Plan (Bailian, Global/Intl) API-Schl\xFCssel ein und Sie sind bereit!",
      Custom: "Benutzerdefiniert",
      "More instructions about configuring `modelProviders` manually.": "Weitere Anweisungen zur manuellen Konfiguration von `modelProviders`.",
      "Select API-KEY configuration mode:": "API-KEY-Konfigurationsmodus ausw\xE4hlen:",
      "(Press Escape to go back)": "(Escape dr\xFCcken zum Zur\xFCckgehen)",
      "(Press Enter to submit, Escape to cancel)": "(Enter zum Absenden, Escape zum Abbrechen)",
      "More instructions please check:": "Weitere Anweisungen finden Sie unter:",
      // ============================================================================
      // Coding Plan International Updates
      // ============================================================================
      "New model configurations are available for {{region}}. Update now?": "Neue Modellkonfigurationen sind f\xFCr {{region}} verf\xFCgbar. Jetzt aktualisieren?",
      "New model configurations are available for Bailian Coding Plan (China). Update now?": "Neue Modellkonfigurationen sind f\xFCr Bailian Coding Plan (China) verf\xFCgbar. Jetzt aktualisieren?",
      "New model configurations are available for Coding Plan (Bailian, Global/Intl). Update now?": "Neue Modellkonfigurationen sind f\xFCr Coding Plan (Bailian, Global/Intl) verf\xFCgbar. Jetzt aktualisieren?",
      '{{region}} configuration updated successfully. Model switched to "{{model}}".': '{{region}}-Konfiguration erfolgreich aktualisiert. Modell auf "{{model}}" umgeschaltet.',
      "Authenticated successfully with {{region}}. API key and model configs saved to settings.json (backed up).": "Erfolgreich mit {{region}} authentifiziert. API-Schl\xFCssel und Modellkonfigurationen wurden in settings.json gespeichert (gesichert)."
    };
  }
});

// packages/cli/src/i18n/locales/en.js
var en_exports = {};
__export(en_exports, {
  default: () => en_default3
});
var en_default3;
var init_en3 = __esm({
  "packages/cli/src/i18n/locales/en.js"() {
    "use strict";
    init_esbuild_shims();
    en_default3 = {
      // ============================================================================
      // Help / UI Components
      // ============================================================================
      // Attachment hints
      "\u2191 to manage attachments": "\u2191 to manage attachments",
      "\u2190 \u2192 select, Delete to remove, \u2193 to exit": "\u2190 \u2192 select, Delete to remove, \u2193 to exit",
      "Attachments: ": "Attachments: ",
      "Basics:": "Basics:",
      "Add context": "Add context",
      "Use {{symbol}} to specify files for context (e.g., {{example}}) to target specific files or folders.": "Use {{symbol}} to specify files for context (e.g., {{example}}) to target specific files or folders.",
      "@": "@",
      "@src/myFile.ts": "@src/myFile.ts",
      "Shell mode": "Shell mode",
      "YOLO mode": "YOLO mode",
      "plan mode": "plan mode",
      "auto-accept edits": "auto-accept edits",
      "Accepting edits": "Accepting edits",
      "(shift + tab to cycle)": "(shift + tab to cycle)",
      "(tab to cycle)": "(tab to cycle)",
      "Execute shell commands via {{symbol}} (e.g., {{example1}}) or use natural language (e.g., {{example2}}).": "Execute shell commands via {{symbol}} (e.g., {{example1}}) or use natural language (e.g., {{example2}}).",
      "!": "!",
      "!npm run start": "!npm run start",
      "start server": "start server",
      "Commands:": "Commands:",
      "shell command": "shell command",
      "Model Context Protocol command (from external servers)": "Model Context Protocol command (from external servers)",
      "Keyboard Shortcuts:": "Keyboard Shortcuts:",
      "Toggle this help display": "Toggle this help display",
      "Toggle shell mode": "Toggle shell mode",
      "Open command menu": "Open command menu",
      "Add file context": "Add file context",
      "Accept suggestion / Autocomplete": "Accept suggestion / Autocomplete",
      "Reverse search history": "Reverse search history",
      "Press ? again to close": "Press ? again to close",
      // Keyboard shortcuts panel descriptions
      "for shell mode": "for shell mode",
      "for commands": "for commands",
      "for file paths": "for file paths",
      "to clear input": "to clear input",
      "to cycle approvals": "to cycle approvals",
      "to quit": "to quit",
      "for newline": "for newline",
      "to clear screen": "to clear screen",
      "to search history": "to search history",
      "to paste images": "to paste images",
      "for external editor": "for external editor",
      "Jump through words in the input": "Jump through words in the input",
      "Close dialogs, cancel requests, or quit application": "Close dialogs, cancel requests, or quit application",
      "New line": "New line",
      "New line (Alt+Enter works for certain linux distros)": "New line (Alt+Enter works for certain linux distros)",
      "Clear the screen": "Clear the screen",
      "Open input in external editor": "Open input in external editor",
      "Send message": "Send message",
      "Initializing...": "Initializing...",
      "Connecting to MCP servers... ({{connected}}/{{total}})": "Connecting to MCP servers... ({{connected}}/{{total}})",
      "Type your message or @path/to/file": "Type your message or @path/to/file",
      "? for shortcuts": "? for shortcuts",
      "Press 'i' for INSERT mode and 'Esc' for NORMAL mode.": "Press 'i' for INSERT mode and 'Esc' for NORMAL mode.",
      "Cancel operation / Clear input (double press)": "Cancel operation / Clear input (double press)",
      "Cycle approval modes": "Cycle approval modes",
      "Cycle through your prompt history": "Cycle through your prompt history",
      "For a full list of shortcuts, see {{docPath}}": "For a full list of shortcuts, see {{docPath}}",
      "docs/keyboard-shortcuts.md": "docs/keyboard-shortcuts.md",
      "for help on Qwen Code": "for help on Qwen Code",
      "show version info": "show version info",
      "submit a bug report": "submit a bug report",
      "About Qwen Code": "About Qwen Code",
      Status: "Status",
      // ============================================================================
      // System Information Fields
      // ============================================================================
      "Qwen Code": "Qwen Code",
      Runtime: "Runtime",
      OS: "OS",
      Auth: "Auth",
      "CLI Version": "CLI Version",
      "Git Commit": "Git Commit",
      Model: "Model",
      Sandbox: "Sandbox",
      "OS Platform": "OS Platform",
      "OS Arch": "OS Arch",
      "OS Release": "OS Release",
      "Node.js Version": "Node.js Version",
      "NPM Version": "NPM Version",
      "Session ID": "Session ID",
      "Auth Method": "Auth Method",
      "Base URL": "Base URL",
      Proxy: "Proxy",
      "Memory Usage": "Memory Usage",
      "IDE Client": "IDE Client",
      // ============================================================================
      // Commands - General
      // ============================================================================
      "Analyzes the project and creates a tailored QWEN.md file.": "Analyzes the project and creates a tailored QWEN.md file.",
      "list available Qwen Code tools. Usage: /tools [desc]": "list available Qwen Code tools. Usage: /tools [desc]",
      "Available Qwen Code CLI tools:": "Available Qwen Code CLI tools:",
      "No tools available": "No tools available",
      "View or change the approval mode for tool usage": "View or change the approval mode for tool usage",
      'Invalid approval mode "{{arg}}". Valid modes: {{modes}}': 'Invalid approval mode "{{arg}}". Valid modes: {{modes}}',
      'Approval mode set to "{{mode}}"': 'Approval mode set to "{{mode}}"',
      "View or change the language setting": "View or change the language setting",
      "change the theme": "change the theme",
      "Select Theme": "Select Theme",
      Preview: "Preview",
      "(Use Enter to select, Tab to configure scope)": "(Use Enter to select, Tab to configure scope)",
      "(Use Enter to apply scope, Tab to go back)": "(Use Enter to apply scope, Tab to go back)",
      "Theme configuration unavailable due to NO_COLOR env variable.": "Theme configuration unavailable due to NO_COLOR env variable.",
      'Theme "{{themeName}}" not found.': 'Theme "{{themeName}}" not found.',
      'Theme "{{themeName}}" not found in selected scope.': 'Theme "{{themeName}}" not found in selected scope.',
      "Clear conversation history and free up context": "Clear conversation history and free up context",
      "Compresses the context by replacing it with a summary.": "Compresses the context by replacing it with a summary.",
      "open full Qwen Code documentation in your browser": "open full Qwen Code documentation in your browser",
      "Configuration not available.": "Configuration not available.",
      "change the auth method": "change the auth method",
      "Configure authentication information for login": "Configure authentication information for login",
      "Copy the last result or code snippet to clipboard": "Copy the last result or code snippet to clipboard",
      // ============================================================================
      // Commands - Agents
      // ============================================================================
      "Manage subagents for specialized task delegation.": "Manage subagents for specialized task delegation.",
      "Manage existing subagents (view, edit, delete).": "Manage existing subagents (view, edit, delete).",
      "Create a new subagent with guided setup.": "Create a new subagent with guided setup.",
      // ============================================================================
      // Agents - Management Dialog
      // ============================================================================
      Agents: "Agents",
      "Choose Action": "Choose Action",
      "Edit {{name}}": "Edit {{name}}",
      "Edit Tools: {{name}}": "Edit Tools: {{name}}",
      "Edit Color: {{name}}": "Edit Color: {{name}}",
      "Delete {{name}}": "Delete {{name}}",
      "Unknown Step": "Unknown Step",
      "Esc to close": "Esc to close",
      "Enter to select, \u2191\u2193 to navigate, Esc to close": "Enter to select, \u2191\u2193 to navigate, Esc to close",
      "Esc to go back": "Esc to go back",
      "Enter to confirm, Esc to cancel": "Enter to confirm, Esc to cancel",
      "Enter to select, \u2191\u2193 to navigate, Esc to go back": "Enter to select, \u2191\u2193 to navigate, Esc to go back",
      "Invalid step: {{step}}": "Invalid step: {{step}}",
      "No subagents found.": "No subagents found.",
      "Use '/agents create' to create your first subagent.": "Use '/agents create' to create your first subagent.",
      "(built-in)": "(built-in)",
      "(overridden by project level agent)": "(overridden by project level agent)",
      "Project Level ({{path}})": "Project Level ({{path}})",
      "User Level ({{path}})": "User Level ({{path}})",
      "Built-in Agents": "Built-in Agents",
      "Extension Agents": "Extension Agents",
      "Using: {{count}} agents": "Using: {{count}} agents",
      "View Agent": "View Agent",
      "Edit Agent": "Edit Agent",
      "Delete Agent": "Delete Agent",
      Back: "Back",
      "No agent selected": "No agent selected",
      "File Path: ": "File Path: ",
      "Tools: ": "Tools: ",
      "Color: ": "Color: ",
      "Description:": "Description:",
      "System Prompt:": "System Prompt:",
      "Open in editor": "Open in editor",
      "Edit tools": "Edit tools",
      "Edit color": "Edit color",
      "\u274C Error:": "\u274C Error:",
      'Are you sure you want to delete agent "{{name}}"?': 'Are you sure you want to delete agent "{{name}}"?',
      // ============================================================================
      // Agents - Creation Wizard
      // ============================================================================
      "Project Level (.qwen/agents/)": "Project Level (.qwen/agents/)",
      "User Level (~/.qwen/agents/)": "User Level (~/.qwen/agents/)",
      "\u2705 Subagent Created Successfully!": "\u2705 Subagent Created Successfully!",
      'Subagent "{{name}}" has been saved to {{level}} level.': 'Subagent "{{name}}" has been saved to {{level}} level.',
      "Name: ": "Name: ",
      "Location: ": "Location: ",
      "\u274C Error saving subagent:": "\u274C Error saving subagent:",
      "Warnings:": "Warnings:",
      'Name "{{name}}" already exists at {{level}} level - will overwrite existing subagent': 'Name "{{name}}" already exists at {{level}} level - will overwrite existing subagent',
      'Name "{{name}}" exists at user level - project level will take precedence': 'Name "{{name}}" exists at user level - project level will take precedence',
      'Name "{{name}}" exists at project level - existing subagent will take precedence': 'Name "{{name}}" exists at project level - existing subagent will take precedence',
      "Description is over {{length}} characters": "Description is over {{length}} characters",
      "System prompt is over {{length}} characters": "System prompt is over {{length}} characters",
      // Agents - Creation Wizard Steps
      "Step {{n}}: Choose Location": "Step {{n}}: Choose Location",
      "Step {{n}}: Choose Generation Method": "Step {{n}}: Choose Generation Method",
      "Generate with Qwen Code (Recommended)": "Generate with Qwen Code (Recommended)",
      "Manual Creation": "Manual Creation",
      "Describe what this subagent should do and when it should be used. (Be comprehensive for best results)": "Describe what this subagent should do and when it should be used. (Be comprehensive for best results)",
      "e.g., Expert code reviewer that reviews code based on best practices...": "e.g., Expert code reviewer that reviews code based on best practices...",
      "Generating subagent configuration...": "Generating subagent configuration...",
      "Failed to generate subagent: {{error}}": "Failed to generate subagent: {{error}}",
      "Step {{n}}: Describe Your Subagent": "Step {{n}}: Describe Your Subagent",
      "Step {{n}}: Enter Subagent Name": "Step {{n}}: Enter Subagent Name",
      "Step {{n}}: Enter System Prompt": "Step {{n}}: Enter System Prompt",
      "Step {{n}}: Enter Description": "Step {{n}}: Enter Description",
      // Agents - Tool Selection
      "Step {{n}}: Select Tools": "Step {{n}}: Select Tools",
      "All Tools (Default)": "All Tools (Default)",
      "All Tools": "All Tools",
      "Read-only Tools": "Read-only Tools",
      "Read & Edit Tools": "Read & Edit Tools",
      "Read & Edit & Execution Tools": "Read & Edit & Execution Tools",
      "All tools selected, including MCP tools": "All tools selected, including MCP tools",
      "Selected tools:": "Selected tools:",
      "Read-only tools:": "Read-only tools:",
      "Edit tools:": "Edit tools:",
      "Execution tools:": "Execution tools:",
      "Step {{n}}: Choose Background Color": "Step {{n}}: Choose Background Color",
      "Step {{n}}: Confirm and Save": "Step {{n}}: Confirm and Save",
      // Agents - Navigation & Instructions
      "Esc to cancel": "Esc to cancel",
      "Press Enter to save, e to save and edit, Esc to go back": "Press Enter to save, e to save and edit, Esc to go back",
      "Press Enter to continue, {{navigation}}Esc to {{action}}": "Press Enter to continue, {{navigation}}Esc to {{action}}",
      cancel: "cancel",
      "go back": "go back",
      "\u2191\u2193 to navigate, ": "\u2191\u2193 to navigate, ",
      "Enter a clear, unique name for this subagent.": "Enter a clear, unique name for this subagent.",
      "e.g., Code Reviewer": "e.g., Code Reviewer",
      "Name cannot be empty.": "Name cannot be empty.",
      "Write the system prompt that defines this subagent's behavior. Be comprehensive for best results.": "Write the system prompt that defines this subagent's behavior. Be comprehensive for best results.",
      "e.g., You are an expert code reviewer...": "e.g., You are an expert code reviewer...",
      "System prompt cannot be empty.": "System prompt cannot be empty.",
      "Describe when and how this subagent should be used.": "Describe when and how this subagent should be used.",
      "e.g., Reviews code for best practices and potential bugs.": "e.g., Reviews code for best practices and potential bugs.",
      "Description cannot be empty.": "Description cannot be empty.",
      "Failed to launch editor: {{error}}": "Failed to launch editor: {{error}}",
      "Failed to save and edit subagent: {{error}}": "Failed to save and edit subagent: {{error}}",
      // ============================================================================
      // Commands - General (continued)
      // ============================================================================
      "View and edit Qwen Code settings": "View and edit Qwen Code settings",
      Settings: "Settings",
      "To see changes, Qwen Code must be restarted. Press r to exit and apply changes now.": "To see changes, Qwen Code must be restarted. Press r to exit and apply changes now.",
      'The command "/{{command}}" is not supported in non-interactive mode.': 'The command "/{{command}}" is not supported in non-interactive mode.',
      // ============================================================================
      // Settings Labels
      // ============================================================================
      "Vim Mode": "Vim Mode",
      "Disable Auto Update": "Disable Auto Update",
      "Attribution: commit": "Attribution: commit",
      "Terminal Bell Notification": "Terminal Bell Notification",
      "Enable Usage Statistics": "Enable Usage Statistics",
      Theme: "Theme",
      "Preferred Editor": "Preferred Editor",
      "Auto-connect to IDE": "Auto-connect to IDE",
      "Enable Prompt Completion": "Enable Prompt Completion",
      "Debug Keystroke Logging": "Debug Keystroke Logging",
      "Language: UI": "Language: UI",
      "Language: Model": "Language: Model",
      "Output Format": "Output Format",
      "Hide Window Title": "Hide Window Title",
      "Show Status in Title": "Show Status in Title",
      "Hide Tips": "Hide Tips",
      "Show Line Numbers in Code": "Show Line Numbers in Code",
      "Show Citations": "Show Citations",
      "Custom Witty Phrases": "Custom Witty Phrases",
      "Show Welcome Back Dialog": "Show Welcome Back Dialog",
      "Enable User Feedback": "Enable User Feedback",
      "How is Qwen doing this session? (optional)": "How is Qwen doing this session? (optional)",
      Bad: "Bad",
      Fine: "Fine",
      Good: "Good",
      Dismiss: "Dismiss",
      "Not Sure Yet": "Not Sure Yet",
      "Any other key": "Any other key",
      "Disable Loading Phrases": "Disable Loading Phrases",
      "Screen Reader Mode": "Screen Reader Mode",
      "IDE Mode": "IDE Mode",
      "Max Session Turns": "Max Session Turns",
      "Skip Next Speaker Check": "Skip Next Speaker Check",
      "Skip Loop Detection": "Skip Loop Detection",
      "Skip Startup Context": "Skip Startup Context",
      "Enable OpenAI Logging": "Enable OpenAI Logging",
      "OpenAI Logging Directory": "OpenAI Logging Directory",
      Timeout: "Timeout",
      "Max Retries": "Max Retries",
      "Disable Cache Control": "Disable Cache Control",
      "Memory Discovery Max Dirs": "Memory Discovery Max Dirs",
      "Load Memory From Include Directories": "Load Memory From Include Directories",
      "Respect .gitignore": "Respect .gitignore",
      "Respect .qwenignore": "Respect .qwenignore",
      "Enable Recursive File Search": "Enable Recursive File Search",
      "Disable Fuzzy Search": "Disable Fuzzy Search",
      "Interactive Shell (PTY)": "Interactive Shell (PTY)",
      "Show Color": "Show Color",
      "Auto Accept": "Auto Accept",
      "Use Ripgrep": "Use Ripgrep",
      "Use Builtin Ripgrep": "Use Builtin Ripgrep",
      "Enable Tool Output Truncation": "Enable Tool Output Truncation",
      "Tool Output Truncation Threshold": "Tool Output Truncation Threshold",
      "Tool Output Truncation Lines": "Tool Output Truncation Lines",
      "Folder Trust": "Folder Trust",
      "Vision Model Preview": "Vision Model Preview",
      "Tool Schema Compliance": "Tool Schema Compliance",
      // Settings enum options
      "Auto (detect from system)": "Auto (detect from system)",
      Text: "Text",
      JSON: "JSON",
      Plan: "Plan",
      Default: "Default",
      "Auto Edit": "Auto Edit",
      YOLO: "YOLO",
      "toggle vim mode on/off": "toggle vim mode on/off",
      "check session stats. Usage: /stats [model|tools]": "check session stats. Usage: /stats [model|tools]",
      "Show model-specific usage statistics.": "Show model-specific usage statistics.",
      "Show tool-specific usage statistics.": "Show tool-specific usage statistics.",
      "exit the cli": "exit the cli",
      "list configured MCP servers and tools, or authenticate with OAuth-enabled servers": "list configured MCP servers and tools, or authenticate with OAuth-enabled servers",
      "Manage workspace directories": "Manage workspace directories",
      "Add directories to the workspace. Use comma to separate multiple paths": "Add directories to the workspace. Use comma to separate multiple paths",
      "Show all directories in the workspace": "Show all directories in the workspace",
      "set external editor preference": "set external editor preference",
      "Select Editor": "Select Editor",
      "Editor Preference": "Editor Preference",
      "These editors are currently supported. Please note that some editors cannot be used in sandbox mode.": "These editors are currently supported. Please note that some editors cannot be used in sandbox mode.",
      "Your preferred editor is:": "Your preferred editor is:",
      "Manage extensions": "Manage extensions",
      "List active extensions": "List active extensions",
      "Update extensions. Usage: update <extension-names>|--all": "Update extensions. Usage: update <extension-names>|--all",
      "Disable an extension": "Disable an extension",
      "Enable an extension": "Enable an extension",
      "Install an extension from a git repo or local path": "Install an extension from a git repo or local path",
      "Uninstall an extension": "Uninstall an extension",
      "No extensions installed.": "No extensions installed.",
      "Usage: /extensions update <extension-names>|--all": "Usage: /extensions update <extension-names>|--all",
      'Extension "{{name}}" not found.': 'Extension "{{name}}" not found.',
      "No extensions to update.": "No extensions to update.",
      "Usage: /extensions install <source>": "Usage: /extensions install <source>",
      'Installing extension from "{{source}}"...': 'Installing extension from "{{source}}"...',
      'Extension "{{name}}" installed successfully.': 'Extension "{{name}}" installed successfully.',
      'Failed to install extension from "{{source}}": {{error}}': 'Failed to install extension from "{{source}}": {{error}}',
      "Usage: /extensions uninstall <extension-name>": "Usage: /extensions uninstall <extension-name>",
      'Uninstalling extension "{{name}}"...': 'Uninstalling extension "{{name}}"...',
      'Extension "{{name}}" uninstalled successfully.': 'Extension "{{name}}" uninstalled successfully.',
      'Failed to uninstall extension "{{name}}": {{error}}': 'Failed to uninstall extension "{{name}}": {{error}}',
      "Usage: /extensions {{command}} <extension> [--scope=<user|workspace>]": "Usage: /extensions {{command}} <extension> [--scope=<user|workspace>]",
      'Unsupported scope "{{scope}}", should be one of "user" or "workspace"': 'Unsupported scope "{{scope}}", should be one of "user" or "workspace"',
      'Extension "{{name}}" disabled for scope "{{scope}}"': 'Extension "{{name}}" disabled for scope "{{scope}}"',
      'Extension "{{name}}" enabled for scope "{{scope}}"': 'Extension "{{name}}" enabled for scope "{{scope}}"',
      "Do you want to continue? [Y/n]: ": "Do you want to continue? [Y/n]: ",
      "Do you want to continue?": "Do you want to continue?",
      'Installing extension "{{name}}".': 'Installing extension "{{name}}".',
      "**Extensions may introduce unexpected behavior. Ensure you have investigated the extension source and trust the author.**": "**Extensions may introduce unexpected behavior. Ensure you have investigated the extension source and trust the author.**",
      "This extension will run the following MCP servers:": "This extension will run the following MCP servers:",
      local: "local",
      remote: "remote",
      "This extension will add the following commands: {{commands}}.": "This extension will add the following commands: {{commands}}.",
      "This extension will append info to your QWEN.md context using {{fileName}}": "This extension will append info to your QWEN.md context using {{fileName}}",
      "This extension will exclude the following core tools: {{tools}}": "This extension will exclude the following core tools: {{tools}}",
      "This extension will install the following skills:": "This extension will install the following skills:",
      "This extension will install the following subagents:": "This extension will install the following subagents:",
      'Installation cancelled for "{{name}}".': 'Installation cancelled for "{{name}}".',
      "You are installing an extension from {{originSource}}. Some features may not work perfectly with Qwen Code.": "You are installing an extension from {{originSource}}. Some features may not work perfectly with Qwen Code.",
      "--ref and --auto-update are not applicable for marketplace extensions.": "--ref and --auto-update are not applicable for marketplace extensions.",
      'Extension "{{name}}" installed successfully and enabled.': 'Extension "{{name}}" installed successfully and enabled.',
      "Installs an extension from a git repository URL, local path, or claude marketplace (marketplace-url:plugin-name).": "Installs an extension from a git repository URL, local path, or claude marketplace (marketplace-url:plugin-name).",
      "The github URL, local path, or marketplace source (marketplace-url:plugin-name) of the extension to install.": "The github URL, local path, or marketplace source (marketplace-url:plugin-name) of the extension to install.",
      "The git ref to install from.": "The git ref to install from.",
      "Enable auto-update for this extension.": "Enable auto-update for this extension.",
      "Enable pre-release versions for this extension.": "Enable pre-release versions for this extension.",
      "Acknowledge the security risks of installing an extension and skip the confirmation prompt.": "Acknowledge the security risks of installing an extension and skip the confirmation prompt.",
      "The source argument must be provided.": "The source argument must be provided.",
      'Extension "{{name}}" successfully uninstalled.': 'Extension "{{name}}" successfully uninstalled.',
      "Uninstalls an extension.": "Uninstalls an extension.",
      "The name or source path of the extension to uninstall.": "The name or source path of the extension to uninstall.",
      "Please include the name of the extension to uninstall as a positional argument.": "Please include the name of the extension to uninstall as a positional argument.",
      "Enables an extension.": "Enables an extension.",
      "The name of the extension to enable.": "The name of the extension to enable.",
      "The scope to enable the extenison in. If not set, will be enabled in all scopes.": "The scope to enable the extenison in. If not set, will be enabled in all scopes.",
      'Extension "{{name}}" successfully enabled for scope "{{scope}}".': 'Extension "{{name}}" successfully enabled for scope "{{scope}}".',
      'Extension "{{name}}" successfully enabled in all scopes.': 'Extension "{{name}}" successfully enabled in all scopes.',
      "Invalid scope: {{scope}}. Please use one of {{scopes}}.": "Invalid scope: {{scope}}. Please use one of {{scopes}}.",
      "Disables an extension.": "Disables an extension.",
      "The name of the extension to disable.": "The name of the extension to disable.",
      "The scope to disable the extenison in.": "The scope to disable the extenison in.",
      'Extension "{{name}}" successfully disabled for scope "{{scope}}".': 'Extension "{{name}}" successfully disabled for scope "{{scope}}".',
      'Extension "{{name}}" successfully updated: {{oldVersion}} \u2192 {{newVersion}}.': 'Extension "{{name}}" successfully updated: {{oldVersion}} \u2192 {{newVersion}}.',
      'Unable to install extension "{{name}}" due to missing install metadata': 'Unable to install extension "{{name}}" due to missing install metadata',
      'Extension "{{name}}" is already up to date.': 'Extension "{{name}}" is already up to date.',
      "Updates all extensions or a named extension to the latest version.": "Updates all extensions or a named extension to the latest version.",
      "Update all extensions.": "Update all extensions.",
      "Either an extension name or --all must be provided": "Either an extension name or --all must be provided",
      "Lists installed extensions.": "Lists installed extensions.",
      "Path:": "Path:",
      "Source:": "Source:",
      "Type:": "Type:",
      "Ref:": "Ref:",
      "Release tag:": "Release tag:",
      "Enabled (User):": "Enabled (User):",
      "Enabled (Workspace):": "Enabled (Workspace):",
      "Context files:": "Context files:",
      "Skills:": "Skills:",
      "Agents:": "Agents:",
      "MCP servers:": "MCP servers:",
      "Link extension failed to install.": "Link extension failed to install.",
      'Extension "{{name}}" linked successfully and enabled.': 'Extension "{{name}}" linked successfully and enabled.',
      "Links an extension from a local path. Updates made to the local path will always be reflected.": "Links an extension from a local path. Updates made to the local path will always be reflected.",
      "The name of the extension to link.": "The name of the extension to link.",
      "Set a specific setting for an extension.": "Set a specific setting for an extension.",
      "Name of the extension to configure.": "Name of the extension to configure.",
      "The setting to configure (name or env var).": "The setting to configure (name or env var).",
      "The scope to set the setting in.": "The scope to set the setting in.",
      "List all settings for an extension.": "List all settings for an extension.",
      "Name of the extension.": "Name of the extension.",
      'Extension "{{name}}" has no settings to configure.': 'Extension "{{name}}" has no settings to configure.',
      'Settings for "{{name}}":': 'Settings for "{{name}}":',
      "(workspace)": "(workspace)",
      "(user)": "(user)",
      "[not set]": "[not set]",
      "[value stored in keychain]": "[value stored in keychain]",
      "Value:": "Value:",
      "Manage extension settings.": "Manage extension settings.",
      "You need to specify a command (set or list).": "You need to specify a command (set or list).",
      // ============================================================================
      // Plugin Choice / Marketplace
      // ============================================================================
      "No plugins available in this marketplace.": "No plugins available in this marketplace.",
      'Select a plugin to install from marketplace "{{name}}":': 'Select a plugin to install from marketplace "{{name}}":',
      "Plugin selection cancelled.": "Plugin selection cancelled.",
      'Select a plugin from "{{name}}"': 'Select a plugin from "{{name}}"',
      "Use \u2191\u2193 or j/k to navigate, Enter to select, Escape to cancel": "Use \u2191\u2193 or j/k to navigate, Enter to select, Escape to cancel",
      "{{count}} more above": "{{count}} more above",
      "{{count}} more below": "{{count}} more below",
      "manage IDE integration": "manage IDE integration",
      "check status of IDE integration": "check status of IDE integration",
      "install required IDE companion for {{ideName}}": "install required IDE companion for {{ideName}}",
      "enable IDE integration": "enable IDE integration",
      "disable IDE integration": "disable IDE integration",
      "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.": "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.",
      "Set up GitHub Actions": "Set up GitHub Actions",
      "Configure terminal keybindings for multiline input (VS Code, Cursor, Windsurf, Trae)": "Configure terminal keybindings for multiline input (VS Code, Cursor, Windsurf, Trae)",
      "Please restart your terminal for the changes to take effect.": "Please restart your terminal for the changes to take effect.",
      "Failed to configure terminal: {{error}}": "Failed to configure terminal: {{error}}",
      "Could not determine {{terminalName}} config path on Windows: APPDATA environment variable is not set.": "Could not determine {{terminalName}} config path on Windows: APPDATA environment variable is not set.",
      "{{terminalName}} keybindings.json exists but is not a valid JSON array. Please fix the file manually or delete it to allow automatic configuration.": "{{terminalName}} keybindings.json exists but is not a valid JSON array. Please fix the file manually or delete it to allow automatic configuration.",
      "File: {{file}}": "File: {{file}}",
      "Failed to parse {{terminalName}} keybindings.json. The file contains invalid JSON. Please fix the file manually or delete it to allow automatic configuration.": "Failed to parse {{terminalName}} keybindings.json. The file contains invalid JSON. Please fix the file manually or delete it to allow automatic configuration.",
      "Error: {{error}}": "Error: {{error}}",
      "Shift+Enter binding already exists": "Shift+Enter binding already exists",
      "Ctrl+Enter binding already exists": "Ctrl+Enter binding already exists",
      "Existing keybindings detected. Will not modify to avoid conflicts.": "Existing keybindings detected. Will not modify to avoid conflicts.",
      "Please check and modify manually if needed: {{file}}": "Please check and modify manually if needed: {{file}}",
      "Added Shift+Enter and Ctrl+Enter keybindings to {{terminalName}}.": "Added Shift+Enter and Ctrl+Enter keybindings to {{terminalName}}.",
      "Modified: {{file}}": "Modified: {{file}}",
      "{{terminalName}} keybindings already configured.": "{{terminalName}} keybindings already configured.",
      "Failed to configure {{terminalName}}.": "Failed to configure {{terminalName}}.",
      "Your terminal is already configured for an optimal experience with multiline input (Shift+Enter and Ctrl+Enter).": "Your terminal is already configured for an optimal experience with multiline input (Shift+Enter and Ctrl+Enter).",
      "Could not detect terminal type. Supported terminals: VS Code, Cursor, Windsurf, and Trae.": "Could not detect terminal type. Supported terminals: VS Code, Cursor, Windsurf, and Trae.",
      'Terminal "{{terminal}}" is not supported yet.': 'Terminal "{{terminal}}" is not supported yet.',
      // ============================================================================
      // Commands - Language
      // ============================================================================
      "Invalid language. Available: {{options}}": "Invalid language. Available: {{options}}",
      "Language subcommands do not accept additional arguments.": "Language subcommands do not accept additional arguments.",
      "Current UI language: {{lang}}": "Current UI language: {{lang}}",
      "Current LLM output language: {{lang}}": "Current LLM output language: {{lang}}",
      "LLM output language not set": "LLM output language not set",
      "Set UI language": "Set UI language",
      "Set LLM output language": "Set LLM output language",
      "Usage: /language ui [{{options}}]": "Usage: /language ui [{{options}}]",
      "Usage: /language output <language>": "Usage: /language output <language>",
      "Example: /language output \u4E2D\u6587": "Example: /language output \u4E2D\u6587",
      "Example: /language output English": "Example: /language output English",
      "Example: /language output \u65E5\u672C\u8A9E": "Example: /language output \u65E5\u672C\u8A9E",
      "Example: /language output Portugu\xEAs": "Example: /language output Portugu\xEAs",
      "UI language changed to {{lang}}": "UI language changed to {{lang}}",
      "LLM output language set to {{lang}}": "LLM output language set to {{lang}}",
      "LLM output language rule file generated at {{path}}": "LLM output language rule file generated at {{path}}",
      "Please restart the application for the changes to take effect.": "Please restart the application for the changes to take effect.",
      "Failed to generate LLM output language rule file: {{error}}": "Failed to generate LLM output language rule file: {{error}}",
      "Invalid command. Available subcommands:": "Invalid command. Available subcommands:",
      "Available subcommands:": "Available subcommands:",
      "To request additional UI language packs, please open an issue on GitHub.": "To request additional UI language packs, please open an issue on GitHub.",
      "Available options:": "Available options:",
      "Set UI language to {{name}}": "Set UI language to {{name}}",
      // ============================================================================
      // Commands - Approval Mode
      // ============================================================================
      "Tool Approval Mode": "Tool Approval Mode",
      "Current approval mode: {{mode}}": "Current approval mode: {{mode}}",
      "Available approval modes:": "Available approval modes:",
      "Approval mode changed to: {{mode}}": "Approval mode changed to: {{mode}}",
      "Approval mode changed to: {{mode}} (saved to {{scope}} settings{{location}})": "Approval mode changed to: {{mode}} (saved to {{scope}} settings{{location}})",
      "Usage: /approval-mode <mode> [--session|--user|--project]": "Usage: /approval-mode <mode> [--session|--user|--project]",
      "Scope subcommands do not accept additional arguments.": "Scope subcommands do not accept additional arguments.",
      "Plan mode - Analyze only, do not modify files or execute commands": "Plan mode - Analyze only, do not modify files or execute commands",
      "Default mode - Require approval for file edits or shell commands": "Default mode - Require approval for file edits or shell commands",
      "Auto-edit mode - Automatically approve file edits": "Auto-edit mode - Automatically approve file edits",
      "YOLO mode - Automatically approve all tools": "YOLO mode - Automatically approve all tools",
      "{{mode}} mode": "{{mode}} mode",
      "Settings service is not available; unable to persist the approval mode.": "Settings service is not available; unable to persist the approval mode.",
      "Failed to save approval mode: {{error}}": "Failed to save approval mode: {{error}}",
      "Failed to change approval mode: {{error}}": "Failed to change approval mode: {{error}}",
      "Apply to current session only (temporary)": "Apply to current session only (temporary)",
      "Persist for this project/workspace": "Persist for this project/workspace",
      "Persist for this user on this machine": "Persist for this user on this machine",
      "Analyze only, do not modify files or execute commands": "Analyze only, do not modify files or execute commands",
      "Require approval for file edits or shell commands": "Require approval for file edits or shell commands",
      "Automatically approve file edits": "Automatically approve file edits",
      "Automatically approve all tools": "Automatically approve all tools",
      "Workspace approval mode exists and takes priority. User-level change will have no effect.": "Workspace approval mode exists and takes priority. User-level change will have no effect.",
      "Apply To": "Apply To",
      "User Settings": "User Settings",
      "Workspace Settings": "Workspace Settings",
      // ============================================================================
      // Commands - Memory
      // ============================================================================
      "Commands for interacting with memory.": "Commands for interacting with memory.",
      "Show the current memory contents.": "Show the current memory contents.",
      "Show project-level memory contents.": "Show project-level memory contents.",
      "Show global memory contents.": "Show global memory contents.",
      "Add content to project-level memory.": "Add content to project-level memory.",
      "Add content to global memory.": "Add content to global memory.",
      "Refresh the memory from the source.": "Refresh the memory from the source.",
      "Usage: /memory add --project <text to remember>": "Usage: /memory add --project <text to remember>",
      "Usage: /memory add --global <text to remember>": "Usage: /memory add --global <text to remember>",
      'Attempting to save to project memory: "{{text}}"': 'Attempting to save to project memory: "{{text}}"',
      'Attempting to save to global memory: "{{text}}"': 'Attempting to save to global memory: "{{text}}"',
      "Current memory content from {{count}} file(s):": "Current memory content from {{count}} file(s):",
      "Memory is currently empty.": "Memory is currently empty.",
      "Project memory file not found or is currently empty.": "Project memory file not found or is currently empty.",
      "Global memory file not found or is currently empty.": "Global memory file not found or is currently empty.",
      "Global memory is currently empty.": "Global memory is currently empty.",
      "Global memory content:\n\n---\n{{content}}\n---": "Global memory content:\n\n---\n{{content}}\n---",
      "Project memory content from {{path}}:\n\n---\n{{content}}\n---": "Project memory content from {{path}}:\n\n---\n{{content}}\n---",
      "Project memory is currently empty.": "Project memory is currently empty.",
      "Refreshing memory from source files...": "Refreshing memory from source files...",
      "Add content to the memory. Use --global for global memory or --project for project memory.": "Add content to the memory. Use --global for global memory or --project for project memory.",
      "Usage: /memory add [--global|--project] <text to remember>": "Usage: /memory add [--global|--project] <text to remember>",
      'Attempting to save to memory {{scope}}: "{{fact}}"': 'Attempting to save to memory {{scope}}: "{{fact}}"',
      // ============================================================================
      // Commands - MCP
      // ============================================================================
      "Authenticate with an OAuth-enabled MCP server": "Authenticate with an OAuth-enabled MCP server",
      "List configured MCP servers and tools": "List configured MCP servers and tools",
      "Restarts MCP servers.": "Restarts MCP servers.",
      "Config not loaded.": "Config not loaded.",
      "Could not retrieve tool registry.": "Could not retrieve tool registry.",
      "No MCP servers configured with OAuth authentication.": "No MCP servers configured with OAuth authentication.",
      "MCP servers with OAuth authentication:": "MCP servers with OAuth authentication:",
      "Use /mcp auth <server-name> to authenticate.": "Use /mcp auth <server-name> to authenticate.",
      "MCP server '{{name}}' not found.": "MCP server '{{name}}' not found.",
      "Successfully authenticated and refreshed tools for '{{name}}'.": "Successfully authenticated and refreshed tools for '{{name}}'.",
      "Failed to authenticate with MCP server '{{name}}': {{error}}": "Failed to authenticate with MCP server '{{name}}': {{error}}",
      "Re-discovering tools from '{{name}}'...": "Re-discovering tools from '{{name}}'...",
      // ============================================================================
      // Commands - Chat
      // ============================================================================
      "Manage conversation history.": "Manage conversation history.",
      "List saved conversation checkpoints": "List saved conversation checkpoints",
      "No saved conversation checkpoints found.": "No saved conversation checkpoints found.",
      "List of saved conversations:": "List of saved conversations:",
      "Note: Newest last, oldest first": "Note: Newest last, oldest first",
      "Save the current conversation as a checkpoint. Usage: /chat save <tag>": "Save the current conversation as a checkpoint. Usage: /chat save <tag>",
      "Missing tag. Usage: /chat save <tag>": "Missing tag. Usage: /chat save <tag>",
      "Delete a conversation checkpoint. Usage: /chat delete <tag>": "Delete a conversation checkpoint. Usage: /chat delete <tag>",
      "Missing tag. Usage: /chat delete <tag>": "Missing tag. Usage: /chat delete <tag>",
      "Conversation checkpoint '{{tag}}' has been deleted.": "Conversation checkpoint '{{tag}}' has been deleted.",
      "Error: No checkpoint found with tag '{{tag}}'.": "Error: No checkpoint found with tag '{{tag}}'.",
      "Resume a conversation from a checkpoint. Usage: /chat resume <tag>": "Resume a conversation from a checkpoint. Usage: /chat resume <tag>",
      "Missing tag. Usage: /chat resume <tag>": "Missing tag. Usage: /chat resume <tag>",
      "No saved checkpoint found with tag: {{tag}}.": "No saved checkpoint found with tag: {{tag}}.",
      "A checkpoint with the tag {{tag}} already exists. Do you want to overwrite it?": "A checkpoint with the tag {{tag}} already exists. Do you want to overwrite it?",
      "No chat client available to save conversation.": "No chat client available to save conversation.",
      "Conversation checkpoint saved with tag: {{tag}}.": "Conversation checkpoint saved with tag: {{tag}}.",
      "No conversation found to save.": "No conversation found to save.",
      "No chat client available to share conversation.": "No chat client available to share conversation.",
      "Invalid file format. Only .md and .json are supported.": "Invalid file format. Only .md and .json are supported.",
      "Error sharing conversation: {{error}}": "Error sharing conversation: {{error}}",
      "Conversation shared to {{filePath}}": "Conversation shared to {{filePath}}",
      "No conversation found to share.": "No conversation found to share.",
      "Share the current conversation to a markdown or json file. Usage: /chat share <file>": "Share the current conversation to a markdown or json file. Usage: /chat share <file>",
      // ============================================================================
      // Commands - Summary
      // ============================================================================
      "Generate a project summary and save it to .qwen/PROJECT_SUMMARY.md": "Generate a project summary and save it to .qwen/PROJECT_SUMMARY.md",
      "No chat client available to generate summary.": "No chat client available to generate summary.",
      "Already generating summary, wait for previous request to complete": "Already generating summary, wait for previous request to complete",
      "No conversation found to summarize.": "No conversation found to summarize.",
      "Failed to generate project context summary: {{error}}": "Failed to generate project context summary: {{error}}",
      "Saved project summary to {{filePathForDisplay}}.": "Saved project summary to {{filePathForDisplay}}.",
      "Saving project summary...": "Saving project summary...",
      "Generating project summary...": "Generating project summary...",
      "Failed to generate summary - no text content received from LLM response": "Failed to generate summary - no text content received from LLM response",
      // ============================================================================
      // Commands - Model
      // ============================================================================
      "Switch the model for this session": "Switch the model for this session",
      "Content generator configuration not available.": "Content generator configuration not available.",
      "Authentication type not available.": "Authentication type not available.",
      "No models available for the current authentication type ({{authType}}).": "No models available for the current authentication type ({{authType}}).",
      // ============================================================================
      // Commands - Clear
      // ============================================================================
      "Starting a new session, resetting chat, and clearing terminal.": "Starting a new session, resetting chat, and clearing terminal.",
      "Starting a new session and clearing.": "Starting a new session and clearing.",
      // ============================================================================
      // Commands - Compress
      // ============================================================================
      "Already compressing, wait for previous request to complete": "Already compressing, wait for previous request to complete",
      "Failed to compress chat history.": "Failed to compress chat history.",
      "Failed to compress chat history: {{error}}": "Failed to compress chat history: {{error}}",
      "Compressing chat history": "Compressing chat history",
      "Chat history compressed from {{originalTokens}} to {{newTokens}} tokens.": "Chat history compressed from {{originalTokens}} to {{newTokens}} tokens.",
      "Compression was not beneficial for this history size.": "Compression was not beneficial for this history size.",
      "Chat history compression did not reduce size. This may indicate issues with the compression prompt.": "Chat history compression did not reduce size. This may indicate issues with the compression prompt.",
      "Could not compress chat history due to a token counting error.": "Could not compress chat history due to a token counting error.",
      "Chat history is already compressed.": "Chat history is already compressed.",
      // ============================================================================
      // Commands - Directory
      // ============================================================================
      "Configuration is not available.": "Configuration is not available.",
      "Please provide at least one path to add.": "Please provide at least one path to add.",
      "The /directory add command is not supported in restrictive sandbox profiles. Please use --include-directories when starting the session instead.": "The /directory add command is not supported in restrictive sandbox profiles. Please use --include-directories when starting the session instead.",
      "Error adding '{{path}}': {{error}}": "Error adding '{{path}}': {{error}}",
      "Successfully added QWEN.md files from the following directories if there are:\n- {{directories}}": "Successfully added QWEN.md files from the following directories if there are:\n- {{directories}}",
      "Error refreshing memory: {{error}}": "Error refreshing memory: {{error}}",
      "Successfully added directories:\n- {{directories}}": "Successfully added directories:\n- {{directories}}",
      "Current workspace directories:\n{{directories}}": "Current workspace directories:\n{{directories}}",
      // ============================================================================
      // Commands - Docs
      // ============================================================================
      "Please open the following URL in your browser to view the documentation:\n{{url}}": "Please open the following URL in your browser to view the documentation:\n{{url}}",
      "Opening documentation in your browser: {{url}}": "Opening documentation in your browser: {{url}}",
      // ============================================================================
      // Dialogs - Tool Confirmation
      // ============================================================================
      "Do you want to proceed?": "Do you want to proceed?",
      "Yes, allow once": "Yes, allow once",
      "Allow always": "Allow always",
      No: "No",
      "No (esc)": "No (esc)",
      "Yes, allow always for this session": "Yes, allow always for this session",
      "Modify in progress:": "Modify in progress:",
      "Save and close external editor to continue": "Save and close external editor to continue",
      "Apply this change?": "Apply this change?",
      "Yes, allow always": "Yes, allow always",
      "Modify with external editor": "Modify with external editor",
      "No, suggest changes (esc)": "No, suggest changes (esc)",
      "Allow execution of: '{{command}}'?": "Allow execution of: '{{command}}'?",
      "Yes, allow always ...": "Yes, allow always ...",
      "Yes, and auto-accept edits": "Yes, and auto-accept edits",
      "Yes, and manually approve edits": "Yes, and manually approve edits",
      "No, keep planning (esc)": "No, keep planning (esc)",
      "URLs to fetch:": "URLs to fetch:",
      "MCP Server: {{server}}": "MCP Server: {{server}}",
      "Tool: {{tool}}": "Tool: {{tool}}",
      'Allow execution of MCP tool "{{tool}}" from server "{{server}}"?': 'Allow execution of MCP tool "{{tool}}" from server "{{server}}"?',
      'Yes, always allow tool "{{tool}}" from server "{{server}}"': 'Yes, always allow tool "{{tool}}" from server "{{server}}"',
      'Yes, always allow all tools from server "{{server}}"': 'Yes, always allow all tools from server "{{server}}"',
      // ============================================================================
      // Dialogs - Shell Confirmation
      // ============================================================================
      "Shell Command Execution": "Shell Command Execution",
      "A custom command wants to run the following shell commands:": "A custom command wants to run the following shell commands:",
      // ============================================================================
      // Dialogs - Pro Quota
      // ============================================================================
      "Pro quota limit reached for {{model}}.": "Pro quota limit reached for {{model}}.",
      "Change auth (executes the /auth command)": "Change auth (executes the /auth command)",
      "Continue with {{model}}": "Continue with {{model}}",
      // ============================================================================
      // Dialogs - Welcome Back
      // ============================================================================
      "Current Plan:": "Current Plan:",
      "Progress: {{done}}/{{total}} tasks completed": "Progress: {{done}}/{{total}} tasks completed",
      ", {{inProgress}} in progress": ", {{inProgress}} in progress",
      "Pending Tasks:": "Pending Tasks:",
      "What would you like to do?": "What would you like to do?",
      "Choose how to proceed with your session:": "Choose how to proceed with your session:",
      "Start new chat session": "Start new chat session",
      "Continue previous conversation": "Continue previous conversation",
      "\u{1F44B} Welcome back! (Last updated: {{timeAgo}})": "\u{1F44B} Welcome back! (Last updated: {{timeAgo}})",
      "\u{1F3AF} Overall Goal:": "\u{1F3AF} Overall Goal:",
      // ============================================================================
      // Dialogs - Auth
      // ============================================================================
      "Get started": "Get started",
      "How would you like to authenticate for this project?": "How would you like to authenticate for this project?",
      "OpenAI API key is required to use OpenAI authentication.": "OpenAI API key is required to use OpenAI authentication.",
      "You must select an auth method to proceed. Press Ctrl+C again to exit.": "You must select an auth method to proceed. Press Ctrl+C again to exit.",
      "(Use Enter to Set Auth)": "(Use Enter to Set Auth)",
      "Terms of Services and Privacy Notice for Qwen Code": "Terms of Services and Privacy Notice for Qwen Code",
      "Qwen OAuth": "Qwen OAuth",
      "Login with QwenChat account to use daily free quota.": "Login with QwenChat account to use daily free quota.",
      "API-KEY": "API-KEY",
      "Use coding plan credentials or your own api-keys/providers.": "Use coding plan credentials or your own api-keys/providers.",
      OpenAI: "OpenAI",
      "Failed to login. Message: {{message}}": "Failed to login. Message: {{message}}",
      "Authentication is enforced to be {{enforcedType}}, but you are currently using {{currentType}}.": "Authentication is enforced to be {{enforcedType}}, but you are currently using {{currentType}}.",
      "Qwen OAuth authentication timed out. Please try again.": "Qwen OAuth authentication timed out. Please try again.",
      "Qwen OAuth authentication cancelled.": "Qwen OAuth authentication cancelled.",
      "Qwen OAuth Authentication": "Qwen OAuth Authentication",
      "Please visit this URL to authorize:": "Please visit this URL to authorize:",
      "Or scan the QR code below:": "Or scan the QR code below:",
      "Waiting for authorization": "Waiting for authorization",
      "Time remaining:": "Time remaining:",
      "(Press ESC or CTRL+C to cancel)": "(Press ESC or CTRL+C to cancel)",
      "Qwen OAuth Authentication Timeout": "Qwen OAuth Authentication Timeout",
      "OAuth token expired (over {{seconds}} seconds). Please select authentication method again.": "OAuth token expired (over {{seconds}} seconds). Please select authentication method again.",
      "Press any key to return to authentication type selection.": "Press any key to return to authentication type selection.",
      "Waiting for Qwen OAuth authentication...": "Waiting for Qwen OAuth authentication...",
      "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.": "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.",
      "Authentication timed out. Please try again.": "Authentication timed out. Please try again.",
      "Waiting for auth... (Press ESC or CTRL+C to cancel)": "Waiting for auth... (Press ESC or CTRL+C to cancel)",
      "Missing API key for OpenAI-compatible auth. Set settings.security.auth.apiKey, or set the {{envKeyHint}} environment variable.": "Missing API key for OpenAI-compatible auth. Set settings.security.auth.apiKey, or set the {{envKeyHint}} environment variable.",
      "{{envKeyHint}} environment variable not found.": "{{envKeyHint}} environment variable not found.",
      "{{envKeyHint}} environment variable not found. Please set it in your .env file or environment variables.": "{{envKeyHint}} environment variable not found. Please set it in your .env file or environment variables.",
      "{{envKeyHint}} environment variable not found (or set settings.security.auth.apiKey). Please set it in your .env file or environment variables.": "{{envKeyHint}} environment variable not found (or set settings.security.auth.apiKey). Please set it in your .env file or environment variables.",
      "Missing API key for OpenAI-compatible auth. Set the {{envKeyHint}} environment variable.": "Missing API key for OpenAI-compatible auth. Set the {{envKeyHint}} environment variable.",
      "Anthropic provider missing required baseUrl in modelProviders[].baseUrl.": "Anthropic provider missing required baseUrl in modelProviders[].baseUrl.",
      "ANTHROPIC_BASE_URL environment variable not found.": "ANTHROPIC_BASE_URL environment variable not found.",
      "Invalid auth method selected.": "Invalid auth method selected.",
      "Failed to authenticate. Message: {{message}}": "Failed to authenticate. Message: {{message}}",
      "Authenticated successfully with {{authType}} credentials.": "Authenticated successfully with {{authType}} credentials.",
      'Invalid QWEN_DEFAULT_AUTH_TYPE value: "{{value}}". Valid values are: {{validValues}}': 'Invalid QWEN_DEFAULT_AUTH_TYPE value: "{{value}}". Valid values are: {{validValues}}',
      "OpenAI Configuration Required": "OpenAI Configuration Required",
      "Please enter your OpenAI configuration. You can get an API key from": "Please enter your OpenAI configuration. You can get an API key from",
      "API Key:": "API Key:",
      "Invalid credentials: {{errorMessage}}": "Invalid credentials: {{errorMessage}}",
      "Failed to validate credentials": "Failed to validate credentials",
      "Press Enter to continue, Tab/\u2191\u2193 to navigate, Esc to cancel": "Press Enter to continue, Tab/\u2191\u2193 to navigate, Esc to cancel",
      // ============================================================================
      // Dialogs - Model
      // ============================================================================
      "Select Model": "Select Model",
      "(Press Esc to close)": "(Press Esc to close)",
      "Current (effective) configuration": "Current (effective) configuration",
      AuthType: "AuthType",
      "API Key": "API Key",
      unset: "unset",
      "(default)": "(default)",
      "(set)": "(set)",
      "(not set)": "(not set)",
      "Failed to switch model to '{{modelId}}'.\n\n{{error}}": "Failed to switch model to '{{modelId}}'.\n\n{{error}}",
      "Qwen 3.5 Plus \u2014 efficient hybrid model with leading coding performance": "Qwen 3.5 Plus \u2014 efficient hybrid model with leading coding performance",
      "The latest Qwen Vision model from Alibaba Cloud ModelStudio (version: qwen3-vl-plus-2025-09-23)": "The latest Qwen Vision model from Alibaba Cloud ModelStudio (version: qwen3-vl-plus-2025-09-23)",
      // ============================================================================
      // Dialogs - Permissions
      // ============================================================================
      "Manage folder trust settings": "Manage folder trust settings",
      // ============================================================================
      // Status Bar
      // ============================================================================
      "Using:": "Using:",
      "{{count}} open file": "{{count}} open file",
      "{{count}} open files": "{{count}} open files",
      "(ctrl+g to view)": "(ctrl+g to view)",
      "{{count}} {{name}} file": "{{count}} {{name}} file",
      "{{count}} {{name}} files": "{{count}} {{name}} files",
      "{{count}} MCP server": "{{count}} MCP server",
      "{{count}} MCP servers": "{{count}} MCP servers",
      "{{count}} Blocked": "{{count}} Blocked",
      "(ctrl+t to view)": "(ctrl+t to view)",
      "(ctrl+t to toggle)": "(ctrl+t to toggle)",
      "Press Ctrl+C again to exit.": "Press Ctrl+C again to exit.",
      "Press Ctrl+D again to exit.": "Press Ctrl+D again to exit.",
      "Press Esc again to clear.": "Press Esc again to clear.",
      // ============================================================================
      // MCP Status
      // ============================================================================
      "No MCP servers configured.": "No MCP servers configured.",
      "\u23F3 MCP servers are starting up ({{count}} initializing)...": "\u23F3 MCP servers are starting up ({{count}} initializing)...",
      "Note: First startup may take longer. Tool availability will update automatically.": "Note: First startup may take longer. Tool availability will update automatically.",
      "Configured MCP servers:": "Configured MCP servers:",
      Ready: "Ready",
      "Starting... (first startup may take longer)": "Starting... (first startup may take longer)",
      Disconnected: "Disconnected",
      "{{count}} tool": "{{count}} tool",
      "{{count}} tools": "{{count}} tools",
      "{{count}} prompt": "{{count}} prompt",
      "{{count}} prompts": "{{count}} prompts",
      "(from {{extensionName}})": "(from {{extensionName}})",
      OAuth: "OAuth",
      "OAuth expired": "OAuth expired",
      "OAuth not authenticated": "OAuth not authenticated",
      "tools and prompts will appear when ready": "tools and prompts will appear when ready",
      "{{count}} tools cached": "{{count}} tools cached",
      "Tools:": "Tools:",
      "Parameters:": "Parameters:",
      "Prompts:": "Prompts:",
      Blocked: "Blocked",
      "\u{1F4A1} Tips:": "\u{1F4A1} Tips:",
      Use: "Use",
      "to show server and tool descriptions": "to show server and tool descriptions",
      "to show tool parameter schemas": "to show tool parameter schemas",
      "to hide descriptions": "to hide descriptions",
      "to authenticate with OAuth-enabled servers": "to authenticate with OAuth-enabled servers",
      Press: "Press",
      "to toggle tool descriptions on/off": "to toggle tool descriptions on/off",
      "Starting OAuth authentication for MCP server '{{name}}'...": "Starting OAuth authentication for MCP server '{{name}}'...",
      "Restarting MCP servers...": "Restarting MCP servers...",
      // ============================================================================
      // Startup Tips
      // ============================================================================
      "Tips:": "Tips:",
      "Use /compress when the conversation gets long to summarize history and free up context.": "Use /compress when the conversation gets long to summarize history and free up context.",
      "Start a fresh idea with /clear or /new; the previous session stays available in history.": "Start a fresh idea with /clear or /new; the previous session stays available in history.",
      "Use /bug to submit issues to the maintainers when something goes off.": "Use /bug to submit issues to the maintainers when something goes off.",
      "Switch auth type quickly with /auth.": "Switch auth type quickly with /auth.",
      "You can run any shell commands from Qwen Code using ! (e.g. !ls).": "You can run any shell commands from Qwen Code using ! (e.g. !ls).",
      "Type / to open the command popup; Tab autocompletes slash commands and saved prompts.": "Type / to open the command popup; Tab autocompletes slash commands and saved prompts.",
      "You can resume a previous conversation by running qwen --continue or qwen --resume.": "You can resume a previous conversation by running qwen --continue or qwen --resume.",
      "You can switch permission mode quickly with Shift+Tab or /approval-mode.": "You can switch permission mode quickly with Shift+Tab or /approval-mode.",
      "You can switch permission mode quickly with Tab or /approval-mode.": "You can switch permission mode quickly with Tab or /approval-mode.",
      "Try /insight to generate personalized insights from your chat history.": "Try /insight to generate personalized insights from your chat history.",
      // ============================================================================
      // Exit Screen / Stats
      // ============================================================================
      "Agent powering down. Goodbye!": "Agent powering down. Goodbye!",
      "To continue this session, run": "To continue this session, run",
      "Interaction Summary": "Interaction Summary",
      "Session ID:": "Session ID:",
      "Tool Calls:": "Tool Calls:",
      "Success Rate:": "Success Rate:",
      "User Agreement:": "User Agreement:",
      reviewed: "reviewed",
      "Code Changes:": "Code Changes:",
      Performance: "Performance",
      "Wall Time:": "Wall Time:",
      "Agent Active:": "Agent Active:",
      "API Time:": "API Time:",
      "Tool Time:": "Tool Time:",
      "Session Stats": "Session Stats",
      "Model Usage": "Model Usage",
      Reqs: "Reqs",
      "Input Tokens": "Input Tokens",
      "Output Tokens": "Output Tokens",
      "Savings Highlight:": "Savings Highlight:",
      "of input tokens were served from the cache, reducing costs.": "of input tokens were served from the cache, reducing costs.",
      "Tip: For a full token breakdown, run `/stats model`.": "Tip: For a full token breakdown, run `/stats model`.",
      "Model Stats For Nerds": "Model Stats For Nerds",
      "Tool Stats For Nerds": "Tool Stats For Nerds",
      Metric: "Metric",
      API: "API",
      Requests: "Requests",
      Errors: "Errors",
      "Avg Latency": "Avg Latency",
      Tokens: "Tokens",
      Total: "Total",
      Prompt: "Prompt",
      Cached: "Cached",
      Thoughts: "Thoughts",
      Tool: "Tool",
      Output: "Output",
      "No API calls have been made in this session.": "No API calls have been made in this session.",
      "Tool Name": "Tool Name",
      Calls: "Calls",
      "Success Rate": "Success Rate",
      "Avg Duration": "Avg Duration",
      "User Decision Summary": "User Decision Summary",
      "Total Reviewed Suggestions:": "Total Reviewed Suggestions:",
      " \xBB Accepted:": " \xBB Accepted:",
      " \xBB Rejected:": " \xBB Rejected:",
      " \xBB Modified:": " \xBB Modified:",
      " Overall Agreement Rate:": " Overall Agreement Rate:",
      "No tool calls have been made in this session.": "No tool calls have been made in this session.",
      "Session start time is unavailable, cannot calculate stats.": "Session start time is unavailable, cannot calculate stats.",
      // ============================================================================
      // Command Format Migration
      // ============================================================================
      "Command Format Migration": "Command Format Migration",
      "Found {{count}} TOML command file:": "Found {{count}} TOML command file:",
      "Found {{count}} TOML command files:": "Found {{count}} TOML command files:",
      "... and {{count}} more": "... and {{count}} more",
      "The TOML format is deprecated. Would you like to migrate them to Markdown format?": "The TOML format is deprecated. Would you like to migrate them to Markdown format?",
      "(Backups will be created and original files will be preserved)": "(Backups will be created and original files will be preserved)",
      // ============================================================================
      // Loading Phrases
      // ============================================================================
      "Waiting for user confirmation...": "Waiting for user confirmation...",
      "(esc to cancel, {{time}})": "(esc to cancel, {{time}})",
      // ============================================================================
      // Loading Phrases
      // ============================================================================
      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...",
        "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..."
      ],
      // ============================================================================
      // Extension Settings Input
      // ============================================================================
      "Enter value...": "Enter value...",
      "Enter sensitive value...": "Enter sensitive value...",
      "Press Enter to submit, Escape to cancel": "Press Enter to submit, Escape to cancel",
      // ============================================================================
      // Command Migration Tool
      // ============================================================================
      "Markdown file already exists: {{filename}}": "Markdown file already exists: {{filename}}",
      "TOML Command Format Deprecation Notice": "TOML Command Format Deprecation Notice",
      "Found {{count}} command file(s) in TOML format:": "Found {{count}} command file(s) in TOML format:",
      "The TOML format for commands is being deprecated in favor of Markdown format.": "The TOML format for commands is being deprecated in favor of Markdown format.",
      "Markdown format is more readable and easier to edit.": "Markdown format is more readable and easier to edit.",
      "You can migrate these files automatically using:": "You can migrate these files automatically using:",
      "Or manually convert each file:": "Or manually convert each file:",
      'TOML: prompt = "..." / description = "..."': 'TOML: prompt = "..." / description = "..."',
      "Markdown: YAML frontmatter + content": "Markdown: YAML frontmatter + content",
      "The migration tool will:": "The migration tool will:",
      "Convert TOML files to Markdown": "Convert TOML files to Markdown",
      "Create backups of original files": "Create backups of original files",
      "Preserve all command functionality": "Preserve all command functionality",
      "TOML format will continue to work for now, but migration is recommended.": "TOML format will continue to work for now, but migration is recommended.",
      // ============================================================================
      // Extensions - Explore Command
      // ============================================================================
      "Open extensions page in your browser": "Open extensions page in your browser",
      "Unknown extensions source: {{source}}.": "Unknown extensions source: {{source}}.",
      "Would open extensions page in your browser: {{url}} (skipped in test environment)": "Would open extensions page in your browser: {{url}} (skipped in test environment)",
      "View available extensions at {{url}}": "View available extensions at {{url}}",
      "Opening extensions page in your browser: {{url}}": "Opening extensions page in your browser: {{url}}",
      "Failed to open browser. Check out the extensions gallery at {{url}}": "Failed to open browser. Check out the extensions gallery at {{url}}",
      // ============================================================================
      // Retry / Rate Limit
      // ============================================================================
      "Rate limit error: {{reason}}": "Rate limit error: {{reason}}",
      "Retrying in {{seconds}} seconds\u2026 (attempt {{attempt}}/{{maxRetries}})": "Retrying in {{seconds}} seconds\u2026 (attempt {{attempt}}/{{maxRetries}})",
      // ============================================================================
      // Coding Plan Authentication
      // ============================================================================
      "Please enter your API key:": "Please enter your API key:",
      "API key cannot be empty.": "API key cannot be empty.",
      "You can get your exclusive Coding Plan API-KEY here:": "You can get your exclusive Coding Plan API-KEY here:",
      "API key is stored in settings.env. You can migrate it to a .env file for better security.": "API key is stored in settings.env. You can migrate it to a .env file for better security.",
      "New model configurations are available for Bailian Coding Plan. Update now?": "New model configurations are available for Bailian Coding Plan. Update now?",
      "Coding Plan configuration updated successfully. New models are now available.": "Coding Plan configuration updated successfully. New models are now available.",
      "Coding Plan API key not found. Please re-authenticate with Coding Plan.": "Coding Plan API key not found. Please re-authenticate with Coding Plan.",
      "Failed to update Coding Plan configuration: {{message}}": "Failed to update Coding Plan configuration: {{message}}",
      // ============================================================================
      // Custom API-KEY Configuration
      // ============================================================================
      "For advanced users who want to configure models manually.": "For advanced users who want to configure models manually.",
      "Please configure your models in settings.json:": "Please configure your models in settings.json:",
      "Set API key via environment variable (e.g., OPENAI_API_KEY)": "Set API key via environment variable (e.g., OPENAI_API_KEY)",
      "Add model configuration to modelProviders['openai'] (or other auth types)": "Add model configuration to modelProviders['openai'] (or other auth types)",
      "Each provider needs: id, envKey (required), plus optional baseUrl, generationConfig": "Each provider needs: id, envKey (required), plus optional baseUrl, generationConfig",
      "Use /model command to select your preferred model from the configured list": "Use /model command to select your preferred model from the configured list",
      "Supported auth types: openai, anthropic, gemini, vertex-ai, etc.": "Supported auth types: openai, anthropic, gemini, vertex-ai, etc.",
      "More instructions please check:": "More instructions please check:",
      // ============================================================================
      // Auth Dialog - View Titles and Labels
      // ============================================================================
      "Coding Plan": "Coding Plan",
      "Coding Plan (Bailian, China)": "Coding Plan (Bailian, China)",
      "Coding Plan (Bailian, Global/Intl)": "Coding Plan (Bailian, Global/Intl)",
      "Paste your api key of Bailian Coding Plan and you're all set!": "Paste your api key of Bailian Coding Plan and you're all set!",
      "Paste your api key of Coding Plan (Bailian, Global/Intl) and you're all set!": "Paste your api key of Coding Plan (Bailian, Global/Intl) and you're all set!",
      Custom: "Custom",
      "More instructions about configuring `modelProviders` manually.": "More instructions about configuring `modelProviders` manually.",
      "Select API-KEY configuration mode:": "Select API-KEY configuration mode:",
      "(Press Escape to go back)": "(Press Escape to go back)",
      "(Press Enter to submit, Escape to cancel)": "(Press Enter to submit, Escape to cancel)",
      // ============================================================================
      // Coding Plan International Updates
      // ============================================================================
      "New model configurations are available for {{region}}. Update now?": "New model configurations are available for {{region}}. Update now?",
      "New model configurations are available for Bailian Coding Plan (China). Update now?": "New model configurations are available for Bailian Coding Plan (China). Update now?",
      "New model configurations are available for Coding Plan (Bailian, Global/Intl). Update now?": "New model configurations are available for Coding Plan (Bailian, Global/Intl). Update now?",
      '{{region}} configuration updated successfully. Model switched to "{{model}}".': '{{region}} configuration updated successfully. Model switched to "{{model}}".',
      "Authenticated successfully with {{region}}. API key and model configs saved to settings.json (backed up).": "Authenticated successfully with {{region}}. API key and model configs saved to settings.json (backed up)."
    };
  }
});

// packages/cli/src/i18n/locales/ja.js
var ja_exports = {};
__export(ja_exports, {
  default: () => ja_default
});
var ja_default;
var init_ja = __esm({
  "packages/cli/src/i18n/locales/ja.js"() {
    "use strict";
    init_esbuild_shims();
    ja_default = {
      // ============================================================================
      // Help / UI Components
      // ============================================================================
      "Basics:": "\u57FA\u672C\u64CD\u4F5C:",
      "Add context": "\u30B3\u30F3\u30C6\u30AD\u30B9\u30C8\u3092\u8FFD\u52A0",
      "Use {{symbol}} to specify files for context (e.g., {{example}}) to target specific files or folders.": "{{symbol}} \u3092\u4F7F\u7528\u3057\u3066\u30B3\u30F3\u30C6\u30AD\u30B9\u30C8\u7528\u306E\u30D5\u30A1\u30A4\u30EB\u3092\u6307\u5B9A\u3057\u307E\u3059(\u4F8B: {{example}}) \u307E\u305F\u3001\u7279\u5B9A\u306E\u30D5\u30A1\u30A4\u30EB\u3084\u30D5\u30A9\u30EB\u30C0\u3092\u5BFE\u8C61\u306B\u3067\u304D\u307E\u3059",
      "@": "@",
      "@src/myFile.ts": "@src/myFile.ts",
      "Shell mode": "\u30B7\u30A7\u30EB\u30E2\u30FC\u30C9",
      "YOLO mode": "YOLO\u30E2\u30FC\u30C9",
      "plan mode": "\u30D7\u30E9\u30F3\u30E2\u30FC\u30C9",
      "auto-accept edits": "\u7DE8\u96C6\u3092\u81EA\u52D5\u627F\u8A8D",
      "Accepting edits": "\u7DE8\u96C6\u3092\u627F\u8A8D\u4E2D",
      "(shift + tab to cycle)": "(Shift + Tab \u3067\u5207\u308A\u66FF\u3048)",
      "Execute shell commands via {{symbol}} (e.g., {{example1}}) or use natural language (e.g., {{example2}}).": "{{symbol}} \u3067\u30B7\u30A7\u30EB\u30B3\u30DE\u30F3\u30C9\u3092\u5B9F\u884C(\u4F8B: {{example1}})\u3001\u307E\u305F\u306F\u81EA\u7136\u8A00\u8A9E\u3067\u5165\u529B(\u4F8B: {{example2}})",
      "!": "!",
      "!npm run start": "!npm run start",
      "start server": "\u30B5\u30FC\u30D0\u30FC\u3092\u8D77\u52D5",
      "Commands:": "\u30B3\u30DE\u30F3\u30C9:",
      "shell command": "\u30B7\u30A7\u30EB\u30B3\u30DE\u30F3\u30C9",
      "Model Context Protocol command (from external servers)": "Model Context Protocol \u30B3\u30DE\u30F3\u30C9(\u5916\u90E8\u30B5\u30FC\u30D0\u30FC\u304B\u3089)",
      "Keyboard Shortcuts:": "\u30AD\u30FC\u30DC\u30FC\u30C9\u30B7\u30E7\u30FC\u30C8\u30AB\u30C3\u30C8:",
      "Jump through words in the input": "\u5165\u529B\u6B04\u306E\u5358\u8A9E\u9593\u3092\u79FB\u52D5",
      "Close dialogs, cancel requests, or quit application": "\u30C0\u30A4\u30A2\u30ED\u30B0\u3092\u9589\u3058\u308B\u3001\u30EA\u30AF\u30A8\u30B9\u30C8\u3092\u30AD\u30E3\u30F3\u30BB\u30EB\u3001\u307E\u305F\u306F\u30A2\u30D7\u30EA\u3092\u7D42\u4E86",
      "New line": "\u6539\u884C",
      "New line (Alt+Enter works for certain linux distros)": "\u6539\u884C(\u4E00\u90E8\u306ELinux\u30C7\u30A3\u30B9\u30C8\u30EA\u30D3\u30E5\u30FC\u30B7\u30E7\u30F3\u3067\u306FAlt+Enter\u304C\u6709\u52B9)",
      "Clear the screen": "\u753B\u9762\u3092\u30AF\u30EA\u30A2",
      "Open input in external editor": "\u5916\u90E8\u30A8\u30C7\u30A3\u30BF\u3067\u5165\u529B\u3092\u958B\u304F",
      "Send message": "\u30E1\u30C3\u30BB\u30FC\u30B8\u3092\u9001\u4FE1",
      "Initializing...": "\u521D\u671F\u5316\u4E2D...",
      "Connecting to MCP servers... ({{connected}}/{{total}})": "MCP\u30B5\u30FC\u30D0\u30FC\u306B\u63A5\u7D9A\u4E2D... ({{connected}}/{{total}})",
      "Type your message or @path/to/file": "\u30E1\u30C3\u30BB\u30FC\u30B8\u3092\u5165\u529B\u3001@\u30D1\u30B9/\u30D5\u30A1\u30A4\u30EB\u3067\u30D5\u30A1\u30A4\u30EB\u3092\u6DFB\u4ED8(D&D\u5BFE\u5FDC)",
      "Press 'i' for INSERT mode and 'Esc' for NORMAL mode.": "'i' \u3067INSERT\u30E2\u30FC\u30C9\u3001'Esc' \u3067NORMAL\u30E2\u30FC\u30C9",
      "Cancel operation / Clear input (double press)": "\u64CD\u4F5C\u3092\u30AD\u30E3\u30F3\u30BB\u30EB / \u5165\u529B\u3092\u30AF\u30EA\u30A2(2\u56DE\u62BC\u3057)",
      "Cycle approval modes": "\u627F\u8A8D\u30E2\u30FC\u30C9\u3092\u5207\u308A\u66FF\u3048",
      "Cycle through your prompt history": "\u30D7\u30ED\u30F3\u30D7\u30C8\u5C65\u6B74\u3092\u9806\u306B\u8868\u793A",
      "For a full list of shortcuts, see {{docPath}}": "\u30B7\u30E7\u30FC\u30C8\u30AB\u30C3\u30C8\u306E\u5B8C\u5168\u306A\u30EA\u30B9\u30C8\u306F {{docPath}} \u3092\u53C2\u7167",
      "docs/keyboard-shortcuts.md": "docs/keyboard-shortcuts.md",
      "for help on Qwen Code": "Qwen Code \u306E\u30D8\u30EB\u30D7",
      "show version info": "\u30D0\u30FC\u30B8\u30E7\u30F3\u60C5\u5831\u3092\u8868\u793A",
      "submit a bug report": "\u30D0\u30B0\u30EC\u30DD\u30FC\u30C8\u3092\u9001\u4FE1",
      "About Qwen Code": "Qwen Code \u306B\u3064\u3044\u3066",
      // ============================================================================
      // System Information Fields
      // ============================================================================
      "CLI Version": "CLI\u30D0\u30FC\u30B8\u30E7\u30F3",
      "Git Commit": "Git\u30B3\u30DF\u30C3\u30C8",
      Model: "\u30E2\u30C7\u30EB",
      Sandbox: "\u30B5\u30F3\u30C9\u30DC\u30C3\u30AF\u30B9",
      "OS Platform": "OS\u30D7\u30E9\u30C3\u30C8\u30D5\u30A9\u30FC\u30E0",
      "OS Arch": "OS\u30A2\u30FC\u30AD\u30C6\u30AF\u30C1\u30E3",
      "OS Release": "OS\u30EA\u30EA\u30FC\u30B9",
      "Node.js Version": "Node.js \u30D0\u30FC\u30B8\u30E7\u30F3",
      "NPM Version": "NPM \u30D0\u30FC\u30B8\u30E7\u30F3",
      "Session ID": "\u30BB\u30C3\u30B7\u30E7\u30F3ID",
      "Auth Method": "\u8A8D\u8A3C\u65B9\u5F0F",
      "Base URL": "\u30D9\u30FC\u30B9URL",
      "Memory Usage": "\u30E1\u30E2\u30EA\u4F7F\u7528\u91CF",
      "IDE Client": "IDE\u30AF\u30E9\u30A4\u30A2\u30F3\u30C8",
      // ============================================================================
      // Commands - General
      // ============================================================================
      "Analyzes the project and creates a tailored QWEN.md file.": "\u30D7\u30ED\u30B8\u30A7\u30AF\u30C8\u3092\u5206\u6790\u3057\u3001\u30AB\u30B9\u30BF\u30DE\u30A4\u30BA\u3055\u308C\u305F QWEN.md \u30D5\u30A1\u30A4\u30EB\u3092\u4F5C\u6210",
      "list available Qwen Code tools. Usage: /tools [desc]": "\u5229\u7528\u53EF\u80FD\u306A Qwen Code \u30C4\u30FC\u30EB\u3092\u4E00\u89A7\u8868\u793A\u3002\u4F7F\u3044\u65B9: /tools [desc]",
      "Available Qwen Code CLI tools:": "\u5229\u7528\u53EF\u80FD\u306A Qwen Code CLI \u30C4\u30FC\u30EB:",
      "No tools available": "\u5229\u7528\u53EF\u80FD\u306A\u30C4\u30FC\u30EB\u306F\u3042\u308A\u307E\u305B\u3093",
      "View or change the approval mode for tool usage": "\u30C4\u30FC\u30EB\u4F7F\u7528\u306E\u627F\u8A8D\u30E2\u30FC\u30C9\u3092\u8868\u793A\u307E\u305F\u306F\u5909\u66F4",
      "View or change the language setting": "\u8A00\u8A9E\u8A2D\u5B9A\u3092\u8868\u793A\u307E\u305F\u306F\u5909\u66F4",
      "change the theme": "\u30C6\u30FC\u30DE\u3092\u5909\u66F4",
      "Select Theme": "\u30C6\u30FC\u30DE\u3092\u9078\u629E",
      Preview: "\u30D7\u30EC\u30D3\u30E5\u30FC",
      "(Use Enter to select, Tab to configure scope)": "(Enter \u3067\u9078\u629E\u3001Tab \u3067\u30B9\u30B3\u30FC\u30D7\u3092\u8A2D\u5B9A)",
      "(Use Enter to apply scope, Tab to select theme)": "(Enter \u3067\u30B9\u30B3\u30FC\u30D7\u3092\u9069\u7528\u3001Tab \u3067\u30C6\u30FC\u30DE\u3092\u9078\u629E)",
      "Theme configuration unavailable due to NO_COLOR env variable.": "NO_COLOR \u74B0\u5883\u5909\u6570\u306E\u305F\u3081\u30C6\u30FC\u30DE\u8A2D\u5B9A\u306F\u5229\u7528\u3067\u304D\u307E\u305B\u3093",
      'Theme "{{themeName}}" not found.': '\u30C6\u30FC\u30DE "{{themeName}}" \u304C\u898B\u3064\u304B\u308A\u307E\u305B\u3093',
      'Theme "{{themeName}}" not found in selected scope.': '\u9078\u629E\u3057\u305F\u30B9\u30B3\u30FC\u30D7\u306B\u30C6\u30FC\u30DE "{{themeName}}" \u304C\u898B\u3064\u304B\u308A\u307E\u305B\u3093',
      "Clear conversation history and free up context": "\u4F1A\u8A71\u5C65\u6B74\u3092\u30AF\u30EA\u30A2\u3057\u3066\u30B3\u30F3\u30C6\u30AD\u30B9\u30C8\u3092\u89E3\u653E",
      "Compresses the context by replacing it with a summary.": "\u30B3\u30F3\u30C6\u30AD\u30B9\u30C8\u3092\u8981\u7D04\u306B\u7F6E\u304D\u63DB\u3048\u3066\u5727\u7E2E",
      "open full Qwen Code documentation in your browser": "\u30D6\u30E9\u30A6\u30B6\u3067 Qwen Code \u306E\u30C9\u30AD\u30E5\u30E1\u30F3\u30C8\u3092\u958B\u304F",
      "Configuration not available.": "\u8A2D\u5B9A\u304C\u5229\u7528\u3067\u304D\u307E\u305B\u3093",
      "change the auth method": "\u8A8D\u8A3C\u65B9\u5F0F\u3092\u5909\u66F4",
      "Configure authentication information for login": "\u30ED\u30B0\u30A4\u30F3\u7528\u306E\u8A8D\u8A3C\u60C5\u5831\u3092\u8A2D\u5B9A",
      "Copy the last result or code snippet to clipboard": "\u6700\u5F8C\u306E\u7D50\u679C\u307E\u305F\u306F\u30B3\u30FC\u30C9\u30B9\u30CB\u30DA\u30C3\u30C8\u3092\u30AF\u30EA\u30C3\u30D7\u30DC\u30FC\u30C9\u306B\u30B3\u30D4\u30FC",
      // ============================================================================
      // Commands - Agents
      // ============================================================================
      "Manage subagents for specialized task delegation.": "\u5C02\u9580\u30BF\u30B9\u30AF\u3092\u59D4\u4EFB\u3059\u308B\u30B5\u30D6\u30A8\u30FC\u30B8\u30A7\u30F3\u30C8\u3092\u7BA1\u7406",
      "Manage existing subagents (view, edit, delete).": "\u65E2\u5B58\u306E\u30B5\u30D6\u30A8\u30FC\u30B8\u30A7\u30F3\u30C8\u3092\u7BA1\u7406(\u8868\u793A\u3001\u7DE8\u96C6\u3001\u524A\u9664)",
      "Create a new subagent with guided setup.": "\u30AC\u30A4\u30C9\u4ED8\u304D\u30BB\u30C3\u30C8\u30A2\u30C3\u30D7\u3067\u65B0\u3057\u3044\u30B5\u30D6\u30A8\u30FC\u30B8\u30A7\u30F3\u30C8\u3092\u4F5C\u6210",
      // ============================================================================
      // Agents - Management Dialog
      // ============================================================================
      Agents: "\u30A8\u30FC\u30B8\u30A7\u30F3\u30C8",
      "Choose Action": "\u30A2\u30AF\u30B7\u30E7\u30F3\u3092\u9078\u629E",
      "Edit {{name}}": "{{name}} \u3092\u7DE8\u96C6",
      "Edit Tools: {{name}}": "\u30C4\u30FC\u30EB\u3092\u7DE8\u96C6: {{name}}",
      "Edit Color: {{name}}": "\u8272\u3092\u7DE8\u96C6: {{name}}",
      "Delete {{name}}": "{{name}} \u3092\u524A\u9664",
      "Unknown Step": "\u4E0D\u660E\u306A\u30B9\u30C6\u30C3\u30D7",
      "Esc to close": "Esc \u3067\u9589\u3058\u308B",
      "Enter to select, \u2191\u2193 to navigate, Esc to close": "Enter \u3067\u9078\u629E\u3001\u2191\u2193 \u3067\u79FB\u52D5\u3001Esc \u3067\u9589\u3058\u308B",
      "Esc to go back": "Esc \u3067\u623B\u308B",
      "Enter to confirm, Esc to cancel": "Enter \u3067\u78BA\u5B9A\u3001Esc \u3067\u30AD\u30E3\u30F3\u30BB\u30EB",
      "Enter to select, \u2191\u2193 to navigate, Esc to go back": "Enter \u3067\u9078\u629E\u3001\u2191\u2193 \u3067\u79FB\u52D5\u3001Esc \u3067\u623B\u308B",
      "Invalid step: {{step}}": "\u7121\u52B9\u306A\u30B9\u30C6\u30C3\u30D7: {{step}}",
      "No subagents found.": "\u30B5\u30D6\u30A8\u30FC\u30B8\u30A7\u30F3\u30C8\u304C\u898B\u3064\u304B\u308A\u307E\u305B\u3093",
      "Use '/agents create' to create your first subagent.": "'/agents create' \u3067\u6700\u521D\u306E\u30B5\u30D6\u30A8\u30FC\u30B8\u30A7\u30F3\u30C8\u3092\u4F5C\u6210\u3057\u3066\u304F\u3060\u3055\u3044",
      "(built-in)": "(\u7D44\u307F\u8FBC\u307F)",
      "(overridden by project level agent)": "(\u30D7\u30ED\u30B8\u30A7\u30AF\u30C8\u30EC\u30D9\u30EB\u306E\u30A8\u30FC\u30B8\u30A7\u30F3\u30C8\u3067\u4E0A\u66F8\u304D)",
      "Project Level ({{path}})": "\u30D7\u30ED\u30B8\u30A7\u30AF\u30C8\u30EC\u30D9\u30EB ({{path}})",
      "User Level ({{path}})": "\u30E6\u30FC\u30B6\u30FC\u30EC\u30D9\u30EB ({{path}})",
      "Built-in Agents": "\u7D44\u307F\u8FBC\u307F\u30A8\u30FC\u30B8\u30A7\u30F3\u30C8",
      "Using: {{count}} agents": "\u4F7F\u7528\u4E2D: {{count}} \u30A8\u30FC\u30B8\u30A7\u30F3\u30C8",
      "View Agent": "\u30A8\u30FC\u30B8\u30A7\u30F3\u30C8\u3092\u8868\u793A",
      "Edit Agent": "\u30A8\u30FC\u30B8\u30A7\u30F3\u30C8\u3092\u7DE8\u96C6",
      "Delete Agent": "\u30A8\u30FC\u30B8\u30A7\u30F3\u30C8\u3092\u524A\u9664",
      Back: "\u623B\u308B",
      "No agent selected": "\u30A8\u30FC\u30B8\u30A7\u30F3\u30C8\u304C\u9078\u629E\u3055\u308C\u3066\u3044\u307E\u305B\u3093",
      "File Path: ": "\u30D5\u30A1\u30A4\u30EB\u30D1\u30B9: ",
      "Tools: ": "\u30C4\u30FC\u30EB: ",
      "Color: ": "\u8272: ",
      "Description:": "\u8AAC\u660E:",
      "System Prompt:": "\u30B7\u30B9\u30C6\u30E0\u30D7\u30ED\u30F3\u30D7\u30C8:",
      "Open in editor": "\u30A8\u30C7\u30A3\u30BF\u3067\u958B\u304F",
      "Edit tools": "\u30C4\u30FC\u30EB\u3092\u7DE8\u96C6",
      "Edit color": "\u8272\u3092\u7DE8\u96C6",
      "\u274C Error:": "\u274C \u30A8\u30E9\u30FC:",
      'Are you sure you want to delete agent "{{name}}"?': '\u30A8\u30FC\u30B8\u30A7\u30F3\u30C8 "{{name}}" \u3092\u524A\u9664\u3057\u3066\u3082\u3088\u308D\u3057\u3044\u3067\u3059\u304B?',
      "Project Level (.qwen/agents/)": "\u30D7\u30ED\u30B8\u30A7\u30AF\u30C8\u30EC\u30D9\u30EB (.qwen/agents/)",
      "User Level (~/.qwen/agents/)": "\u30E6\u30FC\u30B6\u30FC\u30EC\u30D9\u30EB (~/.qwen/agents/)",
      "\u2705 Subagent Created Successfully!": "\u2705 \u30B5\u30D6\u30A8\u30FC\u30B8\u30A7\u30F3\u30C8\u306E\u4F5C\u6210\u306B\u6210\u529F\u3057\u307E\u3057\u305F!",
      'Subagent "{{name}}" has been saved to {{level}} level.': '\u30B5\u30D6\u30A8\u30FC\u30B8\u30A7\u30F3\u30C8 "{{name}}" \u3092 {{level}} \u306B\u4FDD\u5B58\u3057\u307E\u3057\u305F',
      "Name: ": "\u540D\u524D: ",
      "Location: ": "\u5834\u6240: ",
      "\u274C Error saving subagent:": "\u274C \u30B5\u30D6\u30A8\u30FC\u30B8\u30A7\u30F3\u30C8\u4FDD\u5B58\u30A8\u30E9\u30FC:",
      "Warnings:": "\u8B66\u544A:",
      "Step {{n}}: Choose Location": "\u30B9\u30C6\u30C3\u30D7 {{n}}: \u5834\u6240\u3092\u9078\u629E",
      "Step {{n}}: Choose Generation Method": "\u30B9\u30C6\u30C3\u30D7 {{n}}: \u4F5C\u6210\u65B9\u6CD5\u3092\u9078\u629E",
      "Generate with Qwen Code (Recommended)": "Qwen Code \u3067\u751F\u6210(\u63A8\u5968)",
      "Manual Creation": "\u624B\u52D5\u4F5C\u6210",
      "Generating subagent configuration...": "\u30B5\u30D6\u30A8\u30FC\u30B8\u30A7\u30F3\u30C8\u8A2D\u5B9A\u3092\u751F\u6210\u4E2D...",
      "Failed to generate subagent: {{error}}": "\u30B5\u30D6\u30A8\u30FC\u30B8\u30A7\u30F3\u30C8\u306E\u751F\u6210\u306B\u5931\u6557: {{error}}",
      "Step {{n}}: Describe Your Subagent": "\u30B9\u30C6\u30C3\u30D7 {{n}}: \u30B5\u30D6\u30A8\u30FC\u30B8\u30A7\u30F3\u30C8\u3092\u8AAC\u660E",
      "Step {{n}}: Enter Subagent Name": "\u30B9\u30C6\u30C3\u30D7 {{n}}: \u30B5\u30D6\u30A8\u30FC\u30B8\u30A7\u30F3\u30C8\u540D\u3092\u5165\u529B",
      "Step {{n}}: Enter System Prompt": "\u30B9\u30C6\u30C3\u30D7 {{n}}: \u30B7\u30B9\u30C6\u30E0\u30D7\u30ED\u30F3\u30D7\u30C8\u3092\u5165\u529B",
      "Step {{n}}: Enter Description": "\u30B9\u30C6\u30C3\u30D7 {{n}}: \u8AAC\u660E\u3092\u5165\u529B",
      "Step {{n}}: Select Tools": "\u30B9\u30C6\u30C3\u30D7 {{n}}: \u30C4\u30FC\u30EB\u3092\u9078\u629E",
      "All Tools (Default)": "\u5168\u30C4\u30FC\u30EB(\u30C7\u30D5\u30A9\u30EB\u30C8)",
      "All Tools": "\u5168\u30C4\u30FC\u30EB",
      "Read-only Tools": "\u8AAD\u307F\u53D6\u308A\u5C02\u7528\u30C4\u30FC\u30EB",
      "Read & Edit Tools": "\u8AAD\u307F\u53D6\u308A\uFF06\u7DE8\u96C6\u30C4\u30FC\u30EB",
      "Read & Edit & Execution Tools": "\u8AAD\u307F\u53D6\u308A\uFF06\u7DE8\u96C6\uFF06\u5B9F\u884C\u30C4\u30FC\u30EB",
      "Selected tools:": "\u9078\u629E\u3055\u308C\u305F\u30C4\u30FC\u30EB:",
      "Step {{n}}: Choose Background Color": "\u30B9\u30C6\u30C3\u30D7 {{n}}: \u80CC\u666F\u8272\u3092\u9078\u629E",
      "Step {{n}}: Confirm and Save": "\u30B9\u30C6\u30C3\u30D7 {{n}}: \u78BA\u8A8D\u3057\u3066\u4FDD\u5B58",
      "Esc to cancel": "Esc \u3067\u30AD\u30E3\u30F3\u30BB\u30EB",
      cancel: "\u30AD\u30E3\u30F3\u30BB\u30EB",
      "go back": "\u623B\u308B",
      "\u2191\u2193 to navigate, ": "\u2191\u2193 \u3067\u79FB\u52D5\u3001",
      "Name cannot be empty.": "\u540D\u524D\u306F\u7A7A\u306B\u3067\u304D\u307E\u305B\u3093",
      "System prompt cannot be empty.": "\u30B7\u30B9\u30C6\u30E0\u30D7\u30ED\u30F3\u30D7\u30C8\u306F\u7A7A\u306B\u3067\u304D\u307E\u305B\u3093",
      "Description cannot be empty.": "\u8AAC\u660E\u306F\u7A7A\u306B\u3067\u304D\u307E\u305B\u3093",
      "Failed to launch editor: {{error}}": "\u30A8\u30C7\u30A3\u30BF\u306E\u8D77\u52D5\u306B\u5931\u6557: {{error}}",
      "Failed to save and edit subagent: {{error}}": "\u30B5\u30D6\u30A8\u30FC\u30B8\u30A7\u30F3\u30C8\u306E\u4FDD\u5B58\u3068\u7DE8\u96C6\u306B\u5931\u6557: {{error}}",
      'Name "{{name}}" already exists at {{level}} level - will overwrite existing subagent': '"{{name}}" \u306F {{level}} \u306B\u65E2\u306B\u5B58\u5728\u3057\u307E\u3059 - \u65E2\u5B58\u306E\u30B5\u30D6\u30A8\u30FC\u30B8\u30A7\u30F3\u30C8\u3092\u4E0A\u66F8\u304D\u3057\u307E\u3059',
      'Name "{{name}}" exists at user level - project level will take precedence': '"{{name}}" \u306F\u30E6\u30FC\u30B6\u30FC\u30EC\u30D9\u30EB\u306B\u5B58\u5728\u3057\u307E\u3059 - \u30D7\u30ED\u30B8\u30A7\u30AF\u30C8\u30EC\u30D9\u30EB\u304C\u512A\u5148\u3055\u308C\u307E\u3059',
      'Name "{{name}}" exists at project level - existing subagent will take precedence': '"{{name}}" \u306F\u30D7\u30ED\u30B8\u30A7\u30AF\u30C8\u30EC\u30D9\u30EB\u306B\u5B58\u5728\u3057\u307E\u3059 - \u65E2\u5B58\u306E\u30B5\u30D6\u30A8\u30FC\u30B8\u30A7\u30F3\u30C8\u304C\u512A\u5148\u3055\u308C\u307E\u3059',
      "Description is over {{length}} characters": "\u8AAC\u660E\u304C {{length}} \u6587\u5B57\u3092\u8D85\u3048\u3066\u3044\u307E\u3059",
      "System prompt is over {{length}} characters": "\u30B7\u30B9\u30C6\u30E0\u30D7\u30ED\u30F3\u30D7\u30C8\u304C {{length}} \u6587\u5B57\u3092\u8D85\u3048\u3066\u3044\u307E\u3059",
      "Describe what this subagent should do and when it should be used. (Be comprehensive for best results)": "\u3053\u306E\u30B5\u30D6\u30A8\u30FC\u30B8\u30A7\u30F3\u30C8\u306E\u5F79\u5272\u3068\u4F7F\u7528\u30BF\u30A4\u30DF\u30F3\u30B0\u3092\u8AAC\u660E\u3057\u3066\u304F\u3060\u3055\u3044(\u8A73\u7D30\u306B\u8A18\u8FF0\u3059\u308B\u307B\u3069\u826F\u3044\u7D50\u679C\u304C\u5F97\u3089\u308C\u307E\u3059)",
      "e.g., Expert code reviewer that reviews code based on best practices...": "\u4F8B: \u30D9\u30B9\u30C8\u30D7\u30E9\u30AF\u30C6\u30A3\u30B9\u306B\u57FA\u3065\u3044\u3066\u30B3\u30FC\u30C9\u3092\u30EC\u30D3\u30E5\u30FC\u3059\u308B\u30A8\u30AD\u30B9\u30D1\u30FC\u30C8\u30EC\u30D3\u30E5\u30A2\u30FC...",
      "All tools selected, including MCP tools": "MCP\u30C4\u30FC\u30EB\u3092\u542B\u3080\u3059\u3079\u3066\u306E\u30C4\u30FC\u30EB\u3092\u9078\u629E",
      "Read-only tools:": "\u8AAD\u307F\u53D6\u308A\u5C02\u7528\u30C4\u30FC\u30EB:",
      "Edit tools:": "\u7DE8\u96C6\u30C4\u30FC\u30EB:",
      "Execution tools:": "\u5B9F\u884C\u30C4\u30FC\u30EB:",
      "Press Enter to save, e to save and edit, Esc to go back": "Enter \u3067\u4FDD\u5B58\u3001e \u3067\u4FDD\u5B58\u3057\u3066\u7DE8\u96C6\u3001Esc \u3067\u623B\u308B",
      "Press Enter to continue, {{navigation}}Esc to {{action}}": "Enter \u3067\u7D9A\u884C\u3001{{navigation}}Esc \u3067{{action}}",
      "Enter a clear, unique name for this subagent.": "\u3053\u306E\u30B5\u30D6\u30A8\u30FC\u30B8\u30A7\u30F3\u30C8\u306E\u660E\u78BA\u3067\u4E00\u610F\u306A\u540D\u524D\u3092\u5165\u529B\u3057\u3066\u304F\u3060\u3055\u3044",
      "e.g., Code Reviewer": "\u4F8B: \u30B3\u30FC\u30C9\u30EC\u30D3\u30E5\u30A2\u30FC",
      "Write the system prompt that defines this subagent's behavior. Be comprehensive for best results.": "\u3053\u306E\u30B5\u30D6\u30A8\u30FC\u30B8\u30A7\u30F3\u30C8\u306E\u52D5\u4F5C\u3092\u5B9A\u7FA9\u3059\u308B\u30B7\u30B9\u30C6\u30E0\u30D7\u30ED\u30F3\u30D7\u30C8\u3092\u8A18\u8FF0\u3057\u3066\u304F\u3060\u3055\u3044 (\u8A73\u7D30\u306B\u66F8\u304F\u307B\u3069\u826F\u3044\u7D50\u679C\u304C\u5F97\u3089\u308C\u307E\u3059)",
      "e.g., You are an expert code reviewer...": "\u4F8B: \u3042\u306A\u305F\u306F\u30A8\u30AD\u30B9\u30D1\u30FC\u30C8\u30B3\u30FC\u30C9\u30EC\u30D3\u30E5\u30A2\u30FC\u3067\u3059...",
      "Describe when and how this subagent should be used.": "\u3053\u306E\u30B5\u30D6\u30A8\u30FC\u30B8\u30A7\u30F3\u30C8\u3092\u3044\u3064\u3069\u306E\u3088\u3046\u306B\u4F7F\u7528\u3059\u308B\u304B\u3092\u8AAC\u660E\u3057\u3066\u304F\u3060\u3055\u3044",
      "e.g., Reviews code for best practices and potential bugs.": "\u4F8B: \u30D9\u30B9\u30C8\u30D7\u30E9\u30AF\u30C6\u30A3\u30B9\u3068\u6F5C\u5728\u7684\u306A\u30D0\u30B0\u306B\u3064\u3044\u3066\u30B3\u30FC\u30C9\u3092\u30EC\u30D3\u30E5\u30FC\u3057\u307E\u3059\u3002",
      // Commands - General (continued)
      "(Use Enter to select{{tabText}})": "(Enter \u3067\u9078\u629E{{tabText}})",
      ", Tab to change focus": "\u3001Tab \u3067\u30D5\u30A9\u30FC\u30AB\u30B9\u5909\u66F4",
      "To see changes, Qwen Code must be restarted. Press r to exit and apply changes now.": "\u5909\u66F4\u3092\u78BA\u8A8D\u3059\u308B\u306B\u306F Qwen Code \u3092\u518D\u8D77\u52D5\u3059\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059\u3002 r \u3092\u62BC\u3057\u3066\u7D42\u4E86\u3057\u3001\u5909\u66F4\u3092\u9069\u7528\u3057\u3066\u304F\u3060\u3055\u3044",
      'The command "/{{command}}" is not supported in non-interactive mode.': '\u30B3\u30DE\u30F3\u30C9 "/{{command}}" \u306F\u975E\u5BFE\u8A71\u30E2\u30FC\u30C9\u3067\u306F\u30B5\u30DD\u30FC\u30C8\u3055\u308C\u3066\u3044\u307E\u305B\u3093',
      "View and edit Qwen Code settings": "Qwen Code \u306E\u8A2D\u5B9A\u3092\u8868\u793A\u30FB\u7DE8\u96C6",
      Settings: "\u8A2D\u5B9A",
      "Vim Mode": "Vim \u30E2\u30FC\u30C9",
      "Disable Auto Update": "\u81EA\u52D5\u66F4\u65B0\u3092\u7121\u52B9\u5316",
      Language: "\u8A00\u8A9E",
      "Output Format": "\u51FA\u529B\u5F62\u5F0F",
      "Hide Tips": "\u30D2\u30F3\u30C8\u3092\u975E\u8868\u793A",
      "Hide Banner": "\u30D0\u30CA\u30FC\u3092\u975E\u8868\u793A",
      "Show Memory Usage": "\u30E1\u30E2\u30EA\u4F7F\u7528\u91CF\u3092\u8868\u793A",
      "Show Line Numbers": "\u884C\u756A\u53F7\u3092\u8868\u793A",
      Text: "\u30C6\u30AD\u30B9\u30C8",
      JSON: "JSON",
      Plan: "\u30D7\u30E9\u30F3",
      Default: "\u30C7\u30D5\u30A9\u30EB\u30C8",
      "Auto Edit": "\u81EA\u52D5\u7DE8\u96C6",
      YOLO: "YOLO",
      "toggle vim mode on/off": "Vim \u30E2\u30FC\u30C9\u306E\u30AA\u30F3/\u30AA\u30D5\u3092\u5207\u308A\u66FF\u3048",
      "exit the cli": "CLI\u3092\u7D42\u4E86",
      Timeout: "\u30BF\u30A4\u30E0\u30A2\u30A6\u30C8",
      "Max Retries": "\u6700\u5927\u30EA\u30C8\u30E9\u30A4\u56DE\u6570",
      "Auto Accept": "\u81EA\u52D5\u627F\u8A8D",
      "Folder Trust": "\u30D5\u30A9\u30EB\u30C0\u306E\u4FE1\u983C",
      "Enable Prompt Completion": "\u30D7\u30ED\u30F3\u30D7\u30C8\u88DC\u5B8C\u3092\u6709\u52B9\u5316",
      "Debug Keystroke Logging": "\u30AD\u30FC\u30B9\u30C8\u30ED\u30FC\u30AF\u306E\u30C7\u30D0\u30C3\u30B0\u30ED\u30B0",
      "Hide Window Title": "\u30A6\u30A3\u30F3\u30C9\u30A6\u30BF\u30A4\u30C8\u30EB\u3092\u975E\u8868\u793A",
      "Show Status in Title": "\u30BF\u30A4\u30C8\u30EB\u306B\u30B9\u30C6\u30FC\u30BF\u30B9\u3092\u8868\u793A",
      "Hide Context Summary": "\u30B3\u30F3\u30C6\u30AD\u30B9\u30C8\u8981\u7D04\u3092\u975E\u8868\u793A",
      "Hide CWD": "\u4F5C\u696D\u30C7\u30A3\u30EC\u30AF\u30C8\u30EA\u3092\u975E\u8868\u793A",
      "Hide Sandbox Status": "\u30B5\u30F3\u30C9\u30DC\u30C3\u30AF\u30B9\u72B6\u614B\u3092\u975E\u8868\u793A",
      "Hide Model Info": "\u30E2\u30C7\u30EB\u60C5\u5831\u3092\u975E\u8868\u793A",
      "Hide Footer": "\u30D5\u30C3\u30BF\u30FC\u3092\u975E\u8868\u793A",
      "Show Citations": "\u5F15\u7528\u3092\u8868\u793A",
      "Custom Witty Phrases": "\u30AB\u30B9\u30BF\u30E0\u30A6\u30A3\u30C3\u30C8\u30D5\u30EC\u30FC\u30BA",
      "Enable Welcome Back": "\u30A6\u30A7\u30EB\u30AB\u30E0\u30D0\u30C3\u30AF\u6A5F\u80FD\u3092\u6709\u52B9\u5316",
      "Disable Loading Phrases": "\u30ED\u30FC\u30C7\u30A3\u30F3\u30B0\u30D5\u30EC\u30FC\u30BA\u3092\u7121\u52B9\u5316",
      "Screen Reader Mode": "\u30B9\u30AF\u30EA\u30FC\u30F3\u30EA\u30FC\u30C0\u30FC\u30E2\u30FC\u30C9",
      "IDE Mode": "IDE\u30E2\u30FC\u30C9",
      "Max Session Turns": "\u6700\u5927\u30BB\u30C3\u30B7\u30E7\u30F3\u30BF\u30FC\u30F3\u6570",
      "Skip Next Speaker Check": "\u6B21\u306E\u767A\u8A00\u8005\u30C1\u30A7\u30C3\u30AF\u3092\u30B9\u30AD\u30C3\u30D7",
      "Skip Loop Detection": "\u30EB\u30FC\u30D7\u691C\u51FA\u3092\u30B9\u30AD\u30C3\u30D7",
      "Skip Startup Context": "\u8D77\u52D5\u6642\u30B3\u30F3\u30C6\u30AD\u30B9\u30C8\u3092\u30B9\u30AD\u30C3\u30D7",
      "Enable OpenAI Logging": "OpenAI \u30ED\u30B0\u3092\u6709\u52B9\u5316",
      "OpenAI Logging Directory": "OpenAI \u30ED\u30B0\u30C7\u30A3\u30EC\u30AF\u30C8\u30EA",
      "Disable Cache Control": "\u30AD\u30E3\u30C3\u30B7\u30E5\u5236\u5FA1\u3092\u7121\u52B9\u5316",
      "Memory Discovery Max Dirs": "\u30E1\u30E2\u30EA\u691C\u51FA\u306E\u6700\u5927\u30C7\u30A3\u30EC\u30AF\u30C8\u30EA\u6570",
      "Load Memory From Include Directories": "\u30A4\u30F3\u30AF\u30EB\u30FC\u30C9\u30C7\u30A3\u30EC\u30AF\u30C8\u30EA\u304B\u3089\u30E1\u30E2\u30EA\u3092\u8AAD\u307F\u8FBC\u307F",
      "Respect .gitignore": ".gitignore \u3092\u512A\u5148",
      "Respect .qwenignore": ".qwenignore \u3092\u512A\u5148",
      "Enable Recursive File Search": "\u518D\u5E30\u7684\u30D5\u30A1\u30A4\u30EB\u691C\u7D22\u3092\u6709\u52B9\u5316",
      "Disable Fuzzy Search": "\u30D5\u30A1\u30B8\u30FC\u691C\u7D22\u3092\u7121\u52B9\u5316",
      "Enable Interactive Shell": "\u5BFE\u8A71\u578B\u30B7\u30A7\u30EB\u3092\u6709\u52B9\u5316",
      "Show Color": "\u8272\u3092\u8868\u793A",
      "Use Ripgrep": "Ripgrep \u3092\u4F7F\u7528",
      "Use Builtin Ripgrep": "\u7D44\u307F\u8FBC\u307F Ripgrep \u3092\u4F7F\u7528",
      "Enable Tool Output Truncation": "\u30C4\u30FC\u30EB\u51FA\u529B\u306E\u5207\u308A\u8A70\u3081\u3092\u6709\u52B9\u5316",
      "Tool Output Truncation Threshold": "\u30C4\u30FC\u30EB\u51FA\u529B\u5207\u308A\u8A70\u3081\u306E\u3057\u304D\u3044\u5024",
      "Tool Output Truncation Lines": "\u30C4\u30FC\u30EB\u51FA\u529B\u306E\u5207\u308A\u8A70\u3081\u884C\u6570",
      "Vision Model Preview": "\u30D3\u30B8\u30E7\u30F3\u30E2\u30C7\u30EB\u30D7\u30EC\u30D3\u30E5\u30FC",
      "Tool Schema Compliance": "\u30C4\u30FC\u30EB\u30B9\u30AD\u30FC\u30DE\u6E96\u62E0",
      "Auto (detect from system)": "\u81EA\u52D5(\u30B7\u30B9\u30C6\u30E0\u304B\u3089\u691C\u51FA)",
      "check session stats. Usage: /stats [model|tools]": "\u30BB\u30C3\u30B7\u30E7\u30F3\u7D71\u8A08\u3092\u78BA\u8A8D\u3002\u4F7F\u3044\u65B9: /stats [model|tools]",
      "Show model-specific usage statistics.": "\u30E2\u30C7\u30EB\u5225\u306E\u4F7F\u7528\u7D71\u8A08\u3092\u8868\u793A",
      "Show tool-specific usage statistics.": "\u30C4\u30FC\u30EB\u5225\u306E\u4F7F\u7528\u7D71\u8A08\u3092\u8868\u793A",
      "list configured MCP servers and tools, or authenticate with OAuth-enabled servers": "\u8A2D\u5B9A\u6E08\u307F\u306EMCP\u30B5\u30FC\u30D0\u30FC\u3068\u30C4\u30FC\u30EB\u3092\u4E00\u89A7\u8868\u793A\u3001\u307E\u305F\u306FOAuth\u5BFE\u5FDC\u30B5\u30FC\u30D0\u30FC\u3067\u8A8D\u8A3C",
      "Manage workspace directories": "\u30EF\u30FC\u30AF\u30B9\u30DA\u30FC\u30B9\u30C7\u30A3\u30EC\u30AF\u30C8\u30EA\u3092\u7BA1\u7406",
      "Add directories to the workspace. Use comma to separate multiple paths": "\u30EF\u30FC\u30AF\u30B9\u30DA\u30FC\u30B9\u306B\u30C7\u30A3\u30EC\u30AF\u30C8\u30EA\u3092\u8FFD\u52A0\u3002\u8907\u6570\u30D1\u30B9\u306F\u30AB\u30F3\u30DE\u3067\u533A\u5207\u3063\u3066\u304F\u3060\u3055\u3044",
      "Show all directories in the workspace": "\u30EF\u30FC\u30AF\u30B9\u30DA\u30FC\u30B9\u5185\u306E\u3059\u3079\u3066\u306E\u30C7\u30A3\u30EC\u30AF\u30C8\u30EA\u3092\u8868\u793A",
      "set external editor preference": "\u5916\u90E8\u30A8\u30C7\u30A3\u30BF\u306E\u8A2D\u5B9A",
      "Manage extensions": "\u62E1\u5F35\u6A5F\u80FD\u3092\u7BA1\u7406",
      "List active extensions": "\u6709\u52B9\u306A\u62E1\u5F35\u6A5F\u80FD\u3092\u4E00\u89A7\u8868\u793A",
      "Update extensions. Usage: update <extension-names>|--all": "\u62E1\u5F35\u6A5F\u80FD\u3092\u66F4\u65B0\u3002\u4F7F\u3044\u65B9: update <\u62E1\u5F35\u6A5F\u80FD\u540D>|--all",
      "You are installing an extension from {{originSource}}. Some features may not work perfectly with Qwen Code.": "{{originSource}} \u304B\u3089\u62E1\u5F35\u6A5F\u80FD\u3092\u30A4\u30F3\u30B9\u30C8\u30FC\u30EB\u3057\u3066\u3044\u307E\u3059\u3002\u4E00\u90E8\u306E\u6A5F\u80FD\u306F Qwen Code \u3067\u5B8C\u5168\u306B\u52D5\u4F5C\u3057\u306A\u3044\u53EF\u80FD\u6027\u304C\u3042\u308A\u307E\u3059\u3002",
      "manage IDE integration": "IDE\u9023\u643A\u3092\u7BA1\u7406",
      "check status of IDE integration": "IDE\u9023\u643A\u306E\u72B6\u614B\u3092\u78BA\u8A8D",
      "install required IDE companion for {{ideName}}": "{{ideName}} \u7528\u306E\u5FC5\u8981\u306AIDE\u30B3\u30F3\u30D1\u30CB\u30AA\u30F3\u3092\u30A4\u30F3\u30B9\u30C8\u30FC\u30EB",
      "enable IDE integration": "IDE\u9023\u643A\u3092\u6709\u52B9\u5316",
      "disable IDE integration": "IDE\u9023\u643A\u3092\u7121\u52B9\u5316",
      "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.": "\u73FE\u5728\u306E\u74B0\u5883\u3067\u306FIDE\u9023\u643A\u306F\u30B5\u30DD\u30FC\u30C8\u3055\u308C\u3066\u3044\u307E\u305B\u3093\u3002\u3053\u306E\u6A5F\u80FD\u3092\u4F7F\u7528\u3059\u308B\u306B\u306F\u3001VS Code \u307E\u305F\u306F VS Code \u6D3E\u751F\u30A8\u30C7\u30A3\u30BF\u3067 Qwen Code \u3092\u5B9F\u884C\u3057\u3066\u304F\u3060\u3055\u3044",
      "Set up GitHub Actions": "GitHub Actions \u3092\u8A2D\u5B9A",
      "Configure terminal keybindings for multiline input (VS Code, Cursor, Windsurf, Trae)": "\u8907\u6570\u884C\u5165\u529B\u7528\u306E\u30BF\u30FC\u30DF\u30CA\u30EB\u30AD\u30FC\u30D0\u30A4\u30F3\u30C9\u3092\u8A2D\u5B9A(VS Code\u3001Cursor\u3001Windsurf\u3001Trae)",
      "Please restart your terminal for the changes to take effect.": "\u5909\u66F4\u3092\u6709\u52B9\u306B\u3059\u308B\u306B\u306F\u30BF\u30FC\u30DF\u30CA\u30EB\u3092\u518D\u8D77\u52D5\u3057\u3066\u304F\u3060\u3055\u3044",
      "Failed to configure terminal: {{error}}": "\u30BF\u30FC\u30DF\u30CA\u30EB\u306E\u8A2D\u5B9A\u306B\u5931\u6557: {{error}}",
      "Could not determine {{terminalName}} config path on Windows: APPDATA environment variable is not set.": "Windows \u3067 {{terminalName}} \u306E\u8A2D\u5B9A\u30D1\u30B9\u3092\u7279\u5B9A\u3067\u304D\u307E\u305B\u3093: APPDATA \u74B0\u5883\u5909\u6570\u304C\u8A2D\u5B9A\u3055\u308C\u3066\u3044\u307E\u305B\u3093",
      "{{terminalName}} keybindings.json exists but is not a valid JSON array. Please fix the file manually or delete it to allow automatic configuration.": "{{terminalName}} \u306E keybindings.json \u306F\u5B58\u5728\u3057\u307E\u3059\u304C\u3001\u6709\u52B9\u306AJSON\u914D\u5217\u3067\u306F\u3042\u308A\u307E\u305B\u3093\u3002\u30D5\u30A1\u30A4\u30EB\u3092\u624B\u52D5\u3067\u4FEE\u6B63\u3059\u308B\u304B\u3001\u524A\u9664\u3057\u3066\u81EA\u52D5\u8A2D\u5B9A\u3092\u8A31\u53EF\u3057\u3066\u304F\u3060\u3055\u3044",
      "File: {{file}}": "\u30D5\u30A1\u30A4\u30EB: {{file}}",
      "Failed to parse {{terminalName}} keybindings.json. The file contains invalid JSON. Please fix the file manually or delete it to allow automatic configuration.": "{{terminalName}} \u306E keybindings.json \u306E\u89E3\u6790\u306B\u5931\u6557\u3057\u307E\u3057\u305F\u3002\u30D5\u30A1\u30A4\u30EB\u306B\u7121\u52B9\u306AJSON\u304C\u542B\u307E\u308C\u3066\u3044\u307E\u3059\u3002\u624B\u52D5\u3067\u4FEE\u6B63\u3059\u308B\u304B\u3001\u524A\u9664\u3057\u3066\u81EA\u52D5\u8A2D\u5B9A\u3092\u8A31\u53EF\u3057\u3066\u304F\u3060\u3055\u3044",
      "Error: {{error}}": "\u30A8\u30E9\u30FC: {{error}}",
      "Shift+Enter binding already exists": "Shift+Enter \u30D0\u30A4\u30F3\u30C9\u306F\u65E2\u306B\u5B58\u5728\u3057\u307E\u3059",
      "Ctrl+Enter binding already exists": "Ctrl+Enter \u30D0\u30A4\u30F3\u30C9\u306F\u65E2\u306B\u5B58\u5728\u3057\u307E\u3059",
      "Existing keybindings detected. Will not modify to avoid conflicts.": "\u65E2\u5B58\u306E\u30AD\u30FC\u30D0\u30A4\u30F3\u30C9\u304C\u691C\u51FA\u3055\u308C\u307E\u3057\u305F\u3002\u7AF6\u5408\u3092\u907F\u3051\u308B\u305F\u3081\u5909\u66F4\u3092\u3057\u307E\u305B\u3093",
      "Please check and modify manually if needed: {{file}}": "\u5FC5\u8981\u306B\u5FDC\u3058\u3066\u624B\u52D5\u3067\u78BA\u8A8D\u30FB\u5909\u66F4\u3057\u3066\u304F\u3060\u3055\u3044: {{file}}",
      "Added Shift+Enter and Ctrl+Enter keybindings to {{terminalName}}.": "{{terminalName}} \u306B Shift+Enter \u3068 Ctrl+Enter \u306E\u30AD\u30FC\u30D0\u30A4\u30F3\u30C9\u3092\u8FFD\u52A0\u3057\u307E\u3057\u305F",
      "Modified: {{file}}": "\u5909\u66F4\u6E08\u307F: {{file}}",
      "{{terminalName}} keybindings already configured.": "{{terminalName}} \u306E\u30AD\u30FC\u30D0\u30A4\u30F3\u30C9\u306F\u65E2\u306B\u8A2D\u5B9A\u3055\u308C\u3066\u3044\u307E\u3059",
      "Failed to configure {{terminalName}}.": "{{terminalName}} \u306E\u8A2D\u5B9A\u306B\u5931\u6557\u3057\u307E\u3057\u305F",
      "Your terminal is already configured for an optimal experience with multiline input (Shift+Enter and Ctrl+Enter).": "\u30BF\u30FC\u30DF\u30CA\u30EB\u306F\u8907\u6570\u884C\u5165\u529B(Shift+Enter \u3068 Ctrl+Enter)\u306B\u6700\u9069\u5316\u3055\u308C\u3066\u3044\u307E\u3059",
      "Could not detect terminal type. Supported terminals: VS Code, Cursor, Windsurf, and Trae.": "\u30BF\u30FC\u30DF\u30CA\u30EB\u306E\u7A2E\u985E\u3092\u691C\u51FA\u3067\u304D\u307E\u305B\u3093\u3067\u3057\u305F\u3002\u30B5\u30DD\u30FC\u30C8\u3055\u308C\u3066\u3044\u308B\u30BF\u30FC\u30DF\u30CA\u30EB: VS Code\u3001Cursor\u3001Windsurf\u3001Trae",
      'Terminal "{{terminal}}" is not supported yet.': '\u30BF\u30FC\u30DF\u30CA\u30EB "{{terminal}}" \u306F\u307E\u3060\u30B5\u30DD\u30FC\u30C8\u3055\u308C\u3066\u3044\u307E\u305B\u3093',
      // Commands - Language
      "Invalid language. Available: {{options}}": "\u7121\u52B9\u306A\u8A00\u8A9E\u3067\u3059\u3002\u4F7F\u7528\u53EF\u80FD: {{options}}",
      "Language subcommands do not accept additional arguments.": "\u8A00\u8A9E\u30B5\u30D6\u30B3\u30DE\u30F3\u30C9\u306F\u8FFD\u52A0\u306E\u5F15\u6570\u3092\u53D7\u3051\u4ED8\u3051\u307E\u305B\u3093",
      "Current UI language: {{lang}}": "\u73FE\u5728\u306EUI\u8A00\u8A9E: {{lang}}",
      "Current LLM output language: {{lang}}": "\u73FE\u5728\u306ELLM\u51FA\u529B\u8A00\u8A9E: {{lang}}",
      "LLM output language not set": "LLM\u51FA\u529B\u8A00\u8A9E\u304C\u8A2D\u5B9A\u3055\u308C\u3066\u3044\u307E\u305B\u3093",
      "Set UI language": "UI\u8A00\u8A9E\u3092\u8A2D\u5B9A",
      "Set LLM output language": "LLM\u51FA\u529B\u8A00\u8A9E\u3092\u8A2D\u5B9A",
      "Usage: /language ui [{{options}}]": "\u4F7F\u3044\u65B9: /language ui [{{options}}]",
      "Usage: /language output <language>": "\u4F7F\u3044\u65B9: /language output <\u8A00\u8A9E>",
      "Example: /language output \u4E2D\u6587": "\u4F8B: /language output \u4E2D\u6587",
      "Example: /language output English": "\u4F8B: /language output English",
      "Example: /language output \u65E5\u672C\u8A9E": "\u4F8B: /language output \u65E5\u672C\u8A9E",
      "Example: /language output Portugu\xEAs": "\u4F8B: /language output Portugu\xEAs",
      "UI language changed to {{lang}}": "UI\u8A00\u8A9E\u3092 {{lang}} \u306B\u5909\u66F4\u3057\u307E\u3057\u305F",
      "LLM output language rule file generated at {{path}}": "LLM\u51FA\u529B\u8A00\u8A9E\u30EB\u30FC\u30EB\u30D5\u30A1\u30A4\u30EB\u3092 {{path}} \u306B\u751F\u6210\u3057\u307E\u3057\u305F",
      "Please restart the application for the changes to take effect.": "\u5909\u66F4\u3092\u6709\u52B9\u306B\u3059\u308B\u306B\u306F\u30A2\u30D7\u30EA\u30B1\u30FC\u30B7\u30E7\u30F3\u3092\u518D\u8D77\u52D5\u3057\u3066\u304F\u3060\u3055\u3044",
      "Failed to generate LLM output language rule file: {{error}}": "LLM\u51FA\u529B\u8A00\u8A9E\u30EB\u30FC\u30EB\u30D5\u30A1\u30A4\u30EB\u306E\u751F\u6210\u306B\u5931\u6557: {{error}}",
      "Invalid command. Available subcommands:": "\u7121\u52B9\u306A\u30B3\u30DE\u30F3\u30C9\u3067\u3059\u3002\u4F7F\u7528\u53EF\u80FD\u306A\u30B5\u30D6\u30B3\u30DE\u30F3\u30C9:",
      "Available subcommands:": "\u4F7F\u7528\u53EF\u80FD\u306A\u30B5\u30D6\u30B3\u30DE\u30F3\u30C9:",
      "To request additional UI language packs, please open an issue on GitHub.": "\u8FFD\u52A0\u306EUI\u8A00\u8A9E\u30D1\u30C3\u30AF\u3092\u30EA\u30AF\u30A8\u30B9\u30C8\u3059\u308B\u306B\u306F\u3001GitHub \u3067 Issue \u3092\u4F5C\u6210\u3057\u3066\u304F\u3060\u3055\u3044",
      "Available options:": "\u4F7F\u7528\u53EF\u80FD\u306A\u30AA\u30D7\u30B7\u30E7\u30F3:",
      "Set UI language to {{name}}": "UI\u8A00\u8A9E\u3092 {{name}} \u306B\u8A2D\u5B9A",
      // Approval Mode
      "Approval Mode": "\u627F\u8A8D\u30E2\u30FC\u30C9",
      "Current approval mode: {{mode}}": "\u73FE\u5728\u306E\u627F\u8A8D\u30E2\u30FC\u30C9: {{mode}}",
      "Available approval modes:": "\u5229\u7528\u53EF\u80FD\u306A\u627F\u8A8D\u30E2\u30FC\u30C9:",
      "Approval mode changed to: {{mode}}": "\u627F\u8A8D\u30E2\u30FC\u30C9\u3092\u5909\u66F4\u3057\u307E\u3057\u305F: {{mode}}",
      "Approval mode changed to: {{mode}} (saved to {{scope}} settings{{location}})": "\u627F\u8A8D\u30E2\u30FC\u30C9\u3092 {{mode}} \u306B\u5909\u66F4\u3057\u307E\u3057\u305F({{scope}} \u8A2D\u5B9A{{location}}\u306B\u4FDD\u5B58)",
      "Usage: /approval-mode <mode> [--session|--user|--project]": "\u4F7F\u3044\u65B9: /approval-mode <\u30E2\u30FC\u30C9> [--session|--user|--project]",
      "Scope subcommands do not accept additional arguments.": "\u30B9\u30B3\u30FC\u30D7\u30B5\u30D6\u30B3\u30DE\u30F3\u30C9\u306F\u8FFD\u52A0\u306E\u5F15\u6570\u3092\u53D7\u3051\u4ED8\u3051\u307E\u305B\u3093",
      "Plan mode - Analyze only, do not modify files or execute commands": "\u30D7\u30E9\u30F3\u30E2\u30FC\u30C9 - \u5206\u6790\u306E\u307F\u3001\u30D5\u30A1\u30A4\u30EB\u306E\u5909\u66F4\u3084\u30B3\u30DE\u30F3\u30C9\u306E\u5B9F\u884C\u306F\u3057\u307E\u305B\u3093",
      "Default mode - Require approval for file edits or shell commands": "\u30C7\u30D5\u30A9\u30EB\u30C8\u30E2\u30FC\u30C9 - \u30D5\u30A1\u30A4\u30EB\u7DE8\u96C6\u3084\u30B7\u30A7\u30EB\u30B3\u30DE\u30F3\u30C9\u306B\u306F\u627F\u8A8D\u304C\u5FC5\u8981",
      "Auto-edit mode - Automatically approve file edits": "\u81EA\u52D5\u7DE8\u96C6\u30E2\u30FC\u30C9 - \u30D5\u30A1\u30A4\u30EB\u7DE8\u96C6\u3092\u81EA\u52D5\u627F\u8A8D",
      "YOLO mode - Automatically approve all tools": "YOLO\u30E2\u30FC\u30C9 - \u3059\u3079\u3066\u306E\u30C4\u30FC\u30EB\u3092\u81EA\u52D5\u627F\u8A8D",
      "{{mode}} mode": "{{mode}}\u30E2\u30FC\u30C9",
      "Settings service is not available; unable to persist the approval mode.": "\u8A2D\u5B9A\u30B5\u30FC\u30D3\u30B9\u304C\u5229\u7528\u3067\u304D\u307E\u305B\u3093\u3002\u627F\u8A8D\u30E2\u30FC\u30C9\u3092\u4FDD\u5B58\u3067\u304D\u307E\u305B\u3093",
      "Failed to save approval mode: {{error}}": "\u627F\u8A8D\u30E2\u30FC\u30C9\u306E\u4FDD\u5B58\u306B\u5931\u6557: {{error}}",
      "Failed to change approval mode: {{error}}": "\u627F\u8A8D\u30E2\u30FC\u30C9\u306E\u5909\u66F4\u306B\u5931\u6557: {{error}}",
      "Apply to current session only (temporary)": "\u73FE\u5728\u306E\u30BB\u30C3\u30B7\u30E7\u30F3\u306E\u307F\u306B\u9069\u7528(\u4E00\u6642\u7684)",
      "Persist for this project/workspace": "\u3053\u306E\u30D7\u30ED\u30B8\u30A7\u30AF\u30C8/\u30EF\u30FC\u30AF\u30B9\u30DA\u30FC\u30B9\u306B\u4FDD\u5B58",
      "Persist for this user on this machine": "\u3053\u306E\u30DE\u30B7\u30F3\u306E\u3053\u306E\u30E6\u30FC\u30B6\u30FC\u306B\u4FDD\u5B58",
      "Analyze only, do not modify files or execute commands": "\u5206\u6790\u306E\u307F\u3001\u30D5\u30A1\u30A4\u30EB\u306E\u5909\u66F4\u3084\u30B3\u30DE\u30F3\u30C9\u306E\u5B9F\u884C\u306F\u3057\u307E\u305B\u3093",
      "Require approval for file edits or shell commands": "\u30D5\u30A1\u30A4\u30EB\u7DE8\u96C6\u3084\u30B7\u30A7\u30EB\u30B3\u30DE\u30F3\u30C9\u306B\u306F\u627F\u8A8D\u304C\u5FC5\u8981",
      "Automatically approve file edits": "\u30D5\u30A1\u30A4\u30EB\u7DE8\u96C6\u3092\u81EA\u52D5\u627F\u8A8D",
      "Automatically approve all tools": "\u3059\u3079\u3066\u306E\u30C4\u30FC\u30EB\u3092\u81EA\u52D5\u627F\u8A8D",
      "Workspace approval mode exists and takes priority. User-level change will have no effect.": "\u30EF\u30FC\u30AF\u30B9\u30DA\u30FC\u30B9\u306E\u627F\u8A8D\u30E2\u30FC\u30C9\u304C\u5B58\u5728\u3057\u3001\u512A\u5148\u3055\u308C\u307E\u3059\u3002\u30E6\u30FC\u30B6\u30FC\u30EC\u30D9\u30EB\u306E\u5909\u66F4\u306F\u52B9\u679C\u304C\u3042\u308A\u307E\u305B\u3093",
      "(Use Enter to select, Tab to change focus)": "(Enter \u3067\u9078\u629E\u3001Tab \u3067\u30D5\u30A9\u30FC\u30AB\u30B9\u5909\u66F4)",
      "Apply To": "\u9069\u7528\u5148",
      "User Settings": "\u30E6\u30FC\u30B6\u30FC\u8A2D\u5B9A",
      "Workspace Settings": "\u30EF\u30FC\u30AF\u30B9\u30DA\u30FC\u30B9\u8A2D\u5B9A",
      // Memory
      "Commands for interacting with memory.": "\u30E1\u30E2\u30EA\u64CD\u4F5C\u306E\u30B3\u30DE\u30F3\u30C9",
      "Show the current memory contents.": "\u73FE\u5728\u306E\u30E1\u30E2\u30EA\u5185\u5BB9\u3092\u8868\u793A",
      "Show project-level memory contents.": "\u30D7\u30ED\u30B8\u30A7\u30AF\u30C8\u30EC\u30D9\u30EB\u306E\u30E1\u30E2\u30EA\u5185\u5BB9\u3092\u8868\u793A",
      "Show global memory contents.": "\u30B0\u30ED\u30FC\u30D0\u30EB\u30E1\u30E2\u30EA\u5185\u5BB9\u3092\u8868\u793A",
      "Add content to project-level memory.": "\u30D7\u30ED\u30B8\u30A7\u30AF\u30C8\u30EC\u30D9\u30EB\u306E\u30E1\u30E2\u30EA\u306B\u30B3\u30F3\u30C6\u30F3\u30C4\u3092\u8FFD\u52A0",
      "Add content to global memory.": "\u30B0\u30ED\u30FC\u30D0\u30EB\u30E1\u30E2\u30EA\u306B\u30B3\u30F3\u30C6\u30F3\u30C4\u3092\u8FFD\u52A0",
      "Refresh the memory from the source.": "\u30BD\u30FC\u30B9\u304B\u3089\u30E1\u30E2\u30EA\u3092\u66F4\u65B0",
      "Usage: /memory add --project <text to remember>": "\u4F7F\u3044\u65B9: /memory add --project <\u8A18\u61B6\u3059\u308B\u30C6\u30AD\u30B9\u30C8>",
      "Usage: /memory add --global <text to remember>": "\u4F7F\u3044\u65B9: /memory add --global <\u8A18\u61B6\u3059\u308B\u30C6\u30AD\u30B9\u30C8>",
      'Attempting to save to project memory: "{{text}}"': '\u30D7\u30ED\u30B8\u30A7\u30AF\u30C8\u30E1\u30E2\u30EA\u3078\u306E\u4FDD\u5B58\u3092\u8A66\u884C\u4E2D: "{{text}}"',
      'Attempting to save to global memory: "{{text}}"': '\u30B0\u30ED\u30FC\u30D0\u30EB\u30E1\u30E2\u30EA\u3078\u306E\u4FDD\u5B58\u3092\u8A66\u884C\u4E2D: "{{text}}"',
      "Current memory content from {{count}} file(s):": "{{count}} \u500B\u306E\u30D5\u30A1\u30A4\u30EB\u304B\u3089\u306E\u73FE\u5728\u306E\u30E1\u30E2\u30EA\u5185\u5BB9:",
      "Memory is currently empty.": "\u30E1\u30E2\u30EA\u306F\u73FE\u5728\u7A7A\u3067\u3059",
      "Project memory file not found or is currently empty.": "\u30D7\u30ED\u30B8\u30A7\u30AF\u30C8\u30E1\u30E2\u30EA\u30D5\u30A1\u30A4\u30EB\u304C\u898B\u3064\u304B\u3089\u306A\u3044\u304B\u3001\u73FE\u5728\u7A7A\u3067\u3059",
      "Global memory file not found or is currently empty.": "\u30B0\u30ED\u30FC\u30D0\u30EB\u30E1\u30E2\u30EA\u30D5\u30A1\u30A4\u30EB\u304C\u898B\u3064\u304B\u3089\u306A\u3044\u304B\u3001\u73FE\u5728\u7A7A\u3067\u3059",
      "Global memory is currently empty.": "\u30B0\u30ED\u30FC\u30D0\u30EB\u30E1\u30E2\u30EA\u306F\u73FE\u5728\u7A7A\u3067\u3059",
      "Global memory content:\n\n---\n{{content}}\n---": "\u30B0\u30ED\u30FC\u30D0\u30EB\u30E1\u30E2\u30EA\u5185\u5BB9:\n\n---\n{{content}}\n---",
      "Project memory content from {{path}}:\n\n---\n{{content}}\n---": "{{path}} \u304B\u3089\u306E\u30D7\u30ED\u30B8\u30A7\u30AF\u30C8\u30E1\u30E2\u30EA\u5185\u5BB9:\n\n---\n{{content}}\n---",
      "Project memory is currently empty.": "\u30D7\u30ED\u30B8\u30A7\u30AF\u30C8\u30E1\u30E2\u30EA\u306F\u73FE\u5728\u7A7A\u3067\u3059",
      "Refreshing memory from source files...": "\u30BD\u30FC\u30B9\u30D5\u30A1\u30A4\u30EB\u304B\u3089\u30E1\u30E2\u30EA\u3092\u66F4\u65B0\u4E2D...",
      "Add content to the memory. Use --global for global memory or --project for project memory.": "\u30E1\u30E2\u30EA\u306B\u30B3\u30F3\u30C6\u30F3\u30C4\u3092\u8FFD\u52A0\u3002\u30B0\u30ED\u30FC\u30D0\u30EB\u30E1\u30E2\u30EA\u306B\u306F --global\u3001\u30D7\u30ED\u30B8\u30A7\u30AF\u30C8\u30E1\u30E2\u30EA\u306B\u306F --project \u3092\u4F7F\u7528",
      "Usage: /memory add [--global|--project] <text to remember>": "\u4F7F\u3044\u65B9: /memory add [--global|--project] <\u8A18\u61B6\u3059\u308B\u30C6\u30AD\u30B9\u30C8>",
      'Attempting to save to memory {{scope}}: "{{fact}}"': '\u30E1\u30E2\u30EA {{scope}} \u3078\u306E\u4FDD\u5B58\u3092\u8A66\u884C\u4E2D: "{{fact}}"',
      // MCP
      "Authenticate with an OAuth-enabled MCP server": "OAuth\u5BFE\u5FDC\u306EMCP\u30B5\u30FC\u30D0\u30FC\u3067\u8A8D\u8A3C",
      "List configured MCP servers and tools": "\u8A2D\u5B9A\u6E08\u307F\u306EMCP\u30B5\u30FC\u30D0\u30FC\u3068\u30C4\u30FC\u30EB\u3092\u4E00\u89A7\u8868\u793A",
      "No MCP servers configured.": "MCP\u30B5\u30FC\u30D0\u30FC\u304C\u8A2D\u5B9A\u3055\u308C\u3066\u3044\u307E\u305B\u3093",
      "Restarts MCP servers.": "MCP\u30B5\u30FC\u30D0\u30FC\u3092\u518D\u8D77\u52D5\u3057\u307E\u3059",
      "Config not loaded.": "\u8A2D\u5B9A\u304C\u8AAD\u307F\u8FBC\u307E\u308C\u3066\u3044\u307E\u305B\u3093",
      "Could not retrieve tool registry.": "\u30C4\u30FC\u30EB\u30EC\u30B8\u30B9\u30C8\u30EA\u3092\u53D6\u5F97\u3067\u304D\u307E\u305B\u3093\u3067\u3057\u305F",
      "No MCP servers configured with OAuth authentication.": "OAuth\u8A8D\u8A3C\u304C\u8A2D\u5B9A\u3055\u308C\u305FMCP\u30B5\u30FC\u30D0\u30FC\u306F\u3042\u308A\u307E\u305B\u3093",
      "MCP servers with OAuth authentication:": "OAuth\u8A8D\u8A3C\u306EMCP\u30B5\u30FC\u30D0\u30FC:",
      "Use /mcp auth <server-name> to authenticate.": "\u8A8D\u8A3C\u3059\u308B\u306B\u306F /mcp auth <\u30B5\u30FC\u30D0\u30FC\u540D> \u3092\u4F7F\u7528",
      "MCP server '{{name}}' not found.": "MCP\u30B5\u30FC\u30D0\u30FC '{{name}}' \u304C\u898B\u3064\u304B\u308A\u307E\u305B\u3093",
      "Successfully authenticated and refreshed tools for '{{name}}'.": "'{{name}}' \u306E\u8A8D\u8A3C\u3068\u30C4\u30FC\u30EB\u66F4\u65B0\u306B\u6210\u529F\u3057\u307E\u3057\u305F",
      "Failed to authenticate with MCP server '{{name}}': {{error}}": "MCP\u30B5\u30FC\u30D0\u30FC '{{name}}' \u3067\u306E\u8A8D\u8A3C\u306B\u5931\u6557: {{error}}",
      "Re-discovering tools from '{{name}}'...": "'{{name}}' \u304B\u3089\u30C4\u30FC\u30EB\u3092\u518D\u691C\u51FA\u4E2D...",
      "Configured MCP servers:": "\u8A2D\u5B9A\u6E08\u307FMCP\u30B5\u30FC\u30D0\u30FC:",
      Ready: "\u6E96\u5099\u5B8C\u4E86",
      Disconnected: "\u5207\u65AD",
      "{{count}} tool": "{{count}} \u30C4\u30FC\u30EB",
      "{{count}} tools": "{{count}} \u30C4\u30FC\u30EB",
      "Restarting MCP servers...": "MCP\u30B5\u30FC\u30D0\u30FC\u3092\u518D\u8D77\u52D5\u4E2D...",
      // Chat
      "Manage conversation history.": "\u4F1A\u8A71\u5C65\u6B74\u3092\u7BA1\u7406\u3057\u307E\u3059",
      "List saved conversation checkpoints": "\u4FDD\u5B58\u3055\u308C\u305F\u4F1A\u8A71\u30C1\u30A7\u30C3\u30AF\u30DD\u30A4\u30F3\u30C8\u3092\u4E00\u89A7\u8868\u793A",
      "No saved conversation checkpoints found.": "\u4FDD\u5B58\u3055\u308C\u305F\u4F1A\u8A71\u30C1\u30A7\u30C3\u30AF\u30DD\u30A4\u30F3\u30C8\u304C\u898B\u3064\u304B\u308A\u307E\u305B\u3093",
      "List of saved conversations:": "\u4FDD\u5B58\u3055\u308C\u305F\u4F1A\u8A71\u306E\u4E00\u89A7:",
      "Note: Newest last, oldest first": "\u6CE8: \u6700\u65B0\u306E\u3082\u306E\u304C\u4E0B\u306B\u3042\u308A\u3001\u904E\u53BB\u306E\u3082\u306E\u304C\u4E0A\u306B\u3042\u308A\u307E\u3059",
      "Save the current conversation as a checkpoint. Usage: /chat save <tag>": "\u73FE\u5728\u306E\u4F1A\u8A71\u3092\u30C1\u30A7\u30C3\u30AF\u30DD\u30A4\u30F3\u30C8\u3068\u3057\u3066\u4FDD\u5B58\u3002\u4F7F\u3044\u65B9: /chat save <\u30BF\u30B0>",
      "Missing tag. Usage: /chat save <tag>": "\u30BF\u30B0\u304C\u4E0D\u8DB3\u3057\u3066\u3044\u307E\u3059\u3002\u4F7F\u3044\u65B9: /chat save <\u30BF\u30B0>",
      "Delete a conversation checkpoint. Usage: /chat delete <tag>": "\u4F1A\u8A71\u30C1\u30A7\u30C3\u30AF\u30DD\u30A4\u30F3\u30C8\u3092\u524A\u9664\u3002\u4F7F\u3044\u65B9: /chat delete <\u30BF\u30B0>",
      "Missing tag. Usage: /chat delete <tag>": "\u30BF\u30B0\u304C\u4E0D\u8DB3\u3057\u3066\u3044\u307E\u3059\u3002\u4F7F\u3044\u65B9: /chat delete <\u30BF\u30B0>",
      "Conversation checkpoint '{{tag}}' has been deleted.": "\u4F1A\u8A71\u30C1\u30A7\u30C3\u30AF\u30DD\u30A4\u30F3\u30C8 '{{tag}}' \u3092\u524A\u9664\u3057\u307E\u3057\u305F",
      "Error: No checkpoint found with tag '{{tag}}'.": "\u30A8\u30E9\u30FC: \u30BF\u30B0 '{{tag}}' \u306E\u30C1\u30A7\u30C3\u30AF\u30DD\u30A4\u30F3\u30C8\u304C\u898B\u3064\u304B\u308A\u307E\u305B\u3093",
      "Resume a conversation from a checkpoint. Usage: /chat resume <tag>": "\u30C1\u30A7\u30C3\u30AF\u30DD\u30A4\u30F3\u30C8\u304B\u3089\u4F1A\u8A71\u3092\u518D\u958B\u3002\u4F7F\u3044\u65B9: /chat resume <\u30BF\u30B0>",
      "Missing tag. Usage: /chat resume <tag>": "\u30BF\u30B0\u304C\u4E0D\u8DB3\u3057\u3066\u3044\u307E\u3059\u3002\u4F7F\u3044\u65B9: /chat resume <\u30BF\u30B0>",
      "No saved checkpoint found with tag: {{tag}}.": "\u30BF\u30B0 {{tag}} \u306E\u30C1\u30A7\u30C3\u30AF\u30DD\u30A4\u30F3\u30C8\u304C\u898B\u3064\u304B\u308A\u307E\u305B\u3093",
      "A checkpoint with the tag {{tag}} already exists. Do you want to overwrite it?": "\u30BF\u30B0 {{tag}} \u306E\u30C1\u30A7\u30C3\u30AF\u30DD\u30A4\u30F3\u30C8\u306F\u65E2\u306B\u5B58\u5728\u3057\u307E\u3059\u3002\u4E0A\u66F8\u304D\u3057\u307E\u3059\u304B?",
      "No chat client available to save conversation.": "\u4F1A\u8A71\u3092\u4FDD\u5B58\u3059\u308B\u305F\u3081\u306E\u30C1\u30E3\u30C3\u30C8\u30AF\u30E9\u30A4\u30A2\u30F3\u30C8\u304C\u3042\u308A\u307E\u305B\u3093",
      "Conversation checkpoint saved with tag: {{tag}}.": "\u30BF\u30B0 {{tag}} \u3067\u4F1A\u8A71\u30C1\u30A7\u30C3\u30AF\u30DD\u30A4\u30F3\u30C8\u3092\u4FDD\u5B58\u3057\u307E\u3057\u305F",
      "No conversation found to save.": "\u4FDD\u5B58\u3059\u308B\u4F1A\u8A71\u304C\u898B\u3064\u304B\u308A\u307E\u305B\u3093",
      "No chat client available to share conversation.": "\u4F1A\u8A71\u3092\u5171\u6709\u3059\u308B\u305F\u3081\u306E\u30C1\u30E3\u30C3\u30C8\u30AF\u30E9\u30A4\u30A2\u30F3\u30C8\u304C\u3042\u308A\u307E\u305B\u3093",
      "Invalid file format. Only .md and .json are supported.": "\u7121\u52B9\u306A\u30D5\u30A1\u30A4\u30EB\u5F62\u5F0F\u3067\u3059\u3002.md \u3068 .json \u306E\u307F\u30B5\u30DD\u30FC\u30C8\u3055\u308C\u3066\u3044\u307E\u3059",
      "Error sharing conversation: {{error}}": "\u4F1A\u8A71\u306E\u5171\u6709\u4E2D\u306B\u30A8\u30E9\u30FC: {{error}}",
      "Conversation shared to {{filePath}}": "\u4F1A\u8A71\u3092 {{filePath}} \u306B\u5171\u6709\u3057\u307E\u3057\u305F",
      "No conversation found to share.": "\u5171\u6709\u3059\u308B\u4F1A\u8A71\u304C\u898B\u3064\u304B\u308A\u307E\u305B\u3093",
      "Share the current conversation to a markdown or json file. Usage: /chat share <file>": "\u73FE\u5728\u306E\u4F1A\u8A71\u3092markdown\u307E\u305F\u306Fjson\u30D5\u30A1\u30A4\u30EB\u306B\u5171\u6709\u3002\u4F7F\u3044\u65B9: /chat share <\u30D5\u30A1\u30A4\u30EB>",
      // Summary
      "Generate a project summary and save it to .qwen/PROJECT_SUMMARY.md": "\u30D7\u30ED\u30B8\u30A7\u30AF\u30C8\u30B5\u30DE\u30EA\u30FC\u3092\u751F\u6210\u3057\u3001.qwen/PROJECT_SUMMARY.md \u306B\u4FDD\u5B58",
      "No chat client available to generate summary.": "\u30B5\u30DE\u30EA\u30FC\u3092\u751F\u6210\u3059\u308B\u305F\u3081\u306E\u30C1\u30E3\u30C3\u30C8\u30AF\u30E9\u30A4\u30A2\u30F3\u30C8\u304C\u3042\u308A\u307E\u305B\u3093",
      "Already generating summary, wait for previous request to complete": "\u30B5\u30DE\u30EA\u30FC\u751F\u6210\u4E2D\u3067\u3059\u3002\u524D\u306E\u30EA\u30AF\u30A8\u30B9\u30C8\u306E\u5B8C\u4E86\u3092\u304A\u5F85\u3061\u304F\u3060\u3055\u3044",
      "No conversation found to summarize.": "\u8981\u7D04\u3059\u308B\u4F1A\u8A71\u304C\u898B\u3064\u304B\u308A\u307E\u305B\u3093",
      "Failed to generate project context summary: {{error}}": "\u30D7\u30ED\u30B8\u30A7\u30AF\u30C8\u30B3\u30F3\u30C6\u30AD\u30B9\u30C8\u30B5\u30DE\u30EA\u30FC\u306E\u751F\u6210\u306B\u5931\u6557: {{error}}",
      "Saved project summary to {{filePathForDisplay}}.": "\u30D7\u30ED\u30B8\u30A7\u30AF\u30C8\u30B5\u30DE\u30EA\u30FC\u3092 {{filePathForDisplay}} \u306B\u4FDD\u5B58\u3057\u307E\u3057\u305F",
      "Saving project summary...": "\u30D7\u30ED\u30B8\u30A7\u30AF\u30C8\u30B5\u30DE\u30EA\u30FC\u3092\u4FDD\u5B58\u4E2D...",
      "Generating project summary...": "\u30D7\u30ED\u30B8\u30A7\u30AF\u30C8\u30B5\u30DE\u30EA\u30FC\u3092\u751F\u6210\u4E2D...",
      "Failed to generate summary - no text content received from LLM response": "\u30B5\u30DE\u30EA\u30FC\u306E\u751F\u6210\u306B\u5931\u6557 - LLM\u30EC\u30B9\u30DD\u30F3\u30B9\u304B\u3089\u30C6\u30AD\u30B9\u30C8\u30B3\u30F3\u30C6\u30F3\u30C4\u3092\u53D7\u4FE1\u3067\u304D\u307E\u305B\u3093\u3067\u3057\u305F",
      // Model
      "Switch the model for this session": "\u3053\u306E\u30BB\u30C3\u30B7\u30E7\u30F3\u306E\u30E2\u30C7\u30EB\u3092\u5207\u308A\u66FF\u3048",
      "Content generator configuration not available.": "\u30B3\u30F3\u30C6\u30F3\u30C4\u30B8\u30A7\u30CD\u30EC\u30FC\u30BF\u30FC\u8A2D\u5B9A\u304C\u5229\u7528\u3067\u304D\u307E\u305B\u3093",
      "Authentication type not available.": "\u8A8D\u8A3C\u30BF\u30A4\u30D7\u304C\u5229\u7528\u3067\u304D\u307E\u305B\u3093",
      "No models available for the current authentication type ({{authType}}).": "\u73FE\u5728\u306E\u8A8D\u8A3C\u30BF\u30A4\u30D7({{authType}})\u3067\u5229\u7528\u53EF\u80FD\u306A\u30E2\u30C7\u30EB\u306F\u3042\u308A\u307E\u305B\u3093",
      // Clear
      "Starting a new session, resetting chat, and clearing terminal.": "\u65B0\u3057\u3044\u30BB\u30C3\u30B7\u30E7\u30F3\u3092\u958B\u59CB\u3057\u3001\u30C1\u30E3\u30C3\u30C8\u3092\u30EA\u30BB\u30C3\u30C8\u3057\u3001\u30BF\u30FC\u30DF\u30CA\u30EB\u3092\u30AF\u30EA\u30A2\u3057\u3066\u3044\u307E\u3059",
      "Starting a new session and clearing.": "\u65B0\u3057\u3044\u30BB\u30C3\u30B7\u30E7\u30F3\u3092\u958B\u59CB\u3057\u3066\u30AF\u30EA\u30A2\u3057\u3066\u3044\u307E\u3059",
      // Compress
      "Already compressing, wait for previous request to complete": "\u5727\u7E2E\u4E2D\u3067\u3059\u3002\u524D\u306E\u30EA\u30AF\u30A8\u30B9\u30C8\u306E\u5B8C\u4E86\u3092\u304A\u5F85\u3061\u304F\u3060\u3055\u3044",
      "Failed to compress chat history.": "\u30C1\u30E3\u30C3\u30C8\u5C65\u6B74\u306E\u5727\u7E2E\u306B\u5931\u6557\u3057\u307E\u3057\u305F",
      "Failed to compress chat history: {{error}}": "\u30C1\u30E3\u30C3\u30C8\u5C65\u6B74\u306E\u5727\u7E2E\u306B\u5931\u6557: {{error}}",
      "Compressing chat history": "\u30C1\u30E3\u30C3\u30C8\u5C65\u6B74\u3092\u5727\u7E2E\u4E2D",
      "Chat history compressed from {{originalTokens}} to {{newTokens}} tokens.": "\u30C1\u30E3\u30C3\u30C8\u5C65\u6B74\u3092 {{originalTokens}} \u30C8\u30FC\u30AF\u30F3\u304B\u3089 {{newTokens}} \u30C8\u30FC\u30AF\u30F3\u306B\u5727\u7E2E\u3057\u307E\u3057\u305F",
      "Compression was not beneficial for this history size.": "\u3053\u306E\u5C65\u6B74\u30B5\u30A4\u30BA\u306B\u306F\u5727\u7E2E\u306E\u52B9\u679C\u304C\u3042\u308A\u307E\u305B\u3093\u3067\u3057\u305F",
      "Chat history compression did not reduce size. This may indicate issues with the compression prompt.": "\u30C1\u30E3\u30C3\u30C8\u5C65\u6B74\u306E\u5727\u7E2E\u3067\u30B5\u30A4\u30BA\u304C\u6E1B\u5C11\u3057\u307E\u305B\u3093\u3067\u3057\u305F\u3002\u5727\u7E2E\u30D7\u30ED\u30F3\u30D7\u30C8\u306B\u554F\u984C\u304C\u3042\u308B\u53EF\u80FD\u6027\u304C\u3042\u308A\u307E\u3059",
      "Could not compress chat history due to a token counting error.": "\u30C8\u30FC\u30AF\u30F3\u30AB\u30A6\u30F3\u30C8\u30A8\u30E9\u30FC\u306E\u305F\u3081\u3001\u30C1\u30E3\u30C3\u30C8\u5C65\u6B74\u3092\u5727\u7E2E\u3067\u304D\u307E\u305B\u3093\u3067\u3057\u305F",
      "Chat history is already compressed.": "\u30C1\u30E3\u30C3\u30C8\u5C65\u6B74\u306F\u65E2\u306B\u5727\u7E2E\u3055\u308C\u3066\u3044\u307E\u3059",
      // Directory
      "Configuration is not available.": "\u8A2D\u5B9A\u304C\u5229\u7528\u3067\u304D\u307E\u305B\u3093",
      "Please provide at least one path to add.": "\u8FFD\u52A0\u3059\u308B\u30D1\u30B9\u3092\u5C11\u306A\u304F\u3068\u30821\u3064\u6307\u5B9A\u3057\u3066\u304F\u3060\u3055\u3044",
      "The /directory add command is not supported in restrictive sandbox profiles. Please use --include-directories when starting the session instead.": "\u5236\u9650\u7684\u306A\u30B5\u30F3\u30C9\u30DC\u30C3\u30AF\u30B9\u30D7\u30ED\u30D5\u30A1\u30A4\u30EB\u3067\u306F /directory add \u30B3\u30DE\u30F3\u30C9\u306F\u30B5\u30DD\u30FC\u30C8\u3055\u308C\u3066\u3044\u307E\u305B\u3093\u3002\u4EE3\u308F\u308A\u306B\u30BB\u30C3\u30B7\u30E7\u30F3\u958B\u59CB\u6642\u306B --include-directories \u3092\u4F7F\u7528\u3057\u3066\u304F\u3060\u3055\u3044",
      "Error adding '{{path}}': {{error}}": "'{{path}}' \u306E\u8FFD\u52A0\u4E2D\u306B\u30A8\u30E9\u30FC: {{error}}",
      "Successfully added QWEN.md files from the following directories if there are:\n- {{directories}}": "\u4EE5\u4E0B\u306E\u30C7\u30A3\u30EC\u30AF\u30C8\u30EA\u304B\u3089 QWEN.md \u30D5\u30A1\u30A4\u30EB\u3092\u8FFD\u52A0\u3057\u307E\u3057\u305F(\u5B58\u5728\u3059\u308B\u5834\u5408):\n- {{directories}}",
      "Error refreshing memory: {{error}}": "\u30E1\u30E2\u30EA\u306E\u66F4\u65B0\u4E2D\u306B\u30A8\u30E9\u30FC: {{error}}",
      "Successfully added directories:\n- {{directories}}": "\u30C7\u30A3\u30EC\u30AF\u30C8\u30EA\u3092\u6B63\u5E38\u306B\u8FFD\u52A0\u3057\u307E\u3057\u305F:\n- {{directories}}",
      "Current workspace directories:\n{{directories}}": "\u73FE\u5728\u306E\u30EF\u30FC\u30AF\u30B9\u30DA\u30FC\u30B9\u30C7\u30A3\u30EC\u30AF\u30C8\u30EA:\n{{directories}}",
      // Docs
      "Please open the following URL in your browser to view the documentation:\n{{url}}": "\u30C9\u30AD\u30E5\u30E1\u30F3\u30C8\u3092\u8868\u793A\u3059\u308B\u306B\u306F\u3001\u30D6\u30E9\u30A6\u30B6\u3067\u4EE5\u4E0B\u306EURL\u3092\u958B\u3044\u3066\u304F\u3060\u3055\u3044:\n{{url}}",
      "Opening documentation in your browser: {{url}}": "  \u30D6\u30E9\u30A6\u30B6\u3067\u30C9\u30AD\u30E5\u30E1\u30F3\u30C8\u3092\u958B\u304D\u307E\u3057\u305F: {{url}}",
      // Dialogs - Tool Confirmation
      "Do you want to proceed?": "\u7D9A\u884C\u3057\u307E\u3059\u304B?",
      "Yes, allow once": "\u306F\u3044(\u4ECA\u56DE\u306E\u307F\u8A31\u53EF)",
      "Allow always": "\u5E38\u306B\u8A31\u53EF\u3059\u308B",
      No: "\u3044\u3044\u3048",
      "No (esc)": "\u3044\u3044\u3048 (Esc)",
      "Yes, allow always for this session": "\u306F\u3044\u3001\u3053\u306E\u30BB\u30C3\u30B7\u30E7\u30F3\u3067\u5E38\u306B\u8A31\u53EF",
      "Modify in progress:": "\u5909\u66F4\u4E2D:",
      "Save and close external editor to continue": "\u7D9A\u884C\u3059\u308B\u306B\u306F\u5916\u90E8\u30A8\u30C7\u30A3\u30BF\u3092\u4FDD\u5B58\u3057\u3066\u9589\u3058\u3066\u304F\u3060\u3055\u3044",
      "Apply this change?": "\u3053\u306E\u5909\u66F4\u3092\u9069\u7528\u3057\u307E\u3059\u304B?",
      "Yes, allow always": "\u306F\u3044\u3001\u5E38\u306B\u8A31\u53EF",
      "Modify with external editor": "\u5916\u90E8\u30A8\u30C7\u30A3\u30BF\u3067\u7DE8\u96C6",
      "No, suggest changes (esc)": "\u3044\u3044\u3048\u3001\u5909\u66F4\u3092\u63D0\u6848 (Esc)",
      "Allow execution of: '{{command}}'?": "'{{command}}' \u306E\u5B9F\u884C\u3092\u8A31\u53EF\u3057\u307E\u3059\u304B?",
      "Yes, allow always ...": "\u306F\u3044\u3001\u5E38\u306B\u8A31\u53EF...",
      "Yes, and auto-accept edits": "\u306F\u3044\u3001\u7DE8\u96C6\u3092\u81EA\u52D5\u627F\u8A8D",
      "Yes, and manually approve edits": "\u306F\u3044\u3001\u7DE8\u96C6\u3092\u624B\u52D5\u627F\u8A8D",
      "No, keep planning (esc)": "\u3044\u3044\u3048\u3001\u8A08\u753B\u3092\u7D9A\u3051\u308B (Esc)",
      "URLs to fetch:": "\u53D6\u5F97\u3059\u308BURL:",
      "MCP Server: {{server}}": "MCP\u30B5\u30FC\u30D0\u30FC: {{server}}",
      "Tool: {{tool}}": "\u30C4\u30FC\u30EB: {{tool}}",
      'Allow execution of MCP tool "{{tool}}" from server "{{server}}"?': '\u30B5\u30FC\u30D0\u30FC "{{server}}" \u304B\u3089\u306E MCP\u30C4\u30FC\u30EB "{{tool}}" \u306E\u5B9F\u884C\u3092\u8A31\u53EF\u3057\u307E\u3059\u304B?',
      'Yes, always allow tool "{{tool}}" from server "{{server}}"': '\u306F\u3044\u3001\u30B5\u30FC\u30D0\u30FC "{{server}}" \u304B\u3089\u306E\u30C4\u30FC\u30EB "{{tool}}" \u3092\u5E38\u306B\u8A31\u53EF',
      'Yes, always allow all tools from server "{{server}}"': '\u306F\u3044\u3001\u30B5\u30FC\u30D0\u30FC "{{server}}" \u304B\u3089\u306E\u3059\u3079\u3066\u306E\u30C4\u30FC\u30EB\u3092\u5E38\u306B\u8A31\u53EF',
      // Dialogs - Shell Confirmation
      "Shell Command Execution": "\u30B7\u30A7\u30EB\u30B3\u30DE\u30F3\u30C9\u5B9F\u884C",
      "A custom command wants to run the following shell commands:": "\u30AB\u30B9\u30BF\u30E0\u30B3\u30DE\u30F3\u30C9\u304C\u4EE5\u4E0B\u306E\u30B7\u30A7\u30EB\u30B3\u30DE\u30F3\u30C9\u3092\u5B9F\u884C\u3057\u3088\u3046\u3068\u3057\u3066\u3044\u307E\u3059:",
      // Dialogs - Pro Quota
      "Pro quota limit reached for {{model}}.": "{{model}} \u306EPro\u30AF\u30A9\u30FC\u30BF\u4E0A\u9650\u306B\u9054\u3057\u307E\u3057\u305F",
      "Change auth (executes the /auth command)": "\u8A8D\u8A3C\u3092\u5909\u66F4(/auth \u30B3\u30DE\u30F3\u30C9\u3092\u5B9F\u884C)",
      "Continue with {{model}}": "{{model}} \u3067\u7D9A\u884C",
      // Dialogs - Welcome Back
      "Current Plan:": "\u73FE\u5728\u306E\u30D7\u30E9\u30F3:",
      "Progress: {{done}}/{{total}} tasks completed": "\u9032\u6357: {{done}}/{{total}} \u30BF\u30B9\u30AF\u5B8C\u4E86",
      ", {{inProgress}} in progress": "\u3001{{inProgress}} \u9032\u884C\u4E2D",
      "Pending Tasks:": "\u4FDD\u7559\u4E2D\u306E\u30BF\u30B9\u30AF:",
      "What would you like to do?": "\u4F55\u3092\u3057\u307E\u3059\u304B?",
      "Choose how to proceed with your session:": "\u30BB\u30C3\u30B7\u30E7\u30F3\u306E\u7D9A\u884C\u65B9\u6CD5\u3092\u9078\u629E\u3057\u3066\u304F\u3060\u3055\u3044:",
      "Start new chat session": "\u65B0\u3057\u3044\u30C1\u30E3\u30C3\u30C8\u30BB\u30C3\u30B7\u30E7\u30F3\u3092\u958B\u59CB",
      "Continue previous conversation": "\u524D\u56DE\u306E\u4F1A\u8A71\u3092\u7D9A\u884C",
      "\u{1F44B} Welcome back! (Last updated: {{timeAgo}})": "\u{1F44B} \u304A\u304B\u3048\u308A\u306A\u3055\u3044!(\u6700\u7D42\u66F4\u65B0: {{timeAgo}})",
      "\u{1F3AF} Overall Goal:": "\u{1F3AF} \u5168\u4F53\u76EE\u6A19:",
      // Dialogs - Auth
      "Get started": "\u59CB\u3081\u308B",
      "How would you like to authenticate for this project?": "\u3053\u306E\u30D7\u30ED\u30B8\u30A7\u30AF\u30C8\u306E\u8A8D\u8A3C\u65B9\u6CD5\u3092\u9078\u629E\u3057\u3066\u304F\u3060\u3055\u3044:",
      "OpenAI API key is required to use OpenAI authentication.": "OpenAI\u8A8D\u8A3C\u3092\u4F7F\u7528\u3059\u308B\u306B\u306F OpenAI API\u30AD\u30FC\u304C\u5FC5\u8981\u3067\u3059",
      "You must select an auth method to proceed. Press Ctrl+C again to exit.": "\u7D9A\u884C\u3059\u308B\u306B\u306F\u8A8D\u8A3C\u65B9\u6CD5\u3092\u9078\u629E\u3057\u3066\u304F\u3060\u3055\u3044\u3002Ctrl+C \u3092\u3082\u3046\u4E00\u5EA6\u62BC\u3059\u3068\u7D42\u4E86\u3057\u307E\u3059",
      "(Use Enter to Set Auth)": "(Enter \u3067\u8A8D\u8A3C\u3092\u8A2D\u5B9A)",
      "Terms of Services and Privacy Notice for Qwen Code": "Qwen Code \u306E\u5229\u7528\u898F\u7D04\u3068\u30D7\u30E9\u30A4\u30D0\u30B7\u30FC\u901A\u77E5",
      "Qwen OAuth": "Qwen OAuth",
      "Login with QwenChat account to use daily free quota.": "QwenChat\u30A2\u30AB\u30A6\u30F3\u30C8\u3067\u30ED\u30B0\u30A4\u30F3\u3057\u3066\u3001\u6BCE\u65E5\u306E\u7121\u6599\u30AF\u30A9\u30FC\u30BF\u3092\u3054\u5229\u7528\u304F\u3060\u3055\u3044\u3002",
      "API-KEY": "API-KEY",
      "Use coding plan credentials or your own api-keys/providers.": "Coding Plan\u306E\u8A8D\u8A3C\u60C5\u5831\u307E\u305F\u306F\u3054\u81EA\u8EAB\u306EAPI\u30AD\u30FC/\u30D7\u30ED\u30D0\u30A4\u30C0\u30FC\u3092\u3054\u5229\u7528\u304F\u3060\u3055\u3044\u3002",
      OpenAI: "OpenAI",
      "Failed to login. Message: {{message}}": "\u30ED\u30B0\u30A4\u30F3\u306B\u5931\u6557\u3057\u307E\u3057\u305F\u3002\u30E1\u30C3\u30BB\u30FC\u30B8: {{message}}",
      "Authentication is enforced to be {{enforcedType}}, but you are currently using {{currentType}}.": "\u8A8D\u8A3C\u306F {{enforcedType}} \u306B\u5F37\u5236\u3055\u308C\u3066\u3044\u307E\u3059\u304C\u3001\u73FE\u5728 {{currentType}} \u3092\u4F7F\u7528\u3057\u3066\u3044\u307E\u3059",
      "Qwen OAuth authentication timed out. Please try again.": "Qwen OAuth\u8A8D\u8A3C\u304C\u30BF\u30A4\u30E0\u30A2\u30A6\u30C8\u3057\u307E\u3057\u305F\u3002\u518D\u5EA6\u304A\u8A66\u3057\u304F\u3060\u3055\u3044",
      "Qwen OAuth authentication cancelled.": "Qwen OAuth\u8A8D\u8A3C\u304C\u30AD\u30E3\u30F3\u30BB\u30EB\u3055\u308C\u307E\u3057\u305F",
      "Qwen OAuth Authentication": "Qwen OAuth\u8A8D\u8A3C",
      "Please visit this URL to authorize:": "\u8A8D\u8A3C\u3059\u308B\u306B\u306F\u4EE5\u4E0B\u306EURL\u306B\u30A2\u30AF\u30BB\u30B9\u3057\u3066\u304F\u3060\u3055\u3044:",
      "Or scan the QR code below:": "\u307E\u305F\u306F\u4EE5\u4E0B\u306EQR\u30B3\u30FC\u30C9\u3092\u30B9\u30AD\u30E3\u30F3:",
      "Waiting for authorization": "\u8A8D\u8A3C\u3092\u5F85\u3063\u3066\u3044\u307E\u3059",
      "Time remaining:": "\u6B8B\u308A\u6642\u9593:",
      "(Press ESC or CTRL+C to cancel)": "(ESC \u307E\u305F\u306F CTRL+C \u3067\u30AD\u30E3\u30F3\u30BB\u30EB)",
      "Qwen OAuth Authentication Timeout": "Qwen OAuth\u8A8D\u8A3C\u30BF\u30A4\u30E0\u30A2\u30A6\u30C8",
      "OAuth token expired (over {{seconds}} seconds). Please select authentication method again.": "OAuth\u30C8\u30FC\u30AF\u30F3\u304C\u671F\u9650\u5207\u308C\u3067\u3059({{seconds}}\u79D2\u4EE5\u4E0A)\u3002\u8A8D\u8A3C\u65B9\u6CD5\u3092\u518D\u5EA6\u9078\u629E\u3057\u3066\u304F\u3060\u3055\u3044",
      "Press any key to return to authentication type selection.": "\u8A8D\u8A3C\u30BF\u30A4\u30D7\u9078\u629E\u306B\u623B\u308B\u306B\u306F\u4EFB\u610F\u306E\u30AD\u30FC\u3092\u62BC\u3057\u3066\u304F\u3060\u3055\u3044",
      "Waiting for Qwen OAuth authentication...": "Qwen OAuth\u8A8D\u8A3C\u3092\u5F85\u3063\u3066\u3044\u307E\u3059...",
      "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.": "\u6CE8: Qwen OAuth\u3092\u4F7F\u7528\u3057\u3066\u3082\u3001settings.json\u5185\u306E\u65E2\u5B58\u306EAPI\u30AD\u30FC\u306F\u30AF\u30EA\u30A2\u3055\u308C\u307E\u305B\u3093\u3002\u5FC5\u8981\u306B\u5FDC\u3058\u3066\u5F8C\u3067OpenAI\u8A8D\u8A3C\u306B\u5207\u308A\u66FF\u3048\u308B\u3053\u3068\u304C\u3067\u304D\u307E\u3059",
      "Authentication timed out. Please try again.": "\u8A8D\u8A3C\u304C\u30BF\u30A4\u30E0\u30A2\u30A6\u30C8\u3057\u307E\u3057\u305F\u3002\u518D\u5EA6\u304A\u8A66\u3057\u304F\u3060\u3055\u3044",
      "Waiting for auth... (Press ESC or CTRL+C to cancel)": "\u8A8D\u8A3C\u3092\u5F85\u3063\u3066\u3044\u307E\u3059... (ESC \u307E\u305F\u306F CTRL+C \u3067\u30AD\u30E3\u30F3\u30BB\u30EB)",
      "Failed to authenticate. Message: {{message}}": "\u8A8D\u8A3C\u306B\u5931\u6557\u3057\u307E\u3057\u305F\u3002\u30E1\u30C3\u30BB\u30FC\u30B8: {{message}}",
      "Authenticated successfully with {{authType}} credentials.": "{{authType}} \u8A8D\u8A3C\u60C5\u5831\u3067\u6B63\u5E38\u306B\u8A8D\u8A3C\u3055\u308C\u307E\u3057\u305F",
      'Invalid QWEN_DEFAULT_AUTH_TYPE value: "{{value}}". Valid values are: {{validValues}}': '\u7121\u52B9\u306A QWEN_DEFAULT_AUTH_TYPE \u5024: "{{value}}"\u3002\u6709\u52B9\u306A\u5024: {{validValues}}',
      "OpenAI Configuration Required": "OpenAI\u8A2D\u5B9A\u304C\u5FC5\u8981\u3067\u3059",
      "Please enter your OpenAI configuration. You can get an API key from": "OpenAI\u8A2D\u5B9A\u3092\u5165\u529B\u3057\u3066\u304F\u3060\u3055\u3044\u3002API\u30AD\u30FC\u306F\u4EE5\u4E0B\u304B\u3089\u53D6\u5F97\u3067\u304D\u307E\u3059",
      "API Key:": "API\u30AD\u30FC:",
      "Invalid credentials: {{errorMessage}}": "\u7121\u52B9\u306A\u8A8D\u8A3C\u60C5\u5831: {{errorMessage}}",
      "Failed to validate credentials": "\u8A8D\u8A3C\u60C5\u5831\u306E\u691C\u8A3C\u306B\u5931\u6557\u3057\u307E\u3057\u305F",
      "Press Enter to continue, Tab/\u2191\u2193 to navigate, Esc to cancel": "Enter \u3067\u7D9A\u884C\u3001Tab/\u2191\u2193 \u3067\u79FB\u52D5\u3001Esc \u3067\u30AD\u30E3\u30F3\u30BB\u30EB",
      // Dialogs - Model
      "Select Model": "\u30E2\u30C7\u30EB\u3092\u9078\u629E",
      "(Press Esc to close)": "(Esc \u3067\u9589\u3058\u308B)",
      "Qwen 3.5 Plus \u2014 efficient hybrid model with leading coding performance": "Qwen 3.5 Plus \u2014 \u52B9\u7387\u7684\u306A\u30CF\u30A4\u30D6\u30EA\u30C3\u30C9\u30E2\u30C7\u30EB\u3001\u696D\u754C\u30C8\u30C3\u30D7\u30AF\u30E9\u30B9\u306E\u30B3\u30FC\u30C7\u30A3\u30F3\u30B0\u6027\u80FD",
      "The latest Qwen Vision model from Alibaba Cloud ModelStudio (version: qwen3-vl-plus-2025-09-23)": "Alibaba Cloud ModelStudio\u306E\u6700\u65B0Qwen Vision\u30E2\u30C7\u30EB(\u30D0\u30FC\u30B8\u30E7\u30F3: qwen3-vl-plus-2025-09-23)",
      // Dialogs - Permissions
      "Manage folder trust settings": "\u30D5\u30A9\u30EB\u30C0\u4FE1\u983C\u8A2D\u5B9A\u3092\u7BA1\u7406",
      // Status Bar
      "Using:": "\u4F7F\u7528\u4E2D:",
      "{{count}} open file": "{{count}} \u500B\u306E\u30D5\u30A1\u30A4\u30EB\u3092\u958B\u3044\u3066\u3044\u307E\u3059",
      "{{count}} open files": "{{count}} \u500B\u306E\u30D5\u30A1\u30A4\u30EB\u3092\u958B\u3044\u3066\u3044\u307E\u3059",
      "(ctrl+g to view)": "(Ctrl+G \u3067\u8868\u793A)",
      "{{count}} {{name}} file": "{{count}} {{name}} \u30D5\u30A1\u30A4\u30EB",
      "{{count}} {{name}} files": "{{count}} {{name}} \u30D5\u30A1\u30A4\u30EB",
      "{{count}} MCP server": "{{count}} MCP\u30B5\u30FC\u30D0\u30FC",
      "{{count}} MCP servers": "{{count}} MCP\u30B5\u30FC\u30D0\u30FC",
      "{{count}} Blocked": "{{count}} \u30D6\u30ED\u30C3\u30AF",
      "(ctrl+t to view)": "(Ctrl+T \u3067\u8868\u793A)",
      "(ctrl+t to toggle)": "(Ctrl+T \u3067\u5207\u308A\u66FF\u3048)",
      "Press Ctrl+C again to exit.": "Ctrl+C \u3092\u3082\u3046\u4E00\u5EA6\u62BC\u3059\u3068\u7D42\u4E86\u3057\u307E\u3059",
      "Press Ctrl+D again to exit.": "Ctrl+D \u3092\u3082\u3046\u4E00\u5EA6\u62BC\u3059\u3068\u7D42\u4E86\u3057\u307E\u3059",
      "Press Esc again to clear.": "Esc \u3092\u3082\u3046\u4E00\u5EA6\u62BC\u3059\u3068\u30AF\u30EA\u30A2\u3057\u307E\u3059",
      // MCP Status
      "\u23F3 MCP servers are starting up ({{count}} initializing)...": "\u23F3 MCP\u30B5\u30FC\u30D0\u30FC\u3092\u8D77\u52D5\u4E2D({{count}} \u521D\u671F\u5316\u4E2D)...",
      "Note: First startup may take longer. Tool availability will update automatically.": "\u6CE8: \u521D\u56DE\u8D77\u52D5\u306B\u306F\u6642\u9593\u304C\u304B\u304B\u308B\u5834\u5408\u304C\u3042\u308A\u307E\u3059\u3002\u30C4\u30FC\u30EB\u306E\u5229\u7528\u53EF\u80FD\u72B6\u6CC1\u306F\u81EA\u52D5\u7684\u306B\u66F4\u65B0\u3055\u308C\u307E\u3059",
      "Starting... (first startup may take longer)": "\u8D77\u52D5\u4E2D...(\u521D\u56DE\u8D77\u52D5\u306B\u306F\u6642\u9593\u304C\u304B\u304B\u308B\u5834\u5408\u304C\u3042\u308A\u307E\u3059)",
      "{{count}} prompt": "{{count}} \u30D7\u30ED\u30F3\u30D7\u30C8",
      "{{count}} prompts": "{{count}} \u30D7\u30ED\u30F3\u30D7\u30C8",
      "(from {{extensionName}})": "({{extensionName}} \u304B\u3089)",
      OAuth: "OAuth",
      "OAuth expired": "OAuth \u671F\u9650\u5207\u308C",
      "OAuth not authenticated": "OAuth \u672A\u8A8D\u8A3C",
      "tools and prompts will appear when ready": "\u30C4\u30FC\u30EB\u3068\u30D7\u30ED\u30F3\u30D7\u30C8\u306F\u6E96\u5099\u5B8C\u4E86\u5F8C\u306B\u8868\u793A\u3055\u308C\u307E\u3059",
      "{{count}} tools cached": "{{count}} \u30C4\u30FC\u30EB(\u30AD\u30E3\u30C3\u30B7\u30E5\u6E08\u307F)",
      "Tools:": "\u30C4\u30FC\u30EB:",
      "Parameters:": "\u30D1\u30E9\u30E1\u30FC\u30BF:",
      "Prompts:": "\u30D7\u30ED\u30F3\u30D7\u30C8:",
      Blocked: "\u30D6\u30ED\u30C3\u30AF",
      "\u{1F4A1} Tips:": "\u{1F4A1} \u30D2\u30F3\u30C8:",
      Use: "\u4F7F\u7528",
      "to show server and tool descriptions": "\u30B5\u30FC\u30D0\u30FC\u3068\u30C4\u30FC\u30EB\u306E\u8AAC\u660E\u3092\u8868\u793A",
      "to show tool parameter schemas": "\u30C4\u30FC\u30EB\u30D1\u30E9\u30E1\u30FC\u30BF\u30B9\u30AD\u30FC\u30DE\u3092\u8868\u793A",
      "to hide descriptions": "\u8AAC\u660E\u3092\u975E\u8868\u793A",
      "to authenticate with OAuth-enabled servers": "OAuth\u5BFE\u5FDC\u30B5\u30FC\u30D0\u30FC\u3067\u8A8D\u8A3C",
      Press: "\u62BC\u3059",
      "to toggle tool descriptions on/off": "\u30C4\u30FC\u30EB\u8AAC\u660E\u306E\u8868\u793A/\u975E\u8868\u793A\u3092\u5207\u308A\u66FF\u3048",
      "Starting OAuth authentication for MCP server '{{name}}'...": "MCP\u30B5\u30FC\u30D0\u30FC '{{name}}' \u306EOAuth\u8A8D\u8A3C\u3092\u958B\u59CB\u4E2D...",
      // Startup Tips
      "Tips:": "\u30D2\u30F3\u30C8\uFF1A",
      "Use /compress when the conversation gets long to summarize history and free up context.": "\u4F1A\u8A71\u304C\u9577\u304F\u306A\u3063\u305F\u3089 /compress \u3067\u5C65\u6B74\u3092\u8981\u7D04\u3057\u3001\u30B3\u30F3\u30C6\u30AD\u30B9\u30C8\u3092\u89E3\u653E\u3067\u304D\u307E\u3059\u3002",
      "Start a fresh idea with /clear or /new; the previous session stays available in history.": "/clear \u307E\u305F\u306F /new \u3067\u65B0\u3057\u3044\u30A2\u30A4\u30C7\u30A2\u3092\u59CB\u3081\u3089\u308C\u307E\u3059\u3002\u524D\u306E\u30BB\u30C3\u30B7\u30E7\u30F3\u306F\u5C65\u6B74\u306B\u6B8B\u308A\u307E\u3059\u3002",
      "Use /bug to submit issues to the maintainers when something goes off.": "\u554F\u984C\u304C\u767A\u751F\u3057\u305F\u3089 /bug \u3067\u30E1\u30F3\u30C6\u30CA\u30FC\u306B\u5831\u544A\u3067\u304D\u307E\u3059\u3002",
      "Switch auth type quickly with /auth.": "/auth \u3067\u8A8D\u8A3C\u30BF\u30A4\u30D7\u3092\u3059\u3070\u3084\u304F\u5207\u308A\u66FF\u3048\u3089\u308C\u307E\u3059\u3002",
      "You can run any shell commands from Qwen Code using ! (e.g. !ls).": "Qwen Code \u304B\u3089 ! \u3092\u4F7F\u3063\u3066\u4EFB\u610F\u306E\u30B7\u30A7\u30EB\u30B3\u30DE\u30F3\u30C9\u3092\u5B9F\u884C\u3067\u304D\u307E\u3059\uFF08\u4F8B: !ls\uFF09\u3002",
      "Type / to open the command popup; Tab autocompletes slash commands and saved prompts.": "/ \u3092\u5165\u529B\u3057\u3066\u30B3\u30DE\u30F3\u30C9\u30DD\u30C3\u30D7\u30A2\u30C3\u30D7\u3092\u958B\u304D\u307E\u3059\u3002Tab \u3067\u30B9\u30E9\u30C3\u30B7\u30E5\u30B3\u30DE\u30F3\u30C9\u3068\u4FDD\u5B58\u6E08\u307F\u30D7\u30ED\u30F3\u30D7\u30C8\u3092\u88DC\u5B8C\u3067\u304D\u307E\u3059\u3002",
      "You can resume a previous conversation by running qwen --continue or qwen --resume.": "qwen --continue \u307E\u305F\u306F qwen --resume \u3067\u524D\u306E\u4F1A\u8A71\u3092\u518D\u958B\u3067\u304D\u307E\u3059\u3002",
      "You can switch permission mode quickly with Shift+Tab or /approval-mode.": "Shift+Tab \u307E\u305F\u306F /approval-mode \u3067\u6A29\u9650\u30E2\u30FC\u30C9\u3092\u3059\u3070\u3084\u304F\u5207\u308A\u66FF\u3048\u3089\u308C\u307E\u3059\u3002",
      "You can switch permission mode quickly with Tab or /approval-mode.": "Tab \u307E\u305F\u306F /approval-mode \u3067\u6A29\u9650\u30E2\u30FC\u30C9\u3092\u3059\u3070\u3084\u304F\u5207\u308A\u66FF\u3048\u3089\u308C\u307E\u3059\u3002",
      "Try /insight to generate personalized insights from your chat history.": "/insight \u3067\u30C1\u30E3\u30C3\u30C8\u5C65\u6B74\u304B\u3089\u30D1\u30FC\u30BD\u30CA\u30E9\u30A4\u30BA\u3055\u308C\u305F\u30A4\u30F3\u30B5\u30A4\u30C8\u3092\u751F\u6210\u3067\u304D\u307E\u3059\u3002",
      "Tips for getting started:": "\u59CB\u3081\u308B\u305F\u3081\u306E\u30D2\u30F3\u30C8:",
      "1. Ask questions, edit files, or run commands.": "1. \u8CEA\u554F\u3057\u305F\u308A\u3001\u30D5\u30A1\u30A4\u30EB\u3092\u7DE8\u96C6\u3057\u305F\u308A\u3001\u30B3\u30DE\u30F3\u30C9\u3092\u5B9F\u884C\u3057\u305F\u308A\u3067\u304D\u307E\u3059",
      "2. Be specific for the best results.": "2. \u5177\u4F53\u7684\u306B\u6307\u793A\u3059\u308B\u3068\u6700\u826F\u306E\u7D50\u679C\u304C\u5F97\u3089\u308C\u307E\u3059",
      "files to customize your interactions with Qwen Code.": "Qwen Code \u3068\u306E\u5BFE\u8A71\u3092\u30AB\u30B9\u30BF\u30DE\u30A4\u30BA\u3059\u308B\u305F\u3081\u306E\u30D5\u30A1\u30A4\u30EB",
      "for more information.": "\u8A73\u7D30\u60C5\u5831\u3092\u78BA\u8A8D\u3067\u304D\u307E\u3059",
      // Exit Screen / Stats
      "Agent powering down. Goodbye!": "\u30A8\u30FC\u30B8\u30A7\u30F3\u30C8\u3092\u7D42\u4E86\u3057\u307E\u3059\u3002\u3055\u3088\u3046\u306A\u3089!",
      "To continue this session, run": "\u3053\u306E\u30BB\u30C3\u30B7\u30E7\u30F3\u3092\u7D9A\u884C\u3059\u308B\u306B\u306F\u3001\u6B21\u3092\u5B9F\u884C:",
      "Interaction Summary": "\u30A4\u30F3\u30BF\u30E9\u30AF\u30B7\u30E7\u30F3\u6982\u8981",
      "Session ID:": "\u30BB\u30C3\u30B7\u30E7\u30F3ID:",
      "Tool Calls:": "\u30C4\u30FC\u30EB\u547C\u3073\u51FA\u3057:",
      "Success Rate:": "\u6210\u529F\u7387:",
      "User Agreement:": "\u30E6\u30FC\u30B6\u30FC\u540C\u610F:",
      reviewed: "\u30EC\u30D3\u30E5\u30FC\u6E08\u307F",
      "Code Changes:": "\u30B3\u30FC\u30C9\u5909\u66F4:",
      Performance: "\u30D1\u30D5\u30A9\u30FC\u30DE\u30F3\u30B9",
      "Wall Time:": "\u7D4C\u904E\u6642\u9593:",
      "Agent Active:": "\u30A8\u30FC\u30B8\u30A7\u30F3\u30C8\u7A3C\u50CD\u6642\u9593:",
      "API Time:": "API\u6642\u9593:",
      "Tool Time:": "\u30C4\u30FC\u30EB\u6642\u9593:",
      "Session Stats": "\u30BB\u30C3\u30B7\u30E7\u30F3\u7D71\u8A08",
      "Model Usage": "\u30E2\u30C7\u30EB\u4F7F\u7528\u91CF",
      Reqs: "\u30EA\u30AF\u30A8\u30B9\u30C8",
      "Input Tokens": "\u5165\u529B\u30C8\u30FC\u30AF\u30F3",
      "Output Tokens": "\u51FA\u529B\u30C8\u30FC\u30AF\u30F3",
      "Savings Highlight:": "\u7BC0\u7D04\u30CF\u30A4\u30E9\u30A4\u30C8:",
      "of input tokens were served from the cache, reducing costs.": "\u5165\u529B\u30C8\u30FC\u30AF\u30F3\u304C\u30AD\u30E3\u30C3\u30B7\u30E5\u304B\u3089\u63D0\u4F9B\u3055\u308C\u3001\u30B3\u30B9\u30C8\u3092\u524A\u6E1B\u3057\u307E\u3057\u305F",
      "Tip: For a full token breakdown, run `/stats model`.": "\u30D2\u30F3\u30C8: \u30C8\u30FC\u30AF\u30F3\u306E\u8A73\u7D30\u306A\u5185\u8A33\u306F `/stats model` \u3092\u5B9F\u884C\u3057\u3066\u304F\u3060\u3055\u3044",
      "Model Stats For Nerds": "\u30DE\u30CB\u30A2\u5411\u3051\u30E2\u30C7\u30EB\u7D71\u8A08",
      "Tool Stats For Nerds": "\u30DE\u30CB\u30A2\u5411\u3051\u30C4\u30FC\u30EB\u7D71\u8A08",
      Metric: "\u30E1\u30C8\u30EA\u30C3\u30AF",
      API: "API",
      Requests: "\u30EA\u30AF\u30A8\u30B9\u30C8",
      Errors: "\u30A8\u30E9\u30FC",
      "Avg Latency": "\u5E73\u5747\u30EC\u30A4\u30C6\u30F3\u30B7",
      Tokens: "\u30C8\u30FC\u30AF\u30F3",
      Total: "\u5408\u8A08",
      Prompt: "\u30D7\u30ED\u30F3\u30D7\u30C8",
      Cached: "\u30AD\u30E3\u30C3\u30B7\u30E5",
      Thoughts: "\u601D\u8003",
      Tool: "\u30C4\u30FC\u30EB",
      Output: "\u51FA\u529B",
      "No API calls have been made in this session.": "\u3053\u306E\u30BB\u30C3\u30B7\u30E7\u30F3\u3067\u306FAPI\u547C\u3073\u51FA\u3057\u304C\u884C\u308F\u308C\u3066\u3044\u307E\u305B\u3093",
      "Tool Name": "\u30C4\u30FC\u30EB\u540D",
      Calls: "\u547C\u3073\u51FA\u3057",
      "Success Rate": "\u6210\u529F\u7387",
      "Avg Duration": "\u5E73\u5747\u6642\u9593",
      "User Decision Summary": "\u30E6\u30FC\u30B6\u30FC\u6C7A\u5B9A\u30B5\u30DE\u30EA\u30FC",
      "Total Reviewed Suggestions:": "\u7DCF\u30EC\u30D3\u30E5\u30FC\u63D0\u6848\u6570:",
      " \xBB Accepted:": " \xBB \u627F\u8A8D:",
      " \xBB Rejected:": " \xBB \u5374\u4E0B:",
      " \xBB Modified:": " \xBB \u5909\u66F4:",
      " Overall Agreement Rate:": " \u5168\u4F53\u627F\u8A8D\u7387:",
      "No tool calls have been made in this session.": "\u3053\u306E\u30BB\u30C3\u30B7\u30E7\u30F3\u3067\u306F\u30C4\u30FC\u30EB\u547C\u3073\u51FA\u3057\u304C\u884C\u308F\u308C\u3066\u3044\u307E\u305B\u3093",
      "Session start time is unavailable, cannot calculate stats.": "\u30BB\u30C3\u30B7\u30E7\u30F3\u958B\u59CB\u6642\u523B\u304C\u5229\u7528\u3067\u304D\u306A\u3044\u305F\u3081\u3001\u7D71\u8A08\u3092\u8A08\u7B97\u3067\u304D\u307E\u305B\u3093",
      // Loading
      "Waiting for user confirmation...": "\u30E6\u30FC\u30B6\u30FC\u306E\u78BA\u8A8D\u3092\u5F85\u3063\u3066\u3044\u307E\u3059...",
      "(esc to cancel, {{time}})": "(Esc \u3067\u30AD\u30E3\u30F3\u30BB\u30EB\u3001{{time}})",
      // Witty Loading Phrases
      WITTY_LOADING_PHRASES: [
        "\u904B\u4EFB\u305B\u3067\u691C\u7D22\u4E2D...",
        "\u4E2D\u306E\u4EBA\u304C\u30BF\u30A4\u30D4\u30F3\u30B0\u4E2D...",
        "\u30ED\u30B8\u30C3\u30AF\u3092\u6700\u9069\u5316\u4E2D...",
        "\u96FB\u5B50\u306E\u6570\u3092\u78BA\u8A8D\u4E2D...",
        "\u5B87\u5B99\u306E\u30D0\u30B0\u3092\u30C1\u30A7\u30C3\u30AF\u4E2D...",
        "\u5927\u91CF\u306E0\u30681\u3092\u30B3\u30F3\u30D1\u30A4\u30EB\u4E2D...",
        "HDD\u3068\u601D\u3044\u51FA\u3092\u30C7\u30D5\u30E9\u30B0\u4E2D...",
        "\u30D3\u30C3\u30C8\u3092\u3053\u3063\u305D\u308A\u5165\u308C\u66FF\u3048\u4E2D...",
        "\u30CB\u30E5\u30FC\u30ED\u30F3\u306E\u63A5\u7D9A\u3092\u518D\u69CB\u7BC9\u4E2D...",
        "\u3069\u3053\u304B\u306B\u884C\u3063\u305F\u30BB\u30DF\u30B3\u30ED\u30F3\u3092\u635C\u7D22\u4E2D...",
        "\u30D5\u30E9\u30C3\u30AF\u30B9\u30AD\u30E3\u30D1\u30B7\u30BF\u3092\u8ABF\u6574\u4E2D...",
        "\u30D5\u30A9\u30FC\u30B9\u3068\u4EA4\u611F\u4E2D...",
        "\u30A2\u30EB\u30B4\u30EA\u30BA\u30E0\u3092\u30C1\u30E5\u30FC\u30CB\u30F3\u30B0\u4E2D...",
        "\u767D\u3044\u30A6\u30B5\u30AE\u3092\u8FFD\u8DE1\u4E2D...",
        "\u30AB\u30BB\u30C3\u30C8\u30D5\u30FC\u30D5\u30FC\u4E2D...",
        "\u30ED\u30FC\u30C7\u30A3\u30F3\u30B0\u30E1\u30C3\u30BB\u30FC\u30B8\u3092\u8003\u3048\u4E2D...",
        "\u307B\u307C\u5B8C\u4E86...\u591A\u5206...",
        "\u6700\u65B0\u306E\u30DF\u30FC\u30E0\u306B\u3064\u3044\u3066\u8ABF\u67FB\u4E2D...",
        "\u3053\u306E\u8868\u793A\u3092\u6539\u5584\u3059\u308B\u30A2\u30A4\u30C7\u30A2\u3092\u601D\u7D22\u4E2D...",
        "\u3053\u306E\u554F\u984C\u3092\u8003\u3048\u4E2D...",
        "\u305D\u308C\u306F\u30D0\u30B0\u3067\u306A\u304F\u8AB0\u3082\u77E5\u3089\u306A\u3044\u65B0\u6A5F\u80FD\u3060\u3088",
        "\u30C0\u30A4\u30E4\u30EB\u30A2\u30C3\u30D7\u63A5\u7D9A\u97F3\u304C\u7D42\u308F\u308B\u306E\u3092\u5F85\u6A5F\u4E2D...",
        "\u30B3\u30FC\u30C9\u306B\u6CB9\u3092\u8FFD\u52A0\u4E2D...",
        // かなり意訳が入ってるもの
        "\u30A4\u30E4\u30DB\u30F3\u3092\u307B\u3069\u304D\u4E2D...",
        "\u30AB\u30D5\u30A7\u30A4\u30F3\u3092\u30B3\u30FC\u30C9\u306B\u5909\u63DB\u4E2D...",
        "\u5929\u52D5\u8AAC\u3092\u5730\u52D5\u8AAC\u306B\u66F8\u304D\u63DB\u3048\u4E2D...",
        "\u30D7\u30FC\u30EB\u3067\u6642\u8A08\u306E\u5B8C\u6210\u3092\u5F85\u6A5F\u4E2D...",
        "\u7B11\u6483\u7684\u306A\u56DE\u7B54\u3092\u7528\u610F\u4E2D...",
        "\u9069\u5207\u306A\u30DF\u30FC\u30E0\u3092\u8A18\u8FF0\u4E2D...",
        "A\u30DC\u30BF\u30F3\u3092\u62BC\u3057\u3066\u6B21\u3078...",
        "\u30B3\u30FC\u30C9\u306B\u30EA\u30C3\u30AF\u30ED\u30FC\u30EB\u3092\u4ED5\u8FBC\u307F\u4E2D...",
        "\u30D7\u30ED\u30B0\u30E9\u30DE\u30FC\u304C\u8CA7\u4E4F\u306A\u306E\u306F\u30AD\u30E3\u30C3\u30B7\u30E5\u3092\u4F7F\u3044\u3059\u304E\u308B\u304B\u3089...",
        "\u30D7\u30ED\u30B0\u30E9\u30DE\u30FC\u304C\u30C0\u30FC\u30AF\u30E2\u30FC\u30C9\u306A\u306E\u306F\u30D0\u30B0\u3092\u898B\u305F\u304F\u306A\u3044\u304B\u3089...",
        "\u30B3\u30FC\u30C9\u304C\u58CA\u308C\u305F?\u53E9\u3051\u3070\u6CBB\u308B\u3055",
        "USB\u306E\u5DEE\u3057\u8FBC\u307F\u306B\u6311\u6226\u4E2D..."
      ],
      // ============================================================================
      // Custom API-KEY Configuration
      // ============================================================================
      "For advanced users who want to configure models manually.": "\u30E2\u30C7\u30EB\u3092\u624B\u52D5\u3067\u8A2D\u5B9A\u3057\u305F\u3044\u4E0A\u7D1A\u30E6\u30FC\u30B6\u30FC\u5411\u3051\u3002",
      "Please configure your models in settings.json:": "settings.json \u3067\u30E2\u30C7\u30EB\u3092\u8A2D\u5B9A\u3057\u3066\u304F\u3060\u3055\u3044\uFF1A",
      "Set API key via environment variable (e.g., OPENAI_API_KEY)": "\u74B0\u5883\u5909\u6570\u3092\u4F7F\u7528\u3057\u3066 API \u30AD\u30FC\u3092\u8A2D\u5B9A\u3057\u3066\u304F\u3060\u3055\u3044\uFF08\u4F8B\uFF1AOPENAI_API_KEY\uFF09",
      "Add model configuration to modelProviders['openai'] (or other auth types)": "modelProviders['openai']\uFF08\u307E\u305F\u306F\u4ED6\u306E\u8A8D\u8A3C\u30BF\u30A4\u30D7\uFF09\u306B\u30E2\u30C7\u30EB\u8A2D\u5B9A\u3092\u8FFD\u52A0\u3057\u3066\u304F\u3060\u3055\u3044",
      "Each provider needs: id, envKey (required), plus optional baseUrl, generationConfig": "\u5404\u30D7\u30ED\u30D0\u30A4\u30C0\u30FC\u306B\u306F\uFF1Aid\u3001envKey\uFF08\u5FC5\u9808\uFF09\u3001\u304A\u3088\u3073\u30AA\u30D7\u30B7\u30E7\u30F3\u306E baseUrl\u3001generationConfig \u304C\u5FC5\u8981\u3067\u3059",
      "Use /model command to select your preferred model from the configured list": "/model \u30B3\u30DE\u30F3\u30C9\u3092\u4F7F\u7528\u3057\u3066\u3001\u8A2D\u5B9A\u6E08\u307F\u30EA\u30B9\u30C8\u304B\u3089\u304A\u597D\u307F\u306E\u30E2\u30C7\u30EB\u3092\u9078\u629E\u3057\u3066\u304F\u3060\u3055\u3044",
      "Supported auth types: openai, anthropic, gemini, vertex-ai, etc.": "\u30B5\u30DD\u30FC\u30C8\u3055\u308C\u3066\u3044\u308B\u8A8D\u8A3C\u30BF\u30A4\u30D7\uFF1Aopenai\u3001anthropic\u3001gemini\u3001vertex-ai \u306A\u3069",
      // ============================================================================
      // Coding Plan Authentication
      // ============================================================================
      "Please enter your API key:": "API\u30AD\u30FC\u3092\u5165\u529B\u3057\u3066\u304F\u3060\u3055\u3044\uFF1A",
      "API key cannot be empty.": "API\u30AD\u30FC\u306F\u7A7A\u306B\u3067\u304D\u307E\u305B\u3093\u3002",
      "You can get your exclusive Coding Plan API-KEY here:": "Coding Plan \u306E API-KEY \u306F\u3053\u3061\u3089\u3067\u53D6\u5F97\u3067\u304D\u307E\u3059\uFF1A",
      "New model configurations are available for Bailian Coding Plan. Update now?": "Bailian Coding Plan \u306E\u65B0\u3057\u3044\u30E2\u30C7\u30EB\u8A2D\u5B9A\u304C\u5229\u7528\u53EF\u80FD\u3067\u3059\u3002\u4ECA\u3059\u3050\u66F4\u65B0\u3057\u307E\u3059\u304B\uFF1F",
      "Coding Plan configuration updated successfully. New models are now available.": "Coding Plan \u306E\u8A2D\u5B9A\u304C\u6B63\u5E38\u306B\u66F4\u65B0\u3055\u308C\u307E\u3057\u305F\u3002\u65B0\u3057\u3044\u30E2\u30C7\u30EB\u304C\u5229\u7528\u53EF\u80FD\u306B\u306A\u308A\u307E\u3057\u305F\u3002",
      "Coding Plan API key not found. Please re-authenticate with Coding Plan.": "Coding Plan \u306E API \u30AD\u30FC\u304C\u898B\u3064\u304B\u308A\u307E\u305B\u3093\u3002Coding Plan \u3067\u518D\u8A8D\u8A3C\u3057\u3066\u304F\u3060\u3055\u3044\u3002",
      "Failed to update Coding Plan configuration: {{message}}": "Coding Plan \u306E\u8A2D\u5B9A\u66F4\u65B0\u306B\u5931\u6557\u3057\u307E\u3057\u305F: {{message}}",
      // ============================================================================
      // Auth Dialog - View Titles and Labels
      // ============================================================================
      "Coding Plan": "Coding Plan",
      "Coding Plan (Bailian, China)": "Coding Plan (Bailian, \u4E2D\u56FD)",
      "Coding Plan (Bailian, Global/Intl)": "Coding Plan (Bailian, \u30B0\u30ED\u30FC\u30D0\u30EB/\u56FD\u969B)",
      "Paste your api key of Bailian Coding Plan and you're all set!": "Bailian Coding Plan\u306EAPI\u30AD\u30FC\u3092\u8CBC\u308A\u4ED8\u3051\u308B\u3060\u3051\u3067\u6E96\u5099\u5B8C\u4E86\u3067\u3059\uFF01",
      "Paste your api key of Coding Plan (Bailian, Global/Intl) and you're all set!": "Coding Plan (Bailian, \u30B0\u30ED\u30FC\u30D0\u30EB/\u56FD\u969B) \u306EAPI\u30AD\u30FC\u3092\u8CBC\u308A\u4ED8\u3051\u308B\u3060\u3051\u3067\u6E96\u5099\u5B8C\u4E86\u3067\u3059\uFF01",
      Custom: "\u30AB\u30B9\u30BF\u30E0",
      "More instructions about configuring `modelProviders` manually.": "`modelProviders`\u3092\u624B\u52D5\u3067\u8A2D\u5B9A\u3059\u308B\u65B9\u6CD5\u306E\u8A73\u7D30\u306F\u3053\u3061\u3089\u3002",
      "Select API-KEY configuration mode:": "API-KEY\u8A2D\u5B9A\u30E2\u30FC\u30C9\u3092\u9078\u629E\u3057\u3066\u304F\u3060\u3055\u3044\uFF1A",
      "(Press Escape to go back)": "(Escape\u30AD\u30FC\u3067\u623B\u308B)",
      "(Press Enter to submit, Escape to cancel)": "(Enter\u3067\u9001\u4FE1\u3001Escape\u3067\u30AD\u30E3\u30F3\u30BB\u30EB)",
      "More instructions please check:": "\u8A73\u7D30\u306A\u624B\u9806\u306F\u3053\u3061\u3089\u3092\u3054\u78BA\u8A8D\u304F\u3060\u3055\u3044\uFF1A",
      // ============================================================================
      // Coding Plan International Updates
      // ============================================================================
      "New model configurations are available for {{region}}. Update now?": "{{region}} \u306E\u65B0\u3057\u3044\u30E2\u30C7\u30EB\u8A2D\u5B9A\u304C\u5229\u7528\u53EF\u80FD\u3067\u3059\u3002\u4ECA\u3059\u3050\u66F4\u65B0\u3057\u307E\u3059\u304B\uFF1F",
      "New model configurations are available for Bailian Coding Plan (China). Update now?": "Bailian Coding Plan (\u4E2D\u56FD) \u306E\u65B0\u3057\u3044\u30E2\u30C7\u30EB\u8A2D\u5B9A\u304C\u5229\u7528\u53EF\u80FD\u3067\u3059\u3002\u4ECA\u3059\u3050\u66F4\u65B0\u3057\u307E\u3059\u304B\uFF1F",
      "New model configurations are available for Coding Plan (Bailian, Global/Intl). Update now?": "Coding Plan (Bailian, \u30B0\u30ED\u30FC\u30D0\u30EB/\u56FD\u969B) \u306E\u65B0\u3057\u3044\u30E2\u30C7\u30EB\u8A2D\u5B9A\u304C\u5229\u7528\u53EF\u80FD\u3067\u3059\u3002\u4ECA\u3059\u3050\u66F4\u65B0\u3057\u307E\u3059\u304B\uFF1F",
      '{{region}} configuration updated successfully. Model switched to "{{model}}".': '{{region}} \u306E\u8A2D\u5B9A\u304C\u6B63\u5E38\u306B\u66F4\u65B0\u3055\u308C\u307E\u3057\u305F\u3002\u30E2\u30C7\u30EB\u304C "{{model}}" \u306B\u5207\u308A\u66FF\u308F\u308A\u307E\u3057\u305F\u3002',
      "Authenticated successfully with {{region}}. API key and model configs saved to settings.json (backed up).": "{{region}} \u3067\u306E\u8A8D\u8A3C\u306B\u6210\u529F\u3057\u307E\u3057\u305F\u3002API\u30AD\u30FC\u3068\u30E2\u30C7\u30EB\u8A2D\u5B9A\u304C settings.json \u306B\u4FDD\u5B58\u3055\u308C\u307E\u3057\u305F\uFF08\u30D0\u30C3\u30AF\u30A2\u30C3\u30D7\u6E08\u307F\uFF09\u3002"
    };
  }
});

// packages/cli/src/i18n/locales/pt.js
var pt_exports = {};
__export(pt_exports, {
  default: () => pt_default
});
var pt_default;
var init_pt = __esm({
  "packages/cli/src/i18n/locales/pt.js"() {
    "use strict";
    init_esbuild_shims();
    pt_default = {
      // ============================================================================
      // Help / UI Components
      // ============================================================================
      "Basics:": "No\xE7\xF5es b\xE1sicas:",
      "Add context": "Adicionar contexto",
      "Use {{symbol}} to specify files for context (e.g., {{example}}) to target specific files or folders.": "Use {{symbol}} para especificar arquivos para o contexto (ex: {{example}}) para atingir arquivos ou pastas espec\xEDficos.",
      "@": "@",
      "@src/myFile.ts": "@src/myFile.ts",
      "Shell mode": "Modo shell",
      "YOLO mode": "Modo YOLO",
      "plan mode": "modo planejamento",
      "auto-accept edits": "aceitar edi\xE7\xF5es automaticamente",
      "Accepting edits": "Aceitando edi\xE7\xF5es",
      "(shift + tab to cycle)": "(shift + tab para alternar)",
      "Execute shell commands via {{symbol}} (e.g., {{example1}}) or use natural language (e.g., {{example2}}).": "Execute comandos shell via {{symbol}} (ex: {{example1}}) ou use linguagem natural (ex: {{example2}}).",
      "!": "!",
      "!npm run start": "!npm run start",
      "start server": "iniciar servidor",
      "Commands:": "Comandos:",
      "shell command": "comando shell",
      "Model Context Protocol command (from external servers)": "Comando Model Context Protocol (de servidores externos)",
      "Keyboard Shortcuts:": "Atalhos de teclado:",
      "Toggle this help display": "Alternar exibi\xE7\xE3o desta ajuda",
      "Toggle shell mode": "Alternar modo shell",
      "Open command menu": "Abrir menu de comandos",
      "Add file context": "Adicionar contexto de arquivo",
      "Accept suggestion / Autocomplete": "Aceitar sugest\xE3o / Autocompletar",
      "Reverse search history": "Pesquisa reversa no hist\xF3rico",
      "Press ? again to close": "Pressione ? novamente para fechar",
      // Keyboard shortcuts panel descriptions
      "for shell mode": "para modo shell",
      "for commands": "para comandos",
      "for file paths": "para caminhos de arquivo",
      "to clear input": "para limpar entrada",
      "to cycle approvals": "para alternar aprova\xE7\xF5es",
      "to quit": "para sair",
      "for newline": "para nova linha",
      "to clear screen": "para limpar a tela",
      "to search history": "para pesquisar no hist\xF3rico",
      "to paste images": "para colar imagens",
      "for external editor": "para editor externo",
      "Jump through words in the input": "Pular palavras na entrada",
      "Close dialogs, cancel requests, or quit application": "Fechar di\xE1logos, cancelar solicita\xE7\xF5es ou sair do aplicativo",
      "New line": "Nova linha",
      "New line (Alt+Enter works for certain linux distros)": "Nova linha (Alt+Enter funciona em certas distros linux)",
      "Clear the screen": "Limpar a tela",
      "Open input in external editor": "Abrir entrada no editor externo",
      "Send message": "Enviar mensagem",
      "Initializing...": "Inicializando...",
      "Connecting to MCP servers... ({{connected}}/{{total}})": "Conectando aos servidores MCP... ({{connected}}/{{total}})",
      "Type your message or @path/to/file": "Digite sua mensagem ou @caminho/do/arquivo",
      "? for shortcuts": "? para atalhos",
      "Press 'i' for INSERT mode and 'Esc' for NORMAL mode.": "Pressione 'i' para modo INSER\xC7\xC3O e 'Esc' para modo NORMAL.",
      "Cancel operation / Clear input (double press)": "Cancelar opera\xE7\xE3o / Limpar entrada (pressionar duas vezes)",
      "Cycle approval modes": "Alternar modos de aprova\xE7\xE3o",
      "Cycle through your prompt history": "Alternar hist\xF3rico de prompts",
      "For a full list of shortcuts, see {{docPath}}": "Para uma lista completa de atalhos, consulte {{docPath}}",
      "docs/keyboard-shortcuts.md": "docs/keyboard-shortcuts.md",
      "for help on Qwen Code": "para ajuda sobre o Qwen Code",
      "show version info": "mostrar informa\xE7\xF5es de vers\xE3o",
      "submit a bug report": "enviar um relat\xF3rio de erro",
      "About Qwen Code": "Sobre o Qwen Code",
      Status: "Status",
      // ============================================================================
      // System Information Fields
      // ============================================================================
      "Qwen Code": "Qwen Code",
      Runtime: "Runtime",
      OS: "SO",
      Auth: "Autentica\xE7\xE3o",
      "CLI Version": "Vers\xE3o da CLI",
      "Git Commit": "Commit do Git",
      Model: "Modelo",
      Sandbox: "Sandbox",
      "OS Platform": "Plataforma do SO",
      "OS Arch": "Arquitetura do SO",
      "OS Release": "Vers\xE3o do SO",
      "Node.js Version": "Vers\xE3o do Node.js",
      "NPM Version": "Vers\xE3o do NPM",
      "Session ID": "ID da Sess\xE3o",
      "Auth Method": "M\xE9todo de Autentica\xE7\xE3o",
      "Base URL": "URL Base",
      Proxy: "Proxy",
      "Memory Usage": "Uso de Mem\xF3ria",
      "IDE Client": "Cliente IDE",
      // ============================================================================
      // Commands - General
      // ============================================================================
      "Analyzes the project and creates a tailored QWEN.md file.": "Analisa o projeto e cria um arquivo QWEN.md personalizado.",
      "list available Qwen Code tools. Usage: /tools [desc]": "listar ferramentas Qwen Code dispon\xEDveis. Uso: /tools [desc]",
      "Available Qwen Code CLI tools:": "Ferramentas CLI do Qwen Code dispon\xEDveis:",
      "No tools available": "Nenhuma ferramenta dispon\xEDvel",
      "View or change the approval mode for tool usage": "Ver ou alterar o modo de aprova\xE7\xE3o para uso de ferramentas",
      'Invalid approval mode "{{arg}}". Valid modes: {{modes}}': 'Modo de aprova\xE7\xE3o inv\xE1lido "{{arg}}". Modos v\xE1lidos: {{modes}}',
      'Approval mode set to "{{mode}}"': 'Modo de aprova\xE7\xE3o definido como "{{mode}}"',
      "View or change the language setting": "Ver ou alterar a configura\xE7\xE3o de idioma",
      "change the theme": "alterar o tema",
      "Select Theme": "Selecionar Tema",
      Preview: "Visualizar",
      "(Use Enter to select, Tab to configure scope)": "(Use Enter para selecionar, Tab para configurar o escopo)",
      "(Use Enter to apply scope, Tab to go back)": "(Use Enter para aplicar o escopo, Tab para voltar)",
      "Theme configuration unavailable due to NO_COLOR env variable.": "Configura\xE7\xE3o de tema indispon\xEDvel devido \xE0 vari\xE1vel de ambiente NO_COLOR.",
      'Theme "{{themeName}}" not found.': 'Tema "{{themeName}}" n\xE3o encontrado.',
      'Theme "{{themeName}}" not found in selected scope.': 'Tema "{{themeName}}" n\xE3o encontrado no escopo selecionado.',
      "Clear conversation history and free up context": "Limpar hist\xF3rico de conversa e liberar contexto",
      "Compresses the context by replacing it with a summary.": "Comprime o contexto substituindo-o por um resumo.",
      "open full Qwen Code documentation in your browser": "abrir documenta\xE7\xE3o completa do Qwen Code no seu navegador",
      "Configuration not available.": "Configura\xE7\xE3o n\xE3o dispon\xEDvel.",
      "change the auth method": "alterar o m\xE9todo de autentica\xE7\xE3o",
      "Configure authentication information for login": "Configurar informa\xE7\xF5es de autentica\xE7\xE3o para login",
      "Copy the last result or code snippet to clipboard": "Copiar o \xFAltimo resultado ou trecho de c\xF3digo para a \xE1rea de transfer\xEAncia",
      // ============================================================================
      // Commands - Agents
      // ============================================================================
      "Manage subagents for specialized task delegation.": "Gerenciar subagentes para delega\xE7\xE3o de tarefas especializadas.",
      "Manage existing subagents (view, edit, delete).": "Gerenciar subagentes existentes (ver, editar, excluir).",
      "Create a new subagent with guided setup.": "Criar um novo subagente com configura\xE7\xE3o guiada.",
      // ============================================================================
      // Agents - Management Dialog
      // ============================================================================
      Agents: "Agentes",
      "Choose Action": "Escolher A\xE7\xE3o",
      "Edit {{name}}": "Editar {{name}}",
      "Edit Tools: {{name}}": "Editar Ferramentas: {{name}}",
      "Edit Color: {{name}}": "Editar Cor: {{name}}",
      "Delete {{name}}": "Excluir {{name}}",
      "Unknown Step": "Etapa Desconhecida",
      "Esc to close": "Esc para fechar",
      "Enter to select, \u2191\u2193 to navigate, Esc to close": "Enter para selecionar, \u2191\u2193 para navegar, Esc para fechar",
      "Esc to go back": "Esc para voltar",
      "Enter to confirm, Esc to cancel": "Enter para confirmar, Esc para cancelar",
      "Enter to select, \u2191\u2193 to navigate, Esc to go back": "Enter para selecionar, \u2191\u2193 para navegar, Esc para voltar",
      "Invalid step: {{step}}": "Etapa inv\xE1lida: {{step}}",
      "No subagents found.": "Nenhum subagente encontrado.",
      "Use '/agents create' to create your first subagent.": "Use '/agents create' para criar seu primeiro subagente.",
      "(built-in)": "(integrado)",
      "(overridden by project level agent)": "(substitu\xEDdo por agente de n\xEDvel de projeto)",
      "Project Level ({{path}})": "N\xEDvel de Projeto ({{path}})",
      "User Level ({{path}})": "N\xEDvel de Usu\xE1rio ({{path}})",
      "Built-in Agents": "Agentes Integrados",
      "Extension Agents": "Agentes de Extens\xE3o",
      "Using: {{count}} agents": "Usando: {{count}} agentes",
      "View Agent": "Ver Agente",
      "Edit Agent": "Editar Agente",
      "Delete Agent": "Excluir Agente",
      Back: "Voltar",
      "No agent selected": "Nenhum agente selecionado",
      "File Path: ": "Caminho do Arquivo: ",
      "Tools: ": "Ferramentas: ",
      "Color: ": "Cor: ",
      "Description:": "Descri\xE7\xE3o:",
      "System Prompt:": "Prompt do Sistema:",
      "Open in editor": "Abrir no editor",
      "Edit tools": "Editar ferramentas",
      "Edit color": "Editar cor",
      "\u274C Error:": "\u274C Erro:",
      'Are you sure you want to delete agent "{{name}}"?': 'Tem certeza que deseja excluir o agente "{{name}}"?',
      // ============================================================================
      // Agents - Creation Wizard
      // ============================================================================
      "Project Level (.qwen/agents/)": "N\xEDvel de Projeto (.qwen/agents/)",
      "User Level (~/.qwen/agents/)": "N\xEDvel de Usu\xE1rio (~/.qwen/agents/)",
      "\u2705 Subagent Created Successfully!": "\u2705 Subagente criado com sucesso!",
      'Subagent "{{name}}" has been saved to {{level}} level.': 'O subagente "{{name}}" foi salvo no n\xEDvel {{level}}.',
      "Name: ": "Nome: ",
      "Location: ": "Localiza\xE7\xE3o: ",
      "\u274C Error saving subagent:": "\u274C Erro ao salvar subagente:",
      "Warnings:": "Avisos:",
      'Name "{{name}}" already exists at {{level}} level - will overwrite existing subagent': 'O nome "{{name}}" j\xE1 existe no n\xEDvel {{level}} - o subagente existente ser\xE1 substitu\xEDdo',
      'Name "{{name}}" exists at user level - project level will take precedence': 'O nome "{{name}}" existe no n\xEDvel de usu\xE1rio - o n\xEDvel de projeto ter\xE1 preced\xEAncia',
      'Name "{{name}}" exists at project level - existing subagent will take precedence': 'O nome "{{name}}" existe no n\xEDvel de projeto - o subagente existente ter\xE1 preced\xEAncia',
      "Description is over {{length}} characters": "A descri\xE7\xE3o tem mais de {{length}} caracteres",
      "System prompt is over {{length}} characters": "O prompt do sistema tem mais de {{length}} caracteres",
      // ============================================================================
      // Agents - Creation Wizard Steps
      // ============================================================================
      "Step {{n}}: Choose Location": "Etapa {{n}}: Escolher Localiza\xE7\xE3o",
      "Step {{n}}: Choose Generation Method": "Etapa {{n}}: Escolher M\xE9todo de Gera\xE7\xE3o",
      "Generate with Qwen Code (Recommended)": "Gerar com Qwen Code (Recomendado)",
      "Manual Creation": "Cria\xE7\xE3o Manual",
      "Describe what this subagent should do and when it should be used. (Be comprehensive for best results)": "Descreva o que este subagente deve fazer e quando deve ser usado. (Seja abrangente para melhores resultados)",
      "e.g., Expert code reviewer that reviews code based on best practices...": "ex: Revisor de c\xF3digo especialista que revisa c\xF3digo com base em melhores pr\xE1ticas...",
      "Generating subagent configuration...": "Gerando configura\xE7\xE3o do subagente...",
      "Failed to generate subagent: {{error}}": "Falha ao gerar subagente: {{error}}",
      "Step {{n}}: Describe Your Subagent": "Etapa {{n}}: Descreva Seu Subagente",
      "Step {{n}}: Enter Subagent Name": "Etapa {{n}}: Digite o Nome do Subagente",
      "Step {{n}}: Enter System Prompt": "Etapa {{n}}: Digite o Prompt do Sistema",
      "Step {{n}}: Enter Description": "Etapa {{n}}: Digite a Descri\xE7\xE3o",
      // ============================================================================
      // Agents - Tool Selection
      // ============================================================================
      "Step {{n}}: Select Tools": "Etapa {{n}}: Selecionar Ferramentas",
      "All Tools (Default)": "Todas as Ferramentas (Padr\xE3o)",
      "All Tools": "Todas as Ferramentas",
      "Read-only Tools": "Ferramentas de Somente Leitura",
      "Read & Edit Tools": "Ferramentas de Leitura e Edi\xE7\xE3o",
      "Read & Edit & Execution Tools": "Ferramentas de Leitura, Edi\xE7\xE3o e Execu\xE7\xE3o",
      "All tools selected, including MCP tools": "Todas as ferramentas selecionadas, incluindo ferramentas MCP",
      "Selected tools:": "Ferramentas selecionadas:",
      "Read-only tools:": "Ferramentas de somente leitura:",
      "Edit tools:": "Ferramentas de edi\xE7\xE3o:",
      "Execution tools:": "Ferramentas de execu\xE7\xE3o:",
      "Step {{n}}: Choose Background Color": "Etapa {{n}}: Escolher Cor de Fundo",
      "Step {{n}}: Confirm and Save": "Etapa {{n}}: Confirmar e Salvar",
      // ============================================================================
      // Agents - Navigation & Instructions
      // ============================================================================
      "Esc to cancel": "Esc para cancelar",
      "Press Enter to save, e to save and edit, Esc to go back": "Pressione Enter para salvar, e para salvar e editar, Esc para voltar",
      "Press Enter to continue, {{navigation}}Esc to {{action}}": "Pressione Enter para continuar, {{navigation}}Esc para {{action}}",
      cancel: "cancelar",
      "go back": "voltar",
      "\u2191\u2193 to navigate, ": "\u2191\u2193 para navegar, ",
      "Enter a clear, unique name for this subagent.": "Digite um nome claro e \xFAnico para este subagente.",
      "e.g., Code Reviewer": "ex: Revisor de C\xF3digo",
      "Name cannot be empty.": "O nome n\xE3o pode estar vazio.",
      "Write the system prompt that defines this subagent's behavior. Be comprehensive for best results.": "Escreva o prompt do sistema que define o comportamento deste subagente. Seja abrangente para melhores resultados.",
      "e.g., You are an expert code reviewer...": "ex: Voc\xEA \xE9 um revisor de c\xF3digo especialista...",
      "System prompt cannot be empty.": "O prompt do sistema n\xE3o pode estar vazio.",
      "Describe when and how this subagent should be used.": "Descreva quando e como este subagente deve ser usado.",
      "e.g., Reviews code for best practices and potential bugs.": "ex: Revisa o c\xF3digo em busca de melhores pr\xE1ticas e erros potenciais.",
      "Description cannot be empty.": "A descri\xE7\xE3o n\xE3o pode estar vazia.",
      "Failed to launch editor: {{error}}": "Falha ao iniciar editor: {{error}}",
      "Failed to save and edit subagent: {{error}}": "Falha ao salvar e editar subagente: {{error}}",
      // ============================================================================
      // Commands - General (continued)
      // ============================================================================
      "View and edit Qwen Code settings": "Ver e editar configura\xE7\xF5es do Qwen Code",
      Settings: "Configura\xE7\xF5es",
      "To see changes, Qwen Code must be restarted. Press r to exit and apply changes now.": "Para ver as altera\xE7\xF5es, o Qwen Code deve ser reiniciado. Pressione r para sair e aplicar as altera\xE7\xF5es agora.",
      'The command "/{{command}}" is not supported in non-interactive mode.': 'O comando "/{{command}}" n\xE3o \xE9 suportado no modo n\xE3o interativo.',
      // ============================================================================
      // Settings Labels
      // ============================================================================
      "Vim Mode": "Modo Vim",
      "Disable Auto Update": "Desativar Atualiza\xE7\xE3o Autom\xE1tica",
      "Attribution: commit": "Atribui\xE7\xE3o: commit",
      "Terminal Bell Notification": "Notifica\xE7\xE3o Sonora do Terminal",
      "Enable Usage Statistics": "Ativar Estat\xEDsticas de Uso",
      Theme: "Tema",
      "Preferred Editor": "Editor Preferido",
      "Auto-connect to IDE": "Conex\xE3o Autom\xE1tica com IDE",
      "Enable Prompt Completion": "Ativar Autocompletar de Prompts",
      "Debug Keystroke Logging": "Log de Depura\xE7\xE3o de Teclas",
      "Language: UI": "Idioma: Interface",
      "Language: Model": "Idioma: Modelo",
      "Output Format": "Formato de Sa\xEDda",
      "Hide Window Title": "Ocultar T\xEDtulo da Janela",
      "Show Status in Title": "Mostrar Status no T\xEDtulo",
      "Hide Tips": "Ocultar Dicas",
      "Show Line Numbers in Code": "Mostrar N\xFAmeros de Linhas no C\xF3digo",
      "Show Citations": "Mostrar Cita\xE7\xF5es",
      "Custom Witty Phrases": "Frases de Efeito Personalizadas",
      "Show Welcome Back Dialog": "Mostrar Di\xE1logo de Bem-vindo de Volta",
      "Enable User Feedback": "Ativar Feedback do Usu\xE1rio",
      "How is Qwen doing this session? (optional)": "Como o Qwen est\xE1 se saindo nesta sess\xE3o? (opcional)",
      Bad: "Ruim",
      Fine: "Bom",
      Good: "\xD3timo",
      Dismiss: "Ignorar",
      "Not Sure Yet": "N\xE3o tenho certeza ainda",
      "Any other key": "Qualquer outra tecla",
      "Disable Loading Phrases": "Desativar Frases de Carregamento",
      "Screen Reader Mode": "Modo de Leitor de Tela",
      "IDE Mode": "Modo IDE",
      "Max Session Turns": "M\xE1ximo de Turnos da Sess\xE3o",
      "Skip Next Speaker Check": "Pular Verifica\xE7\xE3o do Pr\xF3ximo Falante",
      "Skip Loop Detection": "Pular Detec\xE7\xE3o de Loop",
      "Skip Startup Context": "Pular Contexto de Inicializa\xE7\xE3o",
      "Enable OpenAI Logging": "Ativar Log do OpenAI",
      "OpenAI Logging Directory": "Diret\xF3rio de Log do OpenAI",
      Timeout: "Tempo Limite",
      "Max Retries": "M\xE1ximo de Tentativas",
      "Disable Cache Control": "Desativar Controle de Cache",
      "Memory Discovery Max Dirs": "Descoberta de Mem\xF3ria M\xE1x. Diretorios",
      "Load Memory From Include Directories": "Carregar Mem\xF3ria de Diret\xF3rios Inclu\xEDdos",
      "Respect .gitignore": "Respeitar .gitignore",
      "Respect .qwenignore": "Respeitar .qwenignore",
      "Enable Recursive File Search": "Ativar Pesquisa Recursiva de Arquivos",
      "Disable Fuzzy Search": "Desativar Pesquisa Difusa",
      "Interactive Shell (PTY)": "Shell Interativo (PTY)",
      "Show Color": "Mostrar Cores",
      "Auto Accept": "Aceitar Automaticamente",
      "Use Ripgrep": "Usar Ripgrep",
      "Use Builtin Ripgrep": "Usar Ripgrep Integrado",
      "Enable Tool Output Truncation": "Ativar Truncamento de Sa\xEDda de Ferramenta",
      "Tool Output Truncation Threshold": "Limite de Truncamento de Sa\xEDda de Ferramenta",
      "Tool Output Truncation Lines": "Linhas de Truncamento de Sa\xEDda de Ferramenta",
      "Folder Trust": "Confian\xE7a de Pasta",
      "Vision Model Preview": "Visualiza\xE7\xE3o de Modelo de Vis\xE3o",
      "Tool Schema Compliance": "Conformidade de Esquema de Ferramenta",
      // Settings enum options
      "Auto (detect from system)": "Autom\xE1tico (detectar do sistema)",
      Text: "Texto",
      JSON: "JSON",
      Plan: "Planejamento",
      Default: "Padr\xE3o",
      "Auto Edit": "Edi\xE7\xE3o Autom\xE1tica",
      YOLO: "YOLO",
      "toggle vim mode on/off": "alternar modo vim ligado/desligado",
      "check session stats. Usage: /stats [model|tools]": "verificar estat\xEDsticas da sess\xE3o. Uso: /stats [model|tools]",
      "Show model-specific usage statistics.": "Mostrar estat\xEDsticas de uso espec\xEDficas do modelo.",
      "Show tool-specific usage statistics.": "Mostrar estat\xEDsticas de uso espec\xEDficas da ferramenta.",
      "exit the cli": "sair da cli",
      "list configured MCP servers and tools, or authenticate with OAuth-enabled servers": "listar servidores e ferramentas MCP configurados, ou autenticar com servidores habilitados para OAuth",
      "Manage workspace directories": "Gerenciar diret\xF3rios do workspace",
      "Add directories to the workspace. Use comma to separate multiple paths": "Adicionar diret\xF3rios ao workspace. Use v\xEDrgula para separar v\xE1rios caminhos",
      "Show all directories in the workspace": "Mostrar todos os diret\xF3rios no workspace",
      "set external editor preference": "definir prefer\xEAncia de editor externo",
      "Select Editor": "Selecionar Editor",
      "Editor Preference": "Prefer\xEAncia de Editor",
      "These editors are currently supported. Please note that some editors cannot be used in sandbox mode.": "Estes editores s\xE3o suportados atualmente. Note que alguns editores n\xE3o podem ser usados no modo sandbox.",
      "Your preferred editor is:": "Seu editor preferido \xE9:",
      "Manage extensions": "Gerenciar extens\xF5es",
      "List active extensions": "Listar extens\xF5es ativas",
      "Update extensions. Usage: update <extension-names>|--all": "Atualizar extens\xF5es. Uso: update <nomes-das-extensoes>|--all",
      "Disable an extension": "Desativar uma extens\xE3o",
      "Enable an extension": "Ativar uma extens\xE3o",
      "Install an extension from a git repo or local path": "Instalar uma extens\xE3o de um reposit\xF3rio git ou caminho local",
      "Uninstall an extension": "Desinstalar uma extens\xE3o",
      "No extensions installed.": "Nenhuma extens\xE3o instalada.",
      "Usage: /extensions update <extension-names>|--all": "Uso: /extensions update <nomes-das-extensoes>|--all",
      'Extension "{{name}}" not found.': 'Extens\xE3o "{{name}}" n\xE3o encontrada.',
      "No extensions to update.": "Nenhuma extens\xE3o para atualizar.",
      "Usage: /extensions install <source>": "Uso: /extensions install <fonte>",
      'Installing extension from "{{source}}"...': 'Instalando extens\xE3o de "{{source}}"...',
      'Extension "{{name}}" installed successfully.': 'Extens\xE3o "{{name}}" instalada com sucesso.',
      'Failed to install extension from "{{source}}": {{error}}': 'Falha ao instalar extens\xE3o de "{{source}}": {{error}}',
      "Usage: /extensions uninstall <extension-name>": "Uso: /extensions uninstall <nome-da-extensao>",
      'Uninstalling extension "{{name}}"...': 'Desinstalando extens\xE3o "{{name}}"...',
      'Extension "{{name}}" uninstalled successfully.': 'Extens\xE3o "{{name}}" desinstalada com sucesso.',
      'Failed to uninstall extension "{{name}}": {{error}}': 'Falha ao desinstalar extens\xE3o "{{name}}": {{error}}',
      "Usage: /extensions {{command}} <extension> [--scope=<user|workspace>]": "Uso: /extensions {{command}} <extensao> [--scope=<user|workspace>]",
      'Unsupported scope "{{scope}}", deve ser um de "user" ou "workspace"': 'Escopo n\xE3o suportado "{{scope}}", deve ser um de "user" ou "workspace"',
      'Extension "{{name}}" disabled for scope "{{scope}}"': 'Extens\xE3o "{{name}}" desativada para o escopo "{{scope}}"',
      'Extension "{{name}}" enabled for scope "{{scope}}"': 'Extens\xE3o "{{name}}" ativada para o escopo "{{scope}}"',
      "Do you want to continue? [Y/n]: ": "Voc\xEA deseja continuar? [Y/n]: ",
      "Do you want to continue?": "Voc\xEA deseja continuar?",
      'Installing extension "{{name}}".': 'Instalando extens\xE3o "{{name}}".',
      "**Extensions may introduce unexpected behavior. Ensure you have investigated the extension source and trust the author.**": "**As extens\xF5es podem introduzir comportamentos inesperados. Certifique-se de ter investigado a fonte da extens\xE3o e confie no autor.**",
      "This extension will run the following MCP servers:": "Esta extens\xE3o executar\xE1 os seguintes servidores MCP:",
      local: "local",
      remote: "remoto",
      "This extension will add the following commands: {{commands}}.": "Esta extens\xE3o adicionar\xE1 os seguintes comandos: {{commands}}.",
      "This extension will append info to your QWEN.md context using {{fileName}}": "Esta extens\xE3o anexar\xE1 informa\xE7\xF5es ao seu contexto QWEN.md usando {{fileName}}",
      "This extension will exclude the following core tools: {{tools}}": "Esta extens\xE3o excluir\xE1 as seguintes ferramentas principais: {{tools}}",
      "This extension will install the following skills:": "Esta extens\xE3o instalar\xE1 as seguintes habilidades:",
      "This extension will install the following subagents:": "Esta extens\xE3o instalar\xE1 os seguintes subagentes:",
      'Installation cancelled for "{{name}}".': 'Instala\xE7\xE3o cancelada para "{{name}}".',
      "You are installing an extension from {{originSource}}. Some features may not work perfectly with Qwen Code.": "Voc\xEA est\xE1 instalando uma extens\xE3o de {{originSource}}. Alguns recursos podem n\xE3o funcionar perfeitamente com o Qwen Code.",
      "--ref and --auto-update are not applicable for marketplace extensions.": "--ref e --auto-update n\xE3o s\xE3o aplic\xE1veis para extens\xF5es de marketplace.",
      'Extension "{{name}}" installed successfully and enabled.': 'Extens\xE3o "{{name}}" instalada com sucesso e ativada.',
      "Installs an extension from a git repository URL, local path, or claude marketplace (marketplace-url:plugin-name).": "Instala uma extens\xE3o de uma URL de reposit\xF3rio git, caminho local ou marketplace do claude (marketplace-url:plugin-name).",
      "The github URL, local path, or marketplace source (marketplace-url:plugin-name) of the extension to install.": "A URL do github, caminho local ou fonte do marketplace (marketplace-url:plugin-name) da extens\xE3o para instalar.",
      "The git ref to install from.": "A refer\xEAncia git para instalar.",
      "Enable auto-update for this extension.": "Ativar atualiza\xE7\xE3o autom\xE1tica para esta extens\xE3o.",
      "Enable pre-release versions for this extension.": "Ativar vers\xF5es de pr\xE9-lan\xE7amento para esta extens\xE3o.",
      "Acknowledge the security risks of installing an extension and skip the confirmation prompt.": "Reconhecer os riscos de seguran\xE7a de instalar uma extens\xE3o e pular o prompt de confirma\xE7\xE3o.",
      "The source argument must be provided.": "O argumento fonte deve ser fornecido.",
      'Extension "{{name}}" successfully uninstalled.': 'Extens\xE3o "{{name}}" desinstalada com sucesso.',
      "Uninstalls an extension.": "Desinstala uma extens\xE3o.",
      "The name or source path of the extension to uninstall.": "O nome ou caminho da fonte da extens\xE3o para desinstalar.",
      "Please include the name of the extension to uninstall as a positional argument.": "Inclua o nome da extens\xE3o para desinstalar como um argumento posicional.",
      "Enables an extension.": "Ativa uma extens\xE3o.",
      "The name of the extension to enable.": "O nome da extens\xE3o para ativar.",
      "The scope to enable the extenison in. If not set, will be enabled in all scopes.": "O escopo para ativar a extens\xE3o. Se n\xE3o definido, ser\xE1 ativada em todos os escopos.",
      'Extension "{{name}}" successfully enabled for scope "{{scope}}".': 'Extens\xE3o "{{name}}" ativada com sucesso para o escopo "{{scope}}".',
      'Extension "{{name}}" successfully enabled in all scopes.': 'Extens\xE3o "{{name}}" ativada com sucesso em todos os escopos.',
      "Invalid scope: {{scope}}. Please use one of {{scopes}}.": "Escopo inv\xE1lido: {{scope}}. Use um de {{scopes}}.",
      "Disables an extension.": "Desativa uma extens\xE3o.",
      "The name of the extension to disable.": "O nome da extens\xE3o para desativar.",
      "The scope to disable the extenison in.": "O escopo para desativar a extens\xE3o.",
      'Extension "{{name}}" successfully disabled for scope "{{scope}}".': 'Extens\xE3o "{{name}}" desativada com sucesso para o escopo "{{scope}}".',
      'Extension "{{name}}" successfully updated: {{oldVersion}} \u2192 {{newVersion}}.': 'Extens\xE3o "{{name}}" atualizada com sucesso: {{oldVersion}} \u2192 {{newVersion}}.',
      'Unable to install extension "{{name}}" due to missing install metadata': 'N\xE3o foi poss\xEDvel instalar a extens\xE3o "{{name}}" devido \xE0 falta de metadados de instala\xE7\xE3o',
      'Extension "{{name}}" is already up to date.': 'A extens\xE3o "{{name}}" j\xE1 est\xE1 atualizada.',
      "Updates all extensions or a named extension to the latest version.": "Atualiza todas as extens\xF5es ou uma extens\xE3o nomeada para a \xFAltima vers\xE3o.",
      "Update all extensions.": "Atualizar todas as extens\xF5es.",
      "Either an extension name or --all must be provided": "Um nome de extens\xE3o ou --all deve ser fornecido",
      "Lists installed extensions.": "Lista as extens\xF5es instaladas.",
      "Link extension failed to install.": "Falha ao instalar link da extens\xE3o.",
      'Extension "{{name}}" linked successfully and enabled.': 'Extens\xE3o "{{name}}" vinculada com sucesso e ativada.',
      "Links an extension from a local path. Updates made to the local path will always be reflected.": "Vincula uma extens\xE3o de um caminho local. Atualiza\xE7\xF5es feitas no caminho local sempre ser\xE3o refletidas.",
      "The name of the extension to link.": "O nome da extens\xE3o para vincular.",
      "Set a specific setting for an extension.": "Define uma configura\xE7\xE3o espec\xEDfica para uma extens\xE3o.",
      "Name of the extension to configure.": "Nome da extens\xE3o para configurar.",
      "The setting to configure (name or env var).": "A configura\xE7\xE3o para configurar (nome ou var env).",
      "The scope to set the setting in.": "O escopo para definir a configura\xE7\xE3o.",
      "List all settings for an extension.": "Listar todas as configura\xE7\xF5es de uma extens\xE3o.",
      "Name of the extension.": "Nome da extens\xE3o.",
      'Extension "{{name}}" has no settings to configure.': 'A extens\xE3o "{{name}}" n\xE3o tem configura\xE7\xF5es para configurar.',
      'Settings for "{{name}}":': 'Configura\xE7\xF5es para "{{name}}":',
      "(workspace)": "(workspace)",
      "(user)": "(usu\xE1rio)",
      "[not set]": "[n\xE3o definido]",
      "[value stored in keychain]": "[valor armazenado no chaveiro]",
      "Value:": "Valor:",
      "Manage extension settings.": "Gerenciar configura\xE7\xF5es de extens\xE3o.",
      "You need to specify a command (set or list).": "Voc\xEA precisa especificar um comando (set ou list).",
      // ============================================================================
      // Plugin Choice / Marketplace
      // ============================================================================
      "No plugins available in this marketplace.": "Nenhum plugin dispon\xEDvel neste marketplace.",
      'Select a plugin to install from marketplace "{{name}}":': 'Selecione um plugin para instalar do marketplace "{{name}}":',
      "Plugin selection cancelled.": "Sele\xE7\xE3o de plugin cancelada.",
      'Select a plugin from "{{name}}"': 'Selecione um plugin de "{{name}}"',
      "Use \u2191\u2193 or j/k to navigate, Enter to select, Escape to cancel": "Use \u2191\u2193 ou j/k para navegar, Enter para selecionar, Escape para cancelar",
      "{{count}} more above": "{{count}} mais acima",
      "{{count}} more below": "{{count}} mais abaixo",
      "manage IDE integration": "gerenciar integra\xE7\xE3o com IDE",
      "check status of IDE integration": "verificar status da integra\xE7\xE3o com IDE",
      "install required IDE companion for {{ideName}}": "instalar companion IDE necess\xE1rio para {{ideName}}",
      "enable IDE integration": "ativar integra\xE7\xE3o com IDE",
      "disable IDE integration": "desativar integra\xE7\xE3o com IDE",
      "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.": "A integra\xE7\xE3o com IDE n\xE3o \xE9 suportada no seu ambiente atual. Para usar este recurso, execute o Qwen Code em um destes IDEs suportados: VS Code ou forks do VS Code.",
      "Set up GitHub Actions": "Configurar GitHub Actions",
      "Configure terminal keybindings for multiline input (VS Code, Cursor, Windsurf, Trae)": "Configurar atalhos de terminal para entrada multilinhas (VS Code, Cursor, Windsurf, Trae)",
      "Please restart your terminal for the changes to take effect.": "Reinicie seu terminal para que as altera\xE7\xF5es tenham efeito.",
      "Failed to configure terminal: {{error}}": "Falha ao configurar terminal: {{error}}",
      "Could not determine {{terminalName}} config path on Windows: APPDATA environment variable is not set.": "N\xE3o foi poss\xEDvel determinar o caminho de configura\xE7\xE3o de {{terminalName}} no Windows: vari\xE1vel de ambiente APPDATA n\xE3o est\xE1 definida.",
      "{{terminalName}} keybindings.json exists but is not a valid JSON array. Please fix the file manually or delete it to allow automatic configuration.": "{{terminalName}} keybindings.json existe mas n\xE3o \xE9 um array JSON v\xE1lido. Corrija o arquivo manualmente ou exclua-o para permitir a configura\xE7\xE3o autom\xE1tica.",
      "File: {{file}}": "Arquivo: {{file}}",
      "Failed to parse {{terminalName}} keybindings.json. The file contains invalid JSON. Please fix the file manually or delete it to allow automatic configuration.": "Falha ao analisar {{terminalName}} keybindings.json. O arquivo cont\xE9m JSON inv\xE1lido. Corrija o arquivo manualmente ou exclua-o para permitir a configura\xE7\xE3o autom\xE1tica.",
      "Error: {{error}}": "Erro: {{error}}",
      "Shift+Enter binding already exists": "Atalho Shift+Enter j\xE1 existe",
      "Ctrl+Enter binding already exists": "Atalho Ctrl+Enter j\xE1 existe",
      "Existing keybindings detected. Will not modify to avoid conflicts.": "Atalhos existentes detectados. N\xE3o ser\xE3o modificados para evitar conflitos.",
      "Please check and modify manually if needed: {{file}}": "Verifique e modifique manualmente se necess\xE1rio: {{file}}",
      "Added Shift+Enter and Ctrl+Enter keybindings to {{terminalName}}.": "Adicionados atalhos Shift+Enter e Ctrl+Enter para {{terminalName}}.",
      "Modified: {{file}}": "Modificado: {{file}}",
      "{{terminalName}} keybindings already configured.": "Atalhos de {{terminalName}} j\xE1 configurados.",
      "Failed to configure {{terminalName}}.": "Falha ao configurar {{terminalName}}.",
      "Your terminal is already configured for an optimal experience with multiline input (Shift+Enter and Ctrl+Enter).": "Seu terminal j\xE1 est\xE1 configurado para uma experi\xEAncia ideal com entrada multilinhas (Shift+Enter e Ctrl+Enter).",
      "Could not detect terminal type. Supported terminals: VS Code, Cursor, Windsurf, and Trae.": "N\xE3o foi poss\xEDvel detectar o tipo de terminal. Terminais suportados: VS Code, Cursor, Windsurf e Trae.",
      'Terminal "{{terminal}}" is not supported yet.': 'O terminal "{{terminal}}" ainda n\xE3o \xE9 suportado.',
      // ============================================================================
      // Commands - Language
      // ============================================================================
      "Invalid language. Available: {{options}}": "Idioma inv\xE1lido. Dispon\xEDveis: {{options}}",
      "Language subcommands do not accept additional arguments.": "Subcomandos de idioma n\xE3o aceitam argumentos adicionais.",
      "Current UI language: {{lang}}": "Idioma atual da interface: {{lang}}",
      "Current LLM output language: {{lang}}": "Idioma atual da sa\xEDda do LLM: {{lang}}",
      "LLM output language not set": "Idioma de sa\xEDda do LLM n\xE3o definido",
      "Set UI language": "Definir idioma da interface",
      "Set LLM output language": "Definir idioma de sa\xEDda do LLM",
      "Usage: /language ui [{{options}}]": "Uso: /language ui [{{options}}]",
      "Usage: /language output <language>": "Uso: /language output <idioma>",
      "Example: /language output \u4E2D\u6587": "Exemplo: /language output Portugu\xEAs",
      "Example: /language output English": "Exemplo: /language output Ingl\xEAs",
      "Example: /language output \u65E5\u672C\u8A9E": "Exemplo: /language output Japon\xEAs",
      "Example: /language output Portugu\xEAs": "Exemplo: /language output Portugu\xEAs",
      "UI language changed to {{lang}}": "Idioma da interface alterado para {{lang}}",
      "LLM output language set to {{lang}}": "Idioma de sa\xEDda do LLM definido para {{lang}}",
      "LLM output language rule file generated at {{path}}": "Arquivo de regra de idioma de sa\xEDda do LLM gerado em {{path}}",
      "Please restart the application for the changes to take effect.": "Reinicie o aplicativo para que as altera\xE7\xF5es tenham efeito.",
      "Failed to generate LLM output language rule file: {{error}}": "Falha ao gerar arquivo de regra de idioma de sa\xEDda do LLM: {{error}}",
      "Invalid command. Available subcommands:": "Comando inv\xE1lido. Subcomandos dispon\xEDveis:",
      "Available subcommands:": "Subcomandos dispon\xEDveis:",
      "To request additional UI language packs, please open an issue on GitHub.": "Para solicitar pacotes de idiomas de interface adicionais, abra um problema no GitHub.",
      "Available options:": "Op\xE7\xF5es dispon\xEDveis:",
      "Set UI language to {{name}}": "Definir idioma da interface para {{name}}",
      // ============================================================================
      // Commands - Approval Mode
      // ============================================================================
      "Tool Approval Mode": "Modo de Aprova\xE7\xE3o de Ferramenta",
      "Current approval mode: {{mode}}": "Modo de aprova\xE7\xE3o atual: {{mode}}",
      "Available approval modes:": "Modos de aprova\xE7\xE3o dispon\xEDveis:",
      "Approval mode changed to: {{mode}}": "Modo de aprova\xE7\xE3o alterado para: {{mode}}",
      "Approval mode changed to: {{mode}} (saved to {{scope}} settings{{location}})": "Modo de aprova\xE7\xE3o alterado para: {{mode}} (salvo nas configura\xE7\xF5es de {{scope}}{{location}})",
      "Usage: /approval-mode <mode> [--session|--user|--project]": "Uso: /approval-mode <mode> [--session|--user|--project]",
      "Scope subcommands do not accept additional arguments.": "Subcomandos de escopo n\xE3o aceitam argumentos adicionais.",
      "Plan mode - Analyze only, do not modify files or execute commands": "Modo planejamento - Apenas analisa, n\xE3o modifica arquivos nem executa comandos",
      "Default mode - Require approval for file edits or shell commands": "Modo padr\xE3o - Exige aprova\xE7\xE3o para edi\xE7\xF5es de arquivos ou comandos shell",
      "Auto-edit mode - Automatically approve file edits": "Modo auto-edi\xE7\xE3o - Aprova automaticamente edi\xE7\xF5es de arquivos",
      "YOLO mode - Automatically approve all tools": "Modo YOLO - Aprova automaticamente todas as ferramentas",
      "{{mode}} mode": "Modo {{mode}}",
      "Settings service is not available; unable to persist the approval mode.": "Servi\xE7o de configura\xE7\xF5es n\xE3o dispon\xEDvel; n\xE3o foi poss\xEDvel persistir o modo de aprova\xE7\xE3o.",
      "Failed to save approval mode: {{error}}": "Falha ao salvar modo de aprova\xE7\xE3o: {{error}}",
      "Failed to change approval mode: {{error}}": "Falha ao alterar modo de aprova\xE7\xE3o: {{error}}",
      "Apply to current session only (temporary)": "Aplicar apenas \xE0 sess\xE3o atual (tempor\xE1rio)",
      "Persist for this project/workspace": "Persistir para este projeto/workspace",
      "Persist for this user on this machine": "Persistir para este usu\xE1rio nesta m\xE1quina",
      "Analyze only, do not modify files or execute commands": "Apenas analisar, n\xE3o modificar arquivos nem executar comandos",
      "Require approval for file edits or shell commands": "Exigir aprova\xE7\xE3o para edi\xE7\xF5es de arquivos ou comandos shell",
      "Automatically approve file edits": "Aprovar automaticamente edi\xE7\xF5es de arquivos",
      "Automatically approve all tools": "Aprovar automaticamente todas as ferramentas",
      "Workspace approval mode exists and takes priority. User-level change will have no effect.": "O modo de aprova\xE7\xE3o do workspace existe e tem prioridade. A altera\xE7\xE3o no n\xEDvel do usu\xE1rio n\xE3o ter\xE1 efeito.",
      "Apply To": "Aplicar A",
      "User Settings": "Configura\xE7\xF5es do Usu\xE1rio",
      "Workspace Settings": "Configura\xE7\xF5es do Workspace",
      // ============================================================================
      // Commands - Memory
      // ============================================================================
      "Commands for interacting with memory.": "Comandos para interagir com a mem\xF3ria.",
      "Show the current memory contents.": "Mostrar os conte\xFAdos atuais da mem\xF3ria.",
      "Show project-level memory contents.": "Mostrar conte\xFAdos da mem\xF3ria de n\xEDvel de projeto.",
      "Show global memory contents.": "Mostrar conte\xFAdos da mem\xF3ria global.",
      "Add content to project-level memory.": "Adicionar conte\xFAdo \xE0 mem\xF3ria de n\xEDvel de projeto.",
      "Add content to global memory.": "Adicionar conte\xFAdo \xE0 mem\xF3ria global.",
      "Refresh the memory from the source.": "Atualizar a mem\xF3ria da fonte.",
      "Usage: /memory add --project <text to remember>": "Uso: /memory add --project <texto para lembrar>",
      "Usage: /memory add --global <text to remember>": "Uso: /memory add --global <texto para lembrar>",
      'Attempting to save to project memory: "{{text}}"': 'Tentando salvar na mem\xF3ria do projeto: "{{text}}"',
      'Attempting to save to global memory: "{{text}}"': 'Tentando salvar na mem\xF3ria global: "{{text}}"',
      "Current memory content from {{count}} file(s):": "Conte\xFAdo da mem\xF3ria atual de {{count}} arquivo(s):",
      "Memory is currently empty.": "A mem\xF3ria est\xE1 vazia no momento.",
      "Project memory file not found or is currently empty.": "Arquivo de mem\xF3ria do projeto n\xE3o encontrado ou est\xE1 vazio.",
      "Global memory file not found or is currently empty.": "Arquivo de mem\xF3ria global n\xE3o encontrado ou est\xE1 vazio.",
      "Global memory is currently empty.": "A mem\xF3ria global est\xE1 vazia no momento.",
      "Global memory content:\n\n---\n{{content}}\n---": "Conte\xFAdo da mem\xF3ria global:\n\n---\n{{content}}\n---",
      "Project memory content from {{path}}:\n\n---\n{{content}}\n---": "Conte\xFAdo da mem\xF3ria do projeto de {{path}}:\n\n---\n{{content}}\n---",
      "Project memory is currently empty.": "A mem\xF3ria do projeto est\xE1 vazia no momento.",
      "Refreshing memory from source files...": "Atualizando mem\xF3ria dos arquivos fonte...",
      "Add content to the memory. Use --global for global memory or --project for project memory.": "Adicionar conte\xFAdo \xE0 mem\xF3ria. Use --global para mem\xF3ria global ou --project para mem\xF3ria do projeto.",
      "Usage: /memory add [--global|--project] <text to remember>": "Uso: /memory add [--global|--project] <texto para lembrar>",
      'Attempting to save to memory {{scope}}: "{{fact}}"': 'Tentando salvar na mem\xF3ria {{scope}}: "{{fact}}"',
      // ============================================================================
      // Commands - MCP
      // ============================================================================
      "Authenticate with an OAuth-enabled MCP server": "Autenticar com um servidor MCP habilitado para OAuth",
      "List configured MCP servers and tools": "Listar servidores e ferramentas MCP configurados",
      "Restarts MCP servers.": "Reinicia os servidores MCP.",
      "Config not loaded.": "Configura\xE7\xE3o n\xE3o carregada.",
      "Could not retrieve tool registry.": "N\xE3o foi poss\xEDvel recuperar o registro de ferramentas.",
      "No MCP servers configured with OAuth authentication.": "Nenhum servidor MCP configurado com autentica\xE7\xE3o OAuth.",
      "MCP servers with OAuth authentication:": "Servidores MCP com autentica\xE7\xE3o OAuth:",
      "Use /mcp auth <server-name> to authenticate.": "Use /mcp auth <nome-do-servidor> para autenticar.",
      "MCP server '{{name}}' not found.": "Servidor MCP '{{name}}' n\xE3o encontrado.",
      "Successfully authenticated and refreshed tools for '{{name}}'.": "Autenticado com sucesso e ferramentas atualizadas para '{{name}}'.",
      "Failed to authenticate with MCP server '{{name}}': {{error}}": "Falha ao autenticar com o servidor MCP '{{name}}': {{error}}",
      "Re-discovering tools from '{{name}}'...": "Redescobrindo ferramentas de '{{name}}'...",
      // ============================================================================
      // Commands - Chat
      // ============================================================================
      "Manage conversation history.": "Gerenciar hist\xF3rico de conversas.",
      "List saved conversation checkpoints": "Listar checkpoints de conversa salvos",
      "No saved conversation checkpoints found.": "Nenhum checkpoint de conversa salvo encontrado.",
      "List of saved conversations:": "Lista de conversas salvas:",
      "Note: Newest last, oldest first": "Nota: Mais novos por \xFAltimo, mais antigos primeiro",
      "Save the current conversation as a checkpoint. Usage: /chat save <tag>": "Salvar a conversa atual como um checkpoint. Uso: /chat save <tag>",
      "Missing tag. Usage: /chat save <tag>": "Tag ausente. Uso: /chat save <tag>",
      "Delete a conversation checkpoint. Usage: /chat delete <tag>": "Excluir um checkpoint de conversa. Uso: /chat delete <tag>",
      "Missing tag. Usage: /chat delete <tag>": "Tag ausente. Uso: /chat delete <tag>",
      "Conversation checkpoint '{{tag}}' has been deleted.": "O checkpoint de conversa '{{tag}}' foi exclu\xEDdo.",
      "Error: No checkpoint found with tag '{{tag}}'.": "Erro: Nenhum checkpoint encontrado com a tag '{{tag}}'.",
      "Resume a conversation from a checkpoint. Usage: /chat resume <tag>": "Retomar uma conversa de um checkpoint. Uso: /chat resume <tag>",
      "Missing tag. Usage: /chat resume <tag>": "Tag ausente. Uso: /chat resume <tag>",
      "No saved checkpoint found with tag: {{tag}}.": "Nenhum checkpoint salvo encontrado com a tag: {{tag}}.",
      "A checkpoint with the tag {{tag}} already exists. Do you want to overwrite it?": "Um checkpoint com a tag {{tag}} j\xE1 existe. Voc\xEA deseja substitu\xED-lo?",
      "No chat client available to save conversation.": "Nenhum cliente de chat dispon\xEDvel para salvar a conversa.",
      "Conversation checkpoint saved with tag: {{tag}}.": "Checkpoint de conversa salvo com a tag: {{tag}}.",
      "No conversation found to save.": "Nenhuma conversa encontrada para salvar.",
      "No chat client available to share conversation.": "Nenhum cliente de chat dispon\xEDvel para compartilhar a conversa.",
      "Invalid file format. Only .md and .json are supported.": "Formato de arquivo inv\xE1lido. Apenas .md e .json s\xE3o suportados.",
      "Error sharing conversation: {{error}}": "Erro ao compartilhar conversa: {{error}}",
      "Conversation shared to {{filePath}}": "Conversa compartilhada em {{filePath}}",
      "No conversation found to share.": "Nenhuma conversa encontrada para compartilhar.",
      "Share the current conversation to a markdown or json file. Usage: /chat share <file>": "Compartilhar a conversa atual para um arquivo markdown ou json. Uso: /chat share <arquivo>",
      // ============================================================================
      // Commands - Summary
      // ============================================================================
      "Generate a project summary and save it to .qwen/PROJECT_SUMMARY.md": "Gerar um resumo do projeto e salv\xE1-lo em .qwen/PROJECT_SUMMARY.md",
      "No chat client available to generate summary.": "Nenhum cliente de chat dispon\xEDvel para gerar o resumo.",
      "Already generating summary, wait for previous request to complete": "J\xE1 gerando resumo, aguarde a conclus\xE3o da solicita\xE7\xE3o anterior",
      "No conversation found to summarize.": "Nenhuma conversa encontrada para resumir.",
      "Failed to generate project context summary: {{error}}": "Falha ao gerar resumo do contexto do projeto: {{error}}",
      "Saved project summary to {{filePathForDisplay}}.": "Resumo do projeto salvo em {{filePathForDisplay}}.",
      "Saving project summary...": "Salvando resumo do projeto...",
      "Generating project summary...": "Gerando resumo do projeto...",
      "Failed to generate summary - no text content received from LLM response": "Falha ao gerar resumo - nenhum conte\xFAdo de texto recebido da resposta do LLM",
      // ============================================================================
      // Commands - Model
      // ============================================================================
      "Switch the model for this session": "Trocar o modelo para esta sess\xE3o",
      "Content generator configuration not available.": "Configura\xE7\xE3o do gerador de conte\xFAdo n\xE3o dispon\xEDvel.",
      "Authentication type not available.": "Tipo de autentica\xE7\xE3o n\xE3o dispon\xEDvel.",
      "No models available for the current authentication type ({{authType}}).": "Nenhum modelo dispon\xEDvel para o tipo de autentica\xE7\xE3o atual ({{authType}}).",
      // ============================================================================
      // Commands - Clear
      // ============================================================================
      "Starting a new session, resetting chat, and clearing terminal.": "Iniciando uma nova sess\xE3o, resetando o chat e limpando o terminal.",
      "Starting a new session and clearing.": "Iniciando uma nova sess\xE3o e limpando.",
      // ============================================================================
      // Commands - Compress
      // ============================================================================
      "Already compressing, wait for previous request to complete": "J\xE1 comprimindo, aguarde a conclus\xE3o da solicita\xE7\xE3o anterior",
      "Failed to compress chat history.": "Falha ao comprimir hist\xF3rico do chat.",
      "Failed to compress chat history: {{error}}": "Falha ao comprimir hist\xF3rico do chat: {{error}}",
      "Compressing chat history": "Comprimindo hist\xF3rico do chat",
      "Chat history compressed from {{originalTokens}} to {{newTokens}} tokens.": "Hist\xF3rico do chat comprimido de {{originalTokens}} para {{newTokens}} tokens.",
      "Compression was not beneficial for this history size.": "A compress\xE3o n\xE3o foi ben\xE9fica para este tamanho de hist\xF3rico.",
      "Chat history compression did not reduce size. This may indicate issues with the compression prompt.": "A compress\xE3o do hist\xF3rico do chat n\xE3o reduziu o tamanho. Isso pode indicar problemas com o prompt de compress\xE3o.",
      "Could not compress chat history due to a token counting error.": "N\xE3o foi poss\xEDvel comprimir o hist\xF3rico do chat devido a um erro de contagem de tokens.",
      "Chat history is already compressed.": "O hist\xF3rico do chat j\xE1 est\xE1 comprimido.",
      // ============================================================================
      // Commands - Directory
      // ============================================================================
      "Configuration is not available.": "A configura\xE7\xE3o n\xE3o est\xE1 dispon\xEDvel.",
      "Please provide at least one path to add.": "Forne\xE7a pelo menos um caminho para adicionar.",
      "The /directory add command is not supported in restrictive sandbox profiles. Please use --include-directories when starting the session instead.": "O comando /directory add n\xE3o \xE9 suportado em perfis de sandbox restritivos. Use --include-directories ao iniciar a sess\xE3o.",
      "Error adding '{{path}}': {{error}}": "Erro ao adicionar '{{path}}': {{error}}",
      "Successfully added QWEN.md files from the following directories if there are:\n- {{directories}}": "Arquivos QWEN.md adicionados com sucesso dos seguintes diret\xF3rios, se houverem:\n- {{directories}}",
      "Error refreshing memory: {{error}}": "Erro ao atualizar mem\xF3ria: {{error}}",
      "Successfully added directories:\n- {{directories}}": "Diret\xF3rios adicionados com sucesso:\n- {{directories}}",
      "Current workspace directories:\n{{directories}}": "Diret\xF3rios atuais do workspace:\n{{directories}}",
      // ============================================================================
      // Commands - Docs
      // ============================================================================
      "Please open the following URL in your browser to view the documentation:\n{{url}}": "Abra a seguinte URL no seu navegador para ver a documenta\xE7\xE3o:\n{{url}}",
      "Opening documentation in your browser: {{url}}": "Abrindo documenta\xE7\xE3o no seu navegador: {{url}}",
      // ============================================================================
      // Dialogs - Tool Confirmation
      // ============================================================================
      "Do you want to proceed?": "Voc\xEA deseja prosseguir?",
      "Yes, allow once": "Sim, permitir uma vez",
      "Allow always": "Permitir sempre",
      No: "N\xE3o",
      "No (esc)": "N\xE3o (esc)",
      "Yes, allow always for this session": "Sim, permitir sempre para esta sess\xE3o",
      "Modify in progress:": "Modifica\xE7\xE3o em progresso:",
      "Save and close external editor to continue": "Salve e feche o editor externo para continuar",
      "Apply this change?": "Aplicar esta altera\xE7\xE3o?",
      "Yes, allow always": "Sim, permitir sempre",
      "Modify with external editor": "Modificar com editor externo",
      "No, suggest changes (esc)": "N\xE3o, sugerir altera\xE7\xF5es (esc)",
      "Allow execution of: '{{command}}'?": "Permitir a execu\xE7\xE3o de: '{{command}}'?",
      "Yes, allow always ...": "Sim, permitir sempre ...",
      "Yes, and auto-accept edits": "Sim, e aceitar edi\xE7\xF5es automaticamente",
      "Yes, and manually approve edits": "Sim, e aprovar edi\xE7\xF5es manualmente",
      "No, keep planning (esc)": "N\xE3o, continuar planejando (esc)",
      "URLs to fetch:": "URLs para buscar:",
      "MCP Server: {{server}}": "Servidor MCP: {{server}}",
      "Tool: {{tool}}": "Ferramenta: {{tool}}",
      'Allow execution of MCP tool "{{tool}}" from server "{{server}}"?': 'Permitir a execu\xE7\xE3o da ferramenta MCP "{{tool}}" do servidor "{{server}}"?',
      'Yes, always allow tool "{{tool}}" from server "{{server}}"': 'Sim, sempre permitir a ferramenta "{{tool}}" do servidor "{{server}}"',
      'Yes, always allow all tools from server "{{server}}"': 'Sim, sempre permitir todas as ferramentas do servidor "{{server}}"',
      // ============================================================================
      // Dialogs - Shell Confirmation
      // ============================================================================
      "Shell Command Execution": "Execu\xE7\xE3o de Comando Shell",
      "A custom command wants to run the following shell commands:": "Um comando personalizado deseja executar os seguintes comandos shell:",
      // ============================================================================
      // Dialogs - Pro Quota
      // ============================================================================
      "Pro quota limit reached for {{model}}.": "Limite de cota Pro atingido para {{model}}.",
      "Change auth (executes the /auth command)": "Alterar autentica\xE7\xE3o (executa o comando /auth)",
      "Continue with {{model}}": "Continuar com {{model}}",
      // ============================================================================
      // Dialogs - Welcome Back
      // ============================================================================
      "Current Plan:": "Plano Atual:",
      "Progress: {{done}}/{{total}} tasks completed": "Progresso: {{done}}/{{total}} tarefas conclu\xEDdas",
      ", {{inProgress}} in progress": ", {{inProgress}} em progresso",
      "Pending Tasks:": "Tarefas Pendentes:",
      "What would you like to do?": "O que voc\xEA gostaria de fazer?",
      "Choose how to proceed with your session:": "Escolha como proceder com sua sess\xE3o:",
      "Start new chat session": "Iniciar nova sess\xE3o de chat",
      "Continue previous conversation": "Continuar conversa anterior",
      "\u{1F44B} Welcome back! (Last updated: {{timeAgo}})": "\u{1F44B} Bem-vindo de volta! (\xDAltima atualiza\xE7\xE3o: {{timeAgo}})",
      "\u{1F3AF} Overall Goal:": "\u{1F3AF} Objetivo Geral:",
      // ============================================================================
      // Dialogs - Auth
      // ============================================================================
      "Get started": "Come\xE7ar",
      "How would you like to authenticate for this project?": "Como voc\xEA gostaria de se autenticar para este projeto?",
      "OpenAI API key is required to use OpenAI authentication.": "A chave da API do OpenAI \xE9 necess\xE1ria para usar a autentica\xE7\xE3o do OpenAI.",
      "You must select an auth method to proceed. Press Ctrl+C again to exit.": "Voc\xEA deve selecionar um m\xE9todo de autentica\xE7\xE3o para prosseguir. Pressione Ctrl+C novamente para sair.",
      "(Use Enter to Set Auth)": "(Use Enter para Definir Autentica\xE7\xE3o)",
      "Terms of Services and Privacy Notice for Qwen Code": "Termos de Servi\xE7o e Aviso de Privacidade do Qwen Code",
      "Qwen OAuth": "Qwen OAuth",
      "Login with QwenChat account to use daily free quota.": "Fa\xE7a login com sua conta QwenChat para usar a cota gratuita di\xE1ria.",
      "API-KEY": "API-KEY",
      "Use coding plan credentials or your own api-keys/providers.": "Use credenciais do Coding Plan ou suas pr\xF3prias chaves API/provedores.",
      OpenAI: "OpenAI",
      "Failed to login. Message: {{message}}": "Falha ao fazer login. Mensagem: {{message}}",
      "Authentication is enforced to be {{enforcedType}}, but you are currently using {{currentType}}.": "A autentica\xE7\xE3o \xE9 for\xE7ada para {{enforcedType}}, mas voc\xEA est\xE1 usando {{currentType}} no momento.",
      "Qwen OAuth authentication timed out. Please try again.": "A autentica\xE7\xE3o Qwen OAuth expirou. Tente novamente.",
      "Qwen OAuth authentication cancelled.": "Autentica\xE7\xE3o Qwen OAuth cancelada.",
      "Qwen OAuth Authentication": "Autentica\xE7\xE3o Qwen OAuth",
      "Please visit this URL to authorize:": "Visite esta URL para autorizar:",
      "Or scan the QR code below:": "Ou escaneie o c\xF3digo QR abaixo:",
      "Waiting for authorization": "Aguardando autoriza\xE7\xE3o",
      "Time remaining:": "Tempo restante:",
      "(Press ESC or CTRL+C to cancel)": "(Pressione ESC ou CTRL+C para cancelar)",
      "Qwen OAuth Authentication Timeout": "Tempo Limite de Autentica\xE7\xE3o Qwen OAuth",
      "OAuth token expired (over {{seconds}} seconds). Please select authentication method again.": "Token OAuth expirado (mais de {{seconds}} segundos). Selecione o m\xE9todo de autentica\xE7\xE3o novamente.",
      "Press any key to return to authentication type selection.": "Pressione qualquer tecla para retornar \xE0 sele\xE7\xE3o do tipo de autentica\xE7\xE3o.",
      "Waiting for Qwen OAuth authentication...": "Aguardando autentica\xE7\xE3o Qwen OAuth...",
      "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.": "Nota: Sua chave de API existente no settings.json n\xE3o ser\xE1 limpa ao usar o Qwen OAuth. Voc\xEA pode voltar para a autentica\xE7\xE3o do OpenAI mais tarde, se necess\xE1rio.",
      "Authentication timed out. Please try again.": "A autentica\xE7\xE3o expirou. Tente novamente.",
      "Waiting for auth... (Press ESC or CTRL+C to cancel)": "Aguardando autentica\xE7\xE3o... (Pressione ESC ou CTRL+C para cancelar)",
      "Missing API key for OpenAI-compatible auth. Set settings.security.auth.apiKey, or set the {{envKeyHint}} environment variable.": "Chave de API ausente para autentica\xE7\xE3o compat\xEDvel com OpenAI. Defina settings.security.auth.apiKey ou a vari\xE1vel de ambiente {{envKeyHint}}.",
      "{{envKeyHint}} environment variable not found.": "Vari\xE1vel de ambiente {{envKeyHint}} n\xE3o encontrada.",
      "{{envKeyHint}} environment variable not found. Please set it in your .env file or environment variables.": "Vari\xE1vel de ambiente {{envKeyHint}} n\xE3o encontrada. Defina-a no seu arquivo .env ou vari\xE1veis de ambiente.",
      "{{envKeyHint}} environment variable not found (or set settings.security.auth.apiKey). Please set it in your .env file or environment variables.": "Vari\xE1vel de ambiente {{envKeyHint}} n\xE3o encontrada (ou defina settings.security.auth.apiKey). Defina-a no seu arquivo .env ou vari\xE1veis de ambiente.",
      "Missing API key for OpenAI-compatible auth. Set the {{envKeyHint}} environment variable.": "Chave de API ausente para autentica\xE7\xE3o compat\xEDvel com OpenAI. Defina a vari\xE1vel de ambiente {{envKeyHint}}.",
      "Anthropic provider missing required baseUrl in modelProviders[].baseUrl.": "Provedor Anthropic sem a baseUrl necess\xE1ria em modelProviders[].baseUrl.",
      "ANTHROPIC_BASE_URL environment variable not found.": "Vari\xE1vel de ambiente ANTHROPIC_BASE_URL n\xE3o encontrada.",
      "Invalid auth method selected.": "M\xE9todo de autentica\xE7\xE3o inv\xE1lido selecionado.",
      "Failed to authenticate. Message: {{message}}": "Falha ao autenticar. Mensagem: {{message}}",
      "Authenticated successfully with {{authType}} credentials.": "Autenticado com sucesso com credenciais {{authType}}.",
      'Invalid QWEN_DEFAULT_AUTH_TYPE value: "{{value}}". Valid values are: {{validValues}}': 'Valor QWEN_DEFAULT_AUTH_TYPE inv\xE1lido: "{{value}}". Valores v\xE1lidos s\xE3o: {{validValues}}',
      "OpenAI Configuration Required": "Configura\xE7\xE3o do OpenAI Necess\xE1ria",
      "Please enter your OpenAI configuration. You can get an API key from": "Insira sua configura\xE7\xE3o do OpenAI. Voc\xEA pode obter uma chave de API de",
      "API Key:": "Chave da API:",
      "Invalid credentials: {{errorMessage}}": "Credenciais inv\xE1lidas: {{errorMessage}}",
      "Failed to validate credentials": "Falha ao validar credenciais",
      "Press Enter to continue, Tab/\u2191\u2193 to navigate, Esc to cancel": "Pressione Enter para continuar, Tab/\u2191\u2193 para navegar, Esc para cancelar",
      // ============================================================================
      // Dialogs - Model
      // ============================================================================
      "Select Model": "Selecionar Modelo",
      "(Press Esc to close)": "(Pressione Esc para fechar)",
      "Current (effective) configuration": "Configura\xE7\xE3o atual (efetiva)",
      AuthType: "AuthType",
      "API Key": "Chave da API",
      unset: "n\xE3o definido",
      "(default)": "(padr\xE3o)",
      "(set)": "(definido)",
      "(not set)": "(n\xE3o definido)",
      "Failed to switch model to '{{modelId}}'.\n\n{{error}}": "Falha ao trocar o modelo para '{{modelId}}'.\n\n{{error}}",
      "Qwen 3.5 Plus \u2014 efficient hybrid model with leading coding performance": "Qwen 3.5 Plus \u2014 modelo h\xEDbrido eficiente com desempenho l\xEDder em programa\xE7\xE3o",
      "The latest Qwen Vision model from Alibaba Cloud ModelStudio (version: qwen3-vl-plus-2025-09-23)": "O modelo Qwen Vision mais recente do Alibaba Cloud ModelStudio (vers\xE3o: qwen3-vl-plus-2025-09-23)",
      // ============================================================================
      // Dialogs - Permissions
      // ============================================================================
      "Manage folder trust settings": "Gerenciar configura\xE7\xF5es de confian\xE7a de pasta",
      // ============================================================================
      // Status Bar
      // ============================================================================
      "Using:": "Usando:",
      "{{count}} open file": "{{count}} arquivo aberto",
      "{{count}} open files": "{{count}} arquivos abertos",
      "(ctrl+g to view)": "(ctrl+g para ver)",
      "{{count}} {{name}} file": "{{count}} arquivo {{name}}",
      "{{count}} {{name}} files": "{{count}} arquivos {{name}}",
      "{{count}} MCP server": "{{count}} servidor MCP",
      "{{count}} MCP servers": "{{count}} servidores MCP",
      "{{count}} Blocked": "{{count}} Bloqueados",
      "(ctrl+t to view)": "(ctrl+t para ver)",
      "(ctrl+t to toggle)": "(ctrl+t para alternar)",
      "Press Ctrl+C again to exit.": "Pressione Ctrl+C novamente para sair.",
      "Press Ctrl+D again to exit.": "Pressione Ctrl+D novamente para sair.",
      "Press Esc again to clear.": "Pressione Esc novamente para limpar.",
      // ============================================================================
      // MCP Status
      // ============================================================================
      "No MCP servers configured.": "Nenhum servidor MCP configurado.",
      "\u23F3 MCP servers are starting up ({{count}} initializing)...": "\u23F3 Servidores MCP est\xE3o iniciando ({{count}} inicializando)...",
      "Note: First startup may take longer. Tool availability will update automatically.": "Nota: A primeira inicializa\xE7\xE3o pode demorar mais. A disponibilidade da ferramenta ser\xE1 atualizada automaticamente.",
      "Configured MCP servers:": "Servidores MCP configurados:",
      Ready: "Pronto",
      "Starting... (first startup may take longer)": "Iniciando... (a primeira inicializa\xE7\xE3o pode demorar mais)",
      Disconnected: "Desconectado",
      "{{count}} tool": "{{count}} ferramenta",
      "{{count}} tools": "{{count}} ferramentas",
      "{{count}} prompt": "{{count}} prompt",
      "{{count}} prompts": "{{count}} prompts",
      "(from {{extensionName}})": "(de {{extensionName}})",
      OAuth: "OAuth",
      "OAuth expired": "OAuth expirado",
      "OAuth not authenticated": "OAuth n\xE3o autenticado",
      "tools and prompts will appear when ready": "ferramentas e prompts aparecer\xE3o quando estiverem prontos",
      "{{count}} tools cached": "{{count}} ferramentas em cache",
      "Tools:": "Ferramentas:",
      "Parameters:": "Par\xE2metros:",
      "Prompts:": "Prompts:",
      Blocked: "Bloqueado",
      "\u{1F4A1} Tips:": "\u{1F4A1} Dicas:",
      Use: "Use",
      "to show server and tool descriptions": "para mostrar descri\xE7\xF5es de servidores e ferramentas",
      "to show tool parameter schemas": "para mostrar esquemas de par\xE2metros de ferramentas",
      "to hide descriptions": "para ocultar descri\xE7\xF5es",
      "to authenticate with OAuth-enabled servers": "para autenticar com servidores habilitados para OAuth",
      Press: "Pressione",
      "to toggle tool descriptions on/off": "para alternar descri\xE7\xF5es de ferramentas ligadas/desligadas",
      "Starting OAuth authentication for MCP server '{{name}}'...": "Iniciando autentica\xE7\xE3o OAuth para servidor MCP '{{name}}'...",
      "Restarting MCP servers...": "Reiniciando servidores MCP...",
      // ============================================================================
      // Startup Tips
      // ============================================================================
      "Tips:": "Dicas:",
      "Use /compress when the conversation gets long to summarize history and free up context.": "Use /compress quando a conversa ficar longa para resumir o hist\xF3rico e liberar contexto.",
      "Start a fresh idea with /clear or /new; the previous session stays available in history.": "Comece uma nova ideia com /clear ou /new; a sess\xE3o anterior permanece dispon\xEDvel no hist\xF3rico.",
      "Use /bug to submit issues to the maintainers when something goes off.": "Use /bug para enviar problemas aos mantenedores quando algo der errado.",
      "Switch auth type quickly with /auth.": "Troque o tipo de autentica\xE7\xE3o rapidamente com /auth.",
      "You can run any shell commands from Qwen Code using ! (e.g. !ls).": "Voc\xEA pode executar quaisquer comandos shell do Qwen Code usando ! (ex: !ls).",
      "Type / to open the command popup; Tab autocompletes slash commands and saved prompts.": "Digite / para abrir o popup de comandos; Tab autocompleta comandos de barra e prompts salvos.",
      "You can resume a previous conversation by running qwen --continue or qwen --resume.": "Voc\xEA pode retomar uma conversa anterior executando qwen --continue ou qwen --resume.",
      "You can switch permission mode quickly with Shift+Tab or /approval-mode.": "Voc\xEA pode alternar o modo de permiss\xE3o rapidamente com Shift+Tab ou /approval-mode.",
      "Try /insight to generate personalized insights from your chat history.": "Experimente /insight para gerar insights personalizados do seu hist\xF3rico de conversas.",
      // ============================================================================
      // Exit Screen / Stats
      // ============================================================================
      "Agent powering down. Goodbye!": "Agente desligando. Adeus!",
      "To continue this session, run": "Para continuar esta sess\xE3o, execute",
      "Interaction Summary": "Resumo da Intera\xE7\xE3o",
      "Session ID:": "ID da Sess\xE3o:",
      "Tool Calls:": "Chamadas de Ferramenta:",
      "Success Rate:": "Taxa de Sucesso:",
      "User Agreement:": "Acordo do Usu\xE1rio:",
      reviewed: "revisado",
      "Code Changes:": "Altera\xE7\xF5es de C\xF3digo:",
      Performance: "Desempenho",
      "Wall Time:": "Tempo Total:",
      "Agent Active:": "Agente Ativo:",
      "API Time:": "Tempo de API:",
      "Tool Time:": "Tempo de Ferramenta:",
      "Session Stats": "Estat\xEDsticas da Sess\xE3o",
      "Model Usage": "Uso do Modelo",
      Reqs: "Reqs",
      "Input Tokens": "Tokens de Entrada",
      "Output Tokens": "Tokens de Sa\xEDda",
      "Savings Highlight:": "Destaque de Economia:",
      "of input tokens were served from the cache, reducing costs.": "de tokens de entrada foram servidos do cache, reduzindo custos.",
      "Tip: For a full token breakdown, run `/stats model`.": "Dica: Para um detalhamento completo de tokens, execute `/stats model`.",
      "Model Stats For Nerds": "Estat\xEDsticas de Modelo Para Nerds",
      "Tool Stats For Nerds": "Estat\xEDsticas de Ferramenta Para Nerds",
      Metric: "M\xE9trica",
      API: "API",
      Requests: "Solicita\xE7\xF5es",
      Errors: "Erros",
      "Avg Latency": "Lat\xEAncia M\xE9dia",
      Tokens: "Tokens",
      Total: "Total",
      Prompt: "Prompt",
      Cached: "Cacheado",
      Thoughts: "Pensamentos",
      Tool: "Ferramenta",
      Output: "Sa\xEDda",
      "No API calls have been made in this session.": "Nenhuma chamada de API foi feita nesta sess\xE3o.",
      "Tool Name": "Nome da Ferramenta",
      Calls: "Chamadas",
      "Success Rate": "Taxa de Sucesso",
      "Avg Duration": "Dura\xE7\xE3o M\xE9dia",
      "User Decision Summary": "Resumo de Decis\xE3o do Usu\xE1rio",
      "Total Reviewed Suggestions:": "Total de Sugest\xF5es Revisadas:",
      " \xBB Accepted:": " \xBB Aceitas:",
      " \xBB Rejected:": " \xBB Rejeitadas:",
      " \xBB Modified:": " \xBB Modificadas:",
      " Overall Agreement Rate:": " Taxa Geral de Acordo:",
      "No tool calls have been made in this session.": "Nenhuma chamada de ferramenta foi feita nesta sess\xE3o.",
      "Session start time is unavailable, cannot calculate stats.": "Hora de in\xEDcio da sess\xE3o indispon\xEDvel, n\xE3o \xE9 poss\xEDvel calcular estat\xEDsticas.",
      // ============================================================================
      // Command Format Migration
      // ============================================================================
      "Command Format Migration": "Migra\xE7\xE3o de Formato de Comando",
      "Found {{count}} TOML command file:": "Encontrado {{count}} arquivo de comando TOML:",
      "Found {{count}} TOML command files:": "Encontrados {{count}} arquivos de comando TOML:",
      "... and {{count}} more": "... e mais {{count}}",
      "The TOML format is deprecated. Would you like to migrate them to Markdown format?": "O formato TOML est\xE1 obsoleto. Voc\xEA gostaria de migr\xE1-los para o formato Markdown?",
      "(Backups will be created and original files will be preserved)": "(Backups ser\xE3o criados e arquivos originais ser\xE3o preservados)",
      // ============================================================================
      // Loading Phrases
      // ============================================================================
      "Waiting for user confirmation...": "Aguardando confirma\xE7\xE3o do usu\xE1rio...",
      "(esc to cancel, {{time}})": "(esc para cancelar, {{time}})",
      WITTY_LOADING_PHRASES: [
        "Estou com sorte",
        "Enviando maravilhas...",
        "Pintando os serifos de volta...",
        "Navegando pelo mofo limoso...",
        "Consultando os esp\xEDritos digitais...",
        "Reticulando splines...",
        "Aquecendo os hamsters da IA...",
        "Perguntando \xE0 concha m\xE1gica...",
        "Gerando r\xE9plica espirituosa...",
        "Polindo os algoritmos...",
        "N\xE3o apresse a perfei\xE7\xE3o (ou meu c\xF3digo)...",
        "Preparando bytes frescos...",
        "Contando el\xE9trons...",
        "Engajando processadores cognitivos...",
        "Verificando erros de sintaxe no universo...",
        "Um momento, otimizando o humor...",
        "Embaralhando piadas...",
        "Desembara\xE7ando redes neurais...",
        "Compilando brilhantismo...",
        "Carregando humor.exe...",
        "Invocando a nuvem da sabedoria...",
        "Preparando uma resposta espirituosa...",
        "S\xF3 um segundo, estou depurando a realidade...",
        "Confundindo as op\xE7\xF5es...",
        "Sintonizando as frequ\xEAncias c\xF3smicas...",
        "Criando uma resposta digna da sua paci\xEAncia...",
        "Compilando os 1s e 0s...",
        "Resolvendo depend\xEAncias... e crises existenciais...",
        "Desfragmentando mem\xF3rias... tanto RAM quanto pessoais...",
        "Reiniciando o m\xF3dulo de humor...",
        "Fazendo cache do essencial (principalmente memes de gatos)...",
        "Otimizando para velocidade absurda",
        "Trocando bits... n\xE3o conte para os bytes...",
        "Coletando lixo... volto j\xE1...",
        "Montando a internet...",
        "Convertendo caf\xE9 em c\xF3digo...",
        "Atualizando a sintaxe da realidade...",
        "Reconectando as sinapses...",
        "Procurando um ponto e v\xEDrgula perdido...",
        "Lubrificando as engrenagens da m\xE1quina...",
        "Pr\xE9-aquecendo os servidores...",
        "Calibrando o capacitor de fluxo...",
        "Engajando o motor de improbabilidade...",
        "Canalizando a For\xE7a...",
        "Alinhando as estrelas para uma resposta ideal...",
        "Assim dizemos todos...",
        "Carregando a pr\xF3xima grande ideia...",
        "S\xF3 um momento, estou na zona...",
        "Preparando para deslumbr\xE1-lo com brilhantismo...",
        "S\xF3 um tique, estou polindo minha intelig\xEAncia...",
        "Segure firme, estou criando uma obra-prima...",
        "S\xF3 um instante, estou depurando o universo...",
        "S\xF3 um momento, estou alinhando os pixels...",
        "S\xF3 um segundo, estou otimizando o humor...",
        "S\xF3 um momento, estou ajustando os algoritmos...",
        "Velocidade de dobra engajada...",
        "Minerando mais cristais de Dilithium...",
        "N\xE3o entre em p\xE2nico...",
        "Seguindo o coelho branco...",
        "A verdade est\xE1 l\xE1 fora... em algum lugar...",
        "Soprando o cartucho...",
        "Carregando... Fa\xE7a um barrel roll!",
        "Aguardando o respawn...",
        "Terminando a Kessel Run em menos de 12 parsecs...",
        "O bolo n\xE3o \xE9 uma mentira, s\xF3 ainda est\xE1 carregando...",
        "Mexendo na tela de cria\xE7\xE3o de personagem...",
        "S\xF3 um momento, estou encontrando o meme certo...",
        "Pressionando 'A' para continuar...",
        "Pastoreando gatos digitais...",
        "Polindo os pixels...",
        "Encontrando um trocadilho adequado para a tela de carregamento...",
        "Distraindo voc\xEA com esta frase espirituosa...",
        "Quase l\xE1... provavelmente...",
        "Nossos hamsters est\xE3o trabalhando o mais r\xE1pido que podem...",
        "Dando um tapinha na cabe\xE7a do Cloudy...",
        "Acariciando o gato...",
        "Dando um Rickroll no meu chefe...",
        "Never gonna give you up, never gonna let you down...",
        "Tocando o baixo...",
        "Provando as amoras...",
        "Estou indo longe, estou indo pela velocidade...",
        "Isso \xE9 vida real? Ou \xE9 apenas fantasia?...",
        "Tenho um bom pressentimento sobre isso...",
        "Cutucando o urso...",
        "Fazendo pesquisa sobre os \xFAltimos memes...",
        "Descobrindo como tornar isso mais espirituoso...",
        "Hmmm... deixe-me pensar...",
        "O que voc\xEA chama de um peixe sem olhos? Um pxe...",
        "Por que o computador foi \xE0 terapia? Porque tinha muitos bytes...",
        "Por que programadores n\xE3o gostam da natureza? Porque tem muitos bugs...",
        "Por que programadores preferem o modo escuro? Porque a luz atrai bugs...",
        "Por que o desenvolvedor faliu? Porque usou todo o seu cache...",
        "O que voc\xEA pode fazer com um l\xE1pis quebrado? Nada, ele n\xE3o tem ponta...",
        "Aplicando manuten\xE7\xE3o percussiva...",
        "Procurando a orienta\xE7\xE3o correta do USB...",
        "Garantindo que a fuma\xE7a m\xE1gica permane\xE7a dentro dos fios...",
        "Tentando sair do Vim...",
        "Girando a roda do hamster...",
        "Isso n\xE3o \xE9 um bug, \xE9 um recurso n\xE3o documentado...",
        "Engajar.",
        "Eu voltarei... com uma resposta.",
        "Meu outro processo \xE9 uma TARDIS...",
        "Comungando com o esp\xEDrito da m\xE1quina...",
        "Deixando os pensamentos marinarem...",
        "Lembrei agora onde coloquei minhas chaves...",
        "Ponderando a orbe...",
        "Eu vi coisas que voc\xEAs n\xE3o acreditariam... como um usu\xE1rio que l\xEA mensagens de carregamento.",
        "Iniciando olhar pensativo...",
        "Qual \xE9 o lanche favorito de um computador? Microchips.",
        "Por que desenvolvedores Java usam \xF3culos? Porque eles n\xE3o C#.",
        "Carregando o laser... pew pew!",
        "Dividindo por zero... s\xF3 brincando!",
        "Procurando por um supervisor adulto... digo, processando.",
        "Fazendo bip boop.",
        "Buffering... porque at\xE9 as IAs precisam de um momento.",
        "Entrela\xE7ando part\xEDculas qu\xE2nticas para uma resposta mais r\xE1pida...",
        "Polindo o cromo... nos algoritmos.",
        "Voc\xEA n\xE3o est\xE1 entretido? (Trabalhando nisso!)",
        "Invocando os gremlins do c\xF3digo... para ajudar, \xE9 claro.",
        "S\xF3 esperando o som da conex\xE3o discada terminar...",
        "Recalibrando o humor\xF4metro.",
        "Minha outra tela de carregamento \xE9 ainda mais engra\xE7ada.",
        "Tenho quase certeza que tem um gato andando no teclado em algum lugar...",
        "Aumentando... Aumentando... Ainda carregando.",
        "N\xE3o \xE9 um bug, \xE9 um recurso... desta tela de carregamento.",
        "Voc\xEA j\xE1 tentou desligar e ligar de novo? (A tela de carregamento, n\xE3o eu.)",
        "Construindo pilares adicionais..."
      ],
      // ============================================================================
      // Extension Settings Input
      // ============================================================================
      "Enter value...": "Digite o valor...",
      "Enter sensitive value...": "Digite o valor sens\xEDvel...",
      "Press Enter to submit, Escape to cancel": "Pressione Enter para enviar, Escape para cancelar",
      // ============================================================================
      // Command Migration Tool
      // ============================================================================
      "Markdown file already exists: {{filename}}": "Arquivo Markdown j\xE1 existe: {{filename}}",
      "TOML Command Format Deprecation Notice": "Aviso de Obsolesc\xEAncia do Formato de Comando TOML",
      "Found {{count}} command file(s) in TOML format:": "Encontrado(s) {{count}} arquivo(s) de comando no formato TOML:",
      "The TOML format for commands is being deprecated in favor of Markdown format.": "O formato TOML para comandos est\xE1 sendo descontinuado em favor do formato Markdown.",
      "Markdown format is more readable and easier to edit.": "O formato Markdown \xE9 mais leg\xEDvel e f\xE1cil de editar.",
      "You can migrate these files automatically using:": "Voc\xEA pode migrar esses arquivos automaticamente usando:",
      "Or manually convert each file:": "Ou converter manualmente cada arquivo:",
      'TOML: prompt = "..." / description = "..."': 'TOML: prompt = "..." / description = "..."',
      "Markdown: YAML frontmatter + content": "Markdown: YAML frontmatter + conte\xFAdo",
      "The migration tool will:": "A ferramenta de migra\xE7\xE3o ir\xE1:",
      "Convert TOML files to Markdown": "Converter arquivos TOML para Markdown",
      "Create backups of original files": "Criar backups dos arquivos originais",
      "Preserve all command functionality": "Preservar toda a funcionalidade do comando",
      "TOML format will continue to work for now, but migration is recommended.": "O formato TOML continuar\xE1 a funcionar por enquanto, mas a migra\xE7\xE3o \xE9 recomendada.",
      // ============================================================================
      // Extensions - Explore Command
      // ============================================================================
      "Open extensions page in your browser": "Abrir p\xE1gina de extens\xF5es no seu navegador",
      "Unknown extensions source: {{source}}.": "Fonte de extens\xF5es desconhecida: {{source}}.",
      "Would open extensions page in your browser: {{url}} (skipped in test environment)": "Abriria a p\xE1gina de extens\xF5es no seu navegador: {{url}} (pulado no ambiente de teste)",
      "View available extensions at {{url}}": "Ver extens\xF5es dispon\xEDveis em {{url}}",
      "Opening extensions page in your browser: {{url}}": "Abrindo p\xE1gina de extens\xF5es no seu navegador: {{url}}",
      "Failed to open browser. Check out the extensions gallery at {{url}}": "Falha ao abrir o navegador. Confira a galeria de extens\xF5es em {{url}}",
      // ============================================================================
      // Custom API-KEY Configuration
      // ============================================================================
      "For advanced users who want to configure models manually.": "Para usu\xE1rios avan\xE7ados que desejam configurar modelos manualmente.",
      "Please configure your models in settings.json:": "Por favor, configure seus modelos em settings.json:",
      "Set API key via environment variable (e.g., OPENAI_API_KEY)": "Defina a chave de API via vari\xE1vel de ambiente (ex: OPENAI_API_KEY)",
      "Add model configuration to modelProviders['openai'] (or other auth types)": "Adicione a configura\xE7\xE3o do modelo a modelProviders['openai'] (ou outros tipos de autentica\xE7\xE3o)",
      "Each provider needs: id, envKey (required), plus optional baseUrl, generationConfig": "Cada provedor precisa de: id, envKey (obrigat\xF3rio), al\xE9m de baseUrl e generationConfig opcionais",
      "Use /model command to select your preferred model from the configured list": "Use o comando /model para selecionar seu modelo preferido da lista configurada",
      "Supported auth types: openai, anthropic, gemini, vertex-ai, etc.": "Tipos de autentica\xE7\xE3o suportados: openai, anthropic, gemini, vertex-ai, etc.",
      // ============================================================================
      // Coding Plan Authentication
      // ============================================================================
      "Please enter your API key:": "Por favor, digite sua chave de API:",
      "API key cannot be empty.": "A chave de API n\xE3o pode estar vazia.",
      "You can get your exclusive Coding Plan API-KEY here:": "Voc\xEA pode obter sua chave de API exclusiva do Coding Plan aqui:",
      "New model configurations are available for Bailian Coding Plan. Update now?": "Novas configura\xE7\xF5es de modelo est\xE3o dispon\xEDveis para o Bailian Coding Plan. Atualizar agora?",
      "Coding Plan configuration updated successfully. New models are now available.": "Configura\xE7\xE3o do Coding Plan atualizada com sucesso. Novos modelos agora est\xE3o dispon\xEDveis.",
      "Coding Plan API key not found. Please re-authenticate with Coding Plan.": "Chave de API do Coding Plan n\xE3o encontrada. Por favor, re-autentique com o Coding Plan.",
      "Failed to update Coding Plan configuration: {{message}}": "Falha ao atualizar a configura\xE7\xE3o do Coding Plan: {{message}}",
      // ============================================================================
      // Auth Dialog - View Titles and Labels
      // ============================================================================
      "Coding Plan": "Coding Plan",
      "Coding Plan (Bailian, China)": "Coding Plan (Bailian, China)",
      "Coding Plan (Bailian, Global/Intl)": "Coding Plan (Bailian, Global/Intl)",
      "Paste your api key of Bailian Coding Plan and you're all set!": "Cole sua chave de API do Bailian Coding Plan e pronto!",
      "Paste your api key of Coding Plan (Bailian, Global/Intl) and you're all set!": "Cole sua chave de API do Coding Plan (Bailian, Global/Intl) e pronto!",
      Custom: "Personalizado",
      "More instructions about configuring `modelProviders` manually.": "Mais instru\xE7\xF5es sobre como configurar `modelProviders` manualmente.",
      "Select API-KEY configuration mode:": "Selecione o modo de configura\xE7\xE3o da API-KEY:",
      "(Press Escape to go back)": "(Pressione Escape para voltar)",
      "(Press Enter to submit, Escape to cancel)": "(Pressione Enter para enviar, Escape para cancelar)",
      "More instructions please check:": "Mais instru\xE7\xF5es, consulte:",
      // ============================================================================
      // Coding Plan International Updates
      // ============================================================================
      "New model configurations are available for {{region}}. Update now?": "Novas configura\xE7\xF5es de modelo est\xE3o dispon\xEDveis para o {{region}}. Atualizar agora?",
      "New model configurations are available for Bailian Coding Plan (China). Update now?": "Novas configura\xE7\xF5es de modelo est\xE3o dispon\xEDveis para o Bailian Coding Plan (China). Atualizar agora?",
      "New model configurations are available for Coding Plan (Bailian, Global/Intl). Update now?": "Novas configura\xE7\xF5es de modelo est\xE3o dispon\xEDveis para o Coding Plan (Bailian, Global/Intl). Atualizar agora?",
      '{{region}} configuration updated successfully. Model switched to "{{model}}".': 'Configura\xE7\xE3o do {{region}} atualizada com sucesso. Modelo alterado para "{{model}}".',
      "Authenticated successfully with {{region}}. API key and model configs saved to settings.json (backed up).": "Autenticado com sucesso com {{region}}. Chave de API e configura\xE7\xF5es de modelo salvas em settings.json (com backup)."
    };
  }
});

// packages/cli/src/i18n/locales/ru.js
var ru_exports = {};
__export(ru_exports, {
  default: () => ru_default
});
var ru_default;
var init_ru = __esm({
  "packages/cli/src/i18n/locales/ru.js"() {
    "use strict";
    init_esbuild_shims();
    ru_default = {
      // ============================================================================
      // Справка / Компоненты интерфейса
      // ============================================================================
      // Attachment hints
      "\u2191 to manage attachments": "\u2191 \u0443\u043F\u0440\u0430\u0432\u043B\u0435\u043D\u0438\u0435 \u0432\u043B\u043E\u0436\u0435\u043D\u0438\u044F\u043C\u0438",
      "\u2190 \u2192 select, Delete to remove, \u2193 to exit": "\u2190 \u2192 \u0432\u044B\u0431\u0440\u0430\u0442\u044C, Delete \u0443\u0434\u0430\u043B\u0438\u0442\u044C, \u2193 \u0432\u044B\u0439\u0442\u0438",
      "Attachments: ": "\u0412\u043B\u043E\u0436\u0435\u043D\u0438\u044F: ",
      "Basics:": "\u041E\u0441\u043D\u043E\u0432\u044B:",
      "Add context": "\u0414\u043E\u0431\u0430\u0432\u0438\u0442\u044C \u043A\u043E\u043D\u0442\u0435\u043A\u0441\u0442",
      "Use {{symbol}} to specify files for context (e.g., {{example}}) to target specific files or folders.": "\u0418\u0441\u043F\u043E\u043B\u044C\u0437\u0443\u0439\u0442\u0435 {{symbol}} \u0434\u043B\u044F \u0434\u043E\u0431\u0430\u0432\u043B\u0435\u043D\u0438\u044F \u0444\u0430\u0439\u043B\u043E\u0432 \u0432 \u043A\u043E\u043D\u0442\u0435\u043A\u0441\u0442 (\u043D\u0430\u043F\u0440\u0438\u043C\u0435\u0440, {{example}}) \u0434\u043B\u044F \u0432\u044B\u0431\u043E\u0440\u0430 \u043A\u043E\u043D\u043A\u0440\u0435\u0442\u043D\u044B\u0445 \u0444\u0430\u0439\u043B\u043E\u0432 \u0438\u043B\u0438 \u043F\u0430\u043F\u043E\u043A).",
      "@": "@",
      "@src/myFile.ts": "@src/myFile.ts",
      "Shell mode": "\u0420\u0435\u0436\u0438\u043C \u0442\u0435\u0440\u043C\u0438\u043D\u0430\u043B\u0430",
      "YOLO mode": "\u0420\u0435\u0436\u0438\u043C YOLO",
      "plan mode": "\u0420\u0435\u0436\u0438\u043C \u043F\u043B\u0430\u043D\u0438\u0440\u043E\u0432\u0430\u043D\u0438\u044F",
      "auto-accept edits": "\u0420\u0435\u0436\u0438\u043C \u043F\u0440\u0438\u043D\u044F\u0442\u0438\u044F \u043F\u0440\u0430\u0432\u043E\u043A",
      "Accepting edits": "\u041F\u0440\u0438\u043D\u044F\u0442\u0438\u0435 \u043F\u0440\u0430\u0432\u043E\u043A",
      "(shift + tab to cycle)": "(shift + tab \u0434\u043B\u044F \u043F\u0435\u0440\u0435\u043A\u043B\u044E\u0447\u0435\u043D\u0438\u044F)",
      "(tab to cycle)": "(Tab \u0434\u043B\u044F \u043F\u0435\u0440\u0435\u043A\u043B\u044E\u0447\u0435\u043D\u0438\u044F)",
      "Execute shell commands via {{symbol}} (e.g., {{example1}}) or use natural language (e.g., {{example2}}).": "\u0412\u044B\u043F\u043E\u043B\u043D\u044F\u0439\u0442\u0435 \u043A\u043E\u043C\u0430\u043D\u0434\u044B \u0442\u0435\u0440\u043C\u0438\u043D\u0430\u043B\u0430 \u0447\u0435\u0440\u0435\u0437 {{symbol}} (\u043D\u0430\u043F\u0440\u0438\u043C\u0435\u0440, {{example1}}) \u0438\u043B\u0438 \u0438\u0441\u043F\u043E\u043B\u044C\u0437\u0443\u0439\u0442\u0435 \u0435\u0441\u0442\u0435\u0441\u0442\u0432\u0435\u043D\u043D\u044B\u0439 \u044F\u0437\u044B\u043A (\u043D\u0430\u043F\u0440\u0438\u043C\u0435\u0440, {{example2}}).",
      "!": "!",
      "!npm run start": "!npm run start",
      "start server": "start server",
      "Commands:": "\u041A\u043E\u043C\u0430\u043D\u0434\u044B:",
      "shell command": "\u043A\u043E\u043C\u0430\u043D\u0434\u0430 \u0442\u0435\u0440\u043C\u0438\u043D\u0430\u043B\u0430",
      "Model Context Protocol command (from external servers)": "\u041A\u043E\u043C\u0430\u043D\u0434\u0430 Model Context Protocol (\u0438\u0437 \u0432\u043D\u0435\u0448\u043D\u0438\u0445 \u0441\u0435\u0440\u0432\u0435\u0440\u043E\u0432)",
      "Keyboard Shortcuts:": "\u0413\u043E\u0440\u044F\u0447\u0438\u0435 \u043A\u043B\u0430\u0432\u0438\u0448\u0438:",
      "Toggle this help display": "\u041F\u043E\u043A\u0430\u0437\u0430\u0442\u044C/\u0441\u043A\u0440\u044B\u0442\u044C \u044D\u0442\u0443 \u0441\u043F\u0440\u0430\u0432\u043A\u0443",
      "Toggle shell mode": "\u041F\u0435\u0440\u0435\u043A\u043B\u044E\u0447\u0438\u0442\u044C \u0440\u0435\u0436\u0438\u043C \u043E\u0431\u043E\u043B\u043E\u0447\u043A\u0438",
      "Open command menu": "\u041E\u0442\u043A\u0440\u044B\u0442\u044C \u043C\u0435\u043D\u044E \u043A\u043E\u043C\u0430\u043D\u0434",
      "Add file context": "\u0414\u043E\u0431\u0430\u0432\u0438\u0442\u044C \u0444\u0430\u0439\u043B \u0432 \u043A\u043E\u043D\u0442\u0435\u043A\u0441\u0442",
      "Accept suggestion / Autocomplete": "\u041F\u0440\u0438\u043D\u044F\u0442\u044C \u043F\u043E\u0434\u0441\u043A\u0430\u0437\u043A\u0443 / \u0410\u0432\u0442\u043E\u0434\u043E\u043F\u043E\u043B\u043D\u0435\u043D\u0438\u0435",
      "Reverse search history": "\u041E\u0431\u0440\u0430\u0442\u043D\u044B\u0439 \u043F\u043E\u0438\u0441\u043A \u043F\u043E \u0438\u0441\u0442\u043E\u0440\u0438\u0438",
      "Press ? again to close": "\u041D\u0430\u0436\u043C\u0438\u0442\u0435 ? \u0435\u0449\u0451 \u0440\u0430\u0437, \u0447\u0442\u043E\u0431\u044B \u0437\u0430\u043A\u0440\u044B\u0442\u044C",
      "Jump through words in the input": "\u041F\u0435\u0440\u0435\u0445\u043E\u0434 \u043F\u043E \u0441\u043B\u043E\u0432\u0430\u043C \u0432\u043E \u0432\u0432\u043E\u0434\u0435",
      "Close dialogs, cancel requests, or quit application": "\u0417\u0430\u043A\u0440\u044B\u0442\u044C \u0434\u0438\u0430\u043B\u043E\u0433\u0438, \u043E\u0442\u043C\u0435\u043D\u0438\u0442\u044C \u0437\u0430\u043F\u0440\u043E\u0441\u044B \u0438\u043B\u0438 \u0432\u044B\u0439\u0442\u0438 \u0438\u0437 \u043F\u0440\u0438\u043B\u043E\u0436\u0435\u043D\u0438\u044F",
      "New line": "\u041D\u043E\u0432\u0430\u044F \u0441\u0442\u0440\u043E\u043A\u0430",
      "New line (Alt+Enter works for certain linux distros)": "\u041D\u043E\u0432\u0430\u044F \u0441\u0442\u0440\u043E\u043A\u0430 (Alt+Enter \u0440\u0430\u0431\u043E\u0442\u0430\u0435\u0442 \u0442\u043E\u043B\u044C\u043A\u043E \u0432 \u043D\u0435\u043A\u043E\u0442\u043E\u0440\u044B\u0445 \u0434\u0438\u0441\u0442\u0440\u0438\u0431\u0443\u0442\u0438\u0432\u0430\u0445 Linux)",
      "Clear the screen": "\u041E\u0447\u0438\u0441\u0442\u0438\u0442\u044C \u044D\u043A\u0440\u0430\u043D",
      "Open input in external editor": "\u041E\u0442\u043A\u0440\u044B\u0442\u044C \u0432\u0432\u043E\u0434 \u0432\u043E \u0432\u043D\u0435\u0448\u043D\u0435\u043C \u0440\u0435\u0434\u0430\u043A\u0442\u043E\u0440\u0435",
      "Send message": "\u041E\u0442\u043F\u0440\u0430\u0432\u0438\u0442\u044C \u0441\u043E\u043E\u0431\u0449\u0435\u043D\u0438\u0435",
      "Initializing...": "\u0418\u043D\u0438\u0446\u0438\u0430\u043B\u0438\u0437\u0430\u0446\u0438\u044F...",
      "Connecting to MCP servers... ({{connected}}/{{total}})": "\u041F\u043E\u0434\u043A\u043B\u044E\u0447\u0435\u043D\u0438\u0435 \u043A MCP-\u0441\u0435\u0440\u0432\u0435\u0440\u0430\u043C... ({{connected}}/{{total}})",
      "Type your message or @path/to/file": "\u0412\u0432\u0435\u0434\u0438\u0442\u0435 \u0441\u043E\u043E\u0431\u0449\u0435\u043D\u0438\u0435 \u0438\u043B\u0438 @\u043F\u0443\u0442\u044C/\u043A/\u0444\u0430\u0439\u043B\u0443",
      "? for shortcuts": "? \u2014 \u0433\u043E\u0440\u044F\u0447\u0438\u0435 \u043A\u043B\u0430\u0432\u0438\u0448\u0438",
      "Press 'i' for INSERT mode and 'Esc' for NORMAL mode.": "\u041D\u0430\u0436\u043C\u0438\u0442\u0435 'i' \u0434\u043B\u044F \u0440\u0435\u0436\u0438\u043C\u0430 \u0412\u0421\u0422\u0410\u0412\u041A\u0410 \u0438 'Esc' \u0434\u043B\u044F \u041E\u0411\u042B\u0427\u041D\u041E\u0413\u041E \u0440\u0435\u0436\u0438\u043C\u0430.",
      "Cancel operation / Clear input (double press)": "\u041E\u0442\u043C\u0435\u043D\u0438\u0442\u044C \u043E\u043F\u0435\u0440\u0430\u0446\u0438\u044E / \u041E\u0447\u0438\u0441\u0442\u0438\u0442\u044C \u0432\u0432\u043E\u0434 (\u0434\u0432\u043E\u0439\u043D\u043E\u0435 \u043D\u0430\u0436\u0430\u0442\u0438\u0435)",
      "Cycle approval modes": "\u041F\u0435\u0440\u0435\u043A\u043B\u044E\u0447\u0435\u043D\u0438\u0435 \u0440\u0435\u0436\u0438\u043C\u043E\u0432 \u043F\u043E\u0434\u0442\u0432\u0435\u0440\u0436\u0434\u0435\u043D\u0438\u044F",
      "Cycle through your prompt history": "\u041F\u0440\u043E\u043B\u0438\u0441\u0442\u0430\u0442\u044C \u0438\u0441\u0442\u043E\u0440\u0438\u044E \u0437\u0430\u043F\u0440\u043E\u0441\u043E\u0432",
      "For a full list of shortcuts, see {{docPath}}": "\u041F\u043E\u043B\u043D\u044B\u0439 \u0441\u043F\u0438\u0441\u043E\u043A \u0433\u043E\u0440\u044F\u0447\u0438\u0445 \u043A\u043B\u0430\u0432\u0438\u0448 \u0441\u043C. \u0432 {{docPath}}",
      "docs/keyboard-shortcuts.md": "docs/keyboard-shortcuts.md",
      "for help on Qwen Code": "\u0421\u043F\u0440\u0430\u0432\u043A\u0430 \u043F\u043E Qwen Code",
      "show version info": "\u041F\u0440\u043E\u0441\u043C\u043E\u0442\u0440 \u0438\u043D\u0444\u043E\u0440\u043C\u0430\u0446\u0438\u0438 \u043E \u0432\u0435\u0440\u0441\u0438\u0438",
      "submit a bug report": "\u041E\u0442\u043F\u0440\u0430\u0432\u043A\u0430 \u043E\u0442\u0447\u0451\u0442\u0430 \u043E\u0431 \u043E\u0448\u0438\u0431\u043A\u0435",
      "About Qwen Code": "\u041E\u0431 Qwen Code",
      Status: "\u0421\u0442\u0430\u0442\u0443\u0441",
      // Keyboard shortcuts panel descriptions
      "for shell mode": "\u0440\u0435\u0436\u0438\u043C \u043E\u0431\u043E\u043B\u043E\u0447\u043A\u0438",
      "for commands": "\u043C\u0435\u043D\u044E \u043A\u043E\u043C\u0430\u043D\u0434",
      "for file paths": "\u043F\u0443\u0442\u0438 \u043A \u0444\u0430\u0439\u043B\u0430\u043C",
      "to clear input": "\u043E\u0447\u0438\u0441\u0442\u0438\u0442\u044C \u0432\u0432\u043E\u0434",
      "to cycle approvals": "\u043F\u0435\u0440\u0435\u043A\u043B\u044E\u0447\u0438\u0442\u044C \u0440\u0435\u0436\u0438\u043C",
      "to quit": "\u0432\u044B\u0445\u043E\u0434",
      "for newline": "\u043D\u043E\u0432\u0430\u044F \u0441\u0442\u0440\u043E\u043A\u0430",
      "to clear screen": "\u043E\u0447\u0438\u0441\u0442\u0438\u0442\u044C \u044D\u043A\u0440\u0430\u043D",
      "to search history": "\u043F\u043E\u0438\u0441\u043A \u0432 \u0438\u0441\u0442\u043E\u0440\u0438\u0438",
      "to paste images": "\u0432\u0441\u0442\u0430\u0432\u0438\u0442\u044C \u0438\u0437\u043E\u0431\u0440\u0430\u0436\u0435\u043D\u0438\u044F",
      "for external editor": "\u0432\u043D\u0435\u0448\u043D\u0438\u0439 \u0440\u0435\u0434\u0430\u043A\u0442\u043E\u0440",
      // ============================================================================
      // Поля системной информации
      // ============================================================================
      "Qwen Code": "Qwen Code",
      Runtime: "\u0421\u0440\u0435\u0434\u0430 \u0432\u044B\u043F\u043E\u043B\u043D\u0435\u043D\u0438\u044F",
      OS: "\u041E\u0421",
      Auth: "\u0410\u0443\u0442\u0435\u043D\u0442\u0438\u0444\u0438\u043A\u0430\u0446\u0438\u044F",
      "CLI Version": "\u0412\u0435\u0440\u0441\u0438\u044F CLI",
      "Git Commit": "Git-\u043A\u043E\u043C\u043C\u0438\u0442",
      Model: "\u041C\u043E\u0434\u0435\u043B\u044C",
      Sandbox: "\u041F\u0435\u0441\u043E\u0447\u043D\u0438\u0446\u0430",
      "OS Platform": "\u041F\u043B\u0430\u0442\u0444\u043E\u0440\u043C\u0430 \u041E\u0421",
      "OS Arch": "\u0410\u0440\u0445\u0438\u0442\u0435\u043A\u0442\u0443\u0440\u0430 \u041E\u0421",
      "OS Release": "\u0412\u0435\u0440\u0441\u0438\u044F \u041E\u0421",
      "Node.js Version": "\u0412\u0435\u0440\u0441\u0438\u044F Node.js",
      "NPM Version": "\u0412\u0435\u0440\u0441\u0438\u044F NPM",
      "Session ID": "ID \u0441\u0435\u0441\u0441\u0438\u0438",
      "Auth Method": "\u041C\u0435\u0442\u043E\u0434 \u0430\u0432\u0442\u043E\u0440\u0438\u0437\u0430\u0446\u0438\u0438",
      "Base URL": "\u0411\u0430\u0437\u043E\u0432\u044B\u0439 URL",
      Proxy: "\u041F\u0440\u043E\u043A\u0441\u0438",
      "Memory Usage": "\u0418\u0441\u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u043D\u0438\u0435 \u043F\u0430\u043C\u044F\u0442\u0438",
      "IDE Client": "\u041A\u043B\u0438\u0435\u043D\u0442 IDE",
      // ============================================================================
      // Команды - Общие
      // ============================================================================
      "Analyzes the project and creates a tailored QWEN.md file.": "\u0410\u043D\u0430\u043B\u0438\u0437 \u043F\u0440\u043E\u0435\u043A\u0442\u0430 \u0438 \u0441\u043E\u0437\u0434\u0430\u043D\u0438\u0435 \u0430\u0434\u0430\u043F\u0442\u0438\u0440\u043E\u0432\u0430\u043D\u043D\u043E\u0433\u043E \u0444\u0430\u0439\u043B\u0430 QWEN.md",
      "list available Qwen Code tools. Usage: /tools [desc]": "\u041F\u0440\u043E\u0441\u043C\u043E\u0442\u0440 \u0434\u043E\u0441\u0442\u0443\u043F\u043D\u044B\u0445 \u0438\u043D\u0441\u0442\u0440\u0443\u043C\u0435\u043D\u0442\u043E\u0432 Qwen Code. \u0418\u0441\u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u043D\u0438\u0435: /tools [desc]",
      "Available Qwen Code CLI tools:": "\u0414\u043E\u0441\u0442\u0443\u043F\u043D\u044B\u0435 \u0438\u043D\u0441\u0442\u0440\u0443\u043C\u0435\u043D\u0442\u044B Qwen Code CLI:",
      "No tools available": "\u041D\u0435\u0442 \u0434\u043E\u0441\u0442\u0443\u043F\u043D\u044B\u0445 \u0438\u043D\u0441\u0442\u0440\u0443\u043C\u0435\u043D\u0442\u043E\u0432",
      "View or change the approval mode for tool usage": "\u041F\u0440\u043E\u0441\u043C\u043E\u0442\u0440 \u0438\u043B\u0438 \u0438\u0437\u043C\u0435\u043D\u0435\u043D\u0438\u0435 \u0440\u0435\u0436\u0438\u043C\u0430 \u043F\u043E\u0434\u0442\u0432\u0435\u0440\u0436\u0434\u0435\u043D\u0438\u044F \u0434\u043B\u044F \u0438\u0441\u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u043D\u0438\u044F \u0438\u043D\u0441\u0442\u0440\u0443\u043C\u0435\u043D\u0442\u043E\u0432",
      'Invalid approval mode "{{arg}}". Valid modes: {{modes}}': '\u041D\u0435\u0434\u043E\u043F\u0443\u0441\u0442\u0438\u043C\u044B\u0439 \u0440\u0435\u0436\u0438\u043C \u043F\u043E\u0434\u0442\u0432\u0435\u0440\u0436\u0434\u0435\u043D\u0438\u044F "{{arg}}". \u0414\u043E\u043F\u0443\u0441\u0442\u0438\u043C\u044B\u0435 \u0440\u0435\u0436\u0438\u043C\u044B: {{modes}}',
      'Approval mode set to "{{mode}}"': '\u0420\u0435\u0436\u0438\u043C \u043F\u043E\u0434\u0442\u0432\u0435\u0440\u0436\u0434\u0435\u043D\u0438\u044F \u0443\u0441\u0442\u0430\u043D\u043E\u0432\u043B\u0435\u043D \u043D\u0430 "{{mode}}"',
      "View or change the language setting": "\u041F\u0440\u043E\u0441\u043C\u043E\u0442\u0440 \u0438\u043B\u0438 \u0438\u0437\u043C\u0435\u043D\u0435\u043D\u0438\u0435 \u043D\u0430\u0441\u0442\u0440\u043E\u0435\u043A \u044F\u0437\u044B\u043A\u0430",
      "change the theme": "\u0418\u0437\u043C\u0435\u043D\u0435\u043D\u0438\u0435 \u0442\u0435\u043C\u044B",
      "Select Theme": "\u0412\u044B\u0431\u043E\u0440 \u0442\u0435\u043C\u044B",
      Preview: "\u041F\u0440\u0435\u0434\u043F\u0440\u043E\u0441\u043C\u043E\u0442\u0440",
      "(Use Enter to select, Tab to configure scope)": "(Enter \u0434\u043B\u044F \u0432\u044B\u0431\u043E\u0440\u0430, Tab \u0434\u043B\u044F \u043D\u0430\u0441\u0442\u0440\u043E\u0439\u043A\u0438 \u043E\u0431\u043B\u0430\u0441\u0442\u0438)",
      "(Use Enter to apply scope, Tab to go back)": "(Enter \u0434\u043B\u044F \u043F\u0440\u0438\u043C\u0435\u043D\u0435\u043D\u0438\u044F \u043E\u0431\u043B\u0430\u0441\u0442\u0438, Tab \u0434\u043B\u044F \u0432\u043E\u0437\u0432\u0440\u0430\u0442\u0430)",
      "Theme configuration unavailable due to NO_COLOR env variable.": "\u041D\u0430\u0441\u0442\u0440\u043E\u0439\u043A\u0430 \u0442\u0435\u043C\u044B \u043D\u0435\u0434\u043E\u0441\u0442\u0443\u043F\u043D\u0430 \u0438\u0437-\u0437\u0430 \u043F\u0435\u0440\u0435\u043C\u0435\u043D\u043D\u043E\u0439 \u043E\u043A\u0440\u0443\u0436\u0435\u043D\u0438\u044F NO_COLOR.",
      'Theme "{{themeName}}" not found.': '\u0422\u0435\u043C\u0430 "{{themeName}}" \u043D\u0435 \u043D\u0430\u0439\u0434\u0435\u043D\u0430.',
      'Theme "{{themeName}}" not found in selected scope.': '\u0422\u0435\u043C\u0430 "{{themeName}}" \u043D\u0435 \u043D\u0430\u0439\u0434\u0435\u043D\u0430 \u0432 \u0432\u044B\u0431\u0440\u0430\u043D\u043D\u043E\u0439 \u043E\u0431\u043B\u0430\u0441\u0442\u0438.',
      "Clear conversation history and free up context": "\u041E\u0447\u0438\u0441\u0442\u0438\u0442\u044C \u0438\u0441\u0442\u043E\u0440\u0438\u044E \u0434\u0438\u0430\u043B\u043E\u0433\u0430 \u0438 \u043E\u0441\u0432\u043E\u0431\u043E\u0434\u0438\u0442\u044C \u043A\u043E\u043D\u0442\u0435\u043A\u0441\u0442",
      "Compresses the context by replacing it with a summary.": "\u0421\u0436\u0430\u0442\u0438\u0435 \u043A\u043E\u043D\u0442\u0435\u043A\u0441\u0442\u0430 \u0437\u0430\u043C\u0435\u043D\u043E\u0439 \u043D\u0430 \u043A\u0440\u0430\u0442\u043A\u0443\u044E \u0441\u0432\u043E\u0434\u043A\u0443",
      "open full Qwen Code documentation in your browser": "\u041E\u0442\u043A\u0440\u044B\u0442\u0438\u0435 \u043F\u043E\u043B\u043D\u043E\u0439 \u0434\u043E\u043A\u0443\u043C\u0435\u043D\u0442\u0430\u0446\u0438\u0438 Qwen Code \u0432 \u0431\u0440\u0430\u0443\u0437\u0435\u0440\u0435",
      "Configuration not available.": "\u041A\u043E\u043D\u0444\u0438\u0433\u0443\u0440\u0430\u0446\u0438\u044F \u043D\u0435\u0434\u043E\u0441\u0442\u0443\u043F\u043D\u0430.",
      "change the auth method": "\u0418\u0437\u043C\u0435\u043D\u0435\u043D\u0438\u0435 \u043C\u0435\u0442\u043E\u0434\u0430 \u0430\u0432\u0442\u043E\u0440\u0438\u0437\u0430\u0446\u0438\u0438",
      "Configure authentication information for login": "\u041D\u0430\u0441\u0442\u0440\u043E\u0439\u043A\u0430 \u0430\u0443\u0442\u0435\u043D\u0442\u0438\u0444\u0438\u043A\u0430\u0446\u0438\u043E\u043D\u043D\u043E\u0439 \u0438\u043D\u0444\u043E\u0440\u043C\u0430\u0446\u0438\u0438 \u0434\u043B\u044F \u0432\u0445\u043E\u0434\u0430",
      "Copy the last result or code snippet to clipboard": "\u041A\u043E\u043F\u0438\u0440\u043E\u0432\u0430\u043D\u0438\u0435 \u043F\u043E\u0441\u043B\u0435\u0434\u043D\u0435\u0433\u043E \u0440\u0435\u0437\u0443\u043B\u044C\u0442\u0430\u0442\u0430 \u0438\u043B\u0438 \u0444\u0440\u0430\u0433\u043C\u0435\u043D\u0442\u0430 \u043A\u043E\u0434\u0430 \u0432 \u0431\u0443\u0444\u0435\u0440 \u043E\u0431\u043C\u0435\u043D\u0430",
      // ============================================================================
      // Команды - Агенты
      // ============================================================================
      "Manage subagents for specialized task delegation.": "\u0423\u043F\u0440\u0430\u0432\u043B\u0435\u043D\u0438\u0435 \u043F\u043E\u0434\u0430\u0433\u0435\u043D\u0442\u0430\u043C\u0438 \u0434\u043B\u044F \u0434\u0435\u043B\u0435\u0433\u0438\u0440\u043E\u0432\u0430\u043D\u0438\u044F \u0441\u043F\u0435\u0446\u0438\u0430\u043B\u0438\u0437\u0438\u0440\u043E\u0432\u0430\u043D\u043D\u044B\u0445 \u0437\u0430\u0434\u0430\u0447",
      "Manage existing subagents (view, edit, delete).": "\u0423\u043F\u0440\u0430\u0432\u043B\u0435\u043D\u0438\u0435 \u0441\u0443\u0449\u0435\u0441\u0442\u0432\u0443\u044E\u0449\u0438\u043C\u0438 \u043F\u043E\u0434\u0430\u0433\u0435\u043D\u0442\u0430\u043C\u0438 (\u043F\u0440\u043E\u0441\u043C\u043E\u0442\u0440, \u043F\u0440\u0430\u0432\u043A\u0430, \u0443\u0434\u0430\u043B\u0435\u043D\u0438\u0435)",
      "Create a new subagent with guided setup.": "\u0421\u043E\u0437\u0434\u0430\u043D\u0438\u0435 \u043D\u043E\u0432\u043E\u0433\u043E \u043F\u043E\u0434\u0430\u0433\u0435\u043D\u0442\u0430 \u0441 \u043F\u043E\u0448\u0430\u0433\u043E\u0432\u043E\u0439 \u043D\u0430\u0441\u0442\u0440\u043E\u0439\u043A\u043E\u0439",
      // ============================================================================
      // Агенты - Диалог управления
      // ============================================================================
      Agents: "\u0410\u0433\u0435\u043D\u0442\u044B",
      "Choose Action": "\u0412\u044B\u0431\u0435\u0440\u0438\u0442\u0435 \u0434\u0435\u0439\u0441\u0442\u0432\u0438\u0435",
      "Edit {{name}}": "\u0420\u0435\u0434\u0430\u043A\u0442\u0438\u0440\u043E\u0432\u0430\u0442\u044C {{name}}",
      "Edit Tools: {{name}}": "\u0420\u0435\u0434\u0430\u043A\u0442\u0438\u0440\u043E\u0432\u0430\u0442\u044C \u0438\u043D\u0441\u0442\u0440\u0443\u043C\u0435\u043D\u0442\u044B: {{name}}",
      "Edit Color: {{name}}": "\u0420\u0435\u0434\u0430\u043A\u0442\u0438\u0440\u043E\u0432\u0430\u0442\u044C \u0446\u0432\u0435\u0442: {{name}}",
      "Delete {{name}}": "\u0423\u0434\u0430\u043B\u0438\u0442\u044C {{name}}",
      "Unknown Step": "\u041D\u0435\u0438\u0437\u0432\u0435\u0441\u0442\u043D\u044B\u0439 \u0448\u0430\u0433",
      "Esc to close": "Esc \u0434\u043B\u044F \u0437\u0430\u043A\u0440\u044B\u0442\u0438\u044F",
      "Enter to select, \u2191\u2193 to navigate, Esc to close": "Enter \u0434\u043B\u044F \u0432\u044B\u0431\u043E\u0440\u0430, \u2191\u2193 \u0434\u043B\u044F \u043D\u0430\u0432\u0438\u0433\u0430\u0446\u0438\u0438, Esc \u0434\u043B\u044F \u0437\u0430\u043A\u0440\u044B\u0442\u0438\u044F",
      "Esc to go back": "Esc \u0434\u043B\u044F \u0432\u043E\u0437\u0432\u0440\u0430\u0442\u0430",
      "Enter to confirm, Esc to cancel": "Enter \u0434\u043B\u044F \u043F\u043E\u0434\u0442\u0432\u0435\u0440\u0436\u0434\u0435\u043D\u0438\u044F, Esc \u0434\u043B\u044F \u043E\u0442\u043C\u0435\u043D\u044B",
      "Enter to select, \u2191\u2193 to navigate, Esc to go back": "Enter \u0434\u043B\u044F \u0432\u044B\u0431\u043E\u0440\u0430, \u2191\u2193 \u0434\u043B\u044F \u043D\u0430\u0432\u0438\u0433\u0430\u0446\u0438\u0438, Esc \u0434\u043B\u044F \u0432\u043E\u0437\u0432\u0440\u0430\u0442\u0430",
      "Invalid step: {{step}}": "\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 \u0448\u0430\u0433: {{step}}",
      "No subagents found.": "\u041F\u043E\u0434\u0430\u0433\u0435\u043D\u0442\u044B \u043D\u0435 \u043D\u0430\u0439\u0434\u0435\u043D\u044B.",
      "Use '/agents create' to create your first subagent.": "\u0418\u0441\u043F\u043E\u043B\u044C\u0437\u0443\u0439\u0442\u0435 '/agents create' \u0434\u043B\u044F \u0441\u043E\u0437\u0434\u0430\u043D\u0438\u044F \u043F\u0435\u0440\u0432\u043E\u0433\u043E \u043F\u043E\u0434\u0430\u0433\u0435\u043D\u0442\u0430.",
      "(built-in)": "(\u0432\u0441\u0442\u0440\u043E\u0435\u043D\u043D\u044B\u0439)",
      "(overridden by project level agent)": "(\u043F\u0435\u0440\u0435\u043E\u043F\u0440\u0435\u0434\u0435\u043B\u0435\u043D \u0430\u0433\u0435\u043D\u0442\u043E\u043C \u0443\u0440\u043E\u0432\u043D\u044F \u043F\u0440\u043E\u0435\u043A\u0442\u0430)",
      "Project Level ({{path}})": "\u0423\u0440\u043E\u0432\u0435\u043D\u044C \u043F\u0440\u043E\u0435\u043A\u0442\u0430 ({{path}})",
      "User Level ({{path}})": "\u0423\u0440\u043E\u0432\u0435\u043D\u044C \u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u0442\u0435\u043B\u044F ({{path}})",
      "Built-in Agents": "\u0412\u0441\u0442\u0440\u043E\u0435\u043D\u043D\u044B\u0435 \u0430\u0433\u0435\u043D\u0442\u044B",
      "Extension Agents": "\u0410\u0433\u0435\u043D\u0442\u044B \u0440\u0430\u0441\u0448\u0438\u0440\u0435\u043D\u0438\u0439",
      "Using: {{count}} agents": "\u0418\u0441\u043F\u043E\u043B\u044C\u0437\u0443\u0435\u0442\u0441\u044F: {{count}} \u0430\u0433\u0435\u043D\u0442(\u043E\u0432)",
      "View Agent": "\u041F\u0440\u043E\u0441\u043C\u043E\u0442\u0440\u0435\u0442\u044C \u0430\u0433\u0435\u043D\u0442\u0430",
      "Edit Agent": "\u0420\u0435\u0434\u0430\u043A\u0442\u0438\u0440\u043E\u0432\u0430\u0442\u044C \u0430\u0433\u0435\u043D\u0442\u0430",
      "Delete Agent": "\u0423\u0434\u0430\u043B\u0438\u0442\u044C \u0430\u0433\u0435\u043D\u0442\u0430",
      Back: "\u041D\u0430\u0437\u0430\u0434",
      "No agent selected": "\u0410\u0433\u0435\u043D\u0442 \u043D\u0435 \u0432\u044B\u0431\u0440\u0430\u043D",
      "File Path: ": "\u041F\u0443\u0442\u044C \u043A \u0444\u0430\u0439\u043B\u0443: ",
      "Tools: ": "\u0418\u043D\u0441\u0442\u0440\u0443\u043C\u0435\u043D\u0442\u044B: ",
      "Color: ": "\u0426\u0432\u0435\u0442: ",
      "Description:": "\u041E\u043F\u0438\u0441\u0430\u043D\u0438\u0435:",
      "System Prompt:": "\u0421\u0438\u0441\u0442\u0435\u043C\u043D\u044B\u0439 \u043F\u0440\u043E\u043C\u043F\u0442:",
      "Open in editor": "\u041E\u0442\u043A\u0440\u044B\u0442\u044C \u0432 \u0440\u0435\u0434\u0430\u043A\u0442\u043E\u0440\u0435",
      "Edit tools": "\u0420\u0435\u0434\u0430\u043A\u0442\u0438\u0440\u043E\u0432\u0430\u0442\u044C \u0438\u043D\u0441\u0442\u0440\u0443\u043C\u0435\u043D\u0442\u044B",
      "Edit color": "\u0420\u0435\u0434\u0430\u043A\u0442\u0438\u0440\u043E\u0432\u0430\u0442\u044C \u0446\u0432\u0435\u0442",
      "\u274C Error:": "\u274C \u041E\u0448\u0438\u0431\u043A\u0430:",
      'Are you sure you want to delete agent "{{name}}"?': '\u0412\u044B \u0443\u0432\u0435\u0440\u0435\u043D\u044B, \u0447\u0442\u043E \u0445\u043E\u0442\u0438\u0442\u0435 \u0443\u0434\u0430\u043B\u0438\u0442\u044C \u0430\u0433\u0435\u043D\u0442\u0430 "{{name}}"?',
      // ============================================================================
      // Агенты - Мастер создания
      // ============================================================================
      "Project Level (.qwen/agents/)": "\u0423\u0440\u043E\u0432\u0435\u043D\u044C \u043F\u0440\u043E\u0435\u043A\u0442\u0430 (.qwen/agents/)",
      "User Level (~/.qwen/agents/)": "\u0423\u0440\u043E\u0432\u0435\u043D\u044C \u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u0442\u0435\u043B\u044F (~/.qwen/agents/)",
      "\u2705 Subagent Created Successfully!": "\u2705 \u041F\u043E\u0434\u0430\u0433\u0435\u043D\u0442 \u0443\u0441\u043F\u0435\u0448\u043D\u043E \u0441\u043E\u0437\u0434\u0430\u043D!",
      'Subagent "{{name}}" has been saved to {{level}} level.': '\u041F\u043E\u0434\u0430\u0433\u0435\u043D\u0442 "{{name}}" \u0441\u043E\u0445\u0440\u0430\u043D\u0435\u043D \u043D\u0430 \u0443\u0440\u043E\u0432\u043D\u0435 {{level}}.',
      "Name: ": "\u0418\u043C\u044F: ",
      "Location: ": "\u0420\u0430\u0441\u043F\u043E\u043B\u043E\u0436\u0435\u043D\u0438\u0435: ",
      "\u274C Error saving subagent:": "\u274C \u041E\u0448\u0438\u0431\u043A\u0430 \u0441\u043E\u0445\u0440\u0430\u043D\u0435\u043D\u0438\u044F \u043F\u043E\u0434\u0430\u0433\u0435\u043D\u0442\u0430:",
      "Warnings:": "\u041F\u0440\u0435\u0434\u0443\u043F\u0440\u0435\u0436\u0434\u0435\u043D\u0438\u044F:",
      'Name "{{name}}" already exists at {{level}} level - will overwrite existing subagent': '\u0418\u043C\u044F "{{name}}" \u0443\u0436\u0435 \u0441\u0443\u0449\u0435\u0441\u0442\u0432\u0443\u0435\u0442 \u043D\u0430 \u0443\u0440\u043E\u0432\u043D\u0435 {{level}} - \u0441\u0443\u0449\u0435\u0441\u0442\u0432\u0443\u044E\u0449\u0438\u0439 \u043F\u043E\u0434\u0430\u0433\u0435\u043D\u0442 \u0431\u0443\u0434\u0435\u0442 \u043F\u0435\u0440\u0435\u0437\u0430\u043F\u0438\u0441\u0430\u043D',
      'Name "{{name}}" exists at user level - project level will take precedence': '\u0418\u043C\u044F "{{name}}" \u0441\u0443\u0449\u0435\u0441\u0442\u0432\u0443\u0435\u0442 \u043D\u0430 \u0443\u0440\u043E\u0432\u043D\u0435 \u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u0442\u0435\u043B\u044F - \u0443\u0440\u043E\u0432\u0435\u043D\u044C \u043F\u0440\u043E\u0435\u043A\u0442\u0430 \u0431\u0443\u0434\u0435\u0442 \u0438\u043C\u0435\u0442\u044C \u043F\u0440\u0438\u043E\u0440\u0438\u0442\u0435\u0442',
      'Name "{{name}}" exists at project level - existing subagent will take precedence': '\u0418\u043C\u044F "{{name}}" \u0441\u0443\u0449\u0435\u0441\u0442\u0432\u0443\u0435\u0442 \u043D\u0430 \u0443\u0440\u043E\u0432\u043D\u0435 \u043F\u0440\u043E\u0435\u043A\u0442\u0430 - \u0441\u0443\u0449\u0435\u0441\u0442\u0432\u0443\u044E\u0449\u0438\u0439 \u043F\u043E\u0434\u0430\u0433\u0435\u043D\u0442 \u0431\u0443\u0434\u0435\u0442 \u0438\u043C\u0435\u0442\u044C \u043F\u0440\u0438\u043E\u0440\u0438\u0442\u0435\u0442',
      "Description is over {{length}} characters": "\u041E\u043F\u0438\u0441\u0430\u043D\u0438\u0435 \u043F\u0440\u0435\u0432\u044B\u0448\u0430\u0435\u0442 {{length}} \u0441\u0438\u043C\u0432\u043E\u043B\u043E\u0432",
      "System prompt is over {{length}} characters": "\u0421\u0438\u0441\u0442\u0435\u043C\u043D\u044B\u0439 \u043F\u0440\u043E\u043C\u043F\u0442 \u043F\u0440\u0435\u0432\u044B\u0448\u0430\u0435\u0442 {{length}} \u0441\u0438\u043C\u0432\u043E\u043B\u043E\u0432",
      // Агенты - Шаги мастера создания
      "Step {{n}}: Choose Location": "\u0428\u0430\u0433 {{n}}: \u0412\u044B\u0431\u0435\u0440\u0438\u0442\u0435 \u0440\u0430\u0441\u043F\u043E\u043B\u043E\u0436\u0435\u043D\u0438\u0435",
      "Step {{n}}: Choose Generation Method": "\u0428\u0430\u0433 {{n}}: \u0412\u044B\u0431\u0435\u0440\u0438\u0442\u0435 \u043C\u0435\u0442\u043E\u0434 \u0433\u0435\u043D\u0435\u0440\u0430\u0446\u0438\u0438",
      "Generate with Qwen Code (Recommended)": "\u0421\u0433\u0435\u043D\u0435\u0440\u0438\u0440\u043E\u0432\u0430\u0442\u044C \u0441 \u043F\u043E\u043C\u043E\u0449\u044C\u044E Qwen Code (\u0420\u0435\u043A\u043E\u043C\u0435\u043D\u0434\u0443\u0435\u0442\u0441\u044F)",
      "Manual Creation": "\u0420\u0443\u0447\u043D\u043E\u0435 \u0441\u043E\u0437\u0434\u0430\u043D\u0438\u0435",
      "Describe what this subagent should do and when it should be used. (Be comprehensive for best results)": "\u041E\u043F\u0438\u0448\u0438\u0442\u0435, \u0447\u0442\u043E \u0434\u043E\u043B\u0436\u0435\u043D \u0434\u0435\u043B\u0430\u0442\u044C \u044D\u0442\u043E\u0442 \u043F\u043E\u0434\u0430\u0433\u0435\u043D\u0442 \u0438 \u043A\u043E\u0433\u0434\u0430 \u0435\u0433\u043E \u0441\u043B\u0435\u0434\u0443\u0435\u0442 \u0438\u0441\u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u0442\u044C. (\u0411\u0443\u0434\u044C\u0442\u0435 \u043F\u043E\u0434\u0440\u043E\u0431\u043D\u044B \u0434\u043B\u044F \u043B\u0443\u0447\u0448\u0438\u0445 \u0440\u0435\u0437\u0443\u043B\u044C\u0442\u0430\u0442\u043E\u0432)",
      "e.g., Expert code reviewer that reviews code based on best practices...": "\u043D\u0430\u043F\u0440\u0438\u043C\u0435\u0440, \u042D\u043A\u0441\u043F\u0435\u0440\u0442\u043D\u044B\u0439 \u0440\u0435\u0432\u044C\u044E\u0432\u0435\u0440 \u043A\u043E\u0434\u0430, \u043F\u0440\u043E\u0432\u0435\u0440\u044F\u044E\u0449\u0438\u0439 \u043A\u043E\u0434 \u043D\u0430 \u0441\u043E\u043E\u0442\u0432\u0435\u0442\u0441\u0442\u0432\u0438\u0435 \u043B\u0443\u0447\u0448\u0438\u043C \u043F\u0440\u0430\u043A\u0442\u0438\u043A\u0430\u043C...",
      "Generating subagent configuration...": "\u0413\u0435\u043D\u0435\u0440\u0430\u0446\u0438\u044F \u043A\u043E\u043D\u0444\u0438\u0433\u0443\u0440\u0430\u0446\u0438\u0438 \u043F\u043E\u0434\u0430\u0433\u0435\u043D\u0442\u0430...",
      "Failed to generate subagent: {{error}}": "\u041D\u0435 \u0443\u0434\u0430\u043B\u043E\u0441\u044C \u0441\u0433\u0435\u043D\u0435\u0440\u0438\u0440\u043E\u0432\u0430\u0442\u044C \u043F\u043E\u0434\u0430\u0433\u0435\u043D\u0442\u0430: {{error}}",
      "Step {{n}}: Describe Your Subagent": "\u0428\u0430\u0433 {{n}}: \u041E\u043F\u0438\u0448\u0438\u0442\u0435 \u043F\u043E\u0434\u0430\u0433\u0435\u043D\u0442\u0430",
      "Step {{n}}: Enter Subagent Name": "\u0428\u0430\u0433 {{n}}: \u0412\u0432\u0435\u0434\u0438\u0442\u0435 \u0438\u043C\u044F \u043F\u043E\u0434\u0430\u0433\u0435\u043D\u0442\u0430",
      "Step {{n}}: Enter System Prompt": "\u0428\u0430\u0433 {{n}}: \u0412\u0432\u0435\u0434\u0438\u0442\u0435 \u0441\u0438\u0441\u0442\u0435\u043C\u043D\u044B\u0439 \u043F\u0440\u043E\u043C\u043F\u0442",
      "Step {{n}}: Enter Description": "\u0428\u0430\u0433 {{n}}: \u0412\u0432\u0435\u0434\u0438\u0442\u0435 \u043E\u043F\u0438\u0441\u0430\u043D\u0438\u0435",
      // Агенты - Выбор инструментов
      "Step {{n}}: Select Tools": "\u0428\u0430\u0433 {{n}}: \u0412\u044B\u0431\u0435\u0440\u0438\u0442\u0435 \u0438\u043D\u0441\u0442\u0440\u0443\u043C\u0435\u043D\u0442\u044B",
      "All Tools (Default)": "\u0412\u0441\u0435 \u0438\u043D\u0441\u0442\u0440\u0443\u043C\u0435\u043D\u0442\u044B (\u043F\u043E \u0443\u043C\u043E\u043B\u0447\u0430\u043D\u0438\u044E)",
      "All Tools": "\u0412\u0441\u0435 \u0438\u043D\u0441\u0442\u0440\u0443\u043C\u0435\u043D\u0442\u044B",
      "Read-only Tools": "\u0418\u043D\u0441\u0442\u0440\u0443\u043C\u0435\u043D\u0442\u044B \u0442\u043E\u043B\u044C\u043A\u043E \u0434\u043B\u044F \u0447\u0442\u0435\u043D\u0438\u044F",
      "Read & Edit Tools": "\u0418\u043D\u0441\u0442\u0440\u0443\u043C\u0435\u043D\u0442\u044B \u0434\u043B\u044F \u0447\u0442\u0435\u043D\u0438\u044F \u0438 \u0440\u0435\u0434\u0430\u043A\u0442\u0438\u0440\u043E\u0432\u0430\u043D\u0438\u044F",
      "Read & Edit & Execution Tools": "\u0418\u043D\u0441\u0442\u0440\u0443\u043C\u0435\u043D\u0442\u044B \u0434\u043B\u044F \u0447\u0442\u0435\u043D\u0438\u044F, \u0440\u0435\u0434\u0430\u043A\u0442\u0438\u0440\u043E\u0432\u0430\u043D\u0438\u044F \u0438 \u0432\u044B\u043F\u043E\u043B\u043D\u0435\u043D\u0438\u044F",
      "All tools selected, including MCP tools": "\u0412\u0441\u0435 \u0438\u043D\u0441\u0442\u0440\u0443\u043C\u0435\u043D\u0442\u044B \u0432\u044B\u0431\u0440\u0430\u043D\u044B, \u0432\u043A\u043B\u044E\u0447\u0430\u044F \u0438\u043D\u0441\u0442\u0440\u0443\u043C\u0435\u043D\u0442\u044B MCP",
      "Selected tools:": "\u0412\u044B\u0431\u0440\u0430\u043D\u043D\u044B\u0435 \u0438\u043D\u0441\u0442\u0440\u0443\u043C\u0435\u043D\u0442\u044B:",
      "Read-only tools:": "\u0418\u043D\u0441\u0442\u0440\u0443\u043C\u0435\u043D\u0442\u044B \u0442\u043E\u043B\u044C\u043A\u043E \u0434\u043B\u044F \u0447\u0442\u0435\u043D\u0438\u044F:",
      "Edit tools:": "\u0418\u043D\u0441\u0442\u0440\u0443\u043C\u0435\u043D\u0442\u044B \u0440\u0435\u0434\u0430\u043A\u0442\u0438\u0440\u043E\u0432\u0430\u043D\u0438\u044F:",
      "Execution tools:": "\u0418\u043D\u0441\u0442\u0440\u0443\u043C\u0435\u043D\u0442\u044B \u0432\u044B\u043F\u043E\u043B\u043D\u0435\u043D\u0438\u044F:",
      "Step {{n}}: Choose Background Color": "\u0428\u0430\u0433 {{n}}: \u0412\u044B\u0431\u0435\u0440\u0438\u0442\u0435 \u0446\u0432\u0435\u0442 \u0444\u043E\u043D\u0430",
      "Step {{n}}: Confirm and Save": "\u0428\u0430\u0433 {{n}}: \u041F\u043E\u0434\u0442\u0432\u0435\u0440\u0434\u0438\u0442\u0435 \u0438 \u0441\u043E\u0445\u0440\u0430\u043D\u0438\u0442\u0435",
      // Агенты - Навигация и инструкции
      "Esc to cancel": "Esc \u0434\u043B\u044F \u043E\u0442\u043C\u0435\u043D\u044B",
      "Press Enter to save, e to save and edit, Esc to go back": "Enter \u0434\u043B\u044F \u0441\u043E\u0445\u0440\u0430\u043D\u0435\u043D\u0438\u044F, e \u0434\u043B\u044F \u0441\u043E\u0445\u0440\u0430\u043D\u0435\u043D\u0438\u044F \u0438 \u0440\u0435\u0434\u0430\u043A\u0442\u0438\u0440\u043E\u0432\u0430\u043D\u0438\u044F, Esc \u0434\u043B\u044F \u0432\u043E\u0437\u0432\u0440\u0430\u0442\u0430",
      "Press Enter to continue, {{navigation}}Esc to {{action}}": "Enter \u0434\u043B\u044F \u043F\u0440\u043E\u0434\u043E\u043B\u0436\u0435\u043D\u0438\u044F, {{navigation}}Esc \u0434\u043B\u044F {{action}}",
      cancel: "\u043E\u0442\u043C\u0435\u043D\u044B",
      "go back": "\u0432\u043E\u0437\u0432\u0440\u0430\u0442\u0430",
      "\u2191\u2193 to navigate, ": "\u2191\u2193 \u0434\u043B\u044F \u043D\u0430\u0432\u0438\u0433\u0430\u0446\u0438\u0438, ",
      "Enter a clear, unique name for this subagent.": "\u0412\u0432\u0435\u0434\u0438\u0442\u0435 \u0447\u0435\u0442\u043A\u043E\u0435, \u0443\u043D\u0438\u043A\u0430\u043B\u044C\u043D\u043E\u0435 \u0438\u043C\u044F \u0434\u043B\u044F \u044D\u0442\u043E\u0433\u043E \u043F\u043E\u0434\u0430\u0433\u0435\u043D\u0442\u0430.",
      "e.g., Code Reviewer": "\u043D\u0430\u043F\u0440\u0438\u043C\u0435\u0440, \u0420\u0435\u0432\u044C\u044E\u0432\u0435\u0440 \u043A\u043E\u0434\u0430",
      "Name cannot be empty.": "\u0418\u043C\u044F \u043D\u0435 \u043C\u043E\u0436\u0435\u0442 \u0431\u044B\u0442\u044C \u043F\u0443\u0441\u0442\u044B\u043C.",
      "Write the system prompt that defines this subagent's behavior. Be comprehensive for best results.": "\u041D\u0430\u043F\u0438\u0448\u0438\u0442\u0435 \u0441\u0438\u0441\u0442\u0435\u043C\u043D\u044B\u0439 \u043F\u0440\u043E\u043C\u043F\u0442, \u043E\u043F\u0440\u0435\u0434\u0435\u043B\u044F\u044E\u0449\u0438\u0439 \u043F\u043E\u0432\u0435\u0434\u0435\u043D\u0438\u0435 \u043F\u043E\u0434\u0430\u0433\u0435\u043D\u0442\u0430. \u0411\u0443\u0434\u044C\u0442\u0435 \u043F\u043E\u0434\u0440\u043E\u0431\u043D\u044B \u0434\u043B\u044F \u043B\u0443\u0447\u0448\u0438\u0445 \u0440\u0435\u0437\u0443\u043B\u044C\u0442\u0430\u0442\u043E\u0432.",
      "e.g., You are an expert code reviewer...": "\u043D\u0430\u043F\u0440\u0438\u043C\u0435\u0440, \u0412\u044B \u044D\u043A\u0441\u043F\u0435\u0440\u0442\u043D\u044B\u0439 \u0440\u0435\u0432\u044C\u044E\u0432\u0435\u0440 \u043A\u043E\u0434\u0430...",
      "System prompt cannot be empty.": "\u0421\u0438\u0441\u0442\u0435\u043C\u043D\u044B\u0439 \u043F\u0440\u043E\u043C\u043F\u0442 \u043D\u0435 \u043C\u043E\u0436\u0435\u0442 \u0431\u044B\u0442\u044C \u043F\u0443\u0441\u0442\u044B\u043C.",
      "Describe when and how this subagent should be used.": "\u041E\u043F\u0438\u0448\u0438\u0442\u0435, \u043A\u043E\u0433\u0434\u0430 \u0438 \u043A\u0430\u043A \u0441\u043B\u0435\u0434\u0443\u0435\u0442 \u0438\u0441\u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u0442\u044C \u044D\u0442\u043E\u0433\u043E \u043F\u043E\u0434\u0430\u0433\u0435\u043D\u0442\u0430.",
      "e.g., Reviews code for best practices and potential bugs.": "\u043D\u0430\u043F\u0440\u0438\u043C\u0435\u0440, \u041F\u0440\u043E\u0432\u0435\u0440\u044F\u0435\u0442 \u043A\u043E\u0434 \u043D\u0430 \u0441\u043E\u043E\u0442\u0432\u0435\u0442\u0441\u0442\u0432\u0438\u0435 \u043B\u0443\u0447\u0448\u0438\u043C \u043F\u0440\u0430\u043A\u0442\u0438\u043A\u0430\u043C \u0438 \u043F\u043E\u0442\u0435\u043D\u0446\u0438\u0430\u043B\u044C\u043D\u044B\u0435 \u043E\u0448\u0438\u0431\u043A\u0438.",
      "Description cannot be empty.": "\u041E\u043F\u0438\u0441\u0430\u043D\u0438\u0435 \u043D\u0435 \u043C\u043E\u0436\u0435\u0442 \u0431\u044B\u0442\u044C \u043F\u0443\u0441\u0442\u044B\u043C.",
      "Failed to launch editor: {{error}}": "\u041D\u0435 \u0443\u0434\u0430\u043B\u043E\u0441\u044C \u0437\u0430\u043F\u0443\u0441\u0442\u0438\u0442\u044C \u0440\u0435\u0434\u0430\u043A\u0442\u043E\u0440: {{error}}",
      "Failed to save and edit subagent: {{error}}": "\u041D\u0435 \u0443\u0434\u0430\u043B\u043E\u0441\u044C \u0441\u043E\u0445\u0440\u0430\u043D\u0438\u0442\u044C \u0438 \u043E\u0442\u0440\u0435\u0434\u0430\u043A\u0442\u0438\u0440\u043E\u0432\u0430\u0442\u044C \u043F\u043E\u0434\u0430\u0433\u0435\u043D\u0442\u0430: {{error}}",
      // ============================================================================
      // Команды - Общие (продолжение)
      // ============================================================================
      "View and edit Qwen Code settings": "\u041F\u0440\u043E\u0441\u043C\u043E\u0442\u0440 \u0438 \u0438\u0437\u043C\u0435\u043D\u0435\u043D\u0438\u0435 \u043D\u0430\u0441\u0442\u0440\u043E\u0435\u043A Qwen Code",
      Settings: "\u041D\u0430\u0441\u0442\u0440\u043E\u0439\u043A\u0438",
      "To see changes, Qwen Code must be restarted. Press r to exit and apply changes now.": "\u0414\u043B\u044F \u043F\u0440\u0438\u043C\u0435\u043D\u0435\u043D\u0438\u044F \u0438\u0437\u043C\u0435\u043D\u0435\u043D\u0438\u0439 \u043D\u0435\u043E\u0431\u0445\u043E\u0434\u0438\u043C\u043E \u043F\u0435\u0440\u0435\u0437\u0430\u043F\u0443\u0441\u0442\u0438\u0442\u044C Qwen Code. \u041D\u0430\u0436\u043C\u0438\u0442\u0435 r \u0434\u043B\u044F \u0432\u044B\u0445\u043E\u0434\u0430 \u0438 \u043F\u0440\u0438\u043C\u0435\u043D\u0435\u043D\u0438\u044F \u0438\u0437\u043C\u0435\u043D\u0435\u043D\u0438\u0439.",
      'The command "/{{command}}" is not supported in non-interactive mode.': '\u041A\u043E\u043C\u0430\u043D\u0434\u0430 "/{{command}}" \u043D\u0435 \u043F\u043E\u0434\u0434\u0435\u0440\u0436\u0438\u0432\u0430\u0435\u0442\u0441\u044F \u0432 \u043D\u0435\u0438\u043D\u0442\u0435\u0440\u0430\u043A\u0442\u0438\u0432\u043D\u043E\u043C \u0440\u0435\u0436\u0438\u043C\u0435.',
      // ============================================================================
      // Метки настроек
      // ============================================================================
      "Vim Mode": "\u0420\u0435\u0436\u0438\u043C Vim",
      "Disable Auto Update": "\u041E\u0442\u043A\u043B\u044E\u0447\u0438\u0442\u044C \u0430\u0432\u0442\u043E\u043E\u0431\u043D\u043E\u0432\u043B\u0435\u043D\u0438\u0435",
      "Attribution: commit": "\u0410\u0442\u0440\u0438\u0431\u0443\u0446\u0438\u044F: \u043A\u043E\u043C\u043C\u0438\u0442",
      "Terminal Bell Notification": "\u0417\u0432\u0443\u043A\u043E\u0432\u043E\u0435 \u0443\u0432\u0435\u0434\u043E\u043C\u043B\u0435\u043D\u0438\u0435 \u0442\u0435\u0440\u043C\u0438\u043D\u0430\u043B\u0430",
      "Enable Usage Statistics": "\u0412\u043A\u043B\u044E\u0447\u0438\u0442\u044C \u0441\u0431\u043E\u0440 \u0441\u0442\u0430\u0442\u0438\u0441\u0442\u0438\u043A\u0438 \u0438\u0441\u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u043D\u0438\u044F",
      Theme: "\u0422\u0435\u043C\u0430",
      "Preferred Editor": "\u041F\u0440\u0435\u0434\u043F\u043E\u0447\u0442\u0438\u0442\u0435\u043B\u044C\u043D\u044B\u0439 \u0440\u0435\u0434\u0430\u043A\u0442\u043E\u0440",
      "Auto-connect to IDE": "\u0410\u0432\u0442\u043E\u043F\u043E\u0434\u043A\u043B\u044E\u0447\u0435\u043D\u0438\u0435 \u043A IDE",
      "Enable Prompt Completion": "\u0412\u043A\u043B\u044E\u0447\u0438\u0442\u044C \u0430\u0432\u0442\u043E\u0434\u043E\u043F\u043E\u043B\u043D\u0435\u043D\u0438\u0435 \u043F\u0440\u043E\u043C\u043F\u0442\u043E\u0432",
      "Debug Keystroke Logging": "\u041B\u043E\u0433\u0438\u0440\u043E\u0432\u0430\u043D\u0438\u0435 \u043D\u0430\u0436\u0430\u0442\u0438\u0439 \u043A\u043B\u0430\u0432\u0438\u0448 \u0434\u043B\u044F \u043E\u0442\u043B\u0430\u0434\u043A\u0438",
      "Language: UI": "\u042F\u0437\u044B\u043A: \u0438\u043D\u0442\u0435\u0440\u0444\u0435\u0439\u0441",
      "Language: Model": "\u042F\u0437\u044B\u043A: \u043C\u043E\u0434\u0435\u043B\u044C",
      "Output Format": "\u0424\u043E\u0440\u043C\u0430\u0442 \u0432\u044B\u0432\u043E\u0434\u0430",
      "Hide Window Title": "\u0421\u043A\u0440\u044B\u0442\u044C \u0437\u0430\u0433\u043E\u043B\u043E\u0432\u043E\u043A \u043E\u043A\u043D\u0430",
      "Show Status in Title": "\u041F\u043E\u043A\u0430\u0437\u044B\u0432\u0430\u0442\u044C \u0441\u0442\u0430\u0442\u0443\u0441 \u0432 \u0437\u0430\u0433\u043E\u043B\u043E\u0432\u043A\u0435",
      "Hide Tips": "\u0421\u043A\u0440\u044B\u0442\u044C \u043F\u043E\u0434\u0441\u043A\u0430\u0437\u043A\u0438",
      "Show Line Numbers in Code": "\u041F\u043E\u043A\u0430\u0437\u044B\u0432\u0430\u0442\u044C \u043D\u043E\u043C\u0435\u0440\u0430 \u0441\u0442\u0440\u043E\u043A \u0432 \u043A\u043E\u0434\u0435",
      "Show Citations": "\u041F\u043E\u043A\u0430\u0437\u044B\u0432\u0430\u0442\u044C \u0446\u0438\u0442\u0430\u0442\u044B",
      "Custom Witty Phrases": "\u041F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u0442\u0435\u043B\u044C\u0441\u043A\u0438\u0435 \u043E\u0441\u0442\u0440\u043E\u0443\u043C\u043D\u044B\u0435 \u0444\u0440\u0430\u0437\u044B",
      "Show Welcome Back Dialog": "\u041F\u043E\u043A\u0430\u0437\u044B\u0432\u0430\u0442\u044C \u0434\u0438\u0430\u043B\u043E\u0433 \u043F\u0440\u0438\u0432\u0435\u0442\u0441\u0442\u0432\u0438\u044F",
      "Enable User Feedback": "\u0412\u043A\u043B\u044E\u0447\u0438\u0442\u044C \u043E\u0442\u0437\u044B\u0432\u044B \u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u0442\u0435\u043B\u0435\u0439",
      "How is Qwen doing this session? (optional)": "\u041A\u0430\u043A \u0434\u0435\u043B\u0430 \u0443 Qwen \u0432 \u044D\u0442\u043E\u0439 \u0441\u0435\u0441\u0441\u0438\u0438? (\u043D\u0435\u043E\u0431\u044F\u0437\u0430\u0442\u0435\u043B\u044C\u043D\u043E)",
      Bad: "\u041F\u043B\u043E\u0445\u043E",
      Fine: "\u041D\u043E\u0440\u043C\u0430\u043B\u044C\u043D\u043E",
      Good: "\u0425\u043E\u0440\u043E\u0448\u043E",
      Dismiss: "\u041E\u0442\u043A\u043B\u043E\u043D\u0438\u0442\u044C",
      "Not Sure Yet": "\u041F\u043E\u043A\u0430 \u043D\u0435 \u0443\u0432\u0435\u0440\u0435\u043D",
      "Any other key": "\u041B\u044E\u0431\u0430\u044F \u0434\u0440\u0443\u0433\u0430\u044F \u043A\u043B\u0430\u0432\u0438\u0448\u0430",
      "Disable Loading Phrases": "\u041E\u0442\u043A\u043B\u044E\u0447\u0438\u0442\u044C \u0444\u0440\u0430\u0437\u044B \u043F\u0440\u0438 \u0437\u0430\u0433\u0440\u0443\u0437\u043A\u0435",
      "Screen Reader Mode": "\u0420\u0435\u0436\u0438\u043C \u043F\u0440\u043E\u0433\u0440\u0430\u043C\u043C\u044B \u0447\u0442\u0435\u043D\u0438\u044F \u0441 \u044D\u043A\u0440\u0430\u043D\u0430",
      "IDE Mode": "\u0420\u0435\u0436\u0438\u043C IDE",
      "Max Session Turns": "\u041C\u0430\u043A\u0441. \u043A\u043E\u043B\u0438\u0447\u0435\u0441\u0442\u0432\u043E \u0445\u043E\u0434\u043E\u0432 \u0441\u0435\u0441\u0441\u0438\u0438",
      "Skip Next Speaker Check": "\u041F\u0440\u043E\u043F\u0443\u0441\u0442\u0438\u0442\u044C \u043F\u0440\u043E\u0432\u0435\u0440\u043A\u0443 \u0441\u043B\u0435\u0434\u0443\u044E\u0449\u0435\u0433\u043E \u0433\u043E\u0432\u043E\u0440\u044F\u0449\u0435\u0433\u043E",
      "Skip Loop Detection": "\u041F\u0440\u043E\u043F\u0443\u0441\u0442\u0438\u0442\u044C \u043E\u0431\u043D\u0430\u0440\u0443\u0436\u0435\u043D\u0438\u0435 \u0446\u0438\u043A\u043B\u043E\u0432",
      "Skip Startup Context": "\u041F\u0440\u043E\u043F\u0443\u0441\u0442\u0438\u0442\u044C \u043D\u0430\u0447\u0430\u043B\u044C\u043D\u044B\u0439 \u043A\u043E\u043D\u0442\u0435\u043A\u0441\u0442",
      "Enable OpenAI Logging": "\u0412\u043A\u043B\u044E\u0447\u0438\u0442\u044C \u043B\u043E\u0433\u0438\u0440\u043E\u0432\u0430\u043D\u0438\u0435 OpenAI",
      "OpenAI Logging Directory": "\u0414\u0438\u0440\u0435\u043A\u0442\u043E\u0440\u0438\u044F \u043B\u043E\u0433\u043E\u0432 OpenAI",
      Timeout: "\u0422\u0430\u0439\u043C\u0430\u0443\u0442",
      "Max Retries": "\u041C\u0430\u043A\u0441. \u043A\u043E\u043B\u0438\u0447\u0435\u0441\u0442\u0432\u043E \u043F\u043E\u043F\u044B\u0442\u043E\u043A",
      "Disable Cache Control": "\u041E\u0442\u043A\u043B\u044E\u0447\u0438\u0442\u044C \u0443\u043F\u0440\u0430\u0432\u043B\u0435\u043D\u0438\u0435 \u043A\u044D\u0448\u0435\u043C",
      "Memory Discovery Max Dirs": "\u041C\u0430\u043A\u0441. \u0434\u0438\u0440\u0435\u043A\u0442\u043E\u0440\u0438\u0439 \u0434\u043B\u044F \u043F\u043E\u0438\u0441\u043A\u0430 \u0432 \u043F\u0430\u043C\u044F\u0442\u0438",
      "Load Memory From Include Directories": "\u0417\u0430\u0433\u0440\u0443\u0436\u0430\u0442\u044C \u043F\u0430\u043C\u044F\u0442\u044C \u0438\u0437 \u0432\u043A\u043B\u044E\u0447\u0435\u043D\u043D\u044B\u0445 \u0434\u0438\u0440\u0435\u043A\u0442\u043E\u0440\u0438\u0439",
      "Respect .gitignore": "\u0423\u0447\u0438\u0442\u044B\u0432\u0430\u0442\u044C .gitignore",
      "Respect .qwenignore": "\u0423\u0447\u0438\u0442\u044B\u0432\u0430\u0442\u044C .qwenignore",
      "Enable Recursive File Search": "\u0412\u043A\u043B\u044E\u0447\u0438\u0442\u044C \u0440\u0435\u043A\u0443\u0440\u0441\u0438\u0432\u043D\u044B\u0439 \u043F\u043E\u0438\u0441\u043A \u0444\u0430\u0439\u043B\u043E\u0432",
      "Disable Fuzzy Search": "\u041E\u0442\u043A\u043B\u044E\u0447\u0438\u0442\u044C \u043D\u0435\u0447\u0435\u0442\u043A\u0438\u0439 \u043F\u043E\u0438\u0441\u043A",
      "Interactive Shell (PTY)": "\u0418\u043D\u0442\u0435\u0440\u0430\u043A\u0442\u0438\u0432\u043D\u044B\u0439 \u0442\u0435\u0440\u043C\u0438\u043D\u0430\u043B (PTY)",
      "Show Color": "\u041F\u043E\u043A\u0430\u0437\u044B\u0432\u0430\u0442\u044C \u0446\u0432\u0435\u0442\u0430",
      "Auto Accept": "\u0410\u0432\u0442\u043E\u043F\u043E\u0434\u0442\u0432\u0435\u0440\u0436\u0434\u0435\u043D\u0438\u0435",
      "Use Ripgrep": "\u0418\u0441\u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u0442\u044C Ripgrep",
      "Use Builtin Ripgrep": "\u0418\u0441\u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u0442\u044C \u0432\u0441\u0442\u0440\u043E\u0435\u043D\u043D\u044B\u0439 Ripgrep",
      "Enable Tool Output Truncation": "\u0412\u043A\u043B\u044E\u0447\u0438\u0442\u044C \u043E\u0431\u0440\u0435\u0437\u043A\u0443 \u0432\u044B\u0432\u043E\u0434\u0430 \u0438\u043D\u0441\u0442\u0440\u0443\u043C\u0435\u043D\u0442\u043E\u0432",
      "Tool Output Truncation Threshold": "\u041F\u043E\u0440\u043E\u0433 \u043E\u0431\u0440\u0435\u0437\u043A\u0438 \u0432\u044B\u0432\u043E\u0434\u0430 \u0438\u043D\u0441\u0442\u0440\u0443\u043C\u0435\u043D\u0442\u043E\u0432",
      "Tool Output Truncation Lines": "\u041B\u0438\u043C\u0438\u0442 \u0441\u0442\u0440\u043E\u043A \u0432\u044B\u0432\u043E\u0434\u0430 \u0438\u043D\u0441\u0442\u0440\u0443\u043C\u0435\u043D\u0442\u043E\u0432",
      "Folder Trust": "\u0414\u043E\u0432\u0435\u0440\u0438\u0435 \u043A \u043F\u0430\u043F\u043A\u0435",
      "Vision Model Preview": "\u0412\u0438\u0437\u0443\u0430\u043B\u044C\u043D\u0430\u044F \u043C\u043E\u0434\u0435\u043B\u044C (\u043F\u0440\u0435\u0434\u043F\u0440\u043E\u0441\u043C\u043E\u0442\u0440)",
      "Tool Schema Compliance": "\u0421\u043E\u043E\u0442\u0432\u0435\u0442\u0441\u0442\u0432\u0438\u0435 \u0441\u0445\u0435\u043C\u0435 \u0438\u043D\u0441\u0442\u0440\u0443\u043C\u0435\u043D\u0442\u0430",
      // Варианты перечислений настроек
      "Auto (detect from system)": "\u0410\u0432\u0442\u043E (\u043E\u043F\u0440\u0435\u0434\u0435\u043B\u0438\u0442\u044C \u0438\u0437 \u0441\u0438\u0441\u0442\u0435\u043C\u044B)",
      Text: "\u0422\u0435\u043A\u0441\u0442",
      JSON: "JSON",
      Plan: "\u041F\u043B\u0430\u043D",
      Default: "\u041F\u043E \u0443\u043C\u043E\u043B\u0447\u0430\u043D\u0438\u044E",
      "Auto Edit": "\u0410\u0432\u0442\u043E\u0440\u0435\u0434\u0430\u043A\u0442\u0438\u0440\u043E\u0432\u0430\u043D\u0438\u0435",
      YOLO: "YOLO",
      "toggle vim mode on/off": "\u0412\u043A\u043B\u044E\u0447\u0435\u043D\u0438\u0435/\u0432\u044B\u043A\u043B\u044E\u0447\u0435\u043D\u0438\u0435 \u0440\u0435\u0436\u0438\u043C\u0430 vim",
      "check session stats. Usage: /stats [model|tools]": "\u041F\u0440\u043E\u0441\u043C\u043E\u0442\u0440 \u0441\u0442\u0430\u0442\u0438\u0441\u0442\u0438\u043A\u0438 \u0441\u0435\u0441\u0441\u0438\u0438. \u0418\u0441\u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u043D\u0438\u0435: /stats [model|tools]",
      "Show model-specific usage statistics.": "\u041F\u043E\u043A\u0430\u0437\u0430\u0442\u044C \u0441\u0442\u0430\u0442\u0438\u0441\u0442\u0438\u043A\u0443 \u0438\u0441\u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u043D\u0438\u044F \u043C\u043E\u0434\u0435\u043B\u0438.",
      "Show tool-specific usage statistics.": "\u041F\u043E\u043A\u0430\u0437\u0430\u0442\u044C \u0441\u0442\u0430\u0442\u0438\u0441\u0442\u0438\u043A\u0443 \u0438\u0441\u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u043D\u0438\u044F \u0438\u043D\u0441\u0442\u0440\u0443\u043C\u0435\u043D\u0442\u043E\u0432.",
      "exit the cli": "\u0412\u044B\u0445\u043E\u0434 \u0438\u0437 CLI",
      "list configured MCP servers and tools, or authenticate with OAuth-enabled servers": "\u041F\u043E\u043A\u0430\u0437\u0430\u0442\u044C \u043D\u0430\u0441\u0442\u0440\u043E\u0435\u043D\u043D\u044B\u0435 MCP-\u0441\u0435\u0440\u0432\u0435\u0440\u044B \u0438 \u0438\u043D\u0441\u0442\u0440\u0443\u043C\u0435\u043D\u0442\u044B, \u0438\u043B\u0438 \u0430\u0432\u0442\u043E\u0440\u0438\u0437\u043E\u0432\u0430\u0442\u044C\u0441\u044F \u043D\u0430 \u0441\u0435\u0440\u0432\u0435\u0440\u0430\u0445 \u0441 \u043F\u043E\u0434\u0434\u0435\u0440\u0436\u043A\u043E\u0439 OAuth",
      "Manage workspace directories": "\u0423\u043F\u0440\u0430\u0432\u043B\u0435\u043D\u0438\u0435 \u0434\u0438\u0440\u0435\u043A\u0442\u043E\u0440\u0438\u044F\u043C\u0438 \u0440\u0430\u0431\u043E\u0447\u0435\u0433\u043E \u043F\u0440\u043E\u0441\u0442\u0440\u0430\u043D\u0441\u0442\u0432\u0430",
      "Add directories to the workspace. Use comma to separate multiple paths": "\u0414\u043E\u0431\u0430\u0432\u0438\u0442\u044C \u0434\u0438\u0440\u0435\u043A\u0442\u043E\u0440\u0438\u0438 \u0432 \u0440\u0430\u0431\u043E\u0447\u0435\u0435 \u043F\u0440\u043E\u0441\u0442\u0440\u0430\u043D\u0441\u0442\u0432\u043E. \u0418\u0441\u043F\u043E\u043B\u044C\u0437\u0443\u0439\u0442\u0435 \u0437\u0430\u043F\u044F\u0442\u0443\u044E \u0434\u043B\u044F \u0440\u0430\u0437\u0434\u0435\u043B\u0435\u043D\u0438\u044F \u043F\u0443\u0442\u0435\u0439",
      "Show all directories in the workspace": "\u041F\u043E\u043A\u0430\u0437\u0430\u0442\u044C \u0432\u0441\u0435 \u0434\u0438\u0440\u0435\u043A\u0442\u043E\u0440\u0438\u0438 \u0432 \u0440\u0430\u0431\u043E\u0447\u0435\u043C \u043F\u0440\u043E\u0441\u0442\u0440\u0430\u043D\u0441\u0442\u0432\u0435",
      "set external editor preference": "\u0423\u0441\u0442\u0430\u043D\u043E\u0432\u043A\u0430 \u043F\u0440\u0435\u0434\u043F\u043E\u0447\u0438\u0442\u0430\u0435\u043C\u043E\u0433\u043E \u0432\u043D\u0435\u0448\u043D\u0435\u0433\u043E \u0440\u0435\u0434\u0430\u043A\u0442\u043E\u0440\u0430",
      "Select Editor": "\u0412\u044B\u0431\u0440\u0430\u0442\u044C \u0440\u0435\u0434\u0430\u043A\u0442\u043E\u0440",
      "Editor Preference": "\u041D\u0430\u0441\u0442\u0440\u043E\u0439\u043A\u0430 \u0440\u0435\u0434\u0430\u043A\u0442\u043E\u0440\u0430",
      "These editors are currently supported. Please note that some editors cannot be used in sandbox mode.": "\u0412 \u043D\u0430\u0441\u0442\u043E\u044F\u0449\u0435\u0435 \u0432\u0440\u0435\u043C\u044F \u043F\u043E\u0434\u0434\u0435\u0440\u0436\u0438\u0432\u0430\u044E\u0442\u0441\u044F \u0441\u043B\u0435\u0434\u0443\u044E\u0449\u0438\u0435 \u0440\u0435\u0434\u0430\u043A\u0442\u043E\u0440\u044B. \u041E\u0431\u0440\u0430\u0442\u0438\u0442\u0435 \u0432\u043D\u0438\u043C\u0430\u043D\u0438\u0435, \u0447\u0442\u043E \u043D\u0435\u043A\u043E\u0442\u043E\u0440\u044B\u0435 \u0440\u0435\u0434\u0430\u043A\u0442\u043E\u0440\u044B \u043D\u0435\u043B\u044C\u0437\u044F \u0438\u0441\u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u0442\u044C \u0432 \u0440\u0435\u0436\u0438\u043C\u0435 \u043F\u0435\u0441\u043E\u0447\u043D\u0438\u0446\u044B.",
      "Your preferred editor is:": "\u0412\u0430\u0448 \u043F\u0440\u0435\u0434\u043F\u043E\u0447\u0438\u0442\u0430\u0435\u043C\u044B\u0439 \u0440\u0435\u0434\u0430\u043A\u0442\u043E\u0440:",
      "Manage extensions": "\u0423\u043F\u0440\u0430\u0432\u043B\u0435\u043D\u0438\u0435 \u0440\u0430\u0441\u0448\u0438\u0440\u0435\u043D\u0438\u044F\u043C\u0438",
      "List active extensions": "\u041F\u043E\u043A\u0430\u0437\u0430\u0442\u044C \u0430\u043A\u0442\u0438\u0432\u043D\u044B\u0435 \u0440\u0430\u0441\u0448\u0438\u0440\u0435\u043D\u0438\u044F",
      "Update extensions. Usage: update <extension-names>|--all": "\u041E\u0431\u043D\u043E\u0432\u0438\u0442\u044C \u0440\u0430\u0441\u0448\u0438\u0440\u0435\u043D\u0438\u044F. \u0418\u0441\u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u043D\u0438\u0435: update <extension-names>|--all",
      "Disable an extension": "\u041E\u0442\u043A\u043B\u044E\u0447\u0438\u0442\u044C \u0440\u0430\u0441\u0448\u0438\u0440\u0435\u043D\u0438\u0435",
      "Enable an extension": "\u0412\u043A\u043B\u044E\u0447\u0438\u0442\u044C \u0440\u0430\u0441\u0448\u0438\u0440\u0435\u043D\u0438\u0435",
      "Install an extension from a git repo or local path": "\u0423\u0441\u0442\u0430\u043D\u043E\u0432\u0438\u0442\u044C \u0440\u0430\u0441\u0448\u0438\u0440\u0435\u043D\u0438\u0435 \u0438\u0437 Git-\u0440\u0435\u043F\u043E\u0437\u0438\u0442\u043E\u0440\u0438\u044F \u0438\u043B\u0438 \u043B\u043E\u043A\u0430\u043B\u044C\u043D\u043E\u0433\u043E \u043F\u0443\u0442\u0438",
      "Uninstall an extension": "\u0423\u0434\u0430\u043B\u0438\u0442\u044C \u0440\u0430\u0441\u0448\u0438\u0440\u0435\u043D\u0438\u0435",
      "No extensions installed.": "\u0420\u0430\u0441\u0448\u0438\u0440\u0435\u043D\u0438\u044F \u043D\u0435 \u0443\u0441\u0442\u0430\u043D\u043E\u0432\u043B\u0435\u043D\u044B.",
      "Usage: /extensions update <extension-names>|--all": "\u0418\u0441\u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u043D\u0438\u0435: /extensions update <\u0438\u043C\u0435\u043D\u0430-\u0440\u0430\u0441\u0448\u0438\u0440\u0435\u043D\u0438\u0439>|--all",
      'Extension "{{name}}" not found.': '\u0420\u0430\u0441\u0448\u0438\u0440\u0435\u043D\u0438\u0435 "{{name}}" \u043D\u0435 \u043D\u0430\u0439\u0434\u0435\u043D\u043E.',
      "No extensions to update.": "\u041D\u0435\u0442 \u0440\u0430\u0441\u0448\u0438\u0440\u0435\u043D\u0438\u0439 \u0434\u043B\u044F \u043E\u0431\u043D\u043E\u0432\u043B\u0435\u043D\u0438\u044F.",
      "Usage: /extensions install <source>": "\u0418\u0441\u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u043D\u0438\u0435: /extensions install <\u0438\u0441\u0442\u043E\u0447\u043D\u0438\u043A>",
      'Installing extension from "{{source}}"...': '\u0423\u0441\u0442\u0430\u043D\u043E\u0432\u043A\u0430 \u0440\u0430\u0441\u0448\u0438\u0440\u0435\u043D\u0438\u044F \u0438\u0437 "{{source}}"...',
      'Extension "{{name}}" installed successfully.': '\u0420\u0430\u0441\u0448\u0438\u0440\u0435\u043D\u0438\u0435 "{{name}}" \u0443\u0441\u043F\u0435\u0448\u043D\u043E \u0443\u0441\u0442\u0430\u043D\u043E\u0432\u043B\u0435\u043D\u043E.',
      'Failed to install extension from "{{source}}": {{error}}': '\u041D\u0435 \u0443\u0434\u0430\u043B\u043E\u0441\u044C \u0443\u0441\u0442\u0430\u043D\u043E\u0432\u0438\u0442\u044C \u0440\u0430\u0441\u0448\u0438\u0440\u0435\u043D\u0438\u0435 \u0438\u0437 "{{source}}": {{error}}',
      "Usage: /extensions uninstall <extension-name>": "\u0418\u0441\u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u043D\u0438\u0435: /extensions uninstall <\u0438\u043C\u044F-\u0440\u0430\u0441\u0448\u0438\u0440\u0435\u043D\u0438\u044F>",
      'Uninstalling extension "{{name}}"...': '\u0423\u0434\u0430\u043B\u0435\u043D\u0438\u0435 \u0440\u0430\u0441\u0448\u0438\u0440\u0435\u043D\u0438\u044F "{{name}}"...',
      'Extension "{{name}}" uninstalled successfully.': '\u0420\u0430\u0441\u0448\u0438\u0440\u0435\u043D\u0438\u0435 "{{name}}" \u0443\u0441\u043F\u0435\u0448\u043D\u043E \u0443\u0434\u0430\u043B\u0435\u043D\u043E.',
      'Failed to uninstall extension "{{name}}": {{error}}': '\u041D\u0435 \u0443\u0434\u0430\u043B\u043E\u0441\u044C \u0443\u0434\u0430\u043B\u0438\u0442\u044C \u0440\u0430\u0441\u0448\u0438\u0440\u0435\u043D\u0438\u0435 "{{name}}": {{error}}',
      "Usage: /extensions {{command}} <extension> [--scope=<user|workspace>]": "\u0418\u0441\u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u043D\u0438\u0435: /extensions {{command}} <\u0440\u0430\u0441\u0448\u0438\u0440\u0435\u043D\u0438\u0435> [--scope=<user|workspace>]",
      'Unsupported scope "{{scope}}", should be one of "user" or "workspace"': '\u041D\u0435\u043F\u043E\u0434\u0434\u0435\u0440\u0436\u0438\u0432\u0430\u0435\u043C\u0430\u044F \u043E\u0431\u043B\u0430\u0441\u0442\u044C "{{scope}}", \u0434\u043E\u043B\u0436\u043D\u0430 \u0431\u044B\u0442\u044C "user" \u0438\u043B\u0438 "workspace"',
      'Extension "{{name}}" disabled for scope "{{scope}}"': '\u0420\u0430\u0441\u0448\u0438\u0440\u0435\u043D\u0438\u0435 "{{name}}" \u043E\u0442\u043A\u043B\u044E\u0447\u0435\u043D\u043E \u0434\u043B\u044F \u043E\u0431\u043B\u0430\u0441\u0442\u0438 "{{scope}}"',
      'Extension "{{name}}" enabled for scope "{{scope}}"': '\u0420\u0430\u0441\u0448\u0438\u0440\u0435\u043D\u0438\u0435 "{{name}}" \u0432\u043A\u043B\u044E\u0447\u0435\u043D\u043E \u0434\u043B\u044F \u043E\u0431\u043B\u0430\u0441\u0442\u0438 "{{scope}}"',
      "Do you want to continue? [Y/n]: ": "\u0425\u043E\u0442\u0438\u0442\u0435 \u043F\u0440\u043E\u0434\u043E\u043B\u0436\u0438\u0442\u044C? [Y/n]: ",
      "Do you want to continue?": "\u0425\u043E\u0442\u0438\u0442\u0435 \u043F\u0440\u043E\u0434\u043E\u043B\u0436\u0438\u0442\u044C?",
      'Installing extension "{{name}}".': '\u0423\u0441\u0442\u0430\u043D\u043E\u0432\u043A\u0430 \u0440\u0430\u0441\u0448\u0438\u0440\u0435\u043D\u0438\u044F "{{name}}".',
      "**Extensions may introduce unexpected behavior. Ensure you have investigated the extension source and trust the author.**": "**\u0420\u0430\u0441\u0448\u0438\u0440\u0435\u043D\u0438\u044F \u043C\u043E\u0433\u0443\u0442 \u0432\u044B\u0437\u044B\u0432\u0430\u0442\u044C \u043D\u0435\u043E\u0436\u0438\u0434\u0430\u043D\u043D\u043E\u0435 \u043F\u043E\u0432\u0435\u0434\u0435\u043D\u0438\u0435. \u0423\u0431\u0435\u0434\u0438\u0442\u0435\u0441\u044C, \u0447\u0442\u043E \u0432\u044B \u0438\u0437\u0443\u0447\u0438\u043B\u0438 \u0438\u0441\u0442\u043E\u0447\u043D\u0438\u043A \u0440\u0430\u0441\u0448\u0438\u0440\u0435\u043D\u0438\u044F \u0438 \u0434\u043E\u0432\u0435\u0440\u044F\u0435\u0442\u0435 \u0430\u0432\u0442\u043E\u0440\u0443.**",
      "This extension will run the following MCP servers:": "\u042D\u0442\u043E \u0440\u0430\u0441\u0448\u0438\u0440\u0435\u043D\u0438\u0435 \u0437\u0430\u043F\u0443\u0441\u0442\u0438\u0442 \u0441\u043B\u0435\u0434\u0443\u044E\u0449\u0438\u0435 MCP-\u0441\u0435\u0440\u0432\u0435\u0440\u044B:",
      local: "\u043B\u043E\u043A\u0430\u043B\u044C\u043D\u044B\u0439",
      remote: "\u0443\u0434\u0430\u043B\u0451\u043D\u043D\u044B\u0439",
      "This extension will add the following commands: {{commands}}.": "\u042D\u0442\u043E \u0440\u0430\u0441\u0448\u0438\u0440\u0435\u043D\u0438\u0435 \u0434\u043E\u0431\u0430\u0432\u0438\u0442 \u0441\u043B\u0435\u0434\u0443\u044E\u0449\u0438\u0435 \u043A\u043E\u043C\u0430\u043D\u0434\u044B: {{commands}}.",
      "This extension will append info to your QWEN.md context using {{fileName}}": "\u042D\u0442\u043E \u0440\u0430\u0441\u0448\u0438\u0440\u0435\u043D\u0438\u0435 \u0434\u043E\u0431\u0430\u0432\u0438\u0442 \u0438\u043D\u0444\u043E\u0440\u043C\u0430\u0446\u0438\u044E \u0432 \u0432\u0430\u0448 \u043A\u043E\u043D\u0442\u0435\u043A\u0441\u0442 QWEN.md \u0441 \u043F\u043E\u043C\u043E\u0449\u044C\u044E {{fileName}}",
      "This extension will exclude the following core tools: {{tools}}": "\u042D\u0442\u043E \u0440\u0430\u0441\u0448\u0438\u0440\u0435\u043D\u0438\u0435 \u0438\u0441\u043A\u043B\u044E\u0447\u0438\u0442 \u0441\u043B\u0435\u0434\u0443\u044E\u0449\u0438\u0435 \u043E\u0441\u043D\u043E\u0432\u043D\u044B\u0435 \u0438\u043D\u0441\u0442\u0440\u0443\u043C\u0435\u043D\u0442\u044B: {{tools}}",
      "This extension will install the following skills:": "\u042D\u0442\u043E \u0440\u0430\u0441\u0448\u0438\u0440\u0435\u043D\u0438\u0435 \u0443\u0441\u0442\u0430\u043D\u043E\u0432\u0438\u0442 \u0441\u043B\u0435\u0434\u0443\u044E\u0449\u0438\u0435 \u043D\u0430\u0432\u044B\u043A\u0438:",
      "This extension will install the following subagents:": "\u042D\u0442\u043E \u0440\u0430\u0441\u0448\u0438\u0440\u0435\u043D\u0438\u0435 \u0443\u0441\u0442\u0430\u043D\u043E\u0432\u0438\u0442 \u0441\u043B\u0435\u0434\u0443\u044E\u0449\u0438\u0435 \u043F\u043E\u0434\u0430\u0433\u0435\u043D\u0442\u044B:",
      'Installation cancelled for "{{name}}".': '\u0423\u0441\u0442\u0430\u043D\u043E\u0432\u043A\u0430 "{{name}}" \u043E\u0442\u043C\u0435\u043D\u0435\u043D\u0430.',
      "You are installing an extension from {{originSource}}. Some features may not work perfectly with Qwen Code.": "\u0412\u044B \u0443\u0441\u0442\u0430\u043D\u0430\u0432\u043B\u0438\u0432\u0430\u0435\u0442\u0435 \u0440\u0430\u0441\u0448\u0438\u0440\u0435\u043D\u0438\u0435 \u043E\u0442 {{originSource}}. \u041D\u0435\u043A\u043E\u0442\u043E\u0440\u044B\u0435 \u0444\u0443\u043D\u043A\u0446\u0438\u0438 \u043C\u043E\u0433\u0443\u0442 \u0440\u0430\u0431\u043E\u0442\u0430\u0442\u044C \u043D\u0435 \u0438\u0434\u0435\u0430\u043B\u044C\u043D\u043E \u0441 Qwen Code.",
      "--ref and --auto-update are not applicable for marketplace extensions.": "--ref \u0438 --auto-update \u043D\u0435\u043F\u0440\u0438\u043C\u0435\u043D\u0438\u043C\u044B \u0434\u043B\u044F \u0440\u0430\u0441\u0448\u0438\u0440\u0435\u043D\u0438\u0439 \u0438\u0437 \u043C\u0430\u0440\u043A\u0435\u0442\u043F\u043B\u0435\u0439\u0441\u0430.",
      'Extension "{{name}}" installed successfully and enabled.': '\u0420\u0430\u0441\u0448\u0438\u0440\u0435\u043D\u0438\u0435 "{{name}}" \u0443\u0441\u043F\u0435\u0448\u043D\u043E \u0443\u0441\u0442\u0430\u043D\u043E\u0432\u043B\u0435\u043D\u043E \u0438 \u0432\u043A\u043B\u044E\u0447\u0435\u043D\u043E.',
      "Installs an extension from a git repository URL, local path, or claude marketplace (marketplace-url:plugin-name).": "\u0423\u0441\u0442\u0430\u043D\u0430\u0432\u043B\u0438\u0432\u0430\u0435\u0442 \u0440\u0430\u0441\u0448\u0438\u0440\u0435\u043D\u0438\u0435 \u0438\u0437 URL Git-\u0440\u0435\u043F\u043E\u0437\u0438\u0442\u043E\u0440\u0438\u044F, \u043B\u043E\u043A\u0430\u043B\u044C\u043D\u043E\u0433\u043E \u043F\u0443\u0442\u0438 \u0438\u043B\u0438 \u043C\u0430\u0440\u043A\u0435\u0442\u043F\u043B\u0435\u0439\u0441\u0430 Claude (marketplace-url:plugin-name).",
      "The github URL, local path, or marketplace source (marketplace-url:plugin-name) of the extension to install.": "URL GitHub, \u043B\u043E\u043A\u0430\u043B\u044C\u043D\u044B\u0439 \u043F\u0443\u0442\u044C \u0438\u043B\u0438 \u0438\u0441\u0442\u043E\u0447\u043D\u0438\u043A \u0432 \u043C\u0430\u0440\u043A\u0435\u0442\u043F\u043B\u0435\u0439\u0441\u0435 (marketplace-url:plugin-name) \u0443\u0441\u0442\u0430\u043D\u0430\u0432\u043B\u0438\u0432\u0430\u0435\u043C\u043E\u0433\u043E \u0440\u0430\u0441\u0448\u0438\u0440\u0435\u043D\u0438\u044F.",
      "The git ref to install from.": "Git-\u0441\u0441\u044B\u043B\u043A\u0430 \u0434\u043B\u044F \u0443\u0441\u0442\u0430\u043D\u043E\u0432\u043A\u0438.",
      "Enable auto-update for this extension.": "\u0412\u043A\u043B\u044E\u0447\u0438\u0442\u044C \u0430\u0432\u0442\u043E\u043E\u0431\u043D\u043E\u0432\u043B\u0435\u043D\u0438\u0435 \u0434\u043B\u044F \u044D\u0442\u043E\u0433\u043E \u0440\u0430\u0441\u0448\u0438\u0440\u0435\u043D\u0438\u044F.",
      "Enable pre-release versions for this extension.": "\u0412\u043A\u043B\u044E\u0447\u0438\u0442\u044C \u043F\u0440\u0435-\u0440\u0435\u043B\u0438\u0437\u043D\u044B\u0435 \u0432\u0435\u0440\u0441\u0438\u0438 \u0434\u043B\u044F \u044D\u0442\u043E\u0433\u043E \u0440\u0430\u0441\u0448\u0438\u0440\u0435\u043D\u0438\u044F.",
      "Acknowledge the security risks of installing an extension and skip the confirmation prompt.": "\u041F\u043E\u0434\u0442\u0432\u0435\u0440\u0434\u0438\u0442\u044C \u0440\u0438\u0441\u043A\u0438 \u0431\u0435\u0437\u043E\u043F\u0430\u0441\u043D\u043E\u0441\u0442\u0438 \u0443\u0441\u0442\u0430\u043D\u043E\u0432\u043A\u0438 \u0440\u0430\u0441\u0448\u0438\u0440\u0435\u043D\u0438\u044F \u0438 \u043F\u0440\u043E\u043F\u0443\u0441\u0442\u0438\u0442\u044C \u0437\u0430\u043F\u0440\u043E\u0441 \u043F\u043E\u0434\u0442\u0432\u0435\u0440\u0436\u0434\u0435\u043D\u0438\u044F.",
      "The source argument must be provided.": "\u041D\u0435\u043E\u0431\u0445\u043E\u0434\u0438\u043C\u043E \u0443\u043A\u0430\u0437\u0430\u0442\u044C \u0430\u0440\u0433\u0443\u043C\u0435\u043D\u0442 \u0438\u0441\u0442\u043E\u0447\u043D\u0438\u043A\u0430.",
      'Extension "{{name}}" successfully uninstalled.': '\u0420\u0430\u0441\u0448\u0438\u0440\u0435\u043D\u0438\u0435 "{{name}}" \u0443\u0441\u043F\u0435\u0448\u043D\u043E \u0443\u0434\u0430\u043B\u0435\u043D\u043E.',
      "Uninstalls an extension.": "\u0423\u0434\u0430\u043B\u044F\u0435\u0442 \u0440\u0430\u0441\u0448\u0438\u0440\u0435\u043D\u0438\u0435.",
      "The name or source path of the extension to uninstall.": "\u0418\u043C\u044F \u0438\u043B\u0438 \u043F\u0443\u0442\u044C \u043A \u0438\u0441\u0442\u043E\u0447\u043D\u0438\u043A\u0443 \u0443\u0434\u0430\u043B\u044F\u0435\u043C\u043E\u0433\u043E \u0440\u0430\u0441\u0448\u0438\u0440\u0435\u043D\u0438\u044F.",
      "Please include the name of the extension to uninstall as a positional argument.": "\u041F\u043E\u0436\u0430\u043B\u0443\u0439\u0441\u0442\u0430, \u0443\u043A\u0430\u0436\u0438\u0442\u0435 \u0438\u043C\u044F \u0443\u0434\u0430\u043B\u044F\u0435\u043C\u043E\u0433\u043E \u0440\u0430\u0441\u0448\u0438\u0440\u0435\u043D\u0438\u044F \u043A\u0430\u043A \u043F\u043E\u0437\u0438\u0446\u0438\u043E\u043D\u043D\u044B\u0439 \u0430\u0440\u0433\u0443\u043C\u0435\u043D\u0442.",
      "Enables an extension.": "\u0412\u043A\u043B\u044E\u0447\u0430\u0435\u0442 \u0440\u0430\u0441\u0448\u0438\u0440\u0435\u043D\u0438\u0435.",
      "The name of the extension to enable.": "\u0418\u043C\u044F \u0432\u043A\u043B\u044E\u0447\u0430\u0435\u043C\u043E\u0433\u043E \u0440\u0430\u0441\u0448\u0438\u0440\u0435\u043D\u0438\u044F.",
      "The scope to enable the extenison in. If not set, will be enabled in all scopes.": "\u041E\u0431\u043B\u0430\u0441\u0442\u044C \u0434\u043B\u044F \u0432\u043A\u043B\u044E\u0447\u0435\u043D\u0438\u044F \u0440\u0430\u0441\u0448\u0438\u0440\u0435\u043D\u0438\u044F. \u0415\u0441\u043B\u0438 \u043D\u0435 \u0437\u0430\u0434\u0430\u043D\u0430, \u0431\u0443\u0434\u0435\u0442 \u0432\u043A\u043B\u044E\u0447\u0435\u043D\u043E \u0432\u043E \u0432\u0441\u0435\u0445 \u043E\u0431\u043B\u0430\u0441\u0442\u044F\u0445.",
      'Extension "{{name}}" successfully enabled for scope "{{scope}}".': '\u0420\u0430\u0441\u0448\u0438\u0440\u0435\u043D\u0438\u0435 "{{name}}" \u0443\u0441\u043F\u0435\u0448\u043D\u043E \u0432\u043A\u043B\u044E\u0447\u0435\u043D\u043E \u0434\u043B\u044F \u043E\u0431\u043B\u0430\u0441\u0442\u0438 "{{scope}}".',
      'Extension "{{name}}" successfully enabled in all scopes.': '\u0420\u0430\u0441\u0448\u0438\u0440\u0435\u043D\u0438\u0435 "{{name}}" \u0443\u0441\u043F\u0435\u0448\u043D\u043E \u0432\u043A\u043B\u044E\u0447\u0435\u043D\u043E \u0432\u043E \u0432\u0441\u0435\u0445 \u043E\u0431\u043B\u0430\u0441\u0442\u044F\u0445.',
      "Invalid scope: {{scope}}. Please use one of {{scopes}}.": "\u041D\u0435\u0434\u043E\u043F\u0443\u0441\u0442\u0438\u043C\u0430\u044F \u043E\u0431\u043B\u0430\u0441\u0442\u044C: {{scope}}. \u041F\u043E\u0436\u0430\u043B\u0443\u0439\u0441\u0442\u0430, \u0438\u0441\u043F\u043E\u043B\u044C\u0437\u0443\u0439\u0442\u0435 \u043E\u0434\u043D\u0443 \u0438\u0437 {{scopes}}.",
      "Disables an extension.": "\u041E\u0442\u043A\u043B\u044E\u0447\u0430\u0435\u0442 \u0440\u0430\u0441\u0448\u0438\u0440\u0435\u043D\u0438\u0435.",
      "The name of the extension to disable.": "\u0418\u043C\u044F \u043E\u0442\u043A\u043B\u044E\u0447\u0430\u0435\u043C\u043E\u0433\u043E \u0440\u0430\u0441\u0448\u0438\u0440\u0435\u043D\u0438\u044F.",
      "The scope to disable the extenison in.": "\u041E\u0431\u043B\u0430\u0441\u0442\u044C \u0434\u043B\u044F \u043E\u0442\u043A\u043B\u044E\u0447\u0435\u043D\u0438\u044F \u0440\u0430\u0441\u0448\u0438\u0440\u0435\u043D\u0438\u044F.",
      'Extension "{{name}}" successfully disabled for scope "{{scope}}".': '\u0420\u0430\u0441\u0448\u0438\u0440\u0435\u043D\u0438\u0435 "{{name}}" \u0443\u0441\u043F\u0435\u0448\u043D\u043E \u043E\u0442\u043A\u043B\u044E\u0447\u0435\u043D\u043E \u0434\u043B\u044F \u043E\u0431\u043B\u0430\u0441\u0442\u0438 "{{scope}}".',
      'Extension "{{name}}" successfully updated: {{oldVersion}} \u2192 {{newVersion}}.': '\u0420\u0430\u0441\u0448\u0438\u0440\u0435\u043D\u0438\u0435 "{{name}}" \u0443\u0441\u043F\u0435\u0448\u043D\u043E \u043E\u0431\u043D\u043E\u0432\u043B\u0435\u043D\u043E: {{oldVersion}} \u2192 {{newVersion}}.',
      'Unable to install extension "{{name}}" due to missing install metadata': '\u041D\u0435\u0432\u043E\u0437\u043C\u043E\u0436\u043D\u043E \u0443\u0441\u0442\u0430\u043D\u043E\u0432\u0438\u0442\u044C \u0440\u0430\u0441\u0448\u0438\u0440\u0435\u043D\u0438\u0435 "{{name}}" \u0438\u0437-\u0437\u0430 \u043E\u0442\u0441\u0443\u0442\u0441\u0442\u0432\u0438\u044F \u043C\u0435\u0442\u0430\u0434\u0430\u043D\u043D\u044B\u0445 \u0443\u0441\u0442\u0430\u043D\u043E\u0432\u043A\u0438',
      'Extension "{{name}}" is already up to date.': '\u0420\u0430\u0441\u0448\u0438\u0440\u0435\u043D\u0438\u0435 "{{name}}" \u0443\u0436\u0435 \u0430\u043A\u0442\u0443\u0430\u043B\u044C\u043D\u043E.',
      "Updates all extensions or a named extension to the latest version.": "\u041E\u0431\u043D\u043E\u0432\u043B\u044F\u0435\u0442 \u0432\u0441\u0435 \u0440\u0430\u0441\u0448\u0438\u0440\u0435\u043D\u0438\u044F \u0438\u043B\u0438 \u0443\u043A\u0430\u0437\u0430\u043D\u043D\u043E\u0435 \u0440\u0430\u0441\u0448\u0438\u0440\u0435\u043D\u0438\u0435 \u0434\u043E \u043F\u043E\u0441\u043B\u0435\u0434\u043D\u0435\u0439 \u0432\u0435\u0440\u0441\u0438\u0438.",
      "The name of the extension to update.": "\u0418\u043C\u044F \u043E\u0431\u043D\u043E\u0432\u043B\u044F\u0435\u043C\u043E\u0433\u043E \u0440\u0430\u0441\u0448\u0438\u0440\u0435\u043D\u0438\u044F.",
      "Update all extensions.": "\u041E\u0431\u043D\u043E\u0432\u0438\u0442\u044C \u0432\u0441\u0435 \u0440\u0430\u0441\u0448\u0438\u0440\u0435\u043D\u0438\u044F.",
      "Either an extension name or --all must be provided": "\u041D\u0435\u043E\u0431\u0445\u043E\u0434\u0438\u043C\u043E \u0443\u043A\u0430\u0437\u0430\u0442\u044C \u0438\u043C\u044F \u0440\u0430\u0441\u0448\u0438\u0440\u0435\u043D\u0438\u044F \u0438\u043B\u0438 --all",
      "Lists installed extensions.": "\u041F\u043E\u043A\u0430\u0437\u044B\u0432\u0430\u0435\u0442 \u0443\u0441\u0442\u0430\u043D\u043E\u0432\u043B\u0435\u043D\u043D\u044B\u0435 \u0440\u0430\u0441\u0448\u0438\u0440\u0435\u043D\u0438\u044F.",
      "Path:": "\u041F\u0443\u0442\u044C:",
      "Source:": "\u0418\u0441\u0442\u043E\u0447\u043D\u0438\u043A:",
      "Type:": "\u0422\u0438\u043F:",
      "Ref:": "\u0421\u0441\u044B\u043B\u043A\u0430:",
      "Release tag:": "\u0422\u0435\u0433 \u0440\u0435\u043B\u0438\u0437\u0430:",
      "Enabled (User):": "\u0412\u043A\u043B\u044E\u0447\u0435\u043D\u043E (\u041F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u0442\u0435\u043B\u044C):",
      "Enabled (Workspace):": "\u0412\u043A\u043B\u044E\u0447\u0435\u043D\u043E (\u0420\u0430\u0431\u043E\u0447\u0435\u0435 \u043F\u0440\u043E\u0441\u0442\u0440\u0430\u043D\u0441\u0442\u0432\u043E):",
      "Context files:": "\u041A\u043E\u043D\u0442\u0435\u043A\u0441\u0442\u043D\u044B\u0435 \u0444\u0430\u0439\u043B\u044B:",
      "Skills:": "\u041D\u0430\u0432\u044B\u043A\u0438:",
      "Agents:": "\u0410\u0433\u0435\u043D\u0442\u044B:",
      "MCP servers:": "MCP-\u0441\u0435\u0440\u0432\u0435\u0440\u044B:",
      "Link extension failed to install.": "\u041D\u0435 \u0443\u0434\u0430\u043B\u043E\u0441\u044C \u0443\u0441\u0442\u0430\u043D\u043E\u0432\u0438\u0442\u044C \u0441\u0432\u044F\u0437\u0430\u043D\u043D\u043E\u0435 \u0440\u0430\u0441\u0448\u0438\u0440\u0435\u043D\u0438\u0435.",
      'Extension "{{name}}" linked successfully and enabled.': '\u0420\u0430\u0441\u0448\u0438\u0440\u0435\u043D\u0438\u0435 "{{name}}" \u0443\u0441\u043F\u0435\u0448\u043D\u043E \u0441\u0432\u044F\u0437\u0430\u043D\u043E \u0438 \u0432\u043A\u043B\u044E\u0447\u0435\u043D\u043E.',
      "Links an extension from a local path. Updates made to the local path will always be reflected.": "\u0421\u0432\u044F\u0437\u044B\u0432\u0430\u0435\u0442 \u0440\u0430\u0441\u0448\u0438\u0440\u0435\u043D\u0438\u0435 \u0438\u0437 \u043B\u043E\u043A\u0430\u043B\u044C\u043D\u043E\u0433\u043E \u043F\u0443\u0442\u0438. \u0418\u0437\u043C\u0435\u043D\u0435\u043D\u0438\u044F \u0432 \u043B\u043E\u043A\u0430\u043B\u044C\u043D\u043E\u043C \u043F\u0443\u0442\u0438 \u0431\u0443\u0434\u0443\u0442 \u0432\u0441\u0435\u0433\u0434\u0430 \u043E\u0442\u0440\u0430\u0436\u0430\u0442\u044C\u0441\u044F.",
      "The name of the extension to link.": "\u0418\u043C\u044F \u0441\u0432\u044F\u0437\u044B\u0432\u0430\u0435\u043C\u043E\u0433\u043E \u0440\u0430\u0441\u0448\u0438\u0440\u0435\u043D\u0438\u044F.",
      "Set a specific setting for an extension.": "\u0423\u0441\u0442\u0430\u043D\u043E\u0432\u0438\u0442\u044C \u043A\u043E\u043D\u043A\u0440\u0435\u0442\u043D\u0443\u044E \u043D\u0430\u0441\u0442\u0440\u043E\u0439\u043A\u0443 \u0434\u043B\u044F \u0440\u0430\u0441\u0448\u0438\u0440\u0435\u043D\u0438\u044F.",
      "Name of the extension to configure.": "\u0418\u043C\u044F \u043D\u0430\u0441\u0442\u0440\u0430\u0438\u0432\u0430\u0435\u043C\u043E\u0433\u043E \u0440\u0430\u0441\u0448\u0438\u0440\u0435\u043D\u0438\u044F.",
      "The setting to configure (name or env var).": "\u041D\u0430\u0441\u0442\u0440\u043E\u0439\u043A\u0430 \u0434\u043B\u044F \u043A\u043E\u043D\u0444\u0438\u0433\u0443\u0440\u0438\u0440\u043E\u0432\u0430\u043D\u0438\u044F (\u0438\u043C\u044F \u0438\u043B\u0438 \u043F\u0435\u0440\u0435\u043C\u0435\u043D\u043D\u0430\u044F \u043E\u043A\u0440\u0443\u0436\u0435\u043D\u0438\u044F).",
      "The scope to set the setting in.": "\u041E\u0431\u043B\u0430\u0441\u0442\u044C \u0434\u043B\u044F \u0443\u0441\u0442\u0430\u043D\u043E\u0432\u043A\u0438 \u043D\u0430\u0441\u0442\u0440\u043E\u0439\u043A\u0438.",
      "List all settings for an extension.": "\u041F\u043E\u043A\u0430\u0437\u0430\u0442\u044C \u0432\u0441\u0435 \u043D\u0430\u0441\u0442\u0440\u043E\u0439\u043A\u0438 \u0440\u0430\u0441\u0448\u0438\u0440\u0435\u043D\u0438\u044F.",
      "Name of the extension.": "\u0418\u043C\u044F \u0440\u0430\u0441\u0448\u0438\u0440\u0435\u043D\u0438\u044F.",
      'Extension "{{name}}" has no settings to configure.': '\u0420\u0430\u0441\u0448\u0438\u0440\u0435\u043D\u0438\u0435 "{{name}}" \u043D\u0435 \u0438\u043C\u0435\u0435\u0442 \u043D\u0430\u0441\u0442\u0440\u043E\u0435\u043A \u0434\u043B\u044F \u043A\u043E\u043D\u0444\u0438\u0433\u0443\u0440\u0438\u0440\u043E\u0432\u0430\u043D\u0438\u044F.',
      'Settings for "{{name}}":': '\u041D\u0430\u0441\u0442\u0440\u043E\u0439\u043A\u0438 \u0434\u043B\u044F "{{name}}":',
      "(workspace)": "(\u0440\u0430\u0431\u043E\u0447\u0435\u0435 \u043F\u0440\u043E\u0441\u0442\u0440\u0430\u043D\u0441\u0442\u0432\u043E)",
      "(user)": "(\u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u0442\u0435\u043B\u044C)",
      "[not set]": "[\u043D\u0435 \u0437\u0430\u0434\u0430\u043D\u043E]",
      "[value stored in keychain]": "[\u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435 \u0445\u0440\u0430\u043D\u0438\u0442\u0441\u044F \u0432 \u0441\u0432\u044F\u0437\u043A\u0435 \u043A\u043B\u044E\u0447\u0435\u0439]",
      "Manage extension settings.": "\u0423\u043F\u0440\u0430\u0432\u043B\u0435\u043D\u0438\u0435 \u043D\u0430\u0441\u0442\u0440\u043E\u0439\u043A\u0430\u043C\u0438 \u0440\u0430\u0441\u0448\u0438\u0440\u0435\u043D\u0438\u0439.",
      "You need to specify a command (set or list).": "\u041D\u0435\u043E\u0431\u0445\u043E\u0434\u0438\u043C\u043E \u0443\u043A\u0430\u0437\u0430\u0442\u044C \u043A\u043E\u043C\u0430\u043D\u0434\u0443 (set \u0438\u043B\u0438 list).",
      // ============================================================================
      // Plugin Choice / Marketplace
      // ============================================================================
      "No plugins available in this marketplace.": "\u0412 \u044D\u0442\u043E\u043C \u043C\u0430\u0440\u043A\u0435\u0442\u043F\u043B\u0435\u0439\u0441\u0435 \u043D\u0435\u0442 \u0434\u043E\u0441\u0442\u0443\u043F\u043D\u044B\u0445 \u043F\u043B\u0430\u0433\u0438\u043D\u043E\u0432.",
      'Select a plugin to install from marketplace "{{name}}":': '\u0412\u044B\u0431\u0435\u0440\u0438\u0442\u0435 \u043F\u043B\u0430\u0433\u0438\u043D \u0434\u043B\u044F \u0443\u0441\u0442\u0430\u043D\u043E\u0432\u043A\u0438 \u0438\u0437 \u043C\u0430\u0440\u043A\u0435\u0442\u043F\u043B\u0435\u0439\u0441\u0430 "{{name}}":',
      "Plugin selection cancelled.": "\u0412\u044B\u0431\u043E\u0440 \u043F\u043B\u0430\u0433\u0438\u043D\u0430 \u043E\u0442\u043C\u0435\u043D\u0451\u043D.",
      'Select a plugin from "{{name}}"': '\u0412\u044B\u0431\u0435\u0440\u0438\u0442\u0435 \u043F\u043B\u0430\u0433\u0438\u043D \u0438\u0437 "{{name}}"',
      "Use \u2191\u2193 or j/k to navigate, Enter to select, Escape to cancel": "\u0418\u0441\u043F\u043E\u043B\u044C\u0437\u0443\u0439\u0442\u0435 \u2191\u2193 \u0438\u043B\u0438 j/k \u0434\u043B\u044F \u043D\u0430\u0432\u0438\u0433\u0430\u0446\u0438\u0438, Enter \u0434\u043B\u044F \u0432\u044B\u0431\u043E\u0440\u0430, Escape \u0434\u043B\u044F \u043E\u0442\u043C\u0435\u043D\u044B",
      "{{count}} more above": "\u0435\u0449\u0451 {{count}} \u0432\u044B\u0448\u0435",
      "{{count}} more below": "\u0435\u0449\u0451 {{count}} \u043D\u0438\u0436\u0435",
      "manage IDE integration": "\u0423\u043F\u0440\u0430\u0432\u043B\u0435\u043D\u0438\u0435 \u0438\u043D\u0442\u0435\u0433\u0440\u0430\u0446\u0438\u0435\u0439 \u0441 IDE",
      "check status of IDE integration": "\u041F\u0440\u043E\u0432\u0435\u0440\u0438\u0442\u044C \u0441\u0442\u0430\u0442\u0443\u0441 \u0438\u043D\u0442\u0435\u0433\u0440\u0430\u0446\u0438\u0438 \u0441 IDE",
      "install required IDE companion for {{ideName}}": "\u0423\u0441\u0442\u0430\u043D\u043E\u0432\u0438\u0442\u044C \u043D\u0435\u043E\u0431\u0445\u043E\u0434\u0438\u043C\u044B\u0439 \u043A\u043E\u043C\u043F\u0430\u043D\u044C\u043E\u043D IDE \u0434\u043B\u044F {{ideName}}",
      "enable IDE integration": "\u0412\u043A\u043B\u044E\u0447\u0435\u043D\u0438\u0435 \u0438\u043D\u0442\u0435\u0433\u0440\u0430\u0446\u0438\u0438 \u0441 IDE",
      "disable IDE integration": "\u041E\u0442\u043A\u043B\u044E\u0447\u0435\u043D\u0438\u0435 \u0438\u043D\u0442\u0435\u0433\u0440\u0430\u0446\u0438\u0438 \u0441 IDE",
      "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.": "\u0418\u043D\u0442\u0435\u0433\u0440\u0430\u0446\u0438\u044F \u0441 IDE \u043D\u0435 \u043F\u043E\u0434\u0434\u0435\u0440\u0436\u0438\u0432\u0430\u0435\u0442\u0441\u044F \u0432 \u0432\u0430\u0448\u0435\u043C \u043E\u043A\u0440\u0443\u0436\u0435\u043D\u0438\u0438. \u0414\u043B\u044F \u0438\u0441\u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u043D\u0438\u044F \u044D\u0442\u043E\u0439 \u0444\u0443\u043D\u043A\u0446\u0438\u0438 \u0437\u0430\u043F\u0443\u0441\u0442\u0438\u0442\u0435 Qwen Code \u0432 \u043E\u0434\u043D\u043E\u0439 \u0438\u0437 \u043F\u043E\u0434\u0434\u0435\u0440\u0436\u0438\u0432\u0430\u0435\u043C\u044B\u0445 IDE: VS Code \u0438\u043B\u0438 \u0444\u043E\u0440\u043A\u0430\u0445 VS Code.",
      "Set up GitHub Actions": "\u041D\u0430\u0441\u0442\u0440\u043E\u0439\u043A\u0430 GitHub Actions",
      "Configure terminal keybindings for multiline input (VS Code, Cursor, Windsurf, Trae)": "\u041D\u0430\u0441\u0442\u0440\u043E\u0439\u043A\u0430 \u043F\u0440\u0438\u0432\u044F\u0437\u043A\u0438 \u043A\u043B\u0430\u0432\u0438\u0448 \u0442\u0435\u0440\u043C\u0438\u043D\u0430\u043B\u0430 \u0434\u043B\u044F \u043C\u043D\u043E\u0433\u043E\u0441\u0442\u0440\u043E\u0447\u043D\u043E\u0433\u043E \u0432\u0432\u043E\u0434\u0430 (VS Code, Cursor, Windsurf, Trae)",
      "Please restart your terminal for the changes to take effect.": "\u041F\u043E\u0436\u0430\u043B\u0443\u0439\u0441\u0442\u0430, \u043F\u0435\u0440\u0435\u0437\u0430\u043F\u0443\u0441\u0442\u0438\u0442\u0435 \u0442\u0435\u0440\u043C\u0438\u043D\u0430\u043B \u0434\u043B\u044F \u043F\u0440\u0438\u043C\u0435\u043D\u0435\u043D\u0438\u044F \u0438\u0437\u043C\u0435\u043D\u0435\u043D\u0438\u0439.",
      "Failed to configure terminal: {{error}}": "\u041D\u0435 \u0443\u0434\u0430\u043B\u043E\u0441\u044C \u043D\u0430\u0441\u0442\u0440\u043E\u0438\u0442\u044C \u0442\u0435\u0440\u043C\u0438\u043D\u0430\u043B: {{error}}",
      "Could not determine {{terminalName}} config path on Windows: APPDATA environment variable is not set.": "\u041D\u0435 \u0443\u0434\u0430\u043B\u043E\u0441\u044C \u043E\u043F\u0440\u0435\u0434\u0435\u043B\u0438\u0442\u044C \u043F\u0443\u0442\u044C \u043A\u043E\u043D\u0444\u0438\u0433\u0443\u0440\u0430\u0446\u0438\u0438 {{terminalName}} \u0432 Windows: \u043F\u0435\u0440\u0435\u043C\u0435\u043D\u043D\u0430\u044F \u043E\u043A\u0440\u0443\u0436\u0435\u043D\u0438\u044F APPDATA \u043D\u0435 \u0443\u0441\u0442\u0430\u043D\u043E\u0432\u043B\u0435\u043D\u0430.",
      "{{terminalName}} keybindings.json exists but is not a valid JSON array. Please fix the file manually or delete it to allow automatic configuration.": "{{terminalName}} keybindings.json \u0441\u0443\u0449\u0435\u0441\u0442\u0432\u0443\u0435\u0442, \u043D\u043E \u043D\u0435 \u044F\u0432\u043B\u044F\u0435\u0442\u0441\u044F \u043A\u043E\u0440\u0440\u0435\u043A\u0442\u043D\u044B\u043C \u043C\u0430\u0441\u0441\u0438\u0432\u043E\u043C JSON. \u041F\u043E\u0436\u0430\u043B\u0443\u0439\u0441\u0442\u0430, \u0438\u0441\u043F\u0440\u0430\u0432\u044C\u0442\u0435 \u0444\u0430\u0439\u043B \u0432\u0440\u0443\u0447\u043D\u0443\u044E \u0438\u043B\u0438 \u0443\u0434\u0430\u043B\u0438\u0442\u0435 \u0435\u0433\u043E \u0434\u043B\u044F \u0430\u0432\u0442\u043E\u043C\u0430\u0442\u0438\u0447\u0435\u0441\u043A\u043E\u0439 \u043D\u0430\u0441\u0442\u0440\u043E\u0439\u043A\u0438.",
      "File: {{file}}": "\u0424\u0430\u0439\u043B: {{file}}",
      "Failed to parse {{terminalName}} keybindings.json. The file contains invalid JSON. Please fix the file manually or delete it to allow automatic configuration.": "\u041D\u0435 \u0443\u0434\u0430\u043B\u043E\u0441\u044C \u0440\u0430\u0437\u043E\u0431\u0440\u0430\u0442\u044C {{terminalName}} keybindings.json. \u0424\u0430\u0439\u043B \u0441\u043E\u0434\u0435\u0440\u0436\u0438\u0442 \u043D\u0435\u043A\u043E\u0440\u0440\u0435\u043A\u0442\u043D\u044B\u0439 JSON. \u041F\u043E\u0436\u0430\u043B\u0443\u0439\u0441\u0442\u0430, \u0438\u0441\u043F\u0440\u0430\u0432\u044C\u0442\u0435 \u0444\u0430\u0439\u043B \u0432\u0440\u0443\u0447\u043D\u0443\u044E \u0438\u043B\u0438 \u0443\u0434\u0430\u043B\u0438\u0442\u0435 \u0435\u0433\u043E \u0434\u043B\u044F \u0430\u0432\u0442\u043E\u043C\u0430\u0442\u0438\u0447\u0435\u0441\u043A\u043E\u0439 \u043D\u0430\u0441\u0442\u0440\u043E\u0439\u043A\u0438.",
      "Error: {{error}}": "\u041E\u0448\u0438\u0431\u043A\u0430: {{error}}",
      "Shift+Enter binding already exists": "\u041F\u0440\u0438\u0432\u044F\u0437\u043A\u0430 Shift+Enter \u0443\u0436\u0435 \u0441\u0443\u0449\u0435\u0441\u0442\u0432\u0443\u0435\u0442",
      "Ctrl+Enter binding already exists": "\u041F\u0440\u0438\u0432\u044F\u0437\u043A\u0430 Ctrl+Enter \u0443\u0436\u0435 \u0441\u0443\u0449\u0435\u0441\u0442\u0432\u0443\u0435\u0442",
      "Existing keybindings detected. Will not modify to avoid conflicts.": "\u041E\u0431\u043D\u0430\u0440\u0443\u0436\u0435\u043D\u044B \u0441\u0443\u0449\u0435\u0441\u0442\u0432\u0443\u044E\u0449\u0438\u0435 \u043F\u0440\u0438\u0432\u044F\u0437\u043A\u0438 \u043A\u043B\u0430\u0432\u0438\u0448. \u041D\u0435 \u0431\u0443\u0434\u0443\u0442 \u0438\u0437\u043C\u0435\u043D\u0435\u043D\u044B \u0432\u043E \u0438\u0437\u0431\u0435\u0436\u0430\u043D\u0438\u0435 \u043A\u043E\u043D\u0444\u043B\u0438\u043A\u0442\u043E\u0432.",
      "Please check and modify manually if needed: {{file}}": "\u041F\u043E\u0436\u0430\u043B\u0443\u0439\u0441\u0442\u0430, \u043F\u0440\u043E\u0432\u0435\u0440\u044C\u0442\u0435 \u0438 \u0438\u0437\u043C\u0435\u043D\u0438\u0442\u0435 \u0432\u0440\u0443\u0447\u043D\u0443\u044E \u043F\u0440\u0438 \u043D\u0435\u043E\u0431\u0445\u043E\u0434\u0438\u043C\u043E\u0441\u0442\u0438: {{file}}",
      "Added Shift+Enter and Ctrl+Enter keybindings to {{terminalName}}.": "\u0414\u043E\u0431\u0430\u0432\u043B\u0435\u043D\u044B \u043F\u0440\u0438\u0432\u044F\u0437\u043A\u0438 Shift+Enter \u0438 Ctrl+Enter \u0434\u043B\u044F {{terminalName}}.",
      "Modified: {{file}}": "\u0418\u0437\u043C\u0435\u043D\u0435\u043D\u043E: {{file}}",
      "{{terminalName}} keybindings already configured.": "\u041F\u0440\u0438\u0432\u044F\u0437\u043A\u0438 \u043A\u043B\u0430\u0432\u0438\u0448 {{terminalName}} \u0443\u0436\u0435 \u043D\u0430\u0441\u0442\u0440\u043E\u0435\u043D\u044B.",
      "Failed to configure {{terminalName}}.": "\u041D\u0435 \u0443\u0434\u0430\u043B\u043E\u0441\u044C \u043D\u0430\u0441\u0442\u0440\u043E\u0438\u0442\u044C {{terminalName}}.",
      "Your terminal is already configured for an optimal experience with multiline input (Shift+Enter and Ctrl+Enter).": "\u0412\u0430\u0448 \u0442\u0435\u0440\u043C\u0438\u043D\u0430\u043B \u0443\u0436\u0435 \u043D\u0430\u0441\u0442\u0440\u043E\u0435\u043D \u0434\u043B\u044F \u043E\u043F\u0442\u0438\u043C\u0430\u043B\u044C\u043D\u043E\u0439 \u0440\u0430\u0431\u043E\u0442\u044B \u0441 \u043C\u043D\u043E\u0433\u043E\u0441\u0442\u0440\u043E\u0447\u043D\u044B\u043C \u0432\u0432\u043E\u0434\u043E\u043C (Shift+Enter \u0438 Ctrl+Enter).",
      "Could not detect terminal type. Supported terminals: VS Code, Cursor, Windsurf, and Trae.": "\u041D\u0435 \u0443\u0434\u0430\u043B\u043E\u0441\u044C \u043E\u043F\u0440\u0435\u0434\u0435\u043B\u0438\u0442\u044C \u0442\u0438\u043F \u0442\u0435\u0440\u043C\u0438\u043D\u0430\u043B\u0430. \u041F\u043E\u0434\u0434\u0435\u0440\u0436\u0438\u0432\u0430\u0435\u043C\u044B\u0435 \u0442\u0435\u0440\u043C\u0438\u043D\u0430\u043B\u044B: VS Code, Cursor, Windsurf \u0438 Trae.",
      'Terminal "{{terminal}}" is not supported yet.': '\u0422\u0435\u0440\u043C\u0438\u043D\u0430\u043B "{{terminal}}" \u0435\u0449\u0435 \u043D\u0435 \u043F\u043E\u0434\u0434\u0435\u0440\u0436\u0438\u0432\u0430\u0435\u0442\u0441\u044F.',
      // ============================================================================
      // Команды - Язык
      // ============================================================================
      "Invalid language. Available: {{options}}": "\u041D\u0435\u0434\u043E\u043F\u0443\u0441\u0442\u0438\u043C\u044B\u0439 \u044F\u0437\u044B\u043A. \u0414\u043E\u0441\u0442\u0443\u043F\u043D\u044B: {{options}}",
      "Language subcommands do not accept additional arguments.": "\u041F\u043E\u0434\u043A\u043E\u043C\u0430\u043D\u0434\u044B \u044F\u0437\u044B\u043A\u0430 \u043D\u0435 \u043F\u0440\u0438\u043D\u0438\u043C\u0430\u044E\u0442 \u0434\u043E\u043F\u043E\u043B\u043D\u0438\u0442\u0435\u043B\u044C\u043D\u044B\u0445 \u0430\u0440\u0433\u0443\u043C\u0435\u043D\u0442\u043E\u0432.",
      "Current UI language: {{lang}}": "\u0422\u0435\u043A\u0443\u0449\u0438\u0439 \u044F\u0437\u044B\u043A \u0438\u043D\u0442\u0435\u0440\u0444\u0435\u0439\u0441\u0430: {{lang}}",
      "Current LLM output language: {{lang}}": "\u0422\u0435\u043A\u0443\u0449\u0438\u0439 \u044F\u0437\u044B\u043A \u0432\u044B\u0432\u043E\u0434\u0430 LLM: {{lang}}",
      "LLM output language not set": "\u042F\u0437\u044B\u043A \u0432\u044B\u0432\u043E\u0434\u0430 LLM \u043D\u0435 \u0443\u0441\u0442\u0430\u043D\u043E\u0432\u043B\u0435\u043D",
      "Set UI language": "\u0423\u0441\u0442\u0430\u043D\u043E\u0432\u043A\u0430 \u044F\u0437\u044B\u043A\u0430 \u0438\u043D\u0442\u0435\u0440\u0444\u0435\u0439\u0441\u0430",
      "Set LLM output language": "\u0423\u0441\u0442\u0430\u043D\u043E\u0432\u043A\u0430 \u044F\u0437\u044B\u043A\u0430 \u0432\u044B\u0432\u043E\u0434\u0430 LLM",
      "Usage: /language ui [{{options}}]": "\u0418\u0441\u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u043D\u0438\u0435: /language ui [{{options}}]",
      "Usage: /language output <language>": "\u0418\u0441\u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u043D\u0438\u0435: /language output <language>",
      "Example: /language output \u4E2D\u6587": "\u041F\u0440\u0438\u043C\u0435\u0440: /language output \u4E2D\u6587",
      "Example: /language output English": "\u041F\u0440\u0438\u043C\u0435\u0440: /language output English",
      "Example: /language output \u65E5\u672C\u8A9E": "\u041F\u0440\u0438\u043C\u0435\u0440: /language output \u65E5\u672C\u8A9E",
      "Example: /language output Portugu\xEAs": "\u041F\u0440\u0438\u043C\u0435\u0440: /language output Portugu\xEAs",
      "UI language changed to {{lang}}": "\u042F\u0437\u044B\u043A \u0438\u043D\u0442\u0435\u0440\u0444\u0435\u0439\u0441\u0430 \u0438\u0437\u043C\u0435\u043D\u0435\u043D \u043D\u0430 {{lang}}",
      "LLM output language set to {{lang}}": "\u042F\u0437\u044B\u043A \u0432\u044B\u0432\u043E\u0434\u0430 LLM \u0443\u0441\u0442\u0430\u043D\u043E\u0432\u043B\u0435\u043D \u043D\u0430 {{lang}}",
      "LLM output language rule file generated at {{path}}": "\u0424\u0430\u0439\u043B \u043F\u0440\u0430\u0432\u0438\u043B \u044F\u0437\u044B\u043A\u0430 \u0432\u044B\u0432\u043E\u0434\u0430 LLM \u0441\u043E\u0437\u0434\u0430\u043D \u0432 {{path}}",
      "Please restart the application for the changes to take effect.": "\u041F\u043E\u0436\u0430\u043B\u0443\u0439\u0441\u0442\u0430, \u043F\u0435\u0440\u0435\u0437\u0430\u043F\u0443\u0441\u0442\u0438\u0442\u0435 \u043F\u0440\u0438\u043B\u043E\u0436\u0435\u043D\u0438\u0435 \u0434\u043B\u044F \u043F\u0440\u0438\u043C\u0435\u043D\u0435\u043D\u0438\u044F \u0438\u0437\u043C\u0435\u043D\u0435\u043D\u0438\u0439.",
      "Failed to generate LLM output language rule file: {{error}}": "\u041D\u0435 \u0443\u0434\u0430\u043B\u043E\u0441\u044C \u0441\u043E\u0437\u0434\u0430\u0442\u044C \u0444\u0430\u0439\u043B \u043F\u0440\u0430\u0432\u0438\u043B \u044F\u0437\u044B\u043A\u0430 \u0432\u044B\u0432\u043E\u0434\u0430 LLM: {{error}}",
      "Invalid command. Available subcommands:": "\u041D\u0435\u0432\u0435\u0440\u043D\u0430\u044F \u043A\u043E\u043C\u0430\u043D\u0434\u0430. \u0414\u043E\u0441\u0442\u0443\u043F\u043D\u044B\u0435 \u043F\u043E\u0434\u043A\u043E\u043C\u0430\u043D\u0434\u044B:",
      "Available subcommands:": "\u0414\u043E\u0441\u0442\u0443\u043F\u043D\u044B\u0435 \u043F\u043E\u0434\u043A\u043E\u043C\u0430\u043D\u0434\u044B:",
      "To request additional UI language packs, please open an issue on GitHub.": "\u0414\u043B\u044F \u0437\u0430\u043F\u0440\u043E\u0441\u0430 \u0434\u043E\u043F\u043E\u043B\u043D\u0438\u0442\u0435\u043B\u044C\u043D\u044B\u0445 \u044F\u0437\u044B\u043A\u043E\u0432\u044B\u0445 \u043F\u0430\u043A\u0435\u0442\u043E\u0432 \u0438\u043D\u0442\u0435\u0440\u0444\u0435\u0439\u0441\u0430, \u043F\u043E\u0436\u0430\u043B\u0443\u0439\u0441\u0442\u0430, \u0441\u043E\u0437\u0434\u0430\u0439\u0442\u0435 \u043E\u0431\u0440\u0430\u0449\u0435\u043D\u0438\u0435 \u043D\u0430 GitHub.",
      "Available options:": "\u0414\u043E\u0441\u0442\u0443\u043F\u043D\u044B\u0435 \u0432\u0430\u0440\u0438\u0430\u043D\u0442\u044B:",
      "Set UI language to {{name}}": "\u0423\u0441\u0442\u0430\u043D\u043E\u0432\u0438\u0442\u044C \u044F\u0437\u044B\u043A \u0438\u043D\u0442\u0435\u0440\u0444\u0435\u0439\u0441\u0430 \u043D\u0430 {{name}}",
      // ============================================================================
      // Команды - Режим подтверждения
      // ============================================================================
      "Tool Approval Mode": "\u0420\u0435\u0436\u0438\u043C \u043F\u043E\u0434\u0442\u0432\u0435\u0440\u0436\u0434\u0435\u043D\u0438\u044F \u0438\u043D\u0441\u0442\u0440\u0443\u043C\u0435\u043D\u0442\u043E\u0432",
      "Current approval mode: {{mode}}": "\u0422\u0435\u043A\u0443\u0449\u0438\u0439 \u0440\u0435\u0436\u0438\u043C \u043F\u043E\u0434\u0442\u0432\u0435\u0440\u0436\u0434\u0435\u043D\u0438\u044F: {{mode}}",
      "Available approval modes:": "\u0414\u043E\u0441\u0442\u0443\u043F\u043D\u044B\u0435 \u0440\u0435\u0436\u0438\u043C\u044B \u043F\u043E\u0434\u0442\u0432\u0435\u0440\u0436\u0434\u0435\u043D\u0438\u044F:",
      "Approval mode changed to: {{mode}}": "\u0420\u0435\u0436\u0438\u043C \u043F\u043E\u0434\u0442\u0432\u0435\u0440\u0436\u0434\u0435\u043D\u0438\u044F \u0438\u0437\u043C\u0435\u043D\u0435\u043D \u043D\u0430: {{mode}}",
      "Approval mode changed to: {{mode}} (saved to {{scope}} settings{{location}})": "\u0420\u0435\u0436\u0438\u043C \u043F\u043E\u0434\u0442\u0432\u0435\u0440\u0436\u0434\u0435\u043D\u0438\u044F \u0438\u0437\u043C\u0435\u043D\u0435\u043D \u043D\u0430: {{mode}} (\u0441\u043E\u0445\u0440\u0430\u043D\u0435\u043D\u043E \u0432 \u043D\u0430\u0441\u0442\u0440\u043E\u0439\u043A\u0430\u0445 {{scope}}{{location}})",
      "Usage: /approval-mode <mode> [--session|--user|--project]": "\u0418\u0441\u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u043D\u0438\u0435: /approval-mode <mode> [--session|--user|--project]",
      "Scope subcommands do not accept additional arguments.": "\u041F\u043E\u0434\u043A\u043E\u043C\u0430\u043D\u0434\u044B \u043E\u0431\u043B\u0430\u0441\u0442\u0438 \u043D\u0435 \u043F\u0440\u0438\u043D\u0438\u043C\u0430\u044E\u0442 \u0434\u043E\u043F\u043E\u043B\u043D\u0438\u0442\u0435\u043B\u044C\u043D\u044B\u0445 \u0430\u0440\u0433\u0443\u043C\u0435\u043D\u0442\u043E\u0432.",
      "Plan mode - Analyze only, do not modify files or execute commands": "\u0420\u0435\u0436\u0438\u043C \u043F\u043B\u0430\u043D\u0438\u0440\u043E\u0432\u0430\u043D\u0438\u044F - \u0442\u043E\u043B\u044C\u043A\u043E \u0430\u043D\u0430\u043B\u0438\u0437, \u0431\u0435\u0437 \u0438\u0437\u043C\u0435\u043D\u0435\u043D\u0438\u044F \u0444\u0430\u0439\u043B\u043E\u0432 \u0438\u043B\u0438 \u0432\u044B\u043F\u043E\u043B\u043D\u0435\u043D\u0438\u044F \u043A\u043E\u043C\u0430\u043D\u0434",
      "Default mode - Require approval for file edits or shell commands": "\u0420\u0435\u0436\u0438\u043C \u043F\u043E \u0443\u043C\u043E\u043B\u0447\u0430\u043D\u0438\u044E - \u0442\u0440\u0435\u0431\u0443\u0435\u0442\u0441\u044F \u043F\u043E\u0434\u0442\u0432\u0435\u0440\u0436\u0434\u0435\u043D\u0438\u0435 \u0434\u043B\u044F \u0440\u0435\u0434\u0430\u043A\u0442\u0438\u0440\u043E\u0432\u0430\u043D\u0438\u044F \u0444\u0430\u0439\u043B\u043E\u0432 \u0438\u043B\u0438 \u043A\u043E\u043C\u0430\u043D\u0434 \u0442\u0435\u0440\u043C\u0438\u043D\u0430\u043B\u0430",
      "Auto-edit mode - Automatically approve file edits": "\u0420\u0435\u0436\u0438\u043C \u0430\u0432\u0442\u043E\u0440\u0435\u0434\u0430\u043A\u0442\u0438\u0440\u043E\u0432\u0430\u043D\u0438\u044F - \u0430\u0432\u0442\u043E\u043C\u0430\u0442\u0438\u0447\u0435\u0441\u043A\u043E\u0435 \u043F\u043E\u0434\u0442\u0432\u0435\u0440\u0436\u0434\u0435\u043D\u0438\u0435 \u0438\u0437\u043C\u0435\u043D\u0435\u043D\u0438\u0439 \u0444\u0430\u0439\u043B\u043E\u0432",
      "YOLO mode - Automatically approve all tools": "\u0420\u0435\u0436\u0438\u043C YOLO - \u0430\u0432\u0442\u043E\u043C\u0430\u0442\u0438\u0447\u0435\u0441\u043A\u043E\u0435 \u043F\u043E\u0434\u0442\u0432\u0435\u0440\u0436\u0434\u0435\u043D\u0438\u0435 \u0432\u0441\u0435\u0445 \u0438\u043D\u0441\u0442\u0440\u0443\u043C\u0435\u043D\u0442\u043E\u0432",
      "{{mode}} mode": "\u0420\u0435\u0436\u0438\u043C {{mode}}",
      "Settings service is not available; unable to persist the approval mode.": "\u0421\u043B\u0443\u0436\u0431\u0430 \u043D\u0430\u0441\u0442\u0440\u043E\u0435\u043A \u043D\u0435\u0434\u043E\u0441\u0442\u0443\u043F\u043D\u0430; \u043D\u0435\u0432\u043E\u0437\u043C\u043E\u0436\u043D\u043E \u0441\u043E\u0445\u0440\u0430\u043D\u0438\u0442\u044C \u0440\u0435\u0436\u0438\u043C \u043F\u043E\u0434\u0442\u0432\u0435\u0440\u0436\u0434\u0435\u043D\u0438\u044F.",
      "Failed to save approval mode: {{error}}": "\u041D\u0435 \u0443\u0434\u0430\u043B\u043E\u0441\u044C \u0441\u043E\u0445\u0440\u0430\u043D\u0438\u0442\u044C \u0440\u0435\u0436\u0438\u043C \u043F\u043E\u0434\u0442\u0432\u0435\u0440\u0436\u0434\u0435\u043D\u0438\u044F: {{error}}",
      "Failed to change approval mode: {{error}}": "\u041D\u0435 \u0443\u0434\u0430\u043B\u043E\u0441\u044C \u0438\u0437\u043C\u0435\u043D\u0438\u0442\u044C \u0440\u0435\u0436\u0438\u043C \u043F\u043E\u0434\u0442\u0432\u0435\u0440\u0436\u0434\u0435\u043D\u0438\u044F: {{error}}",
      "Apply to current session only (temporary)": "\u041F\u0440\u0438\u043C\u0435\u043D\u0438\u0442\u044C \u0442\u043E\u043B\u044C\u043A\u043E \u043A \u0442\u0435\u043A\u0443\u0449\u0435\u0439 \u0441\u0435\u0441\u0441\u0438\u0438 (\u0432\u0440\u0435\u043C\u0435\u043D\u043D\u043E)",
      "Persist for this project/workspace": "\u0421\u043E\u0445\u0440\u0430\u043D\u0438\u0442\u044C \u0434\u043B\u044F \u044D\u0442\u043E\u0433\u043E \u043F\u0440\u043E\u0435\u043A\u0442\u0430/\u0440\u0430\u0431\u043E\u0447\u0435\u0433\u043E \u043F\u0440\u043E\u0441\u0442\u0440\u0430\u043D\u0441\u0442\u0432\u0430",
      "Persist for this user on this machine": "\u0421\u043E\u0445\u0440\u0430\u043D\u0438\u0442\u044C \u0434\u043B\u044F \u044D\u0442\u043E\u0433\u043E \u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u0442\u0435\u043B\u044F \u043D\u0430 \u044D\u0442\u043E\u0439 \u043C\u0430\u0448\u0438\u043D\u0435",
      "Analyze only, do not modify files or execute commands": "\u0422\u043E\u043B\u044C\u043A\u043E \u0430\u043D\u0430\u043B\u0438\u0437, \u0431\u0435\u0437 \u0438\u0437\u043C\u0435\u043D\u0435\u043D\u0438\u044F \u0444\u0430\u0439\u043B\u043E\u0432 \u0438\u043B\u0438 \u0432\u044B\u043F\u043E\u043B\u043D\u0435\u043D\u0438\u044F \u043A\u043E\u043C\u0430\u043D\u0434",
      "Require approval for file edits or shell commands": "\u0422\u0440\u0435\u0431\u0443\u0435\u0442\u0441\u044F \u043F\u043E\u0434\u0442\u0432\u0435\u0440\u0436\u0434\u0435\u043D\u0438\u0435 \u0434\u043B\u044F \u0440\u0435\u0434\u0430\u043A\u0442\u0438\u0440\u043E\u0432\u0430\u043D\u0438\u044F \u0444\u0430\u0439\u043B\u043E\u0432 \u0438\u043B\u0438 \u043A\u043E\u043C\u0430\u043D\u0434 \u0442\u0435\u0440\u043C\u0438\u043D\u0430\u043B\u0430",
      "Automatically approve file edits": "\u0410\u0432\u0442\u043E\u043C\u0430\u0442\u0438\u0447\u0435\u0441\u043A\u0438 \u043F\u043E\u0434\u0442\u0432\u0435\u0440\u0436\u0434\u0430\u0442\u044C \u0438\u0437\u043C\u0435\u043D\u0435\u043D\u0438\u044F \u0444\u0430\u0439\u043B\u043E\u0432",
      "Automatically approve all tools": "\u0410\u0432\u0442\u043E\u043C\u0430\u0442\u0438\u0447\u0435\u0441\u043A\u0438 \u043F\u043E\u0434\u0442\u0432\u0435\u0440\u0436\u0434\u0430\u0442\u044C \u0432\u0441\u0435 \u0438\u043D\u0441\u0442\u0440\u0443\u043C\u0435\u043D\u0442\u044B",
      "Workspace approval mode exists and takes priority. User-level change will have no effect.": "\u0420\u0435\u0436\u0438\u043C \u043F\u043E\u0434\u0442\u0432\u0435\u0440\u0436\u0434\u0435\u043D\u0438\u044F \u0440\u0430\u0431\u043E\u0447\u0435\u0433\u043E \u043F\u0440\u043E\u0441\u0442\u0440\u0430\u043D\u0441\u0442\u0432\u0430 \u0441\u0443\u0449\u0435\u0441\u0442\u0432\u0443\u0435\u0442 \u0438 \u0438\u043C\u0435\u0435\u0442 \u043F\u0440\u0438\u043E\u0440\u0438\u0442\u0435\u0442. \u0418\u0437\u043C\u0435\u043D\u0435\u043D\u0438\u0435 \u043D\u0430 \u0443\u0440\u043E\u0432\u043D\u0435 \u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u0442\u0435\u043B\u044F \u043D\u0435 \u0431\u0443\u0434\u0435\u0442 \u0438\u043C\u0435\u0442\u044C \u044D\u0444\u0444\u0435\u043A\u0442\u0430.",
      "Apply To": "\u041F\u0440\u0438\u043C\u0435\u043D\u0438\u0442\u044C \u043A",
      "User Settings": "\u041D\u0430\u0441\u0442\u0440\u043E\u0439\u043A\u0438 \u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u0442\u0435\u043B\u044F",
      "Workspace Settings": "\u041D\u0430\u0441\u0442\u0440\u043E\u0439\u043A\u0438 \u0440\u0430\u0431\u043E\u0447\u0435\u0433\u043E \u043F\u0440\u043E\u0441\u0442\u0440\u0430\u043D\u0441\u0442\u0432\u0430",
      // ============================================================================
      // Команды - Память
      // ============================================================================
      "Commands for interacting with memory.": "\u041A\u043E\u043C\u0430\u043D\u0434\u044B \u0434\u043B\u044F \u0432\u0437\u0430\u0438\u043C\u043E\u0434\u0435\u0439\u0441\u0442\u0432\u0438\u044F \u0441 \u043F\u0430\u043C\u044F\u0442\u044C\u044E",
      "Show the current memory contents.": "\u041F\u043E\u043A\u0430\u0437\u0430\u0442\u044C \u0442\u0435\u043A\u0443\u0449\u0435\u0435 \u0441\u043E\u0434\u0435\u0440\u0436\u0438\u043C\u043E\u0435 \u043F\u0430\u043C\u044F\u0442\u0438.",
      "Show project-level memory contents.": "\u041F\u043E\u043A\u0430\u0437\u0430\u0442\u044C \u043F\u0430\u043C\u044F\u0442\u044C \u0443\u0440\u043E\u0432\u043D\u044F \u043F\u0440\u043E\u0435\u043A\u0442\u0430.",
      "Show global memory contents.": "\u041F\u043E\u043A\u0430\u0437\u0430\u0442\u044C \u0433\u043B\u043E\u0431\u0430\u043B\u044C\u043D\u0443\u044E \u043F\u0430\u043C\u044F\u0442\u044C.",
      "Add content to project-level memory.": "\u0414\u043E\u0431\u0430\u0432\u0438\u0442\u044C \u0441\u043E\u0434\u0435\u0440\u0436\u0438\u043C\u043E\u0435 \u0432 \u043F\u0430\u043C\u044F\u0442\u044C \u0443\u0440\u043E\u0432\u043D\u044F \u043F\u0440\u043E\u0435\u043A\u0442\u0430.",
      "Add content to global memory.": "\u0414\u043E\u0431\u0430\u0432\u0438\u0442\u044C \u0441\u043E\u0434\u0435\u0440\u0436\u0438\u043C\u043E\u0435 \u0432 \u0433\u043B\u043E\u0431\u0430\u043B\u044C\u043D\u0443\u044E \u043F\u0430\u043C\u044F\u0442\u044C.",
      "Refresh the memory from the source.": "\u041E\u0431\u043D\u043E\u0432\u0438\u0442\u044C \u043F\u0430\u043C\u044F\u0442\u044C \u0438\u0437 \u0438\u0441\u0442\u043E\u0447\u043D\u0438\u043A\u0430.",
      "Usage: /memory add --project <text to remember>": "\u0418\u0441\u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u043D\u0438\u0435: /memory add --project <\u0442\u0435\u043A\u0441\u0442 \u0434\u043B\u044F \u0437\u0430\u043F\u043E\u043C\u0438\u043D\u0430\u043D\u0438\u044F>",
      "Usage: /memory add --global <text to remember>": "\u0418\u0441\u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u043D\u0438\u0435: /memory add --global <\u0442\u0435\u043A\u0441\u0442 \u0434\u043B\u044F \u0437\u0430\u043F\u043E\u043C\u0438\u043D\u0430\u043D\u0438\u044F>",
      'Attempting to save to project memory: "{{text}}"': '\u041F\u043E\u043F\u044B\u0442\u043A\u0430 \u0441\u043E\u0445\u0440\u0430\u043D\u0438\u0442\u044C \u0432 \u043F\u0430\u043C\u044F\u0442\u044C \u043F\u0440\u043E\u0435\u043A\u0442\u0430: "{{text}}"',
      'Attempting to save to global memory: "{{text}}"': '\u041F\u043E\u043F\u044B\u0442\u043A\u0430 \u0441\u043E\u0445\u0440\u0430\u043D\u0438\u0442\u044C \u0432 \u0433\u043B\u043E\u0431\u0430\u043B\u044C\u043D\u0443\u044E \u043F\u0430\u043C\u044F\u0442\u044C: "{{text}}"',
      "Current memory content from {{count}} file(s):": "\u0422\u0435\u043A\u0443\u0449\u0435\u0435 \u0441\u043E\u0434\u0435\u0440\u0436\u0438\u043C\u043E\u0435 \u043F\u0430\u043C\u044F\u0442\u0438 \u0438\u0437 {{count}} \u0444\u0430\u0439\u043B\u0430(\u043E\u0432):",
      "Memory is currently empty.": "\u041F\u0430\u043C\u044F\u0442\u044C \u0432 \u043D\u0430\u0441\u0442\u043E\u044F\u0449\u0435\u0435 \u0432\u0440\u0435\u043C\u044F \u043F\u0443\u0441\u0442\u0430.",
      "Project memory file not found or is currently empty.": "\u0424\u0430\u0439\u043B \u043F\u0430\u043C\u044F\u0442\u0438 \u043F\u0440\u043E\u0435\u043A\u0442\u0430 \u043D\u0435 \u043D\u0430\u0439\u0434\u0435\u043D \u0438\u043B\u0438 \u0432 \u043D\u0430\u0441\u0442\u043E\u044F\u0449\u0435\u0435 \u0432\u0440\u0435\u043C\u044F \u043F\u0443\u0441\u0442.",
      "Global memory file not found or is currently empty.": "\u0424\u0430\u0439\u043B \u0433\u043B\u043E\u0431\u0430\u043B\u044C\u043D\u043E\u0439 \u043F\u0430\u043C\u044F\u0442\u0438 \u043D\u0435 \u043D\u0430\u0439\u0434\u0435\u043D \u0438\u043B\u0438 \u0432 \u043D\u0430\u0441\u0442\u043E\u044F\u0449\u0435\u0435 \u0432\u0440\u0435\u043C\u044F \u043F\u0443\u0441\u0442.",
      "Global memory is currently empty.": "\u0413\u043B\u043E\u0431\u0430\u043B\u044C\u043D\u0430\u044F \u043F\u0430\u043C\u044F\u0442\u044C \u0432 \u043D\u0430\u0441\u0442\u043E\u044F\u0449\u0435\u0435 \u0432\u0440\u0435\u043C\u044F \u043F\u0443\u0441\u0442\u0430.",
      "Global memory content:\n\n---\n{{content}}\n---": "\u0421\u043E\u0434\u0435\u0440\u0436\u0438\u043C\u043E\u0435 \u0433\u043B\u043E\u0431\u0430\u043B\u044C\u043D\u043E\u0439 \u043F\u0430\u043C\u044F\u0442\u0438:\n\n---\n{{content}}\n---",
      "Project memory content from {{path}}:\n\n---\n{{content}}\n---": "\u0421\u043E\u0434\u0435\u0440\u0436\u0438\u043C\u043E\u0435 \u043F\u0430\u043C\u044F\u0442\u0438 \u043F\u0440\u043E\u0435\u043A\u0442\u0430 \u0438\u0437 {{path}}:\n\n---\n{{content}}\n---",
      "Project memory is currently empty.": "\u041F\u0430\u043C\u044F\u0442\u044C \u043F\u0440\u043E\u0435\u043A\u0442\u0430 \u0432 \u043D\u0430\u0441\u0442\u043E\u044F\u0449\u0435\u0435 \u0432\u0440\u0435\u043C\u044F \u043F\u0443\u0441\u0442\u0430.",
      "Refreshing memory from source files...": "\u041E\u0431\u043D\u043E\u0432\u043B\u0435\u043D\u0438\u0435 \u043F\u0430\u043C\u044F\u0442\u0438 \u0438\u0437 \u0438\u0441\u0445\u043E\u0434\u043D\u044B\u0445 \u0444\u0430\u0439\u043B\u043E\u0432...",
      "Add content to the memory. Use --global for global memory or --project for project memory.": "\u0414\u043E\u0431\u0430\u0432\u0438\u0442\u044C \u0441\u043E\u0434\u0435\u0440\u0436\u0438\u043C\u043E\u0435 \u0432 \u043F\u0430\u043C\u044F\u0442\u044C. \u0418\u0441\u043F\u043E\u043B\u044C\u0437\u0443\u0439\u0442\u0435 --global \u0434\u043B\u044F \u0433\u043B\u043E\u0431\u0430\u043B\u044C\u043D\u043E\u0439 \u043F\u0430\u043C\u044F\u0442\u0438 \u0438\u043B\u0438 --project \u0434\u043B\u044F \u043F\u0430\u043C\u044F\u0442\u0438 \u043F\u0440\u043E\u0435\u043A\u0442\u0430.",
      "Usage: /memory add [--global|--project] <text to remember>": "\u0418\u0441\u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u043D\u0438\u0435: /memory add [--global|--project] <\u0442\u0435\u043A\u0441\u0442 \u0434\u043B\u044F \u0437\u0430\u043F\u043E\u043C\u0438\u043D\u0430\u043D\u0438\u044F>",
      'Attempting to save to memory {{scope}}: "{{fact}}"': '\u041F\u043E\u043F\u044B\u0442\u043A\u0430 \u0441\u043E\u0445\u0440\u0430\u043D\u0438\u0442\u044C \u0432 \u043F\u0430\u043C\u044F\u0442\u044C {{scope}}: "{{fact}}"',
      // ============================================================================
      // Команды - MCP
      // ============================================================================
      "Authenticate with an OAuth-enabled MCP server": "\u0410\u0432\u0442\u043E\u0440\u0438\u0437\u043E\u0432\u0430\u0442\u044C\u0441\u044F \u043D\u0430 MCP-\u0441\u0435\u0440\u0432\u0435\u0440\u0435 \u0441 \u043F\u043E\u0434\u0434\u0435\u0440\u0436\u043A\u043E\u0439 OAuth",
      "List configured MCP servers and tools": "\u041F\u0440\u043E\u0441\u043C\u043E\u0442\u0440 \u043D\u0430\u0441\u0442\u0440\u043E\u0435\u043D\u043D\u044B\u0445 MCP-\u0441\u0435\u0440\u0432\u0435\u0440\u043E\u0432 \u0438 \u0438\u043D\u0441\u0442\u0440\u0443\u043C\u0435\u043D\u0442\u043E\u0432",
      "Restarts MCP servers.": "\u041F\u0435\u0440\u0435\u0437\u0430\u043F\u0443\u0441\u0442\u0438\u0442\u044C MCP-\u0441\u0435\u0440\u0432\u0435\u0440\u044B.",
      "Config not loaded.": "\u041A\u043E\u043D\u0444\u0438\u0433\u0443\u0440\u0430\u0446\u0438\u044F \u043D\u0435 \u0437\u0430\u0433\u0440\u0443\u0436\u0435\u043D\u0430.",
      "Could not retrieve tool registry.": "\u041D\u0435 \u0443\u0434\u0430\u043B\u043E\u0441\u044C \u043F\u043E\u043B\u0443\u0447\u0438\u0442\u044C \u0440\u0435\u0435\u0441\u0442\u0440 \u0438\u043D\u0441\u0442\u0440\u0443\u043C\u0435\u043D\u0442\u043E\u0432.",
      "No MCP servers configured with OAuth authentication.": "\u041D\u0435\u0442 MCP-\u0441\u0435\u0440\u0432\u0435\u0440\u043E\u0432, \u043D\u0430\u0441\u0442\u0440\u043E\u0435\u043D\u043D\u044B\u0445 \u0441 \u0430\u0432\u0442\u043E\u0440\u0438\u0437\u0430\u0446\u0438\u0435\u0439 OAuth.",
      "MCP servers with OAuth authentication:": "MCP-\u0441\u0435\u0440\u0432\u0435\u0440\u044B \u0441 \u0430\u0432\u0442\u043E\u0440\u0438\u0437\u0430\u0446\u0438\u0435\u0439 OAuth:",
      "Use /mcp auth <server-name> to authenticate.": "\u0418\u0441\u043F\u043E\u043B\u044C\u0437\u0443\u0439\u0442\u0435 /mcp auth <\u0438\u043C\u044F-\u0441\u0435\u0440\u0432\u0435\u0440\u0430> \u0434\u043B\u044F \u0430\u0432\u0442\u043E\u0440\u0438\u0437\u0430\u0446\u0438\u0438.",
      "MCP server '{{name}}' not found.": "MCP-\u0441\u0435\u0440\u0432\u0435\u0440 '{{name}}' \u043D\u0435 \u043D\u0430\u0439\u0434\u0435\u043D.",
      "Successfully authenticated and refreshed tools for '{{name}}'.": "\u0423\u0441\u043F\u0435\u0448\u043D\u043E \u0430\u0432\u0442\u043E\u0440\u0438\u0437\u043E\u0432\u0430\u043D\u043E \u0438 \u043E\u0431\u043D\u043E\u0432\u043B\u0435\u043D\u044B \u0438\u043D\u0441\u0442\u0440\u0443\u043C\u0435\u043D\u0442\u044B \u0434\u043B\u044F '{{name}}'.",
      "Failed to authenticate with MCP server '{{name}}': {{error}}": "\u041D\u0435 \u0443\u0434\u0430\u043B\u043E\u0441\u044C \u0430\u0432\u0442\u043E\u0440\u0438\u0437\u043E\u0432\u0430\u0442\u044C\u0441\u044F \u043D\u0430 MCP-\u0441\u0435\u0440\u0432\u0435\u0440\u0435 '{{name}}': {{error}}",
      "Re-discovering tools from '{{name}}'...": "\u041F\u043E\u0432\u0442\u043E\u0440\u043D\u043E\u0435 \u043E\u0431\u043D\u0430\u0440\u0443\u0436\u0435\u043D\u0438\u0435 \u0438\u043D\u0441\u0442\u0440\u0443\u043C\u0435\u043D\u0442\u043E\u0432 \u043E\u0442 '{{name}}'...",
      // ============================================================================
      // Команды - Чат
      // ============================================================================
      "Manage conversation history.": "\u0423\u043F\u0440\u0430\u0432\u043B\u0435\u043D\u0438\u0435 \u0438\u0441\u0442\u043E\u0440\u0438\u0435\u0439 \u0434\u0438\u0430\u043B\u043E\u0433\u043E\u0432.",
      "List saved conversation checkpoints": "\u041F\u043E\u043A\u0430\u0437\u0430\u0442\u044C \u0441\u043E\u0445\u0440\u0430\u043D\u0435\u043D\u043D\u044B\u0435 \u0442\u043E\u0447\u043A\u0438 \u0432\u043E\u0441\u0441\u0442\u0430\u043D\u043E\u0432\u043B\u0435\u043D\u0438\u044F \u0434\u0438\u0430\u043B\u043E\u0433\u0430",
      "No saved conversation checkpoints found.": "\u041D\u0435 \u043D\u0430\u0439\u0434\u0435\u043D\u043E \u0441\u043E\u0445\u0440\u0430\u043D\u0435\u043D\u043D\u044B\u0445 \u0442\u043E\u0447\u0435\u043A \u0432\u043E\u0441\u0441\u0442\u0430\u043D\u043E\u0432\u043B\u0435\u043D\u0438\u044F \u0434\u0438\u0430\u043B\u043E\u0433\u0430.",
      "List of saved conversations:": "\u0421\u043F\u0438\u0441\u043E\u043A \u0441\u043E\u0445\u0440\u0430\u043D\u0435\u043D\u043D\u044B\u0445 \u0434\u0438\u0430\u043B\u043E\u0433\u043E\u0432:",
      "Note: Newest last, oldest first": "\u041F\u0440\u0438\u043C\u0435\u0447\u0430\u043D\u0438\u0435: \u043D\u043E\u0432\u044B\u0435 \u043F\u043E\u0441\u043B\u0435\u0434\u043D\u0438\u043C\u0438, \u0441\u0442\u0430\u0440\u044B\u0435 \u043F\u0435\u0440\u0432\u044B\u043C\u0438",
      "Save the current conversation as a checkpoint. Usage: /chat save <tag>": "\u0421\u043E\u0445\u0440\u0430\u043D\u0438\u0442\u044C \u0442\u0435\u043A\u0443\u0449\u0438\u0439 \u0434\u0438\u0430\u043B\u043E\u0433 \u043A\u0430\u043A \u0442\u043E\u0447\u043A\u0443 \u0432\u043E\u0441\u0441\u0442\u0430\u043D\u043E\u0432\u043B\u0435\u043D\u0438\u044F. \u0418\u0441\u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u043D\u0438\u0435: /chat save <\u0442\u0435\u0433>",
      "Missing tag. Usage: /chat save <tag>": "\u041E\u0442\u0441\u0443\u0442\u0441\u0442\u0432\u0443\u0435\u0442 \u0442\u0435\u0433. \u0418\u0441\u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u043D\u0438\u0435: /chat save <\u0442\u0435\u0433>",
      "Delete a conversation checkpoint. Usage: /chat delete <tag>": "\u0423\u0434\u0430\u043B\u0438\u0442\u044C \u0442\u043E\u0447\u043A\u0443 \u0432\u043E\u0441\u0441\u0442\u0430\u043D\u043E\u0432\u043B\u0435\u043D\u0438\u044F \u0434\u0438\u0430\u043B\u043E\u0433\u0430. \u0418\u0441\u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u043D\u0438\u0435: /chat delete <\u0442\u0435\u0433>",
      "Missing tag. Usage: /chat delete <tag>": "\u041E\u0442\u0441\u0443\u0442\u0441\u0442\u0432\u0443\u0435\u0442 \u0442\u0435\u0433. \u0418\u0441\u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u043D\u0438\u0435: /chat delete <\u0442\u0435\u0433>",
      "Conversation checkpoint '{{tag}}' has been deleted.": "\u0422\u043E\u0447\u043A\u0430 \u0432\u043E\u0441\u0441\u0442\u0430\u043D\u043E\u0432\u043B\u0435\u043D\u0438\u044F \u0434\u0438\u0430\u043B\u043E\u0433\u0430 '{{tag}}' \u0443\u0434\u0430\u043B\u0435\u043D\u0430.",
      "Error: No checkpoint found with tag '{{tag}}'.": "\u041E\u0448\u0438\u0431\u043A\u0430: \u0442\u043E\u0447\u043A\u0430 \u0432\u043E\u0441\u0441\u0442\u0430\u043D\u043E\u0432\u043B\u0435\u043D\u0438\u044F \u0441 \u0442\u0435\u0433\u043E\u043C '{{tag}}' \u043D\u0435 \u043D\u0430\u0439\u0434\u0435\u043D\u0430.",
      "Resume a conversation from a checkpoint. Usage: /chat resume <tag>": "\u0412\u043E\u0437\u043E\u0431\u043D\u043E\u0432\u0438\u0442\u044C \u0434\u0438\u0430\u043B\u043E\u0433 \u0438\u0437 \u0442\u043E\u0447\u043A\u0438 \u0432\u043E\u0441\u0441\u0442\u0430\u043D\u043E\u0432\u043B\u0435\u043D\u0438\u044F. \u0418\u0441\u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u043D\u0438\u0435: /chat resume <\u0442\u0435\u0433>",
      "Missing tag. Usage: /chat resume <tag>": "\u041E\u0442\u0441\u0443\u0442\u0441\u0442\u0432\u0443\u0435\u0442 \u0442\u0435\u0433. \u0418\u0441\u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u043D\u0438\u0435: /chat resume <\u0442\u0435\u0433>",
      "No saved checkpoint found with tag: {{tag}}.": "\u041D\u0435 \u043D\u0430\u0439\u0434\u0435\u043D\u0430 \u0441\u043E\u0445\u0440\u0430\u043D\u0435\u043D\u043D\u0430\u044F \u0442\u043E\u0447\u043A\u0430 \u0432\u043E\u0441\u0441\u0442\u0430\u043D\u043E\u0432\u043B\u0435\u043D\u0438\u044F \u0441 \u0442\u0435\u0433\u043E\u043C: {{tag}}.",
      "A checkpoint with the tag {{tag}} already exists. Do you want to overwrite it?": "\u0422\u043E\u0447\u043A\u0430 \u0432\u043E\u0441\u0441\u0442\u0430\u043D\u043E\u0432\u043B\u0435\u043D\u0438\u044F \u0441 \u0442\u0435\u0433\u043E\u043C {{tag}} \u0443\u0436\u0435 \u0441\u0443\u0449\u0435\u0441\u0442\u0432\u0443\u0435\u0442. \u041F\u0435\u0440\u0435\u0437\u0430\u043F\u0438\u0441\u0430\u0442\u044C?",
      "No chat client available to save conversation.": "\u041D\u0435\u0442 \u0434\u043E\u0441\u0442\u0443\u043F\u043D\u043E\u0433\u043E \u043A\u043B\u0438\u0435\u043D\u0442\u0430 \u0447\u0430\u0442\u0430 \u0434\u043B\u044F \u0441\u043E\u0445\u0440\u0430\u043D\u0435\u043D\u0438\u044F \u0434\u0438\u0430\u043B\u043E\u0433\u0430.",
      "Conversation checkpoint saved with tag: {{tag}}.": "\u0422\u043E\u0447\u043A\u0430 \u0432\u043E\u0441\u0441\u0442\u0430\u043D\u043E\u0432\u043B\u0435\u043D\u0438\u044F \u0434\u0438\u0430\u043B\u043E\u0433\u0430 \u0441\u043E\u0445\u0440\u0430\u043D\u0435\u043D\u0430 \u0441 \u0442\u0435\u0433\u043E\u043C: {{tag}}.",
      "No conversation found to save.": "\u041D\u0435\u0442 \u0434\u0438\u0430\u043B\u043E\u0433\u0430 \u0434\u043B\u044F \u0441\u043E\u0445\u0440\u0430\u043D\u0435\u043D\u0438\u044F.",
      "No chat client available to share conversation.": "\u041D\u0435\u0442 \u0434\u043E\u0441\u0442\u0443\u043F\u043D\u043E\u0433\u043E \u043A\u043B\u0438\u0435\u043D\u0442\u0430 \u0447\u0430\u0442\u0430 \u0434\u043B\u044F \u044D\u043A\u0441\u043F\u043E\u0440\u0442\u0430 \u0434\u0438\u0430\u043B\u043E\u0433\u0430.",
      "Invalid file format. Only .md and .json are supported.": "\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 \u0444\u043E\u0440\u043C\u0430\u0442 \u0444\u0430\u0439\u043B\u0430. \u041F\u043E\u0434\u0434\u0435\u0440\u0436\u0438\u0432\u0430\u044E\u0442\u0441\u044F \u0442\u043E\u043B\u044C\u043A\u043E .md \u0438 .json.",
      "Error sharing conversation: {{error}}": "\u041E\u0448\u0438\u0431\u043A\u0430 \u043F\u0440\u0438 \u044D\u043A\u0441\u043F\u043E\u0440\u0442\u0435 \u0434\u0438\u0430\u043B\u043E\u0433\u0430: {{error}}",
      "Conversation shared to {{filePath}}": "\u0414\u0438\u0430\u043B\u043E\u0433 \u044D\u043A\u0441\u043F\u043E\u0440\u0442\u0438\u0440\u043E\u0432\u0430\u043D \u0432 {{filePath}}",
      "No conversation found to share.": "\u041D\u0435\u0442 \u0434\u0438\u0430\u043B\u043E\u0433\u0430 \u0434\u043B\u044F \u044D\u043A\u0441\u043F\u043E\u0440\u0442\u0430.",
      "Share the current conversation to a markdown or json file. Usage: /chat share <file>": "\u042D\u043A\u0441\u043F\u043E\u0440\u0442\u0438\u0440\u043E\u0432\u0430\u0442\u044C \u0442\u0435\u043A\u0443\u0449\u0438\u0439 \u0434\u0438\u0430\u043B\u043E\u0433 \u0432 markdown \u0438\u043B\u0438 json \u0444\u0430\u0439\u043B. \u0418\u0441\u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u043D\u0438\u0435: /chat share <\u0444\u0430\u0439\u043B>",
      // ============================================================================
      // Команды - Резюме
      // ============================================================================
      "Generate a project summary and save it to .qwen/PROJECT_SUMMARY.md": "\u0421\u0433\u0435\u043D\u0435\u0440\u0438\u0440\u043E\u0432\u0430\u0442\u044C \u0441\u0432\u043E\u0434\u043A\u0443 \u043F\u0440\u043E\u0435\u043A\u0442\u0430 \u0438 \u0441\u043E\u0445\u0440\u0430\u043D\u0438\u0442\u044C \u0435\u0451 \u0432 .qwen/PROJECT_SUMMARY.md",
      "No chat client available to generate summary.": "\u041D\u0435\u0442 \u0434\u043E\u0441\u0442\u0443\u043F\u043D\u043E\u0433\u043E \u0447\u0430\u0442-\u043A\u043B\u0438\u0435\u043D\u0442\u0430 \u0434\u043B\u044F \u0433\u0435\u043D\u0435\u0440\u0430\u0446\u0438\u0438 \u0441\u0432\u043E\u0434\u043A\u0438.",
      "Already generating summary, wait for previous request to complete": "\u0413\u0435\u043D\u0435\u0440\u0430\u0446\u0438\u044F \u0441\u0432\u043E\u0434\u043A\u0438 \u0443\u0436\u0435 \u0432\u044B\u043F\u043E\u043B\u043D\u044F\u0435\u0442\u0441\u044F, \u0434\u043E\u0436\u0434\u0438\u0442\u0435\u0441\u044C \u0437\u0430\u0432\u0435\u0440\u0448\u0435\u043D\u0438\u044F \u043F\u0440\u0435\u0434\u044B\u0434\u0443\u0449\u0435\u0433\u043E \u0437\u0430\u043F\u0440\u043E\u0441\u0430",
      "No conversation found to summarize.": "\u041D\u0435 \u043D\u0430\u0439\u0434\u0435\u043D\u043E \u0434\u0438\u0430\u043B\u043E\u0433\u043E\u0432 \u0434\u043B\u044F \u0441\u043E\u0437\u0434\u0430\u043D\u0438\u044F \u0441\u0432\u043E\u0434\u043A\u0438.",
      "Failed to generate project context summary: {{error}}": "\u041D\u0435 \u0443\u0434\u0430\u043B\u043E\u0441\u044C \u0441\u0433\u0435\u043D\u0435\u0440\u0438\u0440\u043E\u0432\u0430\u0442\u044C \u0441\u0432\u043E\u0434\u043A\u0443 \u043A\u043E\u043D\u0442\u0435\u043A\u0441\u0442\u0430 \u043F\u0440\u043E\u0435\u043A\u0442\u0430: {{error}}",
      "Saved project summary to {{filePathForDisplay}}.": "\u0421\u0432\u043E\u0434\u043A\u0430 \u043F\u0440\u043E\u0435\u043A\u0442\u0430 \u0441\u043E\u0445\u0440\u0430\u043D\u0435\u043D\u0430 \u0432 {{filePathForDisplay}}",
      "Saving project summary...": "\u0421\u043E\u0445\u0440\u0430\u043D\u0435\u043D\u0438\u0435 \u0441\u0432\u043E\u0434\u043A\u0438 \u043F\u0440\u043E\u0435\u043A\u0442\u0430...",
      "Generating project summary...": "\u0413\u0435\u043D\u0435\u0440\u0430\u0446\u0438\u044F \u0441\u0432\u043E\u0434\u043A\u0438 \u043F\u0440\u043E\u0435\u043A\u0442\u0430...",
      "Failed to generate summary - no text content received from LLM response": "\u041D\u0435 \u0443\u0434\u0430\u043B\u043E\u0441\u044C \u0441\u0433\u0435\u043D\u0435\u0440\u0438\u0440\u043E\u0432\u0430\u0442\u044C \u0441\u0432\u043E\u0434\u043A\u0443 - \u043D\u0435 \u043F\u043E\u043B\u0443\u0447\u0435\u043D \u0442\u0435\u043A\u0441\u0442\u043E\u0432\u044B\u0439 \u043A\u043E\u043D\u0442\u0435\u043D\u0442 \u0438\u0437 \u043E\u0442\u0432\u0435\u0442\u0430 LLM",
      // ============================================================================
      // Команды - Модель
      // ============================================================================
      "Switch the model for this session": "\u041F\u0435\u0440\u0435\u043A\u043B\u044E\u0447\u0435\u043D\u0438\u0435 \u043C\u043E\u0434\u0435\u043B\u0438 \u0434\u043B\u044F \u044D\u0442\u043E\u0439 \u0441\u0435\u0441\u0441\u0438\u0438",
      "Content generator configuration not available.": "\u041A\u043E\u043D\u0444\u0438\u0433\u0443\u0440\u0430\u0446\u0438\u044F \u0433\u0435\u043D\u0435\u0440\u0430\u0442\u043E\u0440\u0430 \u0441\u043E\u0434\u0435\u0440\u0436\u0438\u043C\u043E\u0433\u043E \u043D\u0435\u0434\u043E\u0441\u0442\u0443\u043F\u043D\u0430.",
      "Authentication type not available.": "\u0422\u0438\u043F \u0430\u0432\u0442\u043E\u0440\u0438\u0437\u0430\u0446\u0438\u0438 \u043D\u0435\u0434\u043E\u0441\u0442\u0443\u043F\u0435\u043D.",
      "No models available for the current authentication type ({{authType}}).": "\u041D\u0435\u0442 \u0434\u043E\u0441\u0442\u0443\u043F\u043D\u044B\u0445 \u043C\u043E\u0434\u0435\u043B\u0435\u0439 \u0434\u043B\u044F \u0442\u0435\u043A\u0443\u0449\u0435\u0433\u043E \u0442\u0438\u043F\u0430 \u0430\u0432\u0442\u043E\u0440\u0438\u0437\u0430\u0446\u0438\u0438 ({{authType}}).",
      // ============================================================================
      // Команды - Очистка
      // ============================================================================
      "Starting a new session, resetting chat, and clearing terminal.": "\u041D\u0430\u0447\u0430\u043B\u043E \u043D\u043E\u0432\u043E\u0439 \u0441\u0435\u0441\u0441\u0438\u0438, \u0441\u0431\u0440\u043E\u0441 \u0447\u0430\u0442\u0430 \u0438 \u043E\u0447\u0438\u0441\u0442\u043A\u0430 \u0442\u0435\u0440\u043C\u0438\u043D\u0430\u043B\u0430.",
      "Starting a new session and clearing.": "\u041D\u0430\u0447\u0430\u043B\u043E \u043D\u043E\u0432\u043E\u0439 \u0441\u0435\u0441\u0441\u0438\u0438 \u0438 \u043E\u0447\u0438\u0441\u0442\u043A\u0430.",
      // ============================================================================
      // Команды - Сжатие
      // ============================================================================
      "Already compressing, wait for previous request to complete": "\u0423\u0436\u0435 \u0432\u044B\u043F\u043E\u043B\u043D\u044F\u0435\u0442\u0441\u044F \u0441\u0436\u0430\u0442\u0438\u0435, \u0434\u043E\u0436\u0434\u0438\u0442\u0435\u0441\u044C \u0437\u0430\u0432\u0435\u0440\u0448\u0435\u043D\u0438\u044F \u043F\u0440\u0435\u0434\u044B\u0434\u0443\u0449\u0435\u0433\u043E \u0437\u0430\u043F\u0440\u043E\u0441\u0430",
      "Failed to compress chat history.": "\u041D\u0435 \u0443\u0434\u0430\u043B\u043E\u0441\u044C \u0441\u0436\u0430\u0442\u044C \u0438\u0441\u0442\u043E\u0440\u0438\u044E \u0447\u0430\u0442\u0430.",
      "Failed to compress chat history: {{error}}": "\u041D\u0435 \u0443\u0434\u0430\u043B\u043E\u0441\u044C \u0441\u0436\u0430\u0442\u044C \u0438\u0441\u0442\u043E\u0440\u0438\u044E \u0447\u0430\u0442\u0430: {{error}}",
      "Compressing chat history": "\u0421\u0436\u0430\u0442\u0438\u0435 \u0438\u0441\u0442\u043E\u0440\u0438\u0438 \u0447\u0430\u0442\u0430",
      "Chat history compressed from {{originalTokens}} to {{newTokens}} tokens.": "\u0418\u0441\u0442\u043E\u0440\u0438\u044F \u0447\u0430\u0442\u0430 \u0441\u0436\u0430\u0442\u0430 \u0441 {{originalTokens}} \u0434\u043E {{newTokens}} \u0442\u043E\u043A\u0435\u043D\u043E\u0432.",
      "Compression was not beneficial for this history size.": "\u0421\u0436\u0430\u0442\u0438\u0435 \u043D\u0435 \u0431\u044B\u043B\u043E \u043F\u043E\u043B\u0435\u0437\u043D\u044B\u043C \u0434\u043B\u044F \u044D\u0442\u043E\u0433\u043E \u0440\u0430\u0437\u043C\u0435\u0440\u0430 \u0438\u0441\u0442\u043E\u0440\u0438\u0438.",
      "Chat history compression did not reduce size. This may indicate issues with the compression prompt.": "\u0421\u0436\u0430\u0442\u0438\u0435 \u0438\u0441\u0442\u043E\u0440\u0438\u0438 \u0447\u0430\u0442\u0430 \u043D\u0435 \u0443\u043C\u0435\u043D\u044C\u0448\u0438\u043B\u043E \u0440\u0430\u0437\u043C\u0435\u0440. \u042D\u0442\u043E \u043C\u043E\u0436\u0435\u0442 \u0443\u043A\u0430\u0437\u044B\u0432\u0430\u0442\u044C \u043D\u0430 \u043F\u0440\u043E\u0431\u043B\u0435\u043C\u044B \u0441 \u043F\u0440\u043E\u043C\u043F\u0442\u043E\u043C \u0441\u0436\u0430\u0442\u0438\u044F.",
      "Could not compress chat history due to a token counting error.": "\u041D\u0435 \u0443\u0434\u0430\u043B\u043E\u0441\u044C \u0441\u0436\u0430\u0442\u044C \u0438\u0441\u0442\u043E\u0440\u0438\u044E \u0447\u0430\u0442\u0430 \u0438\u0437-\u0437\u0430 \u043E\u0448\u0438\u0431\u043A\u0438 \u043F\u043E\u0434\u0441\u0447\u0435\u0442\u0430 \u0442\u043E\u043A\u0435\u043D\u043E\u0432.",
      "Chat history is already compressed.": "\u0418\u0441\u0442\u043E\u0440\u0438\u044F \u0447\u0430\u0442\u0430 \u0443\u0436\u0435 \u0441\u0436\u0430\u0442\u0430.",
      // ============================================================================
      // Команды - Директория
      // ============================================================================
      "Configuration is not available.": "\u041A\u043E\u043D\u0444\u0438\u0433\u0443\u0440\u0430\u0446\u0438\u044F \u043D\u0435\u0434\u043E\u0441\u0442\u0443\u043F\u043D\u0430.",
      "Please provide at least one path to add.": "\u041F\u043E\u0436\u0430\u043B\u0443\u0439\u0441\u0442\u0430, \u0443\u043A\u0430\u0436\u0438\u0442\u0435 \u0445\u043E\u0442\u044F \u0431\u044B \u043E\u0434\u0438\u043D \u043F\u0443\u0442\u044C \u0434\u043B\u044F \u0434\u043E\u0431\u0430\u0432\u043B\u0435\u043D\u0438\u044F.",
      "The /directory add command is not supported in restrictive sandbox profiles. Please use --include-directories when starting the session instead.": "\u041A\u043E\u043C\u0430\u043D\u0434\u0430 /directory add \u043D\u0435 \u043F\u043E\u0434\u0434\u0435\u0440\u0436\u0438\u0432\u0430\u0435\u0442\u0441\u044F \u0432 \u043E\u0433\u0440\u0430\u043D\u0438\u0447\u0438\u0442\u0435\u043B\u044C\u043D\u044B\u0445 \u043F\u0440\u043E\u0444\u0438\u043B\u044F\u0445 \u043F\u0435\u0441\u043E\u0447\u043D\u0438\u0446\u044B. \u041F\u043E\u0436\u0430\u043B\u0443\u0439\u0441\u0442\u0430, \u0438\u0441\u043F\u043E\u043B\u044C\u0437\u0443\u0439\u0442\u0435 --include-directories \u043F\u0440\u0438 \u0437\u0430\u043F\u0443\u0441\u043A\u0435 \u0441\u0435\u0441\u0441\u0438\u0438.",
      "Error adding '{{path}}': {{error}}": "\u041E\u0448\u0438\u0431\u043A\u0430 \u043F\u0440\u0438 \u0434\u043E\u0431\u0430\u0432\u043B\u0435\u043D\u0438\u0438 '{{path}}': {{error}}",
      "Successfully added QWEN.md files from the following directories if there are:\n- {{directories}}": "\u0423\u0441\u043F\u0435\u0448\u043D\u043E \u0434\u043E\u0431\u0430\u0432\u043B\u0435\u043D\u044B \u0444\u0430\u0439\u043B\u044B QWEN.md \u0438\u0437 \u0441\u043B\u0435\u0434\u0443\u044E\u0449\u0438\u0445 \u0434\u0438\u0440\u0435\u043A\u0442\u043E\u0440\u0438\u0439 (\u0435\u0441\u043B\u0438 \u043E\u043D\u0438 \u0435\u0441\u0442\u044C):\n- {{directories}}",
      "Error refreshing memory: {{error}}": "\u041E\u0448\u0438\u0431\u043A\u0430 \u043F\u0440\u0438 \u043E\u0431\u043D\u043E\u0432\u043B\u0435\u043D\u0438\u0438 \u043F\u0430\u043C\u044F\u0442\u0438: {{error}}",
      "Successfully added directories:\n- {{directories}}": "\u0423\u0441\u043F\u0435\u0448\u043D\u043E \u0434\u043E\u0431\u0430\u0432\u043B\u0435\u043D\u044B \u0434\u0438\u0440\u0435\u043A\u0442\u043E\u0440\u0438\u0438:\n- {{directories}}",
      "Current workspace directories:\n{{directories}}": "\u0422\u0435\u043A\u0443\u0449\u0438\u0435 \u0434\u0438\u0440\u0435\u043A\u0442\u043E\u0440\u0438\u0438 \u0440\u0430\u0431\u043E\u0447\u0435\u0433\u043E \u043F\u0440\u043E\u0441\u0442\u0440\u0430\u043D\u0441\u0442\u0432\u0430:\n{{directories}}",
      // ============================================================================
      // Команды - Документация
      // ============================================================================
      "Please open the following URL in your browser to view the documentation:\n{{url}}": "\u041F\u043E\u0436\u0430\u043B\u0443\u0439\u0441\u0442\u0430, \u043E\u0442\u043A\u0440\u043E\u0439\u0442\u0435 \u0441\u043B\u0435\u0434\u0443\u044E\u0449\u0438\u0439 URL \u0432 \u0431\u0440\u0430\u0443\u0437\u0435\u0440\u0435 \u0434\u043B\u044F \u043F\u0440\u043E\u0441\u043C\u043E\u0442\u0440\u0430 \u0434\u043E\u043A\u0443\u043C\u0435\u043D\u0442\u0430\u0446\u0438\u0438:\n{{url}}",
      "Opening documentation in your browser: {{url}}": "\u041E\u0442\u043A\u0440\u044B\u0442\u0438\u0435 \u0434\u043E\u043A\u0443\u043C\u0435\u043D\u0442\u0430\u0446\u0438\u0438 \u0432 \u0431\u0440\u0430\u0443\u0437\u0435\u0440\u0435: {{url}}",
      // ============================================================================
      // Диалоги - Подтверждение инструментов
      // ============================================================================
      "Do you want to proceed?": "\u0412\u044B \u0445\u043E\u0442\u0438\u0442\u0435 \u043F\u0440\u043E\u0434\u043E\u043B\u0436\u0438\u0442\u044C?",
      "Yes, allow once": "\u0414\u0430, \u0440\u0430\u0437\u0440\u0435\u0448\u0438\u0442\u044C \u043E\u0434\u0438\u043D \u0440\u0430\u0437",
      "Allow always": "\u0412\u0441\u0435\u0433\u0434\u0430 \u0440\u0430\u0437\u0440\u0435\u0448\u0430\u0442\u044C",
      No: "\u041D\u0435\u0442",
      "No (esc)": "\u041D\u0435\u0442 (esc)",
      "Yes, allow always for this session": "\u0414\u0430, \u0432\u0441\u0435\u0433\u0434\u0430 \u0440\u0430\u0437\u0440\u0435\u0448\u0430\u0442\u044C \u0434\u043B\u044F \u044D\u0442\u043E\u0439 \u0441\u0435\u0441\u0441\u0438\u0438",
      "Modify in progress:": "\u0418\u0434\u0435\u0442 \u0438\u0437\u043C\u0435\u043D\u0435\u043D\u0438\u0435:",
      "Save and close external editor to continue": "\u0421\u043E\u0445\u0440\u0430\u043D\u0438\u0442\u0435 \u0438 \u0437\u0430\u043A\u0440\u043E\u0439\u0442\u0435 \u0432\u043D\u0435\u0448\u043D\u0438\u0439 \u0440\u0435\u0434\u0430\u043A\u0442\u043E\u0440 \u0434\u043B\u044F \u043F\u0440\u043E\u0434\u043E\u043B\u0436\u0435\u043D\u0438\u044F",
      "Apply this change?": "\u041F\u0440\u0438\u043C\u0435\u043D\u0438\u0442\u044C \u044D\u0442\u043E \u0438\u0437\u043C\u0435\u043D\u0435\u043D\u0438\u0435?",
      "Yes, allow always": "\u0414\u0430, \u0432\u0441\u0435\u0433\u0434\u0430 \u0440\u0430\u0437\u0440\u0435\u0448\u0430\u0442\u044C",
      "Modify with external editor": "\u0418\u0437\u043C\u0435\u043D\u0438\u0442\u044C \u0432\u043E \u0432\u043D\u0435\u0448\u043D\u0435\u043C \u0440\u0435\u0434\u0430\u043A\u0442\u043E\u0440\u0435",
      "No, suggest changes (esc)": "\u041D\u0435\u0442, \u043F\u0440\u0435\u0434\u043B\u043E\u0436\u0438\u0442\u044C \u0438\u0437\u043C\u0435\u043D\u0435\u043D\u0438\u044F (esc)",
      "Allow execution of: '{{command}}'?": "\u0420\u0430\u0437\u0440\u0435\u0448\u0438\u0442\u044C \u0432\u044B\u043F\u043E\u043B\u043D\u0435\u043D\u0438\u0435: '{{command}}'?",
      "Yes, allow always ...": "\u0414\u0430, \u0432\u0441\u0435\u0433\u0434\u0430 \u0440\u0430\u0437\u0440\u0435\u0448\u0430\u0442\u044C ...",
      "Yes, and auto-accept edits": "\u0414\u0430, \u0438 \u0430\u0432\u0442\u043E\u043C\u0430\u0442\u0438\u0447\u0435\u0441\u043A\u0438 \u043F\u0440\u0438\u043D\u0438\u043C\u0430\u0442\u044C \u043F\u0440\u0430\u0432\u043A\u0438",
      "Yes, and manually approve edits": "\u0414\u0430, \u0438 \u0432\u0440\u0443\u0447\u043D\u0443\u044E \u043F\u043E\u0434\u0442\u0432\u0435\u0440\u0436\u0434\u0430\u0442\u044C \u043F\u0440\u0430\u0432\u043A\u0438",
      "No, keep planning (esc)": "\u041D\u0435\u0442, \u043F\u0440\u043E\u0434\u043E\u043B\u0436\u0438\u0442\u044C \u043F\u043B\u0430\u043D\u0438\u0440\u043E\u0432\u0430\u043D\u0438\u0435 (esc)",
      "URLs to fetch:": "URL \u0434\u043B\u044F \u0437\u0430\u0433\u0440\u0443\u0437\u043A\u0438:",
      "MCP Server: {{server}}": "MCP-\u0441\u0435\u0440\u0432\u0435\u0440: {{server}}",
      "Tool: {{tool}}": "\u0418\u043D\u0441\u0442\u0440\u0443\u043C\u0435\u043D\u0442: {{tool}}",
      'Allow execution of MCP tool "{{tool}}" from server "{{server}}"?': '\u0420\u0430\u0437\u0440\u0435\u0448\u0438\u0442\u044C \u0432\u044B\u043F\u043E\u043B\u043D\u0435\u043D\u0438\u0435 \u0438\u043D\u0441\u0442\u0440\u0443\u043C\u0435\u043D\u0442\u0430 MCP "{{tool}}" \u0441 \u0441\u0435\u0440\u0432\u0435\u0440\u0430 "{{server}}"?',
      'Yes, always allow tool "{{tool}}" from server "{{server}}"': '\u0414\u0430, \u0432\u0441\u0435\u0433\u0434\u0430 \u0440\u0430\u0437\u0440\u0435\u0448\u0430\u0442\u044C \u0438\u043D\u0441\u0442\u0440\u0443\u043C\u0435\u043D\u0442 "{{tool}}" \u0441 \u0441\u0435\u0440\u0432\u0435\u0440\u0430 "{{server}}"',
      'Yes, always allow all tools from server "{{server}}"': '\u0414\u0430, \u0432\u0441\u0435\u0433\u0434\u0430 \u0440\u0430\u0437\u0440\u0435\u0448\u0430\u0442\u044C \u0432\u0441\u0435 \u0438\u043D\u0441\u0442\u0440\u0443\u043C\u0435\u043D\u0442\u044B \u0441 \u0441\u0435\u0440\u0432\u0435\u0440\u0430 "{{server}}"',
      // ============================================================================
      // Диалоги - Подтверждение оболочки
      // ============================================================================
      "Shell Command Execution": "\u0412\u044B\u043F\u043E\u043B\u043D\u0435\u043D\u0438\u0435 \u043A\u043E\u043C\u0430\u043D\u0434\u044B \u0442\u0435\u0440\u043C\u0438\u043D\u0430\u043B\u0430",
      "A custom command wants to run the following shell commands:": "\u041F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u0442\u0435\u043B\u044C\u0441\u043A\u0430\u044F \u043A\u043E\u043C\u0430\u043D\u0434\u0430 \u0445\u043E\u0447\u0435\u0442 \u0432\u044B\u043F\u043E\u043B\u043D\u0438\u0442\u044C \u0441\u043B\u0435\u0434\u0443\u044E\u0449\u0438\u0435 \u043A\u043E\u043C\u0430\u043D\u0434\u044B \u0442\u0435\u0440\u043C\u0438\u043D\u0430\u043B\u0430:",
      // ============================================================================
      // Диалоги - Квота подписки Pro
      // ============================================================================
      "Pro quota limit reached for {{model}}.": "\u0418\u0441\u0447\u0435\u0440\u043F\u0430\u043D\u0430 \u043A\u0432\u043E\u0442\u0430 \u043F\u043E\u0434\u043F\u0438\u0441\u043A\u0438 Pro \u0434\u043B\u044F {{model}}.",
      "Change auth (executes the /auth command)": "\u0418\u0437\u043C\u0435\u043D\u0438\u0442\u044C \u0430\u0432\u0442\u043E\u0440\u0438\u0437\u0430\u0446\u0438\u044E (\u0432\u044B\u043F\u043E\u043B\u043D\u044F\u0435\u0442 \u043A\u043E\u043C\u0430\u043D\u0434\u0443 /auth)",
      "Continue with {{model}}": "\u041F\u0440\u043E\u0434\u043E\u043B\u0436\u0438\u0442\u044C \u0441 {{model}}",
      // ============================================================================
      // Диалоги - Приветствие при возвращении
      // ============================================================================
      "Current Plan:": "\u0422\u0435\u043A\u0443\u0449\u0438\u0439 \u043F\u043B\u0430\u043D:",
      "Progress: {{done}}/{{total}} tasks completed": "\u041F\u0440\u043E\u0433\u0440\u0435\u0441\u0441: {{done}}/{{total}} \u0437\u0430\u0434\u0430\u0447 \u0432\u044B\u043F\u043E\u043B\u043D\u0435\u043D\u043E",
      ", {{inProgress}} in progress": ", {{inProgress}} \u0432 \u043F\u0440\u043E\u0446\u0435\u0441\u0441\u0435",
      "Pending Tasks:": "\u041E\u0436\u0438\u0434\u0430\u044E\u0449\u0438\u0435 \u0437\u0430\u0434\u0430\u0447\u0438:",
      "What would you like to do?": "\u0427\u0442\u043E \u0432\u044B \u0445\u043E\u0442\u0438\u0442\u0435 \u0441\u0434\u0435\u043B\u0430\u0442\u044C?",
      "Choose how to proceed with your session:": "\u0412\u044B\u0431\u0435\u0440\u0438\u0442\u0435, \u043A\u0430\u043A \u043F\u0440\u043E\u0434\u043E\u043B\u0436\u0438\u0442\u044C \u0441\u0435\u0441\u0441\u0438\u044E:",
      "Start new chat session": "\u041D\u0430\u0447\u0430\u0442\u044C \u043D\u043E\u0432\u0443\u044E \u0441\u0435\u0441\u0441\u0438\u044E \u0447\u0430\u0442\u0430",
      "Continue previous conversation": "\u041F\u0440\u043E\u0434\u043E\u043B\u0436\u0438\u0442\u044C \u043F\u0440\u0435\u0434\u044B\u0434\u0443\u0449\u0438\u0439 \u0434\u0438\u0430\u043B\u043E\u0433",
      "\u{1F44B} Welcome back! (Last updated: {{timeAgo}})": "\u{1F44B} \u0421 \u0432\u043E\u0437\u0432\u0440\u0430\u0449\u0435\u043D\u0438\u0435\u043C! (\u041F\u043E\u0441\u043B\u0435\u0434\u043D\u0435\u0435 \u043E\u0431\u043D\u043E\u0432\u043B\u0435\u043D\u0438\u0435: {{timeAgo}})",
      "\u{1F3AF} Overall Goal:": "\u{1F3AF} \u041E\u0431\u0449\u0430\u044F \u0446\u0435\u043B\u044C:",
      // ============================================================================
      // Диалоги - Авторизация
      // ============================================================================
      "Get started": "\u041D\u0430\u0447\u0430\u0442\u044C",
      "How would you like to authenticate for this project?": "\u041A\u0430\u043A \u0432\u044B \u0445\u043E\u0442\u0438\u0442\u0435 \u0430\u0432\u0442\u043E\u0440\u0438\u0437\u043E\u0432\u0430\u0442\u044C\u0441\u044F \u0434\u043B\u044F \u044D\u0442\u043E\u0433\u043E \u043F\u0440\u043E\u0435\u043A\u0442\u0430?",
      "OpenAI API key is required to use OpenAI authentication.": "\u0414\u043B\u044F \u0438\u0441\u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u043D\u0438\u044F \u0430\u0432\u0442\u043E\u0440\u0438\u0437\u0430\u0446\u0438\u0438 OpenAI \u0442\u0440\u0435\u0431\u0443\u0435\u0442\u0441\u044F \u043A\u043B\u044E\u0447 API OpenAI.",
      "You must select an auth method to proceed. Press Ctrl+C again to exit.": "\u0412\u044B \u0434\u043E\u043B\u0436\u043D\u044B \u0432\u044B\u0431\u0440\u0430\u0442\u044C \u043C\u0435\u0442\u043E\u0434 \u0430\u0432\u0442\u043E\u0440\u0438\u0437\u0430\u0446\u0438\u0438 \u0434\u043B\u044F \u043F\u0440\u043E\u0434\u043E\u043B\u0436\u0435\u043D\u0438\u044F. \u041D\u0430\u0436\u043C\u0438\u0442\u0435 Ctrl+C \u0441\u043D\u043E\u0432\u0430 \u0434\u043B\u044F \u0432\u044B\u0445\u043E\u0434\u0430.",
      "(Use Enter to Set Auth)": "(Enter \u0434\u043B\u044F \u0443\u0441\u0442\u0430\u043D\u043E\u0432\u043A\u0438 \u0430\u0432\u0442\u043E\u0440\u0438\u0437\u0430\u0446\u0438\u0438)",
      "Terms of Services and Privacy Notice for Qwen Code": "\u0423\u0441\u043B\u043E\u0432\u0438\u044F \u043E\u0431\u0441\u043B\u0443\u0436\u0438\u0432\u0430\u043D\u0438\u044F \u0438 \u0443\u0432\u0435\u0434\u043E\u043C\u043B\u0435\u043D\u0438\u0435 \u043E \u043A\u043E\u043D\u0444\u0438\u0434\u0435\u043D\u0446\u0438\u0430\u043B\u044C\u043D\u043E\u0441\u0442\u0438 \u0434\u043B\u044F Qwen Code",
      "Qwen OAuth": "Qwen OAuth",
      "Login with QwenChat account to use daily free quota.": "\u0412\u043E\u0439\u0434\u0438\u0442\u0435 \u0441 \u043F\u043E\u043C\u043E\u0449\u044C\u044E \u0430\u043A\u043A\u0430\u0443\u043D\u0442\u0430 QwenChat, \u0447\u0442\u043E\u0431\u044B \u0438\u0441\u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u0442\u044C \u0435\u0436\u0435\u0434\u043D\u0435\u0432\u043D\u0443\u044E \u0431\u0435\u0441\u043F\u043B\u0430\u0442\u043D\u0443\u044E \u043A\u0432\u043E\u0442\u0443.",
      "API-KEY": "API-KEY",
      "Use coding plan credentials or your own api-keys/providers.": "\u0418\u0441\u043F\u043E\u043B\u044C\u0437\u0443\u0439\u0442\u0435 \u0443\u0447\u0435\u0442\u043D\u044B\u0435 \u0434\u0430\u043D\u043D\u044B\u0435 Coding Plan \u0438\u043B\u0438 \u0441\u0432\u043E\u0438 \u0441\u043E\u0431\u0441\u0442\u0432\u0435\u043D\u043D\u044B\u0435 API-\u043A\u043B\u044E\u0447\u0438/\u043F\u0440\u043E\u0432\u0430\u0439\u0434\u0435\u0440\u044B.",
      OpenAI: "OpenAI",
      "Failed to login. Message: {{message}}": "\u041D\u0435 \u0443\u0434\u0430\u043B\u043E\u0441\u044C \u0432\u043E\u0439\u0442\u0438. \u0421\u043E\u043E\u0431\u0449\u0435\u043D\u0438\u0435: {{message}}",
      "Authentication is enforced to be {{enforcedType}}, but you are currently using {{currentType}}.": "\u0410\u0432\u0442\u043E\u0440\u0438\u0437\u0430\u0446\u0438\u044F \u0434\u043E\u043B\u0436\u043D\u0430 \u0431\u044B\u0442\u044C {{enforcedType}}, \u043D\u043E \u0432\u044B \u0441\u0435\u0439\u0447\u0430\u0441 \u0438\u0441\u043F\u043E\u043B\u044C\u0437\u0443\u0435\u0442\u0435 {{currentType}}.",
      "Qwen OAuth authentication timed out. Please try again.": "\u0412\u0440\u0435\u043C\u044F \u043E\u0436\u0438\u0434\u0430\u043D\u0438\u044F \u0430\u0432\u0442\u043E\u0440\u0438\u0437\u0430\u0446\u0438\u0438 Qwen OAuth \u0438\u0441\u0442\u0435\u043A\u043B\u043E. \u041F\u043E\u0436\u0430\u043B\u0443\u0439\u0441\u0442\u0430, \u043F\u043E\u043F\u0440\u043E\u0431\u0443\u0439\u0442\u0435 \u0441\u043D\u043E\u0432\u0430.",
      "Qwen OAuth authentication cancelled.": "\u0410\u0432\u0442\u043E\u0440\u0438\u0437\u0430\u0446\u0438\u044F Qwen OAuth \u043E\u0442\u043C\u0435\u043D\u0435\u043D\u0430.",
      "Qwen OAuth Authentication": "\u0410\u0432\u0442\u043E\u0440\u0438\u0437\u0430\u0446\u0438\u044F Qwen OAuth",
      "Please visit this URL to authorize:": "\u041F\u043E\u0436\u0430\u043B\u0443\u0439\u0441\u0442\u0430, \u043F\u043E\u0441\u0435\u0442\u0438\u0442\u0435 \u044D\u0442\u043E\u0442 URL \u0434\u043B\u044F \u0430\u0432\u0442\u043E\u0440\u0438\u0437\u0430\u0446\u0438\u0438:",
      "Or scan the QR code below:": "\u0418\u043B\u0438 \u043E\u0442\u0441\u043A\u0430\u043D\u0438\u0440\u0443\u0439\u0442\u0435 QR-\u043A\u043E\u0434 \u043D\u0438\u0436\u0435:",
      "Waiting for authorization": "\u041E\u0436\u0438\u0434\u0430\u043D\u0438\u0435 \u0430\u0432\u0442\u043E\u0440\u0438\u0437\u0430\u0446\u0438\u0438",
      "Time remaining:": "\u041E\u0441\u0442\u0430\u043B\u043E\u0441\u044C \u0432\u0440\u0435\u043C\u0435\u043D\u0438:",
      "(Press ESC or CTRL+C to cancel)": "(\u041D\u0430\u0436\u043C\u0438\u0442\u0435 ESC \u0438\u043B\u0438 CTRL+C \u0434\u043B\u044F \u043E\u0442\u043C\u0435\u043D\u044B)",
      "Qwen OAuth Authentication Timeout": "\u0422\u0430\u0439\u043C\u0430\u0443\u0442 \u0430\u0432\u0442\u043E\u0440\u0438\u0437\u0430\u0446\u0438\u0438 Qwen OAuth",
      "OAuth token expired (over {{seconds}} seconds). Please select authentication method again.": "\u0422\u043E\u043A\u0435\u043D OAuth \u0438\u0441\u0442\u0435\u043A (\u0431\u043E\u043B\u0435\u0435 {{seconds}} \u0441\u0435\u043A\u0443\u043D\u0434). \u041F\u043E\u0436\u0430\u043B\u0443\u0439\u0441\u0442\u0430, \u0432\u044B\u0431\u0435\u0440\u0438\u0442\u0435 \u043C\u0435\u0442\u043E\u0434 \u0430\u0432\u0442\u043E\u0440\u0438\u0437\u0430\u0446\u0438\u0438 \u0441\u043D\u043E\u0432\u0430.",
      "Press any key to return to authentication type selection.": "\u041D\u0430\u0436\u043C\u0438\u0442\u0435 \u043B\u044E\u0431\u0443\u044E \u043A\u043B\u0430\u0432\u0438\u0448\u0443 \u0434\u043B\u044F \u0432\u043E\u0437\u0432\u0440\u0430\u0442\u0430 \u043A \u0432\u044B\u0431\u043E\u0440\u0443 \u0442\u0438\u043F\u0430 \u0430\u0432\u0442\u043E\u0440\u0438\u0437\u0430\u0446\u0438\u0438.",
      "Waiting for Qwen OAuth authentication...": "\u041E\u0436\u0438\u0434\u0430\u043D\u0438\u0435 \u0430\u0432\u0442\u043E\u0440\u0438\u0437\u0430\u0446\u0438\u0438 Qwen OAuth...",
      "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.": "\u041F\u0440\u0438\u043C\u0435\u0447\u0430\u043D\u0438\u0435: \u0412\u0430\u0448 \u0441\u0443\u0449\u0435\u0441\u0442\u0432\u0443\u044E\u0449\u0438\u0439 \u043A\u043B\u044E\u0447 API \u0432 settings.json \u043D\u0435 \u0431\u0443\u0434\u0435\u0442 \u0443\u0434\u0430\u043B\u0435\u043D \u043F\u0440\u0438 \u0438\u0441\u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u043D\u0438\u0438 Qwen OAuth. \u0412\u044B \u043C\u043E\u0436\u0435\u0442\u0435 \u043F\u0435\u0440\u0435\u043A\u043B\u044E\u0447\u0438\u0442\u044C\u0441\u044F \u043E\u0431\u0440\u0430\u0442\u043D\u043E \u043D\u0430 \u0430\u0432\u0442\u043E\u0440\u0438\u0437\u0430\u0446\u0438\u044E OpenAI \u043F\u043E\u0437\u0436\u0435 \u043F\u0440\u0438 \u043D\u0435\u043E\u0431\u0445\u043E\u0434\u0438\u043C\u043E\u0441\u0442\u0438.",
      "Authentication timed out. Please try again.": "\u0412\u0440\u0435\u043C\u044F \u043E\u0436\u0438\u0434\u0430\u043D\u0438\u044F \u0430\u0432\u0442\u043E\u0440\u0438\u0437\u0430\u0446\u0438\u0438 \u0438\u0441\u0442\u0435\u043A\u043B\u043E. \u041F\u043E\u0436\u0430\u043B\u0443\u0439\u0441\u0442\u0430, \u043F\u043E\u043F\u0440\u043E\u0431\u0443\u0439\u0442\u0435 \u0441\u043D\u043E\u0432\u0430.",
      "Waiting for auth... (Press ESC or CTRL+C to cancel)": "\u041E\u0436\u0438\u0434\u0430\u043D\u0438\u0435 \u0430\u0432\u0442\u043E\u0440\u0438\u0437\u0430\u0446\u0438\u0438... (\u041D\u0430\u0436\u043C\u0438\u0442\u0435 ESC \u0438\u043B\u0438 CTRL+C \u0434\u043B\u044F \u043E\u0442\u043C\u0435\u043D\u044B)",
      "Missing API key for OpenAI-compatible auth. Set settings.security.auth.apiKey, or set the {{envKeyHint}} environment variable.": "\u041E\u0442\u0441\u0443\u0442\u0441\u0442\u0432\u0443\u0435\u0442 API-\u043A\u043B\u044E\u0447 \u0434\u043B\u044F \u0430\u0443\u0442\u0435\u043D\u0442\u0438\u0444\u0438\u043A\u0430\u0446\u0438\u0438, \u0441\u043E\u0432\u043C\u0435\u0441\u0442\u0438\u043C\u043E\u0439 \u0441 OpenAI. \u0423\u043A\u0430\u0436\u0438\u0442\u0435 settings.security.auth.apiKey \u0438\u043B\u0438 \u043F\u0435\u0440\u0435\u043C\u0435\u043D\u043D\u0443\u044E \u043E\u043A\u0440\u0443\u0436\u0435\u043D\u0438\u044F {{envKeyHint}}.",
      "{{envKeyHint}} environment variable not found.": "\u041F\u0435\u0440\u0435\u043C\u0435\u043D\u043D\u0430\u044F \u043E\u043A\u0440\u0443\u0436\u0435\u043D\u0438\u044F {{envKeyHint}} \u043D\u0435 \u043D\u0430\u0439\u0434\u0435\u043D\u0430.",
      "{{envKeyHint}} environment variable not found. Please set it in your .env file or environment variables.": "\u041F\u0435\u0440\u0435\u043C\u0435\u043D\u043D\u0430\u044F \u043E\u043A\u0440\u0443\u0436\u0435\u043D\u0438\u044F {{envKeyHint}} \u043D\u0435 \u043D\u0430\u0439\u0434\u0435\u043D\u0430. \u0423\u043A\u0430\u0436\u0438\u0442\u0435 \u0435\u0451 \u0432 \u0444\u0430\u0439\u043B\u0435 .env \u0438\u043B\u0438 \u0441\u0440\u0435\u0434\u0438 \u0441\u0438\u0441\u0442\u0435\u043C\u043D\u044B\u0445 \u043F\u0435\u0440\u0435\u043C\u0435\u043D\u043D\u044B\u0445.",
      "{{envKeyHint}} environment variable not found (or set settings.security.auth.apiKey). Please set it in your .env file or environment variables.": "\u041F\u0435\u0440\u0435\u043C\u0435\u043D\u043D\u0430\u044F \u043E\u043A\u0440\u0443\u0436\u0435\u043D\u0438\u044F {{envKeyHint}} \u043D\u0435 \u043D\u0430\u0439\u0434\u0435\u043D\u0430 (\u0438\u043B\u0438 \u0443\u0441\u0442\u0430\u043D\u043E\u0432\u0438\u0442\u0435 settings.security.auth.apiKey). \u0423\u043A\u0430\u0436\u0438\u0442\u0435 \u0435\u0451 \u0432 \u0444\u0430\u0439\u043B\u0435 .env \u0438\u043B\u0438 \u0441\u0440\u0435\u0434\u0438 \u0441\u0438\u0441\u0442\u0435\u043C\u043D\u044B\u0445 \u043F\u0435\u0440\u0435\u043C\u0435\u043D\u043D\u044B\u0445.",
      "Missing API key for OpenAI-compatible auth. Set the {{envKeyHint}} environment variable.": "\u041E\u0442\u0441\u0443\u0442\u0441\u0442\u0432\u0443\u0435\u0442 API-\u043A\u043B\u044E\u0447 \u0434\u043B\u044F \u0430\u0443\u0442\u0435\u043D\u0442\u0438\u0444\u0438\u043A\u0430\u0446\u0438\u0438, \u0441\u043E\u0432\u043C\u0435\u0441\u0442\u0438\u043C\u043E\u0439 \u0441 OpenAI. \u0423\u0441\u0442\u0430\u043D\u043E\u0432\u0438\u0442\u0435 \u043F\u0435\u0440\u0435\u043C\u0435\u043D\u043D\u0443\u044E \u043E\u043A\u0440\u0443\u0436\u0435\u043D\u0438\u044F {{envKeyHint}}.",
      "Anthropic provider missing required baseUrl in modelProviders[].baseUrl.": "\u0423 \u043F\u0440\u043E\u0432\u0430\u0439\u0434\u0435\u0440\u0430 Anthropic \u043E\u0442\u0441\u0443\u0442\u0441\u0442\u0432\u0443\u0435\u0442 \u043E\u0431\u044F\u0437\u0430\u0442\u0435\u043B\u044C\u043D\u044B\u0439 baseUrl \u0432 modelProviders[].baseUrl.",
      "ANTHROPIC_BASE_URL environment variable not found.": "\u041F\u0435\u0440\u0435\u043C\u0435\u043D\u043D\u0430\u044F \u043E\u043A\u0440\u0443\u0436\u0435\u043D\u0438\u044F ANTHROPIC_BASE_URL \u043D\u0435 \u043D\u0430\u0439\u0434\u0435\u043D\u0430.",
      "Invalid auth method selected.": "\u0412\u044B\u0431\u0440\u0430\u043D \u043D\u0435\u0434\u043E\u043F\u0443\u0441\u0442\u0438\u043C\u044B\u0439 \u043C\u0435\u0442\u043E\u0434 \u0430\u0432\u0442\u043E\u0440\u0438\u0437\u0430\u0446\u0438\u0438.",
      "Failed to authenticate. Message: {{message}}": "\u041D\u0435 \u0443\u0434\u0430\u043B\u043E\u0441\u044C \u0430\u0432\u0442\u043E\u0440\u0438\u0437\u043E\u0432\u0430\u0442\u044C\u0441\u044F. \u0421\u043E\u043E\u0431\u0449\u0435\u043D\u0438\u0435: {{message}}",
      "Authenticated successfully with {{authType}} credentials.": "\u0423\u0441\u043F\u0435\u0448\u043D\u043E \u0430\u0432\u0442\u043E\u0440\u0438\u0437\u043E\u0432\u0430\u043D\u043E \u0441 \u0443\u0447\u0435\u0442\u043D\u044B\u043C\u0438 \u0434\u0430\u043D\u043D\u044B\u043C\u0438 {{authType}}.",
      'Invalid QWEN_DEFAULT_AUTH_TYPE value: "{{value}}". Valid values are: {{validValues}}': '\u041D\u0435\u0432\u0435\u0440\u043D\u043E\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435 QWEN_DEFAULT_AUTH_TYPE: "{{value}}". \u0414\u043E\u043F\u0443\u0441\u0442\u0438\u043C\u044B\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u044F: {{validValues}}',
      "OpenAI Configuration Required": "\u0422\u0440\u0435\u0431\u0443\u0435\u0442\u0441\u044F \u043A\u043E\u043D\u0444\u0438\u0433\u0443\u0440\u0430\u0446\u0438\u044F OpenAI",
      "Please enter your OpenAI configuration. You can get an API key from": "\u041F\u043E\u0436\u0430\u043B\u0443\u0439\u0441\u0442\u0430, \u0432\u0432\u0435\u0434\u0438\u0442\u0435 \u043A\u043E\u043D\u0444\u0438\u0433\u0443\u0440\u0430\u0446\u0438\u044E OpenAI. \u0412\u044B \u043C\u043E\u0436\u0435\u0442\u0435 \u043F\u043E\u043B\u0443\u0447\u0438\u0442\u044C \u043A\u043B\u044E\u0447 API \u043D\u0430",
      "API Key:": "\u041A\u043B\u044E\u0447 API:",
      "Invalid credentials: {{errorMessage}}": "\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0435 \u0443\u0447\u0435\u0442\u043D\u044B\u0435 \u0434\u0430\u043D\u043D\u044B\u0435: {{errorMessage}}",
      "Failed to validate credentials": "\u041D\u0435 \u0443\u0434\u0430\u043B\u043E\u0441\u044C \u043F\u0440\u043E\u0432\u0435\u0440\u0438\u0442\u044C \u0443\u0447\u0435\u0442\u043D\u044B\u0435 \u0434\u0430\u043D\u043D\u044B\u0435",
      "Press Enter to continue, Tab/\u2191\u2193 to navigate, Esc to cancel": "Enter \u0434\u043B\u044F \u043F\u0440\u043E\u0434\u043E\u043B\u0436\u0435\u043D\u0438\u044F, Tab/\u2191\u2193 \u0434\u043B\u044F \u043D\u0430\u0432\u0438\u0433\u0430\u0446\u0438\u0438, Esc \u0434\u043B\u044F \u043E\u0442\u043C\u0435\u043D\u044B",
      // ============================================================================
      // Диалоги - Модель
      // ============================================================================
      "Select Model": "\u0412\u044B\u0431\u0440\u0430\u0442\u044C \u043C\u043E\u0434\u0435\u043B\u044C",
      "(Press Esc to close)": "(\u041D\u0430\u0436\u043C\u0438\u0442\u0435 Esc \u0434\u043B\u044F \u0437\u0430\u043A\u0440\u044B\u0442\u0438\u044F)",
      "Current (effective) configuration": "\u0422\u0435\u043A\u0443\u0449\u0430\u044F (\u0444\u0430\u043A\u0442\u0438\u0447\u0435\u0441\u043A\u0430\u044F) \u043A\u043E\u043D\u0444\u0438\u0433\u0443\u0440\u0430\u0446\u0438\u044F",
      AuthType: "\u0422\u0438\u043F \u0430\u0432\u0442\u043E\u0440\u0438\u0437\u0430\u0446\u0438\u0438",
      "API Key": "API-\u043A\u043B\u044E\u0447",
      unset: "\u043D\u0435 \u0437\u0430\u0434\u0430\u043D\u043E",
      "(default)": "(\u043F\u043E \u0443\u043C\u043E\u043B\u0447\u0430\u043D\u0438\u044E)",
      "(set)": "(\u0443\u0441\u0442\u0430\u043D\u043E\u0432\u043B\u0435\u043D\u043E)",
      "(not set)": "(\u043D\u0435 \u0437\u0430\u0434\u0430\u043D\u043E)",
      "Failed to switch model to '{{modelId}}'.\n\n{{error}}": "\u041D\u0435 \u0443\u0434\u0430\u043B\u043E\u0441\u044C \u043F\u0435\u0440\u0435\u043A\u043B\u044E\u0447\u0438\u0442\u044C\u0441\u044F \u043D\u0430 \u043C\u043E\u0434\u0435\u043B\u044C '{{modelId}}'.\n\n{{error}}",
      "Qwen 3.5 Plus \u2014 efficient hybrid model with leading coding performance": "Qwen 3.5 Plus \u2014 \u044D\u0444\u0444\u0435\u043A\u0442\u0438\u0432\u043D\u0430\u044F \u0433\u0438\u0431\u0440\u0438\u0434\u043D\u0430\u044F \u043C\u043E\u0434\u0435\u043B\u044C \u0441 \u043B\u0438\u0434\u0438\u0440\u0443\u044E\u0449\u0435\u0439 \u043F\u0440\u043E\u0438\u0437\u0432\u043E\u0434\u0438\u0442\u0435\u043B\u044C\u043D\u043E\u0441\u0442\u044C\u044E \u0432 \u043F\u0440\u043E\u0433\u0440\u0430\u043C\u043C\u0438\u0440\u043E\u0432\u0430\u043D\u0438\u0438",
      "The latest Qwen Vision model from Alibaba Cloud ModelStudio (version: qwen3-vl-plus-2025-09-23)": "\u041F\u043E\u0441\u043B\u0435\u0434\u043D\u044F\u044F \u043C\u043E\u0434\u0435\u043B\u044C Qwen Vision \u043E\u0442 Alibaba Cloud ModelStudio (\u0432\u0435\u0440\u0441\u0438\u044F: qwen3-vl-plus-2025-09-23)",
      // ============================================================================
      // Диалоги - Разрешения
      // ============================================================================
      "Manage folder trust settings": "\u0423\u043F\u0440\u0430\u0432\u043B\u0435\u043D\u0438\u0435 \u043D\u0430\u0441\u0442\u0440\u043E\u0439\u043A\u0430\u043C\u0438 \u0434\u043E\u0432\u0435\u0440\u0438\u044F \u043A \u043F\u0430\u043F\u043A\u0430\u043C",
      // ============================================================================
      // Строка состояния
      // ============================================================================
      "Using:": "\u0418\u0441\u043F\u043E\u043B\u044C\u0437\u0443\u0435\u0442\u0441\u044F:",
      "{{count}} open file": "{{count}} \u043E\u0442\u043A\u0440\u044B\u0442\u044B\u0439 \u0444\u0430\u0439\u043B",
      "{{count}} open files": "{{count}} \u043E\u0442\u043A\u0440\u044B\u0442\u044B\u0445 \u0444\u0430\u0439\u043B\u0430(\u043E\u0432)",
      "(ctrl+g to view)": "(ctrl+g \u0434\u043B\u044F \u043F\u0440\u043E\u0441\u043C\u043E\u0442\u0440\u0430)",
      "{{count}} {{name}} file": "{{count}} \u0444\u0430\u0439\u043B {{name}}",
      "{{count}} {{name}} files": "{{count}} \u0444\u0430\u0439\u043B\u0430(\u043E\u0432) {{name}}",
      "{{count}} MCP server": "{{count}} MCP-\u0441\u0435\u0440\u0432\u0435\u0440",
      "{{count}} MCP servers": "{{count}} MCP-\u0441\u0435\u0440\u0432\u0435\u0440\u0430(\u043E\u0432)",
      "{{count}} Blocked": "{{count}} \u0437\u0430\u0431\u043B\u043E\u043A\u0438\u0440\u043E\u0432\u0430\u043D(\u043E)",
      "(ctrl+t to view)": "(ctrl+t \u0434\u043B\u044F \u043F\u0440\u043E\u0441\u043C\u043E\u0442\u0440\u0430)",
      "(ctrl+t to toggle)": "(ctrl+t \u0434\u043B\u044F \u043F\u0435\u0440\u0435\u043A\u043B\u044E\u0447\u0435\u043D\u0438\u044F)",
      "Press Ctrl+C again to exit.": "\u041D\u0430\u0436\u043C\u0438\u0442\u0435 Ctrl+C \u0441\u043D\u043E\u0432\u0430 \u0434\u043B\u044F \u0432\u044B\u0445\u043E\u0434\u0430.",
      "Press Ctrl+D again to exit.": "\u041D\u0430\u0436\u043C\u0438\u0442\u0435 Ctrl+D \u0441\u043D\u043E\u0432\u0430 \u0434\u043B\u044F \u0432\u044B\u0445\u043E\u0434\u0430.",
      "Press Esc again to clear.": "\u041D\u0430\u0436\u043C\u0438\u0442\u0435 Esc \u0441\u043D\u043E\u0432\u0430 \u0434\u043B\u044F \u043E\u0447\u0438\u0441\u0442\u043A\u0438.",
      // ============================================================================
      // Статус MCP
      // ============================================================================
      "No MCP servers configured.": "\u041D\u0435 \u043D\u0430\u0441\u0442\u0440\u043E\u0435\u043D\u043E MCP-\u0441\u0435\u0440\u0432\u0435\u0440\u043E\u0432.",
      "\u23F3 MCP servers are starting up ({{count}} initializing)...": "\u23F3 MCP-\u0441\u0435\u0440\u0432\u0435\u0440\u044B \u0437\u0430\u043F\u0443\u0441\u043A\u0430\u044E\u0442\u0441\u044F ({{count}} \u0438\u043D\u0438\u0446\u0438\u0430\u043B\u0438\u0437\u0438\u0440\u0443\u0435\u0442\u0441\u044F)...",
      "Note: First startup may take longer. Tool availability will update automatically.": "\u041F\u0440\u0438\u043C\u0435\u0447\u0430\u043D\u0438\u0435: \u041F\u0435\u0440\u0432\u044B\u0439 \u0437\u0430\u043F\u0443\u0441\u043A \u043C\u043E\u0436\u0435\u0442 \u0437\u0430\u043D\u044F\u0442\u044C \u0431\u043E\u043B\u044C\u0448\u0435 \u0432\u0440\u0435\u043C\u0435\u043D\u0438. \u0414\u043E\u0441\u0442\u0443\u043F\u043D\u043E\u0441\u0442\u044C \u0438\u043D\u0441\u0442\u0440\u0443\u043C\u0435\u043D\u0442\u043E\u0432 \u043E\u0431\u043D\u043E\u0432\u0438\u0442\u0441\u044F \u0430\u0432\u0442\u043E\u043C\u0430\u0442\u0438\u0447\u0435\u0441\u043A\u0438.",
      "Configured MCP servers:": "\u041D\u0430\u0441\u0442\u0440\u043E\u0435\u043D\u043D\u044B\u0435 MCP-\u0441\u0435\u0440\u0432\u0435\u0440\u044B:",
      Ready: "\u0413\u043E\u0442\u043E\u0432",
      "Starting... (first startup may take longer)": "\u0417\u0430\u043F\u0443\u0441\u043A... (\u043F\u0435\u0440\u0432\u044B\u0439 \u0437\u0430\u043F\u0443\u0441\u043A \u043C\u043E\u0436\u0435\u0442 \u0437\u0430\u043D\u044F\u0442\u044C \u0431\u043E\u043B\u044C\u0448\u0435 \u0432\u0440\u0435\u043C\u0435\u043D\u0438)",
      Disconnected: "\u041E\u0442\u043A\u043B\u044E\u0447\u0435\u043D",
      "{{count}} tool": "{{count}} \u0438\u043D\u0441\u0442\u0440\u0443\u043C\u0435\u043D\u0442",
      "{{count}} tools": "{{count}} \u0438\u043D\u0441\u0442\u0440\u0443\u043C\u0435\u043D\u0442\u0430(\u043E\u0432)",
      "{{count}} prompt": "{{count}} \u043F\u0440\u043E\u043C\u043F\u0442",
      "{{count}} prompts": "{{count}} \u043F\u0440\u043E\u043C\u043F\u0442\u0430(\u043E\u0432)",
      "(from {{extensionName}})": "(\u043E\u0442 {{extensionName}})",
      OAuth: "OAuth",
      "OAuth expired": "OAuth \u0438\u0441\u0442\u0435\u043A",
      "OAuth not authenticated": "OAuth \u043D\u0435 \u0430\u0432\u0442\u043E\u0440\u0438\u0437\u043E\u0432\u0430\u043D",
      "tools and prompts will appear when ready": "\u0438\u043D\u0441\u0442\u0440\u0443\u043C\u0435\u043D\u0442\u044B \u0438 \u043F\u0440\u043E\u043C\u043F\u0442\u044B \u043F\u043E\u044F\u0432\u044F\u0442\u0441\u044F, \u043A\u043E\u0433\u0434\u0430 \u0431\u0443\u0434\u0443\u0442 \u0433\u043E\u0442\u043E\u0432\u044B",
      "{{count}} tools cached": "{{count}} \u0438\u043D\u0441\u0442\u0440\u0443\u043C\u0435\u043D\u0442\u0430(\u043E\u0432) \u0432 \u043A\u044D\u0448\u0435",
      "Tools:": "\u0418\u043D\u0441\u0442\u0440\u0443\u043C\u0435\u043D\u0442\u044B:",
      "Parameters:": "\u041F\u0430\u0440\u0430\u043C\u0435\u0442\u0440\u044B:",
      "Prompts:": "\u041F\u0440\u043E\u043C\u043F\u0442\u044B:",
      Blocked: "\u0417\u0430\u0431\u043B\u043E\u043A\u0438\u0440\u043E\u0432\u0430\u043D\u043E",
      "\u{1F4A1} Tips:": "\u{1F4A1} \u041F\u043E\u0434\u0441\u043A\u0430\u0437\u043A\u0438:",
      Use: "\u0418\u0441\u043F\u043E\u043B\u044C\u0437\u0443\u0439\u0442\u0435",
      "to show server and tool descriptions": "\u0434\u043B\u044F \u043F\u043E\u043A\u0430\u0437\u0430 \u043E\u043F\u0438\u0441\u0430\u043D\u0438\u0439 \u0441\u0435\u0440\u0432\u0435\u0440\u0430 \u0438 \u0438\u043D\u0441\u0442\u0440\u0443\u043C\u0435\u043D\u0442\u043E\u0432",
      "to show tool parameter schemas": "\u0434\u043B\u044F \u043F\u043E\u043A\u0430\u0437\u0430 \u0441\u0445\u0435\u043C \u043F\u0430\u0440\u0430\u043C\u0435\u0442\u0440\u043E\u0432 \u0438\u043D\u0441\u0442\u0440\u0443\u043C\u0435\u043D\u0442\u043E\u0432",
      "to hide descriptions": "\u0434\u043B\u044F \u0441\u043A\u0440\u044B\u0442\u0438\u044F \u043E\u043F\u0438\u0441\u0430\u043D\u0438\u0439",
      "to authenticate with OAuth-enabled servers": "\u0434\u043B\u044F \u0430\u0432\u0442\u043E\u0440\u0438\u0437\u0430\u0446\u0438\u0438 \u043D\u0430 \u0441\u0435\u0440\u0432\u0435\u0440\u0430\u0445 \u0441 \u043F\u043E\u0434\u0434\u0435\u0440\u0436\u043A\u043E\u0439 OAuth",
      Press: "\u041D\u0430\u0436\u043C\u0438\u0442\u0435",
      "to toggle tool descriptions on/off": "\u0434\u043B\u044F \u043F\u0435\u0440\u0435\u043A\u043B\u044E\u0447\u0435\u043D\u0438\u044F \u043E\u043F\u0438\u0441\u0430\u043D\u0438\u0439 \u0438\u043D\u0441\u0442\u0440\u0443\u043C\u0435\u043D\u0442\u043E\u0432",
      "Starting OAuth authentication for MCP server '{{name}}'...": "\u041D\u0430\u0447\u0430\u043B\u043E \u0430\u0432\u0442\u043E\u0440\u0438\u0437\u0430\u0446\u0438\u0438 OAuth \u0434\u043B\u044F MCP-\u0441\u0435\u0440\u0432\u0435\u0440\u0430 '{{name}}'...",
      "Restarting MCP servers...": "\u041F\u0435\u0440\u0435\u0437\u0430\u043F\u0443\u0441\u043A MCP-\u0441\u0435\u0440\u0432\u0435\u0440\u043E\u0432...",
      // ============================================================================
      // Подсказки при запуске
      // ============================================================================
      "Tips for getting started:": "\u041F\u043E\u0434\u0441\u043A\u0430\u0437\u043A\u0438 \u0434\u043B\u044F \u043D\u0430\u0447\u0430\u043B\u0430 \u0440\u0430\u0431\u043E\u0442\u044B:",
      "1. Ask questions, edit files, or run commands.": "1. \u0417\u0430\u0434\u0430\u0432\u0430\u0439\u0442\u0435 \u0432\u043E\u043F\u0440\u043E\u0441\u044B, \u0440\u0435\u0434\u0430\u043A\u0442\u0438\u0440\u0443\u0439\u0442\u0435 \u0444\u0430\u0439\u043B\u044B \u0438\u043B\u0438 \u0432\u044B\u043F\u043E\u043B\u043D\u044F\u0439\u0442\u0435 \u043A\u043E\u043C\u0430\u043D\u0434\u044B.",
      "2. Be specific for the best results.": "2. \u0411\u0443\u0434\u044C\u0442\u0435 \u043A\u043E\u043D\u043A\u0440\u0435\u0442\u043D\u044B \u0434\u043B\u044F \u043B\u0443\u0447\u0448\u0438\u0445 \u0440\u0435\u0437\u0443\u043B\u044C\u0442\u0430\u0442\u043E\u0432.",
      "files to customize your interactions with Qwen Code.": "\u0444\u0430\u0439\u043B\u044B \u0434\u043B\u044F \u043D\u0430\u0441\u0442\u0440\u043E\u0439\u043A\u0438 \u0432\u0437\u0430\u0438\u043C\u043E\u0434\u0435\u0439\u0441\u0442\u0432\u0438\u044F \u0441 Qwen Code.",
      "for more information.": "\u0434\u043B\u044F \u043F\u043E\u043B\u0443\u0447\u0435\u043D\u0438\u044F \u0434\u043E\u043F\u043E\u043B\u043D\u0438\u0442\u0435\u043B\u044C\u043D\u043E\u0439 \u0438\u043D\u0444\u043E\u0440\u043C\u0430\u0446\u0438\u0438.",
      // ============================================================================
      // Экран выхода / Статистика
      // ============================================================================
      "Agent powering down. Goodbye!": "\u0410\u0433\u0435\u043D\u0442 \u0437\u0430\u0432\u0435\u0440\u0448\u0430\u0435\u0442 \u0440\u0430\u0431\u043E\u0442\u0443. \u0414\u043E \u0441\u0432\u0438\u0434\u0430\u043D\u0438\u044F!",
      "To continue this session, run": "\u0414\u043B\u044F \u043F\u0440\u043E\u0434\u043E\u043B\u0436\u0435\u043D\u0438\u044F \u044D\u0442\u043E\u0439 \u0441\u0435\u0441\u0441\u0438\u0438, \u0432\u044B\u043F\u043E\u043B\u043D\u0438\u0442\u0435",
      "Interaction Summary": "\u0421\u0432\u043E\u0434\u043A\u0430 \u0432\u0437\u0430\u0438\u043C\u043E\u0434\u0435\u0439\u0441\u0442\u0432\u0438\u044F",
      "Session ID:": "ID \u0441\u0435\u0441\u0441\u0438\u0438:",
      "Tool Calls:": "\u0412\u044B\u0437\u043E\u0432\u044B \u0438\u043D\u0441\u0442\u0440\u0443\u043C\u0435\u043D\u0442\u043E\u0432:",
      "Success Rate:": "\u041F\u0440\u043E\u0446\u0435\u043D\u0442 \u0443\u0441\u043F\u0435\u0445\u0430:",
      "User Agreement:": "\u0421\u043E\u0433\u043B\u0430\u0441\u0438\u0435 \u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u0442\u0435\u043B\u044F:",
      reviewed: "\u043F\u0440\u043E\u0432\u0435\u0440\u0435\u043D\u043E",
      "Code Changes:": "\u0418\u0437\u043C\u0435\u043D\u0435\u043D\u0438\u044F \u043A\u043E\u0434\u0430:",
      Performance: "\u041F\u0440\u043E\u0438\u0437\u0432\u043E\u0434\u0438\u0442\u0435\u043B\u044C\u043D\u043E\u0441\u0442\u044C",
      "Wall Time:": "\u041E\u0431\u0449\u0435\u0435 \u0432\u0440\u0435\u043C\u044F:",
      "Agent Active:": "\u0410\u043A\u0442\u0438\u0432\u043D\u043E\u0441\u0442\u044C \u0430\u0433\u0435\u043D\u0442\u0430:",
      "API Time:": "\u0412\u0440\u0435\u043C\u044F API:",
      "Tool Time:": "\u0412\u0440\u0435\u043C\u044F \u0438\u043D\u0441\u0442\u0440\u0443\u043C\u0435\u043D\u0442\u043E\u0432:",
      "Session Stats": "\u0421\u0442\u0430\u0442\u0438\u0441\u0442\u0438\u043A\u0430 \u0441\u0435\u0441\u0441\u0438\u0438",
      "Model Usage": "\u0418\u0441\u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u043D\u0438\u0435 \u043C\u043E\u0434\u0435\u043B\u0438",
      Reqs: "\u0417\u0430\u043F\u0440\u043E\u0441\u043E\u0432",
      "Input Tokens": "\u0412\u0445\u043E\u0434\u043D\u044B\u0445 \u0442\u043E\u043A\u0435\u043D\u043E\u0432",
      "Output Tokens": "\u0412\u044B\u0445\u043E\u0434\u043D\u044B\u0445 \u0442\u043E\u043A\u0435\u043D\u043E\u0432",
      "Savings Highlight:": "\u042D\u043A\u043E\u043D\u043E\u043C\u0438\u044F:",
      "of input tokens were served from the cache, reducing costs.": "\u0432\u0445\u043E\u0434\u043D\u044B\u0445 \u0442\u043E\u043A\u0435\u043D\u043E\u0432 \u043E\u0431\u0441\u043B\u0443\u0436\u0435\u043D\u043E \u0438\u0437 \u043A\u044D\u0448\u0430, \u0441\u043D\u0438\u0436\u0430\u044F \u0437\u0430\u0442\u0440\u0430\u0442\u044B.",
      "Tip: For a full token breakdown, run `/stats model`.": "\u041F\u043E\u0434\u0441\u043A\u0430\u0437\u043A\u0430: \u0414\u043B\u044F \u043F\u043E\u043B\u043D\u043E\u0439 \u0440\u0430\u0437\u0431\u0438\u0432\u043A\u0438 \u0442\u043E\u043A\u0435\u043D\u043E\u0432 \u0432\u044B\u043F\u043E\u043B\u043D\u0438\u0442\u0435 `/stats model`.",
      "Model Stats For Nerds": "\u0421\u0442\u0430\u0442\u0438\u0441\u0442\u0438\u043A\u0430 \u043C\u043E\u0434\u0435\u043B\u0438 \u0434\u043B\u044F \u0433\u0438\u043A\u043E\u0432",
      "Tool Stats For Nerds": "\u0421\u0442\u0430\u0442\u0438\u0441\u0442\u0438\u043A\u0430 \u0438\u043D\u0441\u0442\u0440\u0443\u043C\u0435\u043D\u0442\u043E\u0432 \u0434\u043B\u044F \u0433\u0438\u043A\u043E\u0432",
      Metric: "\u041C\u0435\u0442\u0440\u0438\u043A\u0430",
      API: "API",
      Requests: "\u0417\u0430\u043F\u0440\u043E\u0441\u044B",
      Errors: "\u041E\u0448\u0438\u0431\u043A\u0438",
      "Avg Latency": "\u0421\u0440\u0435\u0434\u043D\u044F\u044F \u0437\u0430\u0434\u0435\u0440\u0436\u043A\u0430",
      Tokens: "\u0422\u043E\u043A\u0435\u043D\u044B",
      Total: "\u0412\u0441\u0435\u0433\u043E",
      Prompt: "\u041F\u0440\u043E\u043C\u043F\u0442",
      Cached: "\u041A\u044D\u0448\u0438\u0440\u043E\u0432\u0430\u043D\u043E",
      Thoughts: "\u0420\u0430\u0437\u043C\u044B\u0448\u043B\u0435\u043D\u0438\u044F",
      Tool: "\u0418\u043D\u0441\u0442\u0440\u0443\u043C\u0435\u043D\u0442",
      Output: "\u0412\u044B\u0432\u043E\u0434",
      "No API calls have been made in this session.": "\u0412 \u044D\u0442\u043E\u0439 \u0441\u0435\u0441\u0441\u0438\u0438 \u043D\u0435 \u0431\u044B\u043B\u043E \u0432\u044B\u0437\u043E\u0432\u043E\u0432 API.",
      "Tool Name": "\u0418\u043C\u044F \u0438\u043D\u0441\u0442\u0440\u0443\u043C\u0435\u043D\u0442\u0430",
      Calls: "\u0412\u044B\u0437\u043E\u0432\u044B",
      "Success Rate": "\u041F\u0440\u043E\u0446\u0435\u043D\u0442 \u0443\u0441\u043F\u0435\u0445\u0430",
      "Avg Duration": "\u0421\u0440\u0435\u0434\u043D\u044F\u044F \u0434\u043B\u0438\u0442\u0435\u043B\u044C\u043D\u043E\u0441\u0442\u044C",
      "User Decision Summary": "\u0421\u0432\u043E\u0434\u043A\u0430 \u0440\u0435\u0448\u0435\u043D\u0438\u0439 \u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u0442\u0435\u043B\u044F",
      "Total Reviewed Suggestions:": "\u0412\u0441\u0435\u0433\u043E \u043F\u0440\u043E\u0432\u0435\u0440\u0435\u043D\u043E \u043F\u0440\u0435\u0434\u043B\u043E\u0436\u0435\u043D\u0438\u0439:",
      " \xBB Accepted:": " \xBB \u041F\u0440\u0438\u043D\u044F\u0442\u043E:",
      " \xBB Rejected:": " \xBB \u041E\u0442\u043A\u043B\u043E\u043D\u0435\u043D\u043E:",
      " \xBB Modified:": " \xBB \u0418\u0437\u043C\u0435\u043D\u0435\u043D\u043E:",
      " Overall Agreement Rate:": " \u041E\u0431\u0449\u0438\u0439 \u043F\u0440\u043E\u0446\u0435\u043D\u0442 \u0441\u043E\u0433\u043B\u0430\u0441\u0438\u044F:",
      "No tool calls have been made in this session.": "\u0412 \u044D\u0442\u043E\u0439 \u0441\u0435\u0441\u0441\u0438\u0438 \u043D\u0435 \u0431\u044B\u043B\u043E \u0432\u044B\u0437\u043E\u0432\u043E\u0432 \u0438\u043D\u0441\u0442\u0440\u0443\u043C\u0435\u043D\u0442\u043E\u0432.",
      "Session start time is unavailable, cannot calculate stats.": "\u0412\u0440\u0435\u043C\u044F \u043D\u0430\u0447\u0430\u043B\u0430 \u0441\u0435\u0441\u0441\u0438\u0438 \u043D\u0435\u0434\u043E\u0441\u0442\u0443\u043F\u043D\u043E, \u043D\u0435\u0432\u043E\u0437\u043C\u043E\u0436\u043D\u043E \u0440\u0430\u0441\u0441\u0447\u0438\u0442\u0430\u0442\u044C \u0441\u0442\u0430\u0442\u0438\u0441\u0442\u0438\u043A\u0443.",
      // ============================================================================
      // Command Format Migration
      // ============================================================================
      "Command Format Migration": "\u041C\u0438\u0433\u0440\u0430\u0446\u0438\u044F \u0444\u043E\u0440\u043C\u0430\u0442\u0430 \u043A\u043E\u043C\u0430\u043D\u0434",
      "Found {{count}} TOML command file:": "\u041D\u0430\u0439\u0434\u0435\u043D {{count}} \u0444\u0430\u0439\u043B \u043A\u043E\u043C\u0430\u043D\u0434 TOML:",
      "Found {{count}} TOML command files:": "\u041D\u0430\u0439\u0434\u0435\u043D\u043E {{count}} \u0444\u0430\u0439\u043B\u043E\u0432 \u043A\u043E\u043C\u0430\u043D\u0434 TOML:",
      "... and {{count}} more": "... \u0438 \u0435\u0449\u0451 {{count}}",
      "The TOML format is deprecated. Would you like to migrate them to Markdown format?": "\u0424\u043E\u0440\u043C\u0430\u0442 TOML \u0443\u0441\u0442\u0430\u0440\u0435\u043B. \u0425\u043E\u0442\u0438\u0442\u0435 \u043F\u0435\u0440\u0435\u043D\u0435\u0441\u0442\u0438 \u0438\u0445 \u0432 \u0444\u043E\u0440\u043C\u0430\u0442 Markdown?",
      "(Backups will be created and original files will be preserved)": "(\u0411\u0443\u0434\u0443\u0442 \u0441\u043E\u0437\u0434\u0430\u043D\u044B \u0440\u0435\u0437\u0435\u0440\u0432\u043D\u044B\u0435 \u043A\u043E\u043F\u0438\u0438, \u0438\u0441\u0445\u043E\u0434\u043D\u044B\u0435 \u0444\u0430\u0439\u043B\u044B \u0431\u0443\u0434\u0443\u0442 \u0441\u043E\u0445\u0440\u0430\u043D\u0435\u043D\u044B)",
      // ============================================================================
      // Loading Phrases
      // ============================================================================
      "Waiting for user confirmation...": "\u041E\u0436\u0438\u0434\u0430\u043D\u0438\u0435 \u043F\u043E\u0434\u0442\u0432\u0435\u0440\u0436\u0434\u0435\u043D\u0438\u044F \u043E\u0442 \u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u0442\u0435\u043B\u044F...",
      "(esc to cancel, {{time}})": "(esc \u0434\u043B\u044F \u043E\u0442\u043C\u0435\u043D\u044B, {{time}})",
      // ============================================================================
      // ============================================================================
      // Loading Phrases
      // ============================================================================
      WITTY_LOADING_PHRASES: [
        "\u041C\u043D\u0435 \u043F\u043E\u0432\u0435\u0437\u0451\u0442!",
        "\u0414\u043E\u0441\u0442\u0430\u0432\u043B\u044F\u0435\u043C \u043A\u0440\u0443\u0442\u0438\u0437\u043D\u0443... ",
        "\u0420\u0438\u0441\u0443\u0435\u043C \u0437\u0430\u0441\u0435\u0447\u043A\u0438 \u043D\u0430 \u0431\u0443\u043A\u0432\u0430\u0445...",
        "\u041F\u0440\u043E\u0431\u0438\u0440\u0430\u0435\u043C\u0441\u044F \u0447\u0435\u0440\u0435\u0437 \u0441\u043B\u0438\u0437\u0435\u0432\u0438\u043A\u043E\u0432..",
        "\u0421\u043E\u0432\u0435\u0442\u0443\u0435\u043C\u0441\u044F \u0441 \u0446\u0438\u0444\u0440\u043E\u0432\u044B\u043C\u0438 \u0434\u0443\u0445\u0430\u043C\u0438...",
        "\u0421\u0433\u043B\u0430\u0436\u0438\u0432\u0430\u043D\u0438\u0435 \u0441\u043F\u043B\u0430\u0439\u043D\u043E\u0432...",
        "\u0420\u0430\u0437\u043E\u0433\u0440\u0435\u0432\u0430\u0435\u043C \u0418\u0418-\u0445\u043E\u043C\u044F\u0447\u043A\u043E\u0432...",
        "\u0421\u043F\u0440\u0430\u0448\u0438\u0432\u0430\u0435\u043C \u0432\u043E\u043B\u0448\u0435\u0431\u043D\u0443\u044E \u0440\u0430\u043A\u0443\u0448\u043A\u0443...",
        "\u0413\u0435\u043D\u0435\u0440\u0438\u0440\u0443\u0435\u043C \u043E\u0441\u0442\u0440\u043E\u0443\u043C\u043D\u044B\u0439 \u043E\u0442\u0432\u0435\u0442...",
        "\u041F\u043E\u043B\u0438\u0440\u0443\u0435\u043C \u0430\u043B\u0433\u043E\u0440\u0438\u0442\u043C\u044B...",
        "\u041D\u0435 \u0442\u043E\u0440\u043E\u043F\u0438\u0442\u0435 \u0441\u043E\u0432\u0435\u0440\u0448\u0435\u043D\u0441\u0442\u0432\u043E (\u0438\u043B\u0438 \u043C\u043E\u0439 \u043A\u043E\u0434)...",
        "\u0417\u0430\u0432\u0430\u0440\u0438\u0432\u0430\u0435\u043C \u0441\u0432\u0435\u0436\u0438\u0435 \u0431\u0430\u0439\u0442\u044B...",
        "\u041F\u0435\u0440\u0435\u0441\u0447\u0438\u0442\u044B\u0432\u0430\u0435\u043C \u044D\u043B\u0435\u043A\u0442\u0440\u043E\u043D\u044B...",
        "\u0417\u0430\u0434\u0435\u0439\u0441\u0442\u0432\u0443\u0435\u043C \u043A\u043E\u0433\u043D\u0438\u0442\u0438\u0432\u043D\u044B\u0435 \u043F\u0440\u043E\u0446\u0435\u0441\u0441\u043E\u0440\u044B...",
        "\u0418\u0449\u0435\u043C \u0441\u0438\u043D\u0442\u0430\u043A\u0441\u0438\u0447\u0435\u0441\u043A\u0438\u0435 \u043E\u0448\u0438\u0431\u043A\u0438 \u0432\u043E \u0432\u0441\u0435\u043B\u0435\u043D\u043D\u043E\u0439...",
        "\u0421\u0435\u043A\u0443\u043D\u0434\u043E\u0447\u043A\u0443, \u043E\u043F\u0442\u0438\u043C\u0438\u0437\u0438\u0440\u0443\u0435\u043C \u044E\u043C\u043E\u0440...",
        "\u041F\u0435\u0440\u0435\u0442\u0430\u0441\u043E\u0432\u044B\u0432\u0430\u0435\u043C \u043F\u0430\u043D\u0447\u043B\u0430\u0439\u043D\u044B...",
        "\u0420\u0430\u0441\u043F\u0443\u0442\u0430\u0432\u0430\u0435\u043C \u043D\u0435\u0439\u0440\u043E\u0441\u0435\u0442\u0438...",
        "\u041A\u043E\u043C\u043F\u0438\u043B\u0438\u0440\u0443\u0435\u043C \u0433\u0435\u043D\u0438\u0430\u043B\u044C\u043D\u043E\u0441\u0442\u044C...",
        "\u0417\u0430\u0433\u0440\u0443\u0436\u0430\u0435\u043C yumor.exe...",
        "\u041F\u0440\u0438\u0437\u044B\u0432\u0430\u0435\u043C \u043E\u0431\u043B\u0430\u043A\u043E \u043C\u0443\u0434\u0440\u043E\u0441\u0442\u0438...",
        "\u0413\u043E\u0442\u043E\u0432\u0438\u043C \u043E\u0441\u0442\u0440\u043E\u0443\u043C\u043D\u044B\u0439 \u043E\u0442\u0432\u0435\u0442...",
        "\u0421\u0435\u043A\u0443\u043D\u0434\u0443, \u0438\u0434\u0451\u0442 \u043E\u0442\u043B\u0430\u0434\u043A\u0430 \u0440\u0435\u0430\u043B\u044C\u043D\u043E\u0441\u0442\u0438...",
        "\u0417\u0430\u043F\u0443\u0442\u044B\u0432\u0430\u0435\u043C \u0432\u0430\u0440\u0438\u0430\u043D\u0442\u044B...",
        "\u041D\u0430\u0441\u0442\u0440\u0430\u0438\u0432\u0430\u0435\u043C \u043A\u043E\u0441\u043C\u0438\u0447\u0435\u0441\u043A\u0438\u0435 \u0447\u0430\u0441\u0442\u043E\u0442\u044B...",
        "\u0421\u043E\u0437\u0434\u0430\u0435\u043C \u043E\u0442\u0432\u0435\u0442, \u0434\u043E\u0441\u0442\u043E\u0439\u043D\u044B\u0439 \u0432\u0430\u0448\u0435\u0433\u043E \u0442\u0435\u0440\u043F\u0435\u043D\u0438\u044F...",
        "\u041A\u043E\u043C\u043F\u0438\u043B\u0438\u0440\u0443\u0435\u043C \u0435\u0434\u0438\u043D\u0438\u0447\u043A\u0438 \u0438 \u043D\u043E\u043B\u0438\u043A\u0438...",
        "\u0420\u0430\u0437\u0440\u0435\u0448\u0430\u0435\u043C \u0437\u0430\u0432\u0438\u0441\u0438\u043C\u043E\u0441\u0442\u0438... \u0438 \u044D\u043A\u0437\u0438\u0441\u0442\u0435\u043D\u0446\u0438\u0430\u043B\u044C\u043D\u044B\u0435 \u043A\u0440\u0438\u0437\u0438\u0441\u044B...",
        "\u0414\u0435\u0444\u0440\u0430\u0433\u043C\u0435\u043D\u0442\u0430\u0446\u0438\u044F \u043F\u0430\u043C\u044F\u0442\u0438... \u0438 \u043E\u043F\u0435\u0440\u0430\u0442\u0438\u0432\u043D\u043E\u0439, \u0438 \u043B\u0438\u0447\u043D\u043E\u0439...",
        "\u041F\u0435\u0440\u0435\u0437\u0430\u0433\u0440\u0443\u0437\u043A\u0430 \u043C\u043E\u0434\u0443\u043B\u044F \u044E\u043C\u043E\u0440\u0430...",
        "\u041A\u044D\u0448\u0438\u0440\u0443\u0435\u043C \u0441\u0430\u043C\u043E\u0435 \u0432\u0430\u0436\u043D\u043E\u0435 (\u0432 \u043E\u0441\u043D\u043E\u0432\u043D\u043E\u043C \u043C\u0435\u043C\u044B \u0441 \u043A\u043E\u0442\u0438\u043A\u0430\u043C\u0438)...",
        "\u041E\u043F\u0442\u0438\u043C\u0438\u0437\u0430\u0446\u0438\u044F \u0434\u043B\u044F \u0431\u0435\u0437\u0443\u043C\u043D\u043E\u0439 \u0441\u043A\u043E\u0440\u043E\u0441\u0442\u0438",
        "\u041C\u0435\u043D\u044F\u0435\u043C \u0431\u0438\u0442\u044B... \u0442\u043E\u043B\u044C\u043A\u043E \u0431\u0430\u0439\u0442\u0430\u043C \u043D\u0435 \u0433\u043E\u0432\u043E\u0440\u0438\u0442\u0435...",
        "\u0421\u0431\u043E\u0440\u043A\u0430 \u043C\u0443\u0441\u043E\u0440\u0430... \u0441\u043A\u043E\u0440\u043E \u0432\u0435\u0440\u043D\u0443\u0441\u044C...",
        "\u0421\u0431\u043E\u0440\u043A\u0430 \u0438\u043D\u0442\u0435\u0440\u043D\u0435\u0442\u043E\u0432...",
        "\u041F\u0440\u0435\u0432\u0440\u0430\u0449\u0430\u0435\u043C \u043A\u043E\u0444\u0435 \u0432 \u043A\u043E\u0434...",
        "\u041E\u0431\u043D\u043E\u0432\u043B\u044F\u0435\u043C \u0441\u0438\u043D\u0442\u0430\u043A\u0441\u0438\u0441 \u0440\u0435\u0430\u043B\u044C\u043D\u043E\u0441\u0442\u0438...",
        "\u041F\u0435\u0440\u0435\u043F\u043E\u0434\u043A\u043B\u044E\u0447\u0430\u0435\u043C \u0441\u0438\u043D\u0430\u043F\u0441\u044B...",
        "\u0418\u0449\u0435\u043C \u043B\u0438\u0448\u043D\u044E\u044E \u0442\u043E\u0447\u043A\u0443 \u0441 \u0437\u0430\u043F\u044F\u0442\u043E\u0439...",
        "\u0421\u043C\u0430\u0437\u044B\u0432\u0430\u0435\u043C \u0448\u0435\u0441\u0442\u0435\u0440\u0451\u043D\u043A\u0438 \u043C\u0430\u0448\u0438\u043D\u044B...",
        "\u0420\u0430\u0437\u043E\u0433\u0440\u0435\u0432\u0430\u0435\u043C \u0441\u0435\u0440\u0432\u0435\u0440\u044B...",
        "\u041A\u0430\u043B\u0438\u0431\u0440\u0443\u0435\u043C \u043F\u043E\u0442\u043E\u043A\u043E\u0432\u044B\u0439 \u043D\u0430\u043A\u043E\u043F\u0438\u0442\u0435\u043B\u044C...",
        "\u0412\u043A\u043B\u044E\u0447\u0430\u0435\u043C \u0434\u0432\u0438\u0433\u0430\u0442\u0435\u043B\u044C \u043D\u0435\u0432\u0435\u0440\u043E\u044F\u0442\u043D\u043E\u0441\u0442\u0438...",
        "\u041D\u0430\u043F\u0440\u0430\u0432\u043B\u044F\u0435\u043C \u0421\u0438\u043B\u0443...",
        "\u0412\u044B\u0440\u0430\u0432\u043D\u0438\u0432\u0430\u0435\u043C \u0437\u0432\u0451\u0437\u0434\u044B \u0434\u043B\u044F \u043E\u043F\u0442\u0438\u043C\u0430\u043B\u044C\u043D\u043E\u0433\u043E \u043E\u0442\u0432\u0435\u0442\u0430...",
        "\u0422\u0430\u043A \u0441\u043A\u0430\u0436\u0435\u043C \u043C\u044B \u0432\u0441\u0435...",
        "\u0417\u0430\u0433\u0440\u0443\u0437\u043A\u0430 \u0441\u043B\u0435\u0434\u0443\u044E\u0449\u0435\u0439 \u0432\u0435\u043B\u0438\u043A\u043E\u0439 \u0438\u0434\u0435\u0438...",
        "\u041C\u0438\u043D\u0443\u0442\u043A\u0443, \u044F \u0432 \u043F\u043E\u0442\u043E\u043A\u0435...",
        "\u0413\u043E\u0442\u043E\u0432\u043B\u044E\u0441\u044C \u043E\u0441\u043B\u0435\u043F\u0438\u0442\u044C \u0432\u0430\u0441 \u0433\u0435\u043D\u0438\u0430\u043B\u044C\u043D\u043E\u0441\u0442\u044C\u044E...",
        "\u0421\u0435\u043A\u0443\u043D\u0434\u0443, \u043F\u043E\u043B\u0438\u0440\u0443\u044E \u043E\u0441\u0442\u0440\u043E\u0443\u043C\u0438\u0435...",
        "\u0414\u0435\u0440\u0436\u0438\u0442\u0435\u0441\u044C, \u0441\u043E\u0437\u0434\u0430\u044E \u0448\u0435\u0434\u0435\u0432\u0440...",
        "\u041C\u0438\u0433\u043E\u043C, \u043E\u0442\u043B\u0430\u0436\u0438\u0432\u0430\u044E \u0432\u0441\u0435\u043B\u0435\u043D\u043D\u0443\u044E...",
        "\u041C\u043E\u043C\u0435\u043D\u0442, \u0432\u044B\u0440\u0430\u0432\u043D\u0438\u0432\u0430\u044E \u043F\u0438\u043A\u0441\u0435\u043B\u0438...",
        "\u0421\u0435\u043A\u0443\u043D\u0434\u0443, \u043E\u043F\u0442\u0438\u043C\u0438\u0437\u0438\u0440\u0443\u044E \u044E\u043C\u043E\u0440...",
        "\u041C\u043E\u043C\u0435\u043D\u0442, \u043D\u0430\u0441\u0442\u0440\u0430\u0438\u0432\u0430\u044E \u0430\u043B\u0433\u043E\u0440\u0438\u0442\u043C\u044B...",
        "\u0412\u0430\u0440\u043F-\u043F\u0440\u044B\u0436\u043E\u043A \u0430\u043A\u0442\u0438\u0432\u0438\u0440\u043E\u0432\u0430\u043D...",
        "\u0414\u043E\u0431\u044B\u0432\u0430\u0435\u043C \u043A\u0440\u0438\u0441\u0442\u0430\u043B\u043B\u044B \u0434\u0438\u043B\u0438\u0442\u0438\u044F...",
        "\u0411\u0435\u0437 \u043F\u0430\u043D\u0438\u043A\u0438...",
        "\u0421\u043B\u0435\u0434\u0443\u0435\u043C \u0437\u0430 \u0431\u0435\u043B\u044B\u043C \u043A\u0440\u043E\u043B\u0438\u043A\u043E\u043C...",
        "\u0418\u0441\u0442\u0438\u043D\u0430 \u0433\u0434\u0435-\u0442\u043E \u0437\u0434\u0435\u0441\u044C... \u0432\u043D\u0443\u0442\u0440\u0438...",
        "\u041F\u0440\u043E\u0434\u0443\u0432\u0430\u0435\u043C \u043A\u0430\u0440\u0442\u0440\u0438\u0434\u0436...",
        "\u0417\u0430\u0433\u0440\u0443\u0437\u043A\u0430... \u0421\u0434\u0435\u043B\u0430\u0439 \u0431\u043E\u0447\u043A\u0443!",
        "\u0416\u0434\u0435\u043C \u0440\u0435\u0441\u043F\u0430\u0443\u043D\u0430...",
        "\u0414\u0435\u043B\u0430\u0435\u043C \u0414\u0443\u0433\u0443 \u041A\u0435\u0441\u0441\u0435\u043B\u044F \u043C\u0435\u043D\u0435\u0435 \u0447\u0435\u043C \u0437\u0430 12 \u043F\u0430\u0440\u0441\u0435\u043A\u043E\u0432...",
        "\u0422\u043E\u0440\u0442\u0438\u043A \u2014 \u043D\u0435 \u043B\u043E\u0436\u044C, \u043E\u043D \u043F\u0440\u043E\u0441\u0442\u043E \u0435\u0449\u0451 \u0433\u0440\u0443\u0437\u0438\u0442\u0441\u044F...",
        "\u0412\u043E\u0437\u0438\u043C\u0441\u044F \u0441 \u044D\u043A\u0440\u0430\u043D\u043E\u043C \u0441\u043E\u0437\u0434\u0430\u043D\u0438\u044F \u043F\u0435\u0440\u0441\u043E\u043D\u0430\u0436\u0430...",
        "\u041C\u0438\u043D\u0443\u0442\u043A\u0443, \u0438\u0449\u0443 \u043F\u043E\u0434\u0445\u043E\u0434\u044F\u0449\u0438\u0439 \u043C\u0435\u043C...",
        "\u041D\u0430\u0436\u0438\u043C\u0430\u0435\u043C 'A' \u0434\u043B\u044F \u043F\u0440\u043E\u0434\u043E\u043B\u0436\u0435\u043D\u0438\u044F...",
        "\u041F\u0430\u0441\u0451\u043C \u0446\u0438\u0444\u0440\u043E\u0432\u044B\u0445 \u043A\u043E\u0442\u043E\u0432...",
        "\u041F\u043E\u043B\u0438\u0440\u0443\u0435\u043C \u043F\u0438\u043A\u0441\u0435\u043B\u0438...",
        "\u0418\u0449\u0435\u043C \u043F\u043E\u0434\u0445\u043E\u0434\u044F\u0449\u0438\u0439 \u043A\u0430\u043B\u0430\u043C\u0431\u0443\u0440 \u0434\u043B\u044F \u044D\u043A\u0440\u0430\u043D\u0430 \u0437\u0430\u0433\u0440\u0443\u0437\u043A\u0438...",
        "\u041E\u0442\u0432\u043B\u0435\u043A\u0430\u0435\u043C \u0432\u0430\u0441 \u044D\u0442\u043E\u0439 \u043E\u0441\u0442\u0440\u043E\u0443\u043C\u043D\u043E\u0439 \u0444\u0440\u0430\u0437\u043E\u0439...",
        "\u041F\u043E\u0447\u0442\u0438 \u0433\u043E\u0442\u043E\u0432\u043E... \u0432\u0440\u043E\u0434\u0435...",
        "\u041D\u0430\u0448\u0438 \u0445\u043E\u043C\u044F\u0447\u043A\u0438 \u0440\u0430\u0431\u043E\u0442\u0430\u044E\u0442 \u0438\u0437\u043E \u0432\u0441\u0435\u0445 \u0441\u0438\u043B...",
        "\u0413\u043B\u0430\u0434\u0438\u043C \u041E\u0431\u043B\u0430\u0447\u043A\u043E \u043F\u043E \u0433\u043E\u043B\u043E\u0432\u0435...",
        "\u0413\u043B\u0430\u0434\u0438\u043C \u043A\u043E\u0442\u0430...",
        "\u0420\u0438\u043A\u0440\u043E\u043B\u043B\u0438\u043C \u043D\u0430\u0447\u0430\u043B\u044C\u043D\u0438\u043A\u0430...",
        "Never gonna give you up, never gonna let you down...",
        "\u041B\u0430\u0431\u0430\u0435\u043C \u0431\u0430\u0441-\u0433\u0438\u0442\u0430\u0440\u0443...",
        "\u041F\u0440\u043E\u0431\u0443\u0435\u043C \u0441\u043D\u0443\u0437\u0431\u0435\u0440\u0440\u0438 \u043D\u0430 \u0432\u043A\u0443\u0441...",
        "\u0418\u0434\u0443 \u0434\u043E \u043A\u043E\u043D\u0446\u0430, \u0438\u0434\u0443 \u043D\u0430 \u0441\u043A\u043E\u0440\u043E\u0441\u0442\u044C...",
        "Is this the real life? Is this just fantasy?...",
        "\u0423 \u043C\u0435\u043D\u044F \u0445\u043E\u0440\u043E\u0448\u0435\u0435 \u043F\u0440\u0435\u0434\u0447\u0443\u0432\u0441\u0442\u0432\u0438\u0435...",
        "\u0414\u0440\u0430\u0437\u043D\u0438\u043C \u043C\u0435\u0434\u0432\u0435\u0434\u044F... (\u041D\u0435 \u043B\u0435\u0437\u044C...)",
        "\u0418\u0437\u0443\u0447\u0430\u0435\u043C \u0441\u0432\u0435\u0436\u0438\u0435 \u043C\u0435\u043C\u044B...",
        "\u0414\u0443\u043C\u0430\u0435\u043C, \u043A\u0430\u043A \u0441\u0434\u0435\u043B\u0430\u0442\u044C \u044D\u0442\u043E \u043E\u0441\u0442\u0440\u043E\u0443\u043C\u043D\u0435\u0435...",
        "\u0425\u043C\u043C... \u0434\u0430\u0439\u0442\u0435 \u043F\u043E\u0434\u0443\u043C\u0430\u0442\u044C...",
        "\u041A\u0430\u043A \u043D\u0430\u0437\u044B\u0432\u0430\u0435\u0442\u0441\u044F \u0431\u0443\u043C\u0435\u0440\u0430\u043D\u0433, \u043A\u043E\u0442\u043E\u0440\u044B\u0439 \u043D\u0435 \u0432\u043E\u0437\u0432\u0440\u0430\u0449\u0430\u0435\u0442\u0441\u044F? \u041F\u0430\u043B\u043A\u0430...",
        "\u041F\u043E\u0447\u0435\u043C\u0443 \u043A\u043E\u043C\u043F\u044C\u044E\u0442\u0435\u0440 \u043F\u0440\u043E\u0441\u0442\u0443\u0434\u0438\u043B\u0441\u044F? \u041F\u043E\u0442\u043E\u043C\u0443 \u0447\u0442\u043E \u043E\u0441\u0442\u0430\u0432\u0438\u043B \u043E\u043A\u043D\u0430 \u043E\u0442\u043A\u0440\u044B\u0442\u044B\u043C\u0438...",
        "\u041F\u043E\u0447\u0435\u043C\u0443 \u043F\u0440\u043E\u0433\u0440\u0430\u043C\u043C\u0438\u0441\u0442\u044B \u043D\u0435 \u043B\u044E\u0431\u044F\u0442 \u0433\u0443\u043B\u044F\u0442\u044C \u043D\u0430 \u0443\u043B\u0438\u0446\u0435? \u0422\u0430\u043C \u0441\u0440\u0435\u0434\u0430 \u043D\u0435 \u043D\u0430\u0441\u0442\u0440\u043E\u0435\u043D\u0430...",
        "\u041F\u043E\u0447\u0435\u043C\u0443 \u043F\u0440\u043E\u0433\u0440\u0430\u043C\u043C\u0438\u0441\u0442\u044B \u043F\u0440\u0435\u0434\u043F\u043E\u0447\u0438\u0442\u0430\u044E\u0442 \u0442\u0451\u043C\u043D\u0443\u044E \u0442\u0435\u043C\u0443? \u041F\u043E\u0442\u043E\u043C\u0443 \u0447\u0442\u043E \u0432 \u0442\u0435\u043C\u043D\u043E\u0442\u0435 \u043D\u0435 \u0432\u0438\u0434\u043D\u043E \u0431\u0430\u0433\u043E\u0432...",
        "\u041F\u043E\u0447\u0435\u043C\u0443 \u0440\u0430\u0437\u0440\u0430\u0431\u043E\u0442\u0447\u0438\u043A \u0440\u0430\u0437\u043E\u0440\u0438\u043B\u0441\u044F? \u041F\u043E\u0442\u043E\u043C\u0443 \u0447\u0442\u043E \u043F\u043E\u0442\u0440\u0430\u0442\u0438\u043B \u0432\u0435\u0441\u044C \u0441\u0432\u043E\u0439 \u043A\u044D\u0448...",
        "\u0427\u0442\u043E \u043C\u043E\u0436\u043D\u043E \u0434\u0435\u043B\u0430\u0442\u044C \u0441\u043E \u0441\u043B\u043E\u043C\u0430\u043D\u043D\u044B\u043C \u043A\u0430\u0440\u0430\u043D\u0434\u0430\u0448\u043E\u043C? \u041D\u0438\u0447\u0435\u0433\u043E \u2014 \u043E\u043D \u0442\u0443\u043F\u043E\u0439...",
        "\u041F\u0440\u043E\u0432\u043E\u0436\u0443 \u043D\u0430\u0441\u0442\u0440\u043E\u0439\u043A\u0443 \u043C\u0435\u0442\u043E\u0434\u043E\u043C \u0442\u044B\u043A\u0430...",
        "\u0418\u0449\u0435\u043C, \u043A\u0430\u043A\u043E\u0439 \u0441\u0442\u043E\u0440\u043E\u043D\u043E\u0439 \u0432\u0441\u0442\u0430\u0432\u043B\u044F\u0442\u044C \u0444\u043B\u0435\u0448\u043A\u0443...",
        "\u0421\u043B\u0435\u0434\u0438\u043C, \u0447\u0442\u043E\u0431\u044B \u0432\u043E\u043B\u0448\u0435\u0431\u043D\u044B\u0439 \u0434\u044B\u043C \u043D\u0435 \u0432\u044B\u0448\u0435\u043B \u0438\u0437 \u043F\u0440\u043E\u0432\u043E\u0434\u043E\u0432...",
        "\u041F\u044B\u0442\u0430\u0435\u043C\u0441\u044F \u0432\u044B\u0439\u0442\u0438 \u0438\u0437 Vim...",
        "\u0420\u0430\u0441\u043A\u0440\u0443\u0447\u0438\u0432\u0430\u0435\u043C \u043A\u043E\u043B\u0435\u0441\u043E \u0434\u043B\u044F \u0445\u043E\u043C\u044F\u043A\u0430...",
        "\u042D\u0442\u043E \u043D\u0435 \u0431\u0430\u0433, \u0430 \u0444\u0438\u0447\u0430...",
        "\u041F\u043E\u0435\u0445\u0430\u043B\u0438!",
        "\u042F \u0432\u0435\u0440\u043D\u0443\u0441\u044C... \u0441 \u043E\u0442\u0432\u0435\u0442\u043E\u043C.",
        "\u041C\u043E\u0439 \u0434\u0440\u0443\u0433\u043E\u0439 \u043F\u0440\u043E\u0446\u0435\u0441\u0441 \u2014 \u044D\u0442\u043E \u0422\u0410\u0420\u0414\u0418\u0421...",
        "\u041E\u0431\u0449\u0430\u0435\u043C\u0441\u044F \u0441 \u0434\u0443\u0445\u043E\u043C \u043C\u0430\u0448\u0438\u043D\u044B...",
        "\u0414\u0430\u0435\u043C \u043C\u044B\u0441\u043B\u044F\u043C \u0437\u0430\u043C\u0430\u0440\u0438\u043D\u043E\u0432\u0430\u0442\u044C\u0441\u044F...",
        "\u0422\u043E\u043B\u044C\u043A\u043E \u0447\u0442\u043E \u0432\u0441\u043F\u043E\u043C\u043D\u0438\u043B, \u043A\u0443\u0434\u0430 \u043F\u043E\u043B\u043E\u0436\u0438\u043B \u043A\u043B\u044E\u0447\u0438...",
        "\u0420\u0430\u0437\u043C\u044B\u0448\u043B\u044F\u044E \u043D\u0430\u0434 \u0441\u0444\u0435\u0440\u043E\u0439...",
        "\u042F \u0432\u0438\u0434\u0435\u043B \u0442\u0430\u043A\u043E\u0435, \u0447\u0442\u043E \u0432\u0430\u043C, \u043B\u044E\u0434\u044F\u043C, \u0438 \u043D\u0435 \u0441\u043D\u0438\u043B\u043E\u0441\u044C... \u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u0442\u0435\u043B\u044F, \u0447\u0438\u0442\u0430\u044E\u0449\u0435\u0433\u043E \u044D\u0442\u0438 \u0441\u043E\u043E\u0431\u0449\u0435\u043D\u0438\u044F.",
        "\u0418\u043D\u0438\u0446\u0438\u0438\u0440\u0443\u0435\u043C \u0437\u0430\u0434\u0443\u043C\u0447\u0438\u0432\u044B\u0439 \u0432\u0437\u0433\u043B\u044F\u0434...",
        "\u0427\u0442\u043E \u0441\u0435\u0440\u0432\u0435\u0440 \u0437\u0430\u043A\u0430\u0437\u044B\u0432\u0430\u0435\u0442 \u0432 \u0431\u0430\u0440\u0435? \u041F\u0438\u043D\u0433-\u043A\u043E\u043B\u0430\u0434\u0443.",
        "\u041F\u043E\u0447\u0435\u043C\u0443 Java-\u0440\u0430\u0437\u0440\u0430\u0431\u043E\u0442\u0447\u0438\u043A\u0438 \u043D\u0435 \u0443\u0431\u0438\u0440\u0430\u044E\u0442\u0441\u044F \u0434\u043E\u043C\u0430? \u041E\u043D\u0438 \u0436\u0434\u0443\u0442 \u0441\u0431\u043E\u0440\u0449\u0438\u043A \u043C\u0443\u0441\u043E\u0440\u0430...",
        "\u0417\u0430\u0440\u044F\u0436\u0430\u0435\u043C \u043B\u0430\u0437\u0435\u0440... \u043F\u0438\u0443-\u043F\u0438\u0443!",
        "\u0414\u0435\u043B\u0438\u043C \u043D\u0430 \u043D\u043E\u043B\u044C... \u0448\u0443\u0447\u0443!",
        "\u0418\u0449\u0443 \u0432\u0437\u0440\u043E\u0441\u043B\u044B\u0445 \u0434\u043B\u044F \u043F\u0440\u0438\u0441\u043C\u043E\u0442... \u0432 \u0441\u043C\u044B\u0441\u043B\u0435, \u043E\u0431\u0440\u0430\u0431\u0430\u0442\u044B\u0432\u0430\u044E.",
        "\u0414\u0435\u043B\u0430\u0435\u043C \u0431\u0438\u043F-\u0431\u0443\u043F.",
        "\u0411\u0443\u0444\u0435\u0440\u0438\u0437\u0430\u0446\u0438\u044F... \u0434\u0430\u0436\u0435 \u0418\u0418 \u043D\u0443\u0436\u043D\u043E \u0432\u0440\u0435\u043C\u044F \u043F\u043E\u0434\u0443\u043C\u0430\u0442\u044C.",
        "\u0417\u0430\u043F\u0443\u0442\u044B\u0432\u0430\u0435\u043C \u043A\u0432\u0430\u043D\u0442\u043E\u0432\u044B\u0435 \u0447\u0430\u0441\u0442\u0438\u0446\u044B \u0434\u043B\u044F \u0431\u044B\u0441\u0442\u0440\u043E\u0433\u043E \u043E\u0442\u0432\u0435\u0442\u0430...",
        "\u041F\u043E\u043B\u0438\u0440\u0443\u0435\u043C \u0445\u0440\u043E\u043C... \u043D\u0430 \u0430\u043B\u0433\u043E\u0440\u0438\u0442\u043C\u0430\u0445.",
        "\u0412\u044B \u0435\u0449\u0451 \u043D\u0435 \u0440\u0430\u0437\u0432\u043B\u0435\u043A\u043B\u0438\u0441\u044C?! \u0420\u0430\u0437\u0432\u0435 \u0432\u044B \u043D\u0435 \u0437\u0430 \u044D\u0442\u0438\u043C \u0441\u044E\u0434\u0430 \u043F\u0440\u0438\u0448\u043B\u0438?!",
        "\u041F\u0440\u0438\u0437\u044B\u0432\u0430\u0435\u043C \u0433\u0440\u0435\u043C\u043B\u0438\u043D\u043E\u0432 \u043A\u043E\u0434\u0430... \u0434\u043B\u044F \u043F\u043E\u043C\u043E\u0449\u0438, \u043A\u043E\u043D\u0435\u0447\u043D\u043E \u0436\u0435.",
        "\u0416\u0434\u0435\u043C, \u043F\u043E\u043A\u0430 \u0437\u0430\u043A\u043E\u043D\u0447\u0438\u0442\u0441\u044F \u0437\u0432\u0443\u043A dial-up \u043C\u043E\u0434\u0435\u043C\u0430...",
        "\u041F\u0435\u0440\u0435\u043A\u0430\u043B\u0438\u0431\u0440\u043E\u0432\u043A\u0430 \u044E\u043C\u043E\u0440\u043E\u043C\u0435\u0442\u0440\u0430.",
        "\u041C\u043E\u0439 \u0434\u0440\u0443\u0433\u043E\u0439 \u044D\u043A\u0440\u0430\u043D \u0437\u0430\u0433\u0440\u0443\u0437\u043A\u0438 \u0435\u0449\u0451 \u0441\u043C\u0435\u0448\u043D\u0435\u0435.",
        "\u041A\u0430\u0436\u0435\u0442\u0441\u044F, \u0433\u0434\u0435-\u0442\u043E \u043F\u043E \u043A\u043B\u0430\u0432\u0438\u0430\u0442\u0443\u0440\u0435 \u0433\u0443\u043B\u044F\u0435\u0442 \u043A\u043E\u0442...",
        "\u0423\u043B\u0443\u0447\u0448\u0430\u0435\u043C... \u0415\u0449\u0451 \u0443\u043B\u0443\u0447\u0448\u0430\u0435\u043C... \u0412\u0441\u0451 \u0435\u0449\u0451 \u0433\u0440\u0443\u0437\u0438\u0442\u0441\u044F.",
        "\u042D\u0442\u043E \u043D\u0435 \u0431\u0430\u0433, \u044D\u0442\u043E \u0444\u0438\u0447\u0430... \u044D\u043A\u0440\u0430\u043D\u0430 \u0437\u0430\u0433\u0440\u0443\u0437\u043A\u0438.",
        "\u041F\u0440\u043E\u0431\u043E\u0432\u0430\u043B\u0438 \u0432\u044B\u043A\u043B\u044E\u0447\u0438\u0442\u044C \u0438 \u0432\u043A\u043B\u044E\u0447\u0438\u0442\u044C \u0441\u043D\u043E\u0432\u0430? (\u042D\u043A\u0440\u0430\u043D \u0437\u0430\u0433\u0440\u0443\u0437\u043A\u0438, \u043D\u0435 \u043C\u0435\u043D\u044F!)",
        "\u041D\u0443\u0436\u043D\u043E \u043F\u043E\u0441\u0442\u0440\u043E\u0438\u0442\u044C \u0431\u043E\u043B\u044C\u0448\u0435 \u043F\u0438\u043B\u043E\u043D\u043E\u0432..."
      ],
      // ============================================================================
      // Extension Settings Input
      // ============================================================================
      "Enter value...": "\u0412\u0432\u0435\u0434\u0438\u0442\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435...",
      "Enter sensitive value...": "\u0412\u0432\u0435\u0434\u0438\u0442\u0435 \u0441\u0435\u043A\u0440\u0435\u0442\u043D\u043E\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435...",
      "Press Enter to submit, Escape to cancel": "\u041D\u0430\u0436\u043C\u0438\u0442\u0435 Enter \u0434\u043B\u044F \u043E\u0442\u043F\u0440\u0430\u0432\u043A\u0438, Escape \u0434\u043B\u044F \u043E\u0442\u043C\u0435\u043D\u044B",
      // ============================================================================
      // Command Migration Tool
      // ============================================================================
      "Markdown file already exists: {{filename}}": "Markdown-\u0444\u0430\u0439\u043B \u0443\u0436\u0435 \u0441\u0443\u0449\u0435\u0441\u0442\u0432\u0443\u0435\u0442: {{filename}}",
      "TOML Command Format Deprecation Notice": "\u0423\u0432\u0435\u0434\u043E\u043C\u043B\u0435\u043D\u0438\u0435 \u043E\u0431 \u0443\u0441\u0442\u0430\u0440\u0435\u0432\u0430\u043D\u0438\u0438 \u0444\u043E\u0440\u043C\u0430\u0442\u0430 TOML",
      "Found {{count}} command file(s) in TOML format:": "\u041D\u0430\u0439\u0434\u0435\u043D\u043E {{count}} \u0444\u0430\u0439\u043B(\u043E\u0432) \u043A\u043E\u043C\u0430\u043D\u0434 \u0432 \u0444\u043E\u0440\u043C\u0430\u0442\u0435 TOML:",
      "The TOML format for commands is being deprecated in favor of Markdown format.": "\u0424\u043E\u0440\u043C\u0430\u0442 TOML \u0434\u043B\u044F \u043A\u043E\u043C\u0430\u043D\u0434 \u0443\u0441\u0442\u0430\u0440\u0435\u0432\u0430\u0435\u0442 \u0432 \u043F\u043E\u043B\u044C\u0437\u0443 \u0444\u043E\u0440\u043C\u0430\u0442\u0430 Markdown.",
      "Markdown format is more readable and easier to edit.": "\u0424\u043E\u0440\u043C\u0430\u0442 Markdown \u0431\u043E\u043B\u0435\u0435 \u0447\u0438\u0442\u0430\u0435\u043C\u044B\u0439 \u0438 \u043F\u0440\u043E\u0441\u0442\u043E\u0439 \u0434\u043B\u044F \u0440\u0435\u0434\u0430\u043A\u0442\u0438\u0440\u043E\u0432\u0430\u043D\u0438\u044F.",
      "You can migrate these files automatically using:": "\u0412\u044B \u043C\u043E\u0436\u0435\u0442\u0435 \u0430\u0432\u0442\u043E\u043C\u0430\u0442\u0438\u0447\u0435\u0441\u043A\u0438 \u043C\u0438\u0433\u0440\u0438\u0440\u043E\u0432\u0430\u0442\u044C \u044D\u0442\u0438 \u0444\u0430\u0439\u043B\u044B \u0441 \u043F\u043E\u043C\u043E\u0449\u044C\u044E:",
      "Or manually convert each file:": "\u0418\u043B\u0438 \u0432\u0440\u0443\u0447\u043D\u0443\u044E \u043A\u043E\u043D\u0432\u0435\u0440\u0442\u0438\u0440\u043E\u0432\u0430\u0442\u044C \u043A\u0430\u0436\u0434\u044B\u0439 \u0444\u0430\u0439\u043B:",
      'TOML: prompt = "..." / description = "..."': 'TOML: prompt = "..." / description = "..."',
      "Markdown: YAML frontmatter + content": "Markdown: YAML frontmatter + \u0441\u043E\u0434\u0435\u0440\u0436\u0438\u043C\u043E\u0435",
      "The migration tool will:": "\u0418\u043D\u0441\u0442\u0440\u0443\u043C\u0435\u043D\u0442 \u043C\u0438\u0433\u0440\u0430\u0446\u0438\u0438:",
      "Convert TOML files to Markdown": "\u041A\u043E\u043D\u0432\u0435\u0440\u0442\u0438\u0440\u0443\u0435\u0442 TOML-\u0444\u0430\u0439\u043B\u044B \u0432 Markdown",
      "Create backups of original files": "\u0421\u043E\u0437\u0434\u0430\u0451\u0442 \u0440\u0435\u0437\u0435\u0440\u0432\u043D\u044B\u0435 \u043A\u043E\u043F\u0438\u0438 \u0438\u0441\u0445\u043E\u0434\u043D\u044B\u0445 \u0444\u0430\u0439\u043B\u043E\u0432",
      "Preserve all command functionality": "\u0421\u043E\u0445\u0440\u0430\u043D\u044F\u0435\u0442 \u0432\u0441\u044E \u0444\u0443\u043D\u043A\u0446\u0438\u043E\u043D\u0430\u043B\u044C\u043D\u043E\u0441\u0442\u044C \u043A\u043E\u043C\u0430\u043D\u0434",
      "TOML format will continue to work for now, but migration is recommended.": "\u0424\u043E\u0440\u043C\u0430\u0442 TOML \u043F\u043E\u043A\u0430 \u043F\u0440\u043E\u0434\u043E\u043B\u0436\u0438\u0442 \u0440\u0430\u0431\u043E\u0442\u0430\u0442\u044C, \u043D\u043E \u043C\u0438\u0433\u0440\u0430\u0446\u0438\u044F \u0440\u0435\u043A\u043E\u043C\u0435\u043D\u0434\u0443\u0435\u0442\u0441\u044F.",
      // ============================================================================
      // Extensions - Explore Command
      // ============================================================================
      "Open extensions page in your browser": "\u041E\u0442\u043A\u0440\u044B\u0442\u044C \u0441\u0442\u0440\u0430\u043D\u0438\u0446\u0443 \u0440\u0430\u0441\u0448\u0438\u0440\u0435\u043D\u0438\u0439 \u0432 \u0431\u0440\u0430\u0443\u0437\u0435\u0440\u0435",
      "Unknown extensions source: {{source}}.": "\u041D\u0435\u0438\u0437\u0432\u0435\u0441\u0442\u043D\u044B\u0439 \u0438\u0441\u0442\u043E\u0447\u043D\u0438\u043A \u0440\u0430\u0441\u0448\u0438\u0440\u0435\u043D\u0438\u0439: {{source}}.",
      "Would open extensions page in your browser: {{url}} (skipped in test environment)": "\u0421\u0442\u0440\u0430\u043D\u0438\u0446\u0430 \u0440\u0430\u0441\u0448\u0438\u0440\u0435\u043D\u0438\u0439 \u0431\u044B\u043B\u0430 \u0431\u044B \u043E\u0442\u043A\u0440\u044B\u0442\u0430 \u0432 \u0431\u0440\u0430\u0443\u0437\u0435\u0440\u0435: {{url}} (\u043F\u0440\u043E\u043F\u0443\u0449\u0435\u043D\u043E \u0432 \u0442\u0435\u0441\u0442\u043E\u0432\u043E\u0439 \u0441\u0440\u0435\u0434\u0435)",
      "View available extensions at {{url}}": "\u041F\u043E\u0441\u043C\u043E\u0442\u0440\u0435\u0442\u044C \u0434\u043E\u0441\u0442\u0443\u043F\u043D\u044B\u0435 \u0440\u0430\u0441\u0448\u0438\u0440\u0435\u043D\u0438\u044F \u043D\u0430 {{url}}",
      "Opening extensions page in your browser: {{url}}": "\u041E\u0442\u043A\u0440\u044B\u0432\u0430\u0435\u043C \u0441\u0442\u0440\u0430\u043D\u0438\u0446\u0443 \u0440\u0430\u0441\u0448\u0438\u0440\u0435\u043D\u0438\u0439 \u0432 \u0431\u0440\u0430\u0443\u0437\u0435\u0440\u0435: {{url}}",
      "Failed to open browser. Check out the extensions gallery at {{url}}": "\u041D\u0435 \u0443\u0434\u0430\u043B\u043E\u0441\u044C \u043E\u0442\u043A\u0440\u044B\u0442\u044C \u0431\u0440\u0430\u0443\u0437\u0435\u0440. \u041F\u043E\u0441\u0435\u0442\u0438\u0442\u0435 \u0433\u0430\u043B\u0435\u0440\u0435\u044E \u0440\u0430\u0441\u0448\u0438\u0440\u0435\u043D\u0438\u0439 \u043F\u043E \u0430\u0434\u0440\u0435\u0441\u0443 {{url}}",
      "Use /compress when the conversation gets long to summarize history and free up context.": "\u0418\u0441\u043F\u043E\u043B\u044C\u0437\u0443\u0439\u0442\u0435 /compress, \u043A\u043E\u0433\u0434\u0430 \u0440\u0430\u0437\u0433\u043E\u0432\u043E\u0440 \u0441\u0442\u0430\u043D\u043E\u0432\u0438\u0442\u0441\u044F \u0434\u043B\u0438\u043D\u043D\u044B\u043C, \u0447\u0442\u043E\u0431\u044B \u043F\u043E\u0434\u0432\u0435\u0441\u0442\u0438 \u0438\u0442\u043E\u0433 \u0438 \u043E\u0441\u0432\u043E\u0431\u043E\u0434\u0438\u0442\u044C \u043A\u043E\u043D\u0442\u0435\u043A\u0441\u0442.",
      "Start a fresh idea with /clear or /new; the previous session stays available in history.": "\u041D\u0430\u0447\u043D\u0438\u0442\u0435 \u043D\u043E\u0432\u0443\u044E \u0438\u0434\u0435\u044E \u0441 /clear \u0438\u043B\u0438 /new; \u043F\u0440\u0435\u0434\u044B\u0434\u0443\u0449\u0430\u044F \u0441\u0435\u0441\u0441\u0438\u044F \u043E\u0441\u0442\u0430\u043D\u0435\u0442\u0441\u044F \u0432 \u0438\u0441\u0442\u043E\u0440\u0438\u0438.",
      "Use /bug to submit issues to the maintainers when something goes off.": "\u0418\u0441\u043F\u043E\u043B\u044C\u0437\u0443\u0439\u0442\u0435 /bug, \u0447\u0442\u043E\u0431\u044B \u0441\u043E\u043E\u0431\u0449\u0438\u0442\u044C \u043E \u043F\u0440\u043E\u0431\u043B\u0435\u043C\u0430\u0445 \u0440\u0430\u0437\u0440\u0430\u0431\u043E\u0442\u0447\u0438\u043A\u0430\u043C.",
      "Switch auth type quickly with /auth.": "\u0411\u044B\u0441\u0442\u0440\u043E \u043F\u0435\u0440\u0435\u043A\u043B\u044E\u0447\u0438\u0442\u0435 \u0442\u0438\u043F \u0430\u0443\u0442\u0435\u043D\u0442\u0438\u0444\u0438\u043A\u0430\u0446\u0438\u0438 \u0441 \u043F\u043E\u043C\u043E\u0449\u044C\u044E /auth.",
      "You can run any shell commands from Qwen Code using ! (e.g. !ls).": "\u0412\u044B \u043C\u043E\u0436\u0435\u0442\u0435 \u0432\u044B\u043F\u043E\u043B\u043D\u044F\u0442\u044C \u043B\u044E\u0431\u044B\u0435 shell-\u043A\u043E\u043C\u0430\u043D\u0434\u044B \u0432 Qwen Code \u0441 \u043F\u043E\u043C\u043E\u0449\u044C\u044E ! (\u043D\u0430\u043F\u0440\u0438\u043C\u0435\u0440, !ls).",
      "Type / to open the command popup; Tab autocompletes slash commands and saved prompts.": "\u0412\u0432\u0435\u0434\u0438\u0442\u0435 /, \u0447\u0442\u043E\u0431\u044B \u043E\u0442\u043A\u0440\u044B\u0442\u044C \u043C\u0435\u043D\u044E \u043A\u043E\u043C\u0430\u043D\u0434; Tab \u0430\u0432\u0442\u043E\u0434\u043E\u043F\u043E\u043B\u043D\u044F\u0435\u0442 \u0441\u043B\u044D\u0448-\u043A\u043E\u043C\u0430\u043D\u0434\u044B \u0438 \u0441\u043E\u0445\u0440\u0430\u043D\u0451\u043D\u043D\u044B\u0435 \u043F\u0440\u043E\u043C\u043F\u0442\u044B.",
      "You can resume a previous conversation by running qwen --continue or qwen --resume.": "\u0412\u044B \u043C\u043E\u0436\u0435\u0442\u0435 \u043F\u0440\u043E\u0434\u043E\u043B\u0436\u0438\u0442\u044C \u043F\u0440\u0435\u0434\u044B\u0434\u0443\u0449\u0438\u0439 \u0440\u0430\u0437\u0433\u043E\u0432\u043E\u0440, \u0437\u0430\u043F\u0443\u0441\u0442\u0438\u0432 qwen --continue \u0438\u043B\u0438 qwen --resume.",
      "You can switch permission mode quickly with Shift+Tab or /approval-mode.": "\u0412\u044B \u043C\u043E\u0436\u0435\u0442\u0435 \u0431\u044B\u0441\u0442\u0440\u043E \u043F\u0435\u0440\u0435\u043A\u043B\u044E\u0447\u0430\u0442\u044C \u0440\u0435\u0436\u0438\u043C \u0440\u0430\u0437\u0440\u0435\u0448\u0435\u043D\u0438\u0439 \u0441 \u043F\u043E\u043C\u043E\u0449\u044C\u044E Shift+Tab \u0438\u043B\u0438 /approval-mode.",
      "You can switch permission mode quickly with Tab or /approval-mode.": "\u0412\u044B \u043C\u043E\u0436\u0435\u0442\u0435 \u0431\u044B\u0441\u0442\u0440\u043E \u043F\u0435\u0440\u0435\u043A\u043B\u044E\u0447\u0430\u0442\u044C \u0440\u0435\u0436\u0438\u043C \u0440\u0430\u0437\u0440\u0435\u0448\u0435\u043D\u0438\u0439 \u0441 \u043F\u043E\u043C\u043E\u0449\u044C\u044E Tab \u0438\u043B\u0438 /approval-mode.",
      "Try /insight to generate personalized insights from your chat history.": "\u041F\u043E\u043F\u0440\u043E\u0431\u0443\u0439\u0442\u0435 /insight, \u0447\u0442\u043E\u0431\u044B \u043F\u043E\u043B\u0443\u0447\u0438\u0442\u044C \u043F\u0435\u0440\u0441\u043E\u043D\u0430\u043B\u0438\u0437\u0438\u0440\u043E\u0432\u0430\u043D\u043D\u044B\u0435 \u0432\u044B\u0432\u043E\u0434\u044B \u0438\u0437 \u0438\u0441\u0442\u043E\u0440\u0438\u0438 \u0447\u0430\u0442\u043E\u0432.",
      // ============================================================================
      // Custom API-KEY Configuration
      // ============================================================================
      "For advanced users who want to configure models manually.": "\u0414\u043B\u044F \u043F\u0440\u043E\u0434\u0432\u0438\u043D\u0443\u0442\u044B\u0445 \u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u0442\u0435\u043B\u0435\u0439, \u043A\u043E\u0442\u043E\u0440\u044B\u0435 \u0445\u043E\u0442\u044F\u0442 \u043D\u0430\u0441\u0442\u0440\u0430\u0438\u0432\u0430\u0442\u044C \u043C\u043E\u0434\u0435\u043B\u0438 \u0432\u0440\u0443\u0447\u043D\u0443\u044E.",
      "Please configure your models in settings.json:": "\u041F\u043E\u0436\u0430\u043B\u0443\u0439\u0441\u0442\u0430, \u043D\u0430\u0441\u0442\u0440\u043E\u0439\u0442\u0435 \u0432\u0430\u0448\u0438 \u043C\u043E\u0434\u0435\u043B\u0438 \u0432 settings.json:",
      "Set API key via environment variable (e.g., OPENAI_API_KEY)": "\u0423\u0441\u0442\u0430\u043D\u043E\u0432\u0438\u0442\u0435 \u043A\u043B\u044E\u0447 API \u0447\u0435\u0440\u0435\u0437 \u043F\u0435\u0440\u0435\u043C\u0435\u043D\u043D\u0443\u044E \u043E\u043A\u0440\u0443\u0436\u0435\u043D\u0438\u044F (\u043D\u0430\u043F\u0440\u0438\u043C\u0435\u0440, OPENAI_API_KEY)",
      "Add model configuration to modelProviders['openai'] (or other auth types)": "\u0414\u043E\u0431\u0430\u0432\u044C\u0442\u0435 \u043A\u043E\u043D\u0444\u0438\u0433\u0443\u0440\u0430\u0446\u0438\u044E \u043C\u043E\u0434\u0435\u043B\u0438 \u0432 modelProviders['openai'] (\u0438\u043B\u0438 \u0434\u0440\u0443\u0433\u0438\u0435 \u0442\u0438\u043F\u044B \u0430\u0443\u0442\u0435\u043D\u0442\u0438\u0444\u0438\u043A\u0430\u0446\u0438\u0438)",
      "Each provider needs: id, envKey (required), plus optional baseUrl, generationConfig": "\u041A\u0430\u0436\u0434\u043E\u043C\u0443 \u043F\u0440\u043E\u0432\u0430\u0439\u0434\u0435\u0440\u0443 \u043D\u0443\u0436\u043D\u044B: id, envKey (\u043E\u0431\u044F\u0437\u0430\u0442\u0435\u043B\u044C\u043D\u043E), \u0430 \u0442\u0430\u043A\u0436\u0435 \u043E\u043F\u0446\u0438\u043E\u043D\u0430\u043B\u044C\u043D\u044B\u0435 baseUrl, generationConfig",
      "Use /model command to select your preferred model from the configured list": "\u0418\u0441\u043F\u043E\u043B\u044C\u0437\u0443\u0439\u0442\u0435 \u043A\u043E\u043C\u0430\u043D\u0434\u0443 /model, \u0447\u0442\u043E\u0431\u044B \u0432\u044B\u0431\u0440\u0430\u0442\u044C \u043F\u0440\u0435\u0434\u043F\u043E\u0447\u0438\u0442\u0430\u0435\u043C\u0443\u044E \u043C\u043E\u0434\u0435\u043B\u044C \u0438\u0437 \u043D\u0430\u0441\u0442\u0440\u043E\u0435\u043D\u043D\u043E\u0433\u043E \u0441\u043F\u0438\u0441\u043A\u0430",
      "Supported auth types: openai, anthropic, gemini, vertex-ai, etc.": "\u041F\u043E\u0434\u0434\u0435\u0440\u0436\u0438\u0432\u0430\u0435\u043C\u044B\u0435 \u0442\u0438\u043F\u044B \u0430\u0443\u0442\u0435\u043D\u0442\u0438\u0444\u0438\u043A\u0430\u0446\u0438\u0438: openai, anthropic, gemini, vertex-ai \u0438 \u0434\u0440.",
      // ============================================================================
      // Coding Plan Authentication
      // ============================================================================
      "Please enter your API key:": "\u041F\u043E\u0436\u0430\u043B\u0443\u0439\u0441\u0442\u0430, \u0432\u0432\u0435\u0434\u0438\u0442\u0435 \u0432\u0430\u0448 API-\u043A\u043B\u044E\u0447:",
      "API key cannot be empty.": "API-\u043A\u043B\u044E\u0447 \u043D\u0435 \u043C\u043E\u0436\u0435\u0442 \u0431\u044B\u0442\u044C \u043F\u0443\u0441\u0442\u044B\u043C.",
      "You can get your exclusive Coding Plan API-KEY here:": "\u041F\u043E\u043B\u0443\u0447\u0438\u0442\u0435 \u0441\u0432\u043E\u0439 \u044D\u043A\u0441\u043A\u043B\u044E\u0437\u0438\u0432\u043D\u044B\u0439 API-KEY Coding Plan \u0437\u0434\u0435\u0441\u044C:",
      "New model configurations are available for Bailian Coding Plan. Update now?": "\u0414\u043E\u0441\u0442\u0443\u043F\u043D\u044B \u043D\u043E\u0432\u044B\u0435 \u043A\u043E\u043D\u0444\u0438\u0433\u0443\u0440\u0430\u0446\u0438\u0438 \u043C\u043E\u0434\u0435\u043B\u0435\u0439 \u0434\u043B\u044F Bailian Coding Plan. \u041E\u0431\u043D\u043E\u0432\u0438\u0442\u044C \u0441\u0435\u0439\u0447\u0430\u0441?",
      "Coding Plan configuration updated successfully. New models are now available.": "\u041A\u043E\u043D\u0444\u0438\u0433\u0443\u0440\u0430\u0446\u0438\u044F Coding Plan \u0443\u0441\u043F\u0435\u0448\u043D\u043E \u043E\u0431\u043D\u043E\u0432\u043B\u0435\u043D\u0430. \u041D\u043E\u0432\u044B\u0435 \u043C\u043E\u0434\u0435\u043B\u0438 \u0442\u0435\u043F\u0435\u0440\u044C \u0434\u043E\u0441\u0442\u0443\u043F\u043D\u044B.",
      "Coding Plan API key not found. Please re-authenticate with Coding Plan.": "API-\u043A\u043B\u044E\u0447 Coding Plan \u043D\u0435 \u043D\u0430\u0439\u0434\u0435\u043D. \u041F\u043E\u0436\u0430\u043B\u0443\u0439\u0441\u0442\u0430, \u043F\u043E\u0432\u0442\u043E\u0440\u043D\u043E \u0430\u0432\u0442\u043E\u0440\u0438\u0437\u0443\u0439\u0442\u0435\u0441\u044C \u0441 Coding Plan.",
      "Failed to update Coding Plan configuration: {{message}}": "\u041D\u0435 \u0443\u0434\u0430\u043B\u043E\u0441\u044C \u043E\u0431\u043D\u043E\u0432\u0438\u0442\u044C \u043A\u043E\u043D\u0444\u0438\u0433\u0443\u0440\u0430\u0446\u0438\u044E Coding Plan: {{message}}",
      // ============================================================================
      // Auth Dialog - View Titles and Labels
      // ============================================================================
      "Coding Plan": "Coding Plan",
      "Coding Plan (Bailian, China)": "Coding Plan (Bailian, \u041A\u0438\u0442\u0430\u0439)",
      "Coding Plan (Bailian, Global/Intl)": "Coding Plan (Bailian, \u0413\u043B\u043E\u0431\u0430\u043B\u044C\u043D\u044B\u0439/\u041C\u0435\u0436\u0434\u0443\u043D\u0430\u0440\u043E\u0434\u043D\u044B\u0439)",
      "Paste your api key of Bailian Coding Plan and you're all set!": "\u0412\u0441\u0442\u0430\u0432\u044C\u0442\u0435 \u0432\u0430\u0448 API-\u043A\u043B\u044E\u0447 Bailian Coding Plan \u0438 \u0432\u0441\u0451 \u0433\u043E\u0442\u043E\u0432\u043E!",
      "Paste your api key of Coding Plan (Bailian, Global/Intl) and you're all set!": "\u0412\u0441\u0442\u0430\u0432\u044C\u0442\u0435 \u0432\u0430\u0448 API-\u043A\u043B\u044E\u0447 Coding Plan (Bailian, \u0413\u043B\u043E\u0431\u0430\u043B\u044C\u043D\u044B\u0439/\u041C\u0435\u0436\u0434\u0443\u043D\u0430\u0440\u043E\u0434\u043D\u044B\u0439) \u0438 \u0432\u0441\u0451 \u0433\u043E\u0442\u043E\u0432\u043E!",
      Custom: "\u041F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u0442\u0435\u043B\u044C\u0441\u043A\u0438\u0439",
      "More instructions about configuring `modelProviders` manually.": "\u0414\u043E\u043F\u043E\u043B\u043D\u0438\u0442\u0435\u043B\u044C\u043D\u044B\u0435 \u0438\u043D\u0441\u0442\u0440\u0443\u043A\u0446\u0438\u0438 \u043F\u043E \u0440\u0443\u0447\u043D\u043E\u0439 \u043D\u0430\u0441\u0442\u0440\u043E\u0439\u043A\u0435 `modelProviders`.",
      "Select API-KEY configuration mode:": "\u0412\u044B\u0431\u0435\u0440\u0438\u0442\u0435 \u0440\u0435\u0436\u0438\u043C \u043A\u043E\u043D\u0444\u0438\u0433\u0443\u0440\u0430\u0446\u0438\u0438 API-KEY:",
      "(Press Escape to go back)": "(\u041D\u0430\u0436\u043C\u0438\u0442\u0435 Escape \u0434\u043B\u044F \u0432\u043E\u0437\u0432\u0440\u0430\u0442\u0430)",
      "(Press Enter to submit, Escape to cancel)": "(\u041D\u0430\u0436\u043C\u0438\u0442\u0435 Enter \u0434\u043B\u044F \u043E\u0442\u043F\u0440\u0430\u0432\u043A\u0438, Escape \u0434\u043B\u044F \u043E\u0442\u043C\u0435\u043D\u044B)",
      "More instructions please check:": "\u0414\u043E\u043F\u043E\u043B\u043D\u0438\u0442\u0435\u043B\u044C\u043D\u044B\u0435 \u0438\u043D\u0441\u0442\u0440\u0443\u043A\u0446\u0438\u0438 \u0441\u043C.:",
      // ============================================================================
      // Coding Plan International Updates
      // ============================================================================
      "New model configurations are available for {{region}}. Update now?": "\u0414\u043E\u0441\u0442\u0443\u043F\u043D\u044B \u043D\u043E\u0432\u044B\u0435 \u043A\u043E\u043D\u0444\u0438\u0433\u0443\u0440\u0430\u0446\u0438\u0438 \u043C\u043E\u0434\u0435\u043B\u0435\u0439 \u0434\u043B\u044F {{region}}. \u041E\u0431\u043D\u043E\u0432\u0438\u0442\u044C \u0441\u0435\u0439\u0447\u0430\u0441?",
      "New model configurations are available for Bailian Coding Plan (China). Update now?": "\u0414\u043E\u0441\u0442\u0443\u043F\u043D\u044B \u043D\u043E\u0432\u044B\u0435 \u043A\u043E\u043D\u0444\u0438\u0433\u0443\u0440\u0430\u0446\u0438\u0438 \u043C\u043E\u0434\u0435\u043B\u0435\u0439 \u0434\u043B\u044F Bailian Coding Plan (\u041A\u0438\u0442\u0430\u0439). \u041E\u0431\u043D\u043E\u0432\u0438\u0442\u044C \u0441\u0435\u0439\u0447\u0430\u0441?",
      "New model configurations are available for Coding Plan (Bailian, Global/Intl). Update now?": "\u0414\u043E\u0441\u0442\u0443\u043F\u043D\u044B \u043D\u043E\u0432\u044B\u0435 \u043A\u043E\u043D\u0444\u0438\u0433\u0443\u0440\u0430\u0446\u0438\u0438 \u043C\u043E\u0434\u0435\u043B\u0435\u0439 \u0434\u043B\u044F Coding Plan (Bailian, \u0413\u043B\u043E\u0431\u0430\u043B\u044C\u043D\u044B\u0439/\u041C\u0435\u0436\u0434\u0443\u043D\u0430\u0440\u043E\u0434\u043D\u044B\u0439). \u041E\u0431\u043D\u043E\u0432\u0438\u0442\u044C \u0441\u0435\u0439\u0447\u0430\u0441?",
      '{{region}} configuration updated successfully. Model switched to "{{model}}".': '\u041A\u043E\u043D\u0444\u0438\u0433\u0443\u0440\u0430\u0446\u0438\u044F {{region}} \u0443\u0441\u043F\u0435\u0448\u043D\u043E \u043E\u0431\u043D\u043E\u0432\u043B\u0435\u043D\u0430. \u041C\u043E\u0434\u0435\u043B\u044C \u043F\u0435\u0440\u0435\u043A\u043B\u044E\u0447\u0435\u043D\u0430 \u043D\u0430 "{{model}}".',
      "Authenticated successfully with {{region}}. API key and model configs saved to settings.json (backed up).": "\u0423\u0441\u043F\u0435\u0448\u043D\u0430\u044F \u0430\u0443\u0442\u0435\u043D\u0442\u0438\u0444\u0438\u043A\u0430\u0446\u0438\u044F \u0441 {{region}}. API-\u043A\u043B\u044E\u0447 \u0438 \u043A\u043E\u043D\u0444\u0438\u0433\u0443\u0440\u0430\u0446\u0438\u0438 \u043C\u043E\u0434\u0435\u043B\u0435\u0439 \u0441\u043E\u0445\u0440\u0430\u043D\u0435\u043D\u044B \u0432 settings.json (\u0440\u0435\u0437\u0435\u0440\u0432\u043D\u0430\u044F \u043A\u043E\u043F\u0438\u044F \u0441\u043E\u0437\u0434\u0430\u043D\u0430)."
    };
  }
});

// packages/cli/src/i18n/locales/zh.js
var zh_exports = {};
__export(zh_exports, {
  default: () => zh_default
});
var zh_default;
var init_zh = __esm({
  "packages/cli/src/i18n/locales/zh.js"() {
    "use strict";
    init_esbuild_shims();
    zh_default = {
      // ============================================================================
      // Help / UI Components
      // ============================================================================
      // Attachment hints
      "\u2191 to manage attachments": "\u2191 \u7BA1\u7406\u9644\u4EF6",
      "\u2190 \u2192 select, Delete to remove, \u2193 to exit": "\u2190 \u2192 \u9009\u62E9\uFF0CDelete \u5220\u9664\uFF0C\u2193 \u9000\u51FA",
      "Attachments: ": "\u9644\u4EF6\uFF1A",
      "Basics:": "\u57FA\u7840\u529F\u80FD\uFF1A",
      "Add context": "\u6DFB\u52A0\u4E0A\u4E0B\u6587",
      "Use {{symbol}} to specify files for context (e.g., {{example}}) to target specific files or folders.": "\u4F7F\u7528 {{symbol}} \u6307\u5B9A\u6587\u4EF6\u4F5C\u4E3A\u4E0A\u4E0B\u6587\uFF08\u4F8B\u5982\uFF0C{{example}}\uFF09\uFF0C\u7528\u4E8E\u5B9A\u4F4D\u7279\u5B9A\u6587\u4EF6\u6216\u6587\u4EF6\u5939",
      "@": "@",
      "@src/myFile.ts": "@src/myFile.ts",
      "Shell mode": "Shell \u6A21\u5F0F",
      "YOLO mode": "YOLO \u6A21\u5F0F",
      "plan mode": "\u89C4\u5212\u6A21\u5F0F",
      "auto-accept edits": "\u81EA\u52A8\u63A5\u53D7\u7F16\u8F91",
      "Accepting edits": "\u63A5\u53D7\u7F16\u8F91",
      "(shift + tab to cycle)": "(shift + tab \u5207\u6362)",
      "(tab to cycle)": "(\u6309 tab \u5207\u6362)",
      "Execute shell commands via {{symbol}} (e.g., {{example1}}) or use natural language (e.g., {{example2}}).": "\u901A\u8FC7 {{symbol}} \u6267\u884C shell \u547D\u4EE4\uFF08\u4F8B\u5982\uFF0C{{example1}}\uFF09\u6216\u4F7F\u7528\u81EA\u7136\u8BED\u8A00\uFF08\u4F8B\u5982\uFF0C{{example2}}\uFF09",
      "!": "!",
      "!npm run start": "!npm run start",
      "start server": "start server",
      "Commands:": "\u547D\u4EE4:",
      "shell command": "shell \u547D\u4EE4",
      "Model Context Protocol command (from external servers)": "\u6A21\u578B\u4E0A\u4E0B\u6587\u534F\u8BAE\u547D\u4EE4\uFF08\u6765\u81EA\u5916\u90E8\u670D\u52A1\u5668\uFF09",
      "Keyboard Shortcuts:": "\u952E\u76D8\u5FEB\u6377\u952E\uFF1A",
      "Toggle this help display": "\u5207\u6362\u6B64\u5E2E\u52A9\u663E\u793A",
      "Toggle shell mode": "\u5207\u6362\u547D\u4EE4\u884C\u6A21\u5F0F",
      "Open command menu": "\u6253\u5F00\u547D\u4EE4\u83DC\u5355",
      "Add file context": "\u6DFB\u52A0\u6587\u4EF6\u4E0A\u4E0B\u6587",
      "Accept suggestion / Autocomplete": "\u63A5\u53D7\u5EFA\u8BAE / \u81EA\u52A8\u8865\u5168",
      "Reverse search history": "\u53CD\u5411\u641C\u7D22\u5386\u53F2",
      "Press ? again to close": "\u518D\u6B21\u6309 ? \u5173\u95ED",
      // Keyboard shortcuts panel descriptions
      "for shell mode": "\u547D\u4EE4\u884C\u6A21\u5F0F",
      "for commands": "\u547D\u4EE4\u83DC\u5355",
      "for file paths": "\u6587\u4EF6\u8DEF\u5F84",
      "to clear input": "\u6E05\u7A7A\u8F93\u5165",
      "to cycle approvals": "\u5207\u6362\u5BA1\u6279\u6A21\u5F0F",
      "to quit": "\u9000\u51FA",
      "for newline": "\u6362\u884C",
      "to clear screen": "\u6E05\u5C4F",
      "to search history": "\u641C\u7D22\u5386\u53F2",
      "to paste images": "\u7C98\u8D34\u56FE\u7247",
      "for external editor": "\u5916\u90E8\u7F16\u8F91\u5668",
      "Jump through words in the input": "\u5728\u8F93\u5165\u4E2D\u6309\u5355\u8BCD\u8DF3\u8F6C",
      "Close dialogs, cancel requests, or quit application": "\u5173\u95ED\u5BF9\u8BDD\u6846\u3001\u53D6\u6D88\u8BF7\u6C42\u6216\u9000\u51FA\u5E94\u7528\u7A0B\u5E8F",
      "New line": "\u6362\u884C",
      "New line (Alt+Enter works for certain linux distros)": "\u6362\u884C\uFF08\u67D0\u4E9B Linux \u53D1\u884C\u7248\u652F\u6301 Alt+Enter\uFF09",
      "Clear the screen": "\u6E05\u5C4F",
      "Open input in external editor": "\u5728\u5916\u90E8\u7F16\u8F91\u5668\u4E2D\u6253\u5F00\u8F93\u5165",
      "Send message": "\u53D1\u9001\u6D88\u606F",
      "Initializing...": "\u6B63\u5728\u521D\u59CB\u5316...",
      "Connecting to MCP servers... ({{connected}}/{{total}})": "\u6B63\u5728\u8FDE\u63A5\u5230 MCP \u670D\u52A1\u5668... ({{connected}}/{{total}})",
      "Type your message or @path/to/file": "\u8F93\u5165\u60A8\u7684\u6D88\u606F\u6216 @ \u6587\u4EF6\u8DEF\u5F84",
      "? for shortcuts": "\u6309 ? \u67E5\u770B\u5FEB\u6377\u952E",
      "Press 'i' for INSERT mode and 'Esc' for NORMAL mode.": "\u6309 'i' \u8FDB\u5165\u63D2\u5165\u6A21\u5F0F\uFF0C\u6309 'Esc' \u8FDB\u5165\u666E\u901A\u6A21\u5F0F",
      "Cancel operation / Clear input (double press)": "\u53D6\u6D88\u64CD\u4F5C / \u6E05\u7A7A\u8F93\u5165\uFF08\u53CC\u51FB\uFF09",
      "Cycle approval modes": "\u5FAA\u73AF\u5207\u6362\u5BA1\u6279\u6A21\u5F0F",
      "Cycle through your prompt history": "\u5FAA\u73AF\u6D4F\u89C8\u63D0\u793A\u5386\u53F2",
      "For a full list of shortcuts, see {{docPath}}": "\u5B8C\u6574\u5FEB\u6377\u952E\u5217\u8868\uFF0C\u8BF7\u53C2\u9605 {{docPath}}",
      "docs/keyboard-shortcuts.md": "docs/keyboard-shortcuts.md",
      "for help on Qwen Code": "\u83B7\u53D6 Qwen Code \u5E2E\u52A9",
      "show version info": "\u663E\u793A\u7248\u672C\u4FE1\u606F",
      "submit a bug report": "\u63D0\u4EA4\u9519\u8BEF\u62A5\u544A",
      "About Qwen Code": "\u5173\u4E8E Qwen Code",
      Status: "\u72B6\u6001",
      // ============================================================================
      // System Information Fields
      // ============================================================================
      "Qwen Code": "Qwen Code",
      Runtime: "\u8FD0\u884C\u73AF\u5883",
      OS: "\u64CD\u4F5C\u7CFB\u7EDF",
      Auth: "\u8BA4\u8BC1",
      "CLI Version": "CLI \u7248\u672C",
      "Git Commit": "Git \u63D0\u4EA4",
      Model: "\u6A21\u578B",
      Sandbox: "\u6C99\u7BB1",
      "OS Platform": "\u64CD\u4F5C\u7CFB\u7EDF\u5E73\u53F0",
      "OS Arch": "\u64CD\u4F5C\u7CFB\u7EDF\u67B6\u6784",
      "OS Release": "\u64CD\u4F5C\u7CFB\u7EDF\u7248\u672C",
      "Node.js Version": "Node.js \u7248\u672C",
      "NPM Version": "NPM \u7248\u672C",
      "Session ID": "\u4F1A\u8BDD ID",
      "Auth Method": "\u8BA4\u8BC1\u65B9\u5F0F",
      "Base URL": "\u57FA\u7840 URL",
      Proxy: "\u4EE3\u7406",
      "Memory Usage": "\u5185\u5B58\u4F7F\u7528",
      "IDE Client": "IDE \u5BA2\u6237\u7AEF",
      // ============================================================================
      // Commands - General
      // ============================================================================
      "Analyzes the project and creates a tailored QWEN.md file.": "\u5206\u6790\u9879\u76EE\u5E76\u521B\u5EFA\u5B9A\u5236\u7684 QWEN.md \u6587\u4EF6",
      "list available Qwen Code tools. Usage: /tools [desc]": "\u5217\u51FA\u53EF\u7528\u7684 Qwen Code \u5DE5\u5177\u3002\u7528\u6CD5\uFF1A/tools [desc]",
      "Available Qwen Code CLI tools:": "\u53EF\u7528\u7684 Qwen Code CLI \u5DE5\u5177\uFF1A",
      "No tools available": "\u6CA1\u6709\u53EF\u7528\u5DE5\u5177",
      "View or change the approval mode for tool usage": "\u67E5\u770B\u6216\u66F4\u6539\u5DE5\u5177\u4F7F\u7528\u7684\u5BA1\u6279\u6A21\u5F0F",
      'Invalid approval mode "{{arg}}". Valid modes: {{modes}}': '\u65E0\u6548\u7684\u5BA1\u6279\u6A21\u5F0F "{{arg}}"\u3002\u6709\u6548\u6A21\u5F0F\uFF1A{{modes}}',
      'Approval mode set to "{{mode}}"': '\u5BA1\u6279\u6A21\u5F0F\u5DF2\u8BBE\u7F6E\u4E3A "{{mode}}"',
      "View or change the language setting": "\u67E5\u770B\u6216\u66F4\u6539\u8BED\u8A00\u8BBE\u7F6E",
      "change the theme": "\u66F4\u6539\u4E3B\u9898",
      "Select Theme": "\u9009\u62E9\u4E3B\u9898",
      Preview: "\u9884\u89C8",
      "(Use Enter to select, Tab to configure scope)": "\uFF08\u4F7F\u7528 Enter \u9009\u62E9\uFF0CTab \u914D\u7F6E\u4F5C\u7528\u57DF\uFF09",
      "(Use Enter to apply scope, Tab to go back)": "\uFF08\u4F7F\u7528 Enter \u5E94\u7528\u4F5C\u7528\u57DF\uFF0CTab \u8FD4\u56DE\uFF09",
      "Theme configuration unavailable due to NO_COLOR env variable.": "\u7531\u4E8E NO_COLOR \u73AF\u5883\u53D8\u91CF\uFF0C\u4E3B\u9898\u914D\u7F6E\u4E0D\u53EF\u7528\u3002",
      'Theme "{{themeName}}" not found.': '\u672A\u627E\u5230\u4E3B\u9898 "{{themeName}}"\u3002',
      'Theme "{{themeName}}" not found in selected scope.': '\u5728\u6240\u9009\u4F5C\u7528\u57DF\u4E2D\u672A\u627E\u5230\u4E3B\u9898 "{{themeName}}"\u3002',
      "Clear conversation history and free up context": "\u6E05\u9664\u5BF9\u8BDD\u5386\u53F2\u5E76\u91CA\u653E\u4E0A\u4E0B\u6587",
      "Compresses the context by replacing it with a summary.": "\u901A\u8FC7\u7528\u6458\u8981\u66FF\u6362\u6765\u538B\u7F29\u4E0A\u4E0B\u6587",
      "open full Qwen Code documentation in your browser": "\u5728\u6D4F\u89C8\u5668\u4E2D\u6253\u5F00\u5B8C\u6574\u7684 Qwen Code \u6587\u6863",
      "Configuration not available.": "\u914D\u7F6E\u4E0D\u53EF\u7528",
      "change the auth method": "\u66F4\u6539\u8BA4\u8BC1\u65B9\u6CD5",
      "Configure authentication information for login": "\u914D\u7F6E\u767B\u5F55\u8BA4\u8BC1\u4FE1\u606F",
      "Copy the last result or code snippet to clipboard": "\u5C06\u6700\u540E\u7684\u7ED3\u679C\u6216\u4EE3\u7801\u7247\u6BB5\u590D\u5236\u5230\u526A\u8D34\u677F",
      // ============================================================================
      // Commands - Agents
      // ============================================================================
      "Manage subagents for specialized task delegation.": "\u7BA1\u7406\u7528\u4E8E\u4E13\u95E8\u4EFB\u52A1\u59D4\u6D3E\u7684\u5B50\u667A\u80FD\u4F53",
      "Manage existing subagents (view, edit, delete).": "\u7BA1\u7406\u73B0\u6709\u5B50\u667A\u80FD\u4F53\uFF08\u67E5\u770B\u3001\u7F16\u8F91\u3001\u5220\u9664\uFF09",
      "Create a new subagent with guided setup.": "\u901A\u8FC7\u5F15\u5BFC\u5F0F\u8BBE\u7F6E\u521B\u5EFA\u65B0\u7684\u5B50\u667A\u80FD\u4F53",
      // ============================================================================
      // Agents - Management Dialog
      // ============================================================================
      Agents: "\u667A\u80FD\u4F53",
      "Choose Action": "\u9009\u62E9\u64CD\u4F5C",
      "Edit {{name}}": "\u7F16\u8F91 {{name}}",
      "Edit Tools: {{name}}": "\u7F16\u8F91\u5DE5\u5177: {{name}}",
      "Edit Color: {{name}}": "\u7F16\u8F91\u989C\u8272: {{name}}",
      "Delete {{name}}": "\u5220\u9664 {{name}}",
      "Unknown Step": "\u672A\u77E5\u6B65\u9AA4",
      "Esc to close": "\u6309 Esc \u5173\u95ED",
      "Enter to select, \u2191\u2193 to navigate, Esc to close": "Enter \u9009\u62E9\uFF0C\u2191\u2193 \u5BFC\u822A\uFF0CEsc \u5173\u95ED",
      "Esc to go back": "\u6309 Esc \u8FD4\u56DE",
      "Enter to confirm, Esc to cancel": "Enter \u786E\u8BA4\uFF0CEsc \u53D6\u6D88",
      "Enter to select, \u2191\u2193 to navigate, Esc to go back": "Enter \u9009\u62E9\uFF0C\u2191\u2193 \u5BFC\u822A\uFF0CEsc \u8FD4\u56DE",
      "Invalid step: {{step}}": "\u65E0\u6548\u6B65\u9AA4: {{step}}",
      "No subagents found.": "\u672A\u627E\u5230\u5B50\u667A\u80FD\u4F53\u3002",
      "Use '/agents create' to create your first subagent.": "\u4F7F\u7528 '/agents create' \u521B\u5EFA\u60A8\u7684\u7B2C\u4E00\u4E2A\u5B50\u667A\u80FD\u4F53\u3002",
      "(built-in)": "\uFF08\u5185\u7F6E\uFF09",
      "(overridden by project level agent)": "\uFF08\u5DF2\u88AB\u9879\u76EE\u7EA7\u667A\u80FD\u4F53\u8986\u76D6\uFF09",
      "Project Level ({{path}})": "\u9879\u76EE\u7EA7 ({{path}})",
      "User Level ({{path}})": "\u7528\u6237\u7EA7 ({{path}})",
      "Built-in Agents": "\u5185\u7F6E\u667A\u80FD\u4F53",
      "Extension Agents": "\u6269\u5C55\u667A\u80FD\u4F53",
      "Using: {{count}} agents": "\u4F7F\u7528\u4E2D: {{count}} \u4E2A\u667A\u80FD\u4F53",
      "View Agent": "\u67E5\u770B\u667A\u80FD\u4F53",
      "Edit Agent": "\u7F16\u8F91\u667A\u80FD\u4F53",
      "Delete Agent": "\u5220\u9664\u667A\u80FD\u4F53",
      Back: "\u8FD4\u56DE",
      "No agent selected": "\u672A\u9009\u62E9\u667A\u80FD\u4F53",
      "File Path: ": "\u6587\u4EF6\u8DEF\u5F84: ",
      "Tools: ": "\u5DE5\u5177: ",
      "Color: ": "\u989C\u8272: ",
      "Description:": "\u63CF\u8FF0:",
      "System Prompt:": "\u7CFB\u7EDF\u63D0\u793A:",
      "Open in editor": "\u5728\u7F16\u8F91\u5668\u4E2D\u6253\u5F00",
      "Edit tools": "\u7F16\u8F91\u5DE5\u5177",
      "Edit color": "\u7F16\u8F91\u989C\u8272",
      "\u274C Error:": "\u274C \u9519\u8BEF:",
      'Are you sure you want to delete agent "{{name}}"?': '\u60A8\u786E\u5B9A\u8981\u5220\u9664\u667A\u80FD\u4F53 "{{name}}" \u5417\uFF1F',
      // ============================================================================
      // Agents - Creation Wizard
      // ============================================================================
      "Project Level (.qwen/agents/)": "\u9879\u76EE\u7EA7 (.qwen/agents/)",
      "User Level (~/.qwen/agents/)": "\u7528\u6237\u7EA7 (~/.qwen/agents/)",
      "\u2705 Subagent Created Successfully!": "\u2705 \u5B50\u667A\u80FD\u4F53\u521B\u5EFA\u6210\u529F\uFF01",
      'Subagent "{{name}}" has been saved to {{level}} level.': '\u5B50\u667A\u80FD\u4F53 "{{name}}" \u5DF2\u4FDD\u5B58\u5230 {{level}} \u7EA7\u522B\u3002',
      "Name: ": "\u540D\u79F0: ",
      "Location: ": "\u4F4D\u7F6E: ",
      "\u274C Error saving subagent:": "\u274C \u4FDD\u5B58\u5B50\u667A\u80FD\u4F53\u65F6\u51FA\u9519:",
      "Warnings:": "\u8B66\u544A:",
      'Name "{{name}}" already exists at {{level}} level - will overwrite existing subagent': '\u540D\u79F0 "{{name}}" \u5728 {{level}} \u7EA7\u522B\u5DF2\u5B58\u5728 - \u5C06\u8986\u76D6\u73B0\u6709\u5B50\u667A\u80FD\u4F53',
      'Name "{{name}}" exists at user level - project level will take precedence': '\u540D\u79F0 "{{name}}" \u5728\u7528\u6237\u7EA7\u522B\u5B58\u5728 - \u9879\u76EE\u7EA7\u522B\u5C06\u4F18\u5148',
      'Name "{{name}}" exists at project level - existing subagent will take precedence': '\u540D\u79F0 "{{name}}" \u5728\u9879\u76EE\u7EA7\u522B\u5B58\u5728 - \u73B0\u6709\u5B50\u667A\u80FD\u4F53\u5C06\u4F18\u5148',
      "Description is over {{length}} characters": "\u63CF\u8FF0\u8D85\u8FC7 {{length}} \u4E2A\u5B57\u7B26",
      "System prompt is over {{length}} characters": "\u7CFB\u7EDF\u63D0\u793A\u8D85\u8FC7 {{length}} \u4E2A\u5B57\u7B26",
      // Agents - Creation Wizard Steps
      "Step {{n}}: Choose Location": "\u6B65\u9AA4 {{n}}: \u9009\u62E9\u4F4D\u7F6E",
      "Step {{n}}: Choose Generation Method": "\u6B65\u9AA4 {{n}}: \u9009\u62E9\u751F\u6210\u65B9\u5F0F",
      "Generate with Qwen Code (Recommended)": "\u4F7F\u7528 Qwen Code \u751F\u6210\uFF08\u63A8\u8350\uFF09",
      "Manual Creation": "\u624B\u52A8\u521B\u5EFA",
      "Describe what this subagent should do and when it should be used. (Be comprehensive for best results)": "\u63CF\u8FF0\u6B64\u5B50\u667A\u80FD\u4F53\u5E94\u8BE5\u505A\u4EC0\u4E48\u4EE5\u53CA\u4F55\u65F6\u4F7F\u7528\u5B83\u3002\uFF08\u4E3A\u4E86\u83B7\u5F97\u6700\u4F73\u6548\u679C\uFF0C\u8BF7\u5168\u9762\u63CF\u8FF0\uFF09",
      "e.g., Expert code reviewer that reviews code based on best practices...": "\u4F8B\u5982\uFF1A\u4E13\u4E1A\u7684\u4EE3\u7801\u5BA1\u67E5\u5458\uFF0C\u6839\u636E\u6700\u4F73\u5B9E\u8DF5\u5BA1\u67E5\u4EE3\u7801...",
      "Generating subagent configuration...": "\u6B63\u5728\u751F\u6210\u5B50\u667A\u80FD\u4F53\u914D\u7F6E...",
      "Failed to generate subagent: {{error}}": "\u751F\u6210\u5B50\u667A\u80FD\u4F53\u5931\u8D25: {{error}}",
      "Step {{n}}: Describe Your Subagent": "\u6B65\u9AA4 {{n}}: \u63CF\u8FF0\u60A8\u7684\u5B50\u667A\u80FD\u4F53",
      "Step {{n}}: Enter Subagent Name": "\u6B65\u9AA4 {{n}}: \u8F93\u5165\u5B50\u667A\u80FD\u4F53\u540D\u79F0",
      "Step {{n}}: Enter System Prompt": "\u6B65\u9AA4 {{n}}: \u8F93\u5165\u7CFB\u7EDF\u63D0\u793A",
      "Step {{n}}: Enter Description": "\u6B65\u9AA4 {{n}}: \u8F93\u5165\u63CF\u8FF0",
      // Agents - Tool Selection
      "Step {{n}}: Select Tools": "\u6B65\u9AA4 {{n}}: \u9009\u62E9\u5DE5\u5177",
      "All Tools (Default)": "\u6240\u6709\u5DE5\u5177\uFF08\u9ED8\u8BA4\uFF09",
      "All Tools": "\u6240\u6709\u5DE5\u5177",
      "Read-only Tools": "\u53EA\u8BFB\u5DE5\u5177",
      "Read & Edit Tools": "\u8BFB\u53D6\u548C\u7F16\u8F91\u5DE5\u5177",
      "Read & Edit & Execution Tools": "\u8BFB\u53D6\u3001\u7F16\u8F91\u548C\u6267\u884C\u5DE5\u5177",
      "All tools selected, including MCP tools": "\u5DF2\u9009\u62E9\u6240\u6709\u5DE5\u5177\uFF0C\u5305\u62EC MCP \u5DE5\u5177",
      "Selected tools:": "\u5DF2\u9009\u62E9\u7684\u5DE5\u5177:",
      "Read-only tools:": "\u53EA\u8BFB\u5DE5\u5177:",
      "Edit tools:": "\u7F16\u8F91\u5DE5\u5177:",
      "Execution tools:": "\u6267\u884C\u5DE5\u5177:",
      "Step {{n}}: Choose Background Color": "\u6B65\u9AA4 {{n}}: \u9009\u62E9\u80CC\u666F\u989C\u8272",
      "Step {{n}}: Confirm and Save": "\u6B65\u9AA4 {{n}}: \u786E\u8BA4\u5E76\u4FDD\u5B58",
      // Agents - Navigation & Instructions
      "Esc to cancel": "\u6309 Esc \u53D6\u6D88",
      "Press Enter to save, e to save and edit, Esc to go back": "\u6309 Enter \u4FDD\u5B58\uFF0Ce \u4FDD\u5B58\u5E76\u7F16\u8F91\uFF0CEsc \u8FD4\u56DE",
      "Press Enter to continue, {{navigation}}Esc to {{action}}": "\u6309 Enter \u7EE7\u7EED\uFF0C{{navigation}}Esc {{action}}",
      cancel: "\u53D6\u6D88",
      "go back": "\u8FD4\u56DE",
      "\u2191\u2193 to navigate, ": "\u2191\u2193 \u5BFC\u822A\uFF0C",
      "Enter a clear, unique name for this subagent.": "\u4E3A\u6B64\u5B50\u667A\u80FD\u4F53\u8F93\u5165\u4E00\u4E2A\u6E05\u6670\u3001\u552F\u4E00\u7684\u540D\u79F0\u3002",
      "e.g., Code Reviewer": "\u4F8B\u5982\uFF1A\u4EE3\u7801\u5BA1\u67E5\u5458",
      "Name cannot be empty.": "\u540D\u79F0\u4E0D\u80FD\u4E3A\u7A7A\u3002",
      "Write the system prompt that defines this subagent's behavior. Be comprehensive for best results.": "\u7F16\u5199\u5B9A\u4E49\u6B64\u5B50\u667A\u80FD\u4F53\u884C\u4E3A\u7684\u7CFB\u7EDF\u63D0\u793A\u3002\u4E3A\u4E86\u83B7\u5F97\u6700\u4F73\u6548\u679C\uFF0C\u8BF7\u5168\u9762\u63CF\u8FF0\u3002",
      "e.g., You are an expert code reviewer...": "\u4F8B\u5982\uFF1A\u60A8\u662F\u4E00\u4F4D\u4E13\u4E1A\u7684\u4EE3\u7801\u5BA1\u67E5\u5458...",
      "System prompt cannot be empty.": "\u7CFB\u7EDF\u63D0\u793A\u4E0D\u80FD\u4E3A\u7A7A\u3002",
      "Describe when and how this subagent should be used.": "\u63CF\u8FF0\u4F55\u65F6\u4EE5\u53CA\u5982\u4F55\u4F7F\u7528\u6B64\u5B50\u667A\u80FD\u4F53\u3002",
      "e.g., Reviews code for best practices and potential bugs.": "\u4F8B\u5982\uFF1A\u5BA1\u67E5\u4EE3\u7801\u4EE5\u67E5\u627E\u6700\u4F73\u5B9E\u8DF5\u548C\u6F5C\u5728\u9519\u8BEF\u3002",
      "Description cannot be empty.": "\u63CF\u8FF0\u4E0D\u80FD\u4E3A\u7A7A\u3002",
      "Failed to launch editor: {{error}}": "\u542F\u52A8\u7F16\u8F91\u5668\u5931\u8D25: {{error}}",
      "Failed to save and edit subagent: {{error}}": "\u4FDD\u5B58\u5E76\u7F16\u8F91\u5B50\u667A\u80FD\u4F53\u5931\u8D25: {{error}}",
      // ============================================================================
      // Commands - General (continued)
      // ============================================================================
      "View and edit Qwen Code settings": "\u67E5\u770B\u548C\u7F16\u8F91 Qwen Code \u8BBE\u7F6E",
      Settings: "\u8BBE\u7F6E",
      "To see changes, Qwen Code must be restarted. Press r to exit and apply changes now.": "\u8981\u67E5\u770B\u66F4\u6539\uFF0C\u5FC5\u987B\u91CD\u542F Qwen Code\u3002\u6309 r \u9000\u51FA\u5E76\u7ACB\u5373\u5E94\u7528\u66F4\u6539\u3002",
      'The command "/{{command}}" is not supported in non-interactive mode.': '\u4E0D\u652F\u6301\u5728\u975E\u4EA4\u4E92\u6A21\u5F0F\u4E0B\u4F7F\u7528\u547D\u4EE4 "/{{command}}"\u3002',
      // ============================================================================
      // Settings Labels
      // ============================================================================
      "Vim Mode": "Vim \u6A21\u5F0F",
      "Disable Auto Update": "\u7981\u7528\u81EA\u52A8\u66F4\u65B0",
      "Attribution: commit": "\u7F72\u540D\uFF1A\u63D0\u4EA4",
      "Terminal Bell Notification": "\u7EC8\u7AEF\u54CD\u94C3\u901A\u77E5",
      "Enable Usage Statistics": "\u542F\u7528\u4F7F\u7528\u7EDF\u8BA1",
      Theme: "\u4E3B\u9898",
      "Preferred Editor": "\u9996\u9009\u7F16\u8F91\u5668",
      "Auto-connect to IDE": "\u81EA\u52A8\u8FDE\u63A5\u5230 IDE",
      "Enable Prompt Completion": "\u542F\u7528\u63D0\u793A\u8865\u5168",
      "Debug Keystroke Logging": "\u8C03\u8BD5\u6309\u952E\u8BB0\u5F55",
      "Language: UI": "\u8BED\u8A00\uFF1A\u754C\u9762",
      "Language: Model": "\u8BED\u8A00\uFF1A\u6A21\u578B",
      "Output Format": "\u8F93\u51FA\u683C\u5F0F",
      "Hide Window Title": "\u9690\u85CF\u7A97\u53E3\u6807\u9898",
      "Show Status in Title": "\u5728\u6807\u9898\u4E2D\u663E\u793A\u72B6\u6001",
      "Hide Tips": "\u9690\u85CF\u63D0\u793A",
      "Show Line Numbers in Code": "\u5728\u4EE3\u7801\u4E2D\u663E\u793A\u884C\u53F7",
      "Show Citations": "\u663E\u793A\u5F15\u7528",
      "Custom Witty Phrases": "\u81EA\u5B9A\u4E49\u8BD9\u8C10\u77ED\u8BED",
      "Show Welcome Back Dialog": "\u663E\u793A\u6B22\u8FCE\u56DE\u6765\u5BF9\u8BDD\u6846",
      "Enable User Feedback": "\u542F\u7528\u7528\u6237\u53CD\u9988",
      "How is Qwen doing this session? (optional)": "Qwen \u8FD9\u6B21\u8868\u73B0\u5982\u4F55\uFF1F\uFF08\u53EF\u9009\uFF09",
      Bad: "\u4E0D\u6EE1\u610F",
      Fine: "\u8FD8\u884C",
      Good: "\u6EE1\u610F",
      Dismiss: "\u5FFD\u7565",
      "Not Sure Yet": "\u6682\u4E0D\u8BC4\u4EF7",
      "Any other key": "\u4EFB\u610F\u5176\u4ED6\u952E",
      "Disable Loading Phrases": "\u7981\u7528\u52A0\u8F7D\u77ED\u8BED",
      "Screen Reader Mode": "\u5C4F\u5E55\u9605\u8BFB\u5668\u6A21\u5F0F",
      "IDE Mode": "IDE \u6A21\u5F0F",
      "Max Session Turns": "\u6700\u5927\u4F1A\u8BDD\u8F6E\u6B21",
      "Skip Next Speaker Check": "\u8DF3\u8FC7\u4E0B\u4E00\u4E2A\u8BF4\u8BDD\u8005\u68C0\u67E5",
      "Skip Loop Detection": "\u8DF3\u8FC7\u5FAA\u73AF\u68C0\u6D4B",
      "Skip Startup Context": "\u8DF3\u8FC7\u542F\u52A8\u4E0A\u4E0B\u6587",
      "Enable OpenAI Logging": "\u542F\u7528 OpenAI \u65E5\u5FD7",
      "OpenAI Logging Directory": "OpenAI \u65E5\u5FD7\u76EE\u5F55",
      Timeout: "\u8D85\u65F6",
      "Max Retries": "\u6700\u5927\u91CD\u8BD5\u6B21\u6570",
      "Disable Cache Control": "\u7981\u7528\u7F13\u5B58\u63A7\u5236",
      "Memory Discovery Max Dirs": "\u5185\u5B58\u53D1\u73B0\u6700\u5927\u76EE\u5F55\u6570",
      "Load Memory From Include Directories": "\u4ECE\u5305\u542B\u76EE\u5F55\u52A0\u8F7D\u5185\u5B58",
      "Respect .gitignore": "\u9075\u5B88 .gitignore",
      "Respect .qwenignore": "\u9075\u5B88 .qwenignore",
      "Enable Recursive File Search": "\u542F\u7528\u9012\u5F52\u6587\u4EF6\u641C\u7D22",
      "Disable Fuzzy Search": "\u7981\u7528\u6A21\u7CCA\u641C\u7D22",
      "Interactive Shell (PTY)": "\u4EA4\u4E92\u5F0F Shell (PTY)",
      "Show Color": "\u663E\u793A\u989C\u8272",
      "Auto Accept": "\u81EA\u52A8\u63A5\u53D7",
      "Use Ripgrep": "\u4F7F\u7528 Ripgrep",
      "Use Builtin Ripgrep": "\u4F7F\u7528\u5185\u7F6E Ripgrep",
      "Enable Tool Output Truncation": "\u542F\u7528\u5DE5\u5177\u8F93\u51FA\u622A\u65AD",
      "Tool Output Truncation Threshold": "\u5DE5\u5177\u8F93\u51FA\u622A\u65AD\u9608\u503C",
      "Tool Output Truncation Lines": "\u5DE5\u5177\u8F93\u51FA\u622A\u65AD\u884C\u6570",
      "Folder Trust": "\u6587\u4EF6\u5939\u4FE1\u4EFB",
      "Vision Model Preview": "\u89C6\u89C9\u6A21\u578B\u9884\u89C8",
      "Tool Schema Compliance": "\u5DE5\u5177 Schema \u517C\u5BB9\u6027",
      // Settings enum options
      "Auto (detect from system)": "\u81EA\u52A8\uFF08\u4ECE\u7CFB\u7EDF\u68C0\u6D4B\uFF09",
      Text: "\u6587\u672C",
      JSON: "JSON",
      Plan: "\u89C4\u5212",
      Default: "\u9ED8\u8BA4",
      "Auto Edit": "\u81EA\u52A8\u7F16\u8F91",
      YOLO: "YOLO",
      "toggle vim mode on/off": "\u5207\u6362 vim \u6A21\u5F0F\u5F00\u5173",
      "check session stats. Usage: /stats [model|tools]": "\u68C0\u67E5\u4F1A\u8BDD\u7EDF\u8BA1\u4FE1\u606F\u3002\u7528\u6CD5\uFF1A/stats [model|tools]",
      "Show model-specific usage statistics.": "\u663E\u793A\u6A21\u578B\u76F8\u5173\u7684\u4F7F\u7528\u7EDF\u8BA1\u4FE1\u606F",
      "Show tool-specific usage statistics.": "\u663E\u793A\u5DE5\u5177\u76F8\u5173\u7684\u4F7F\u7528\u7EDF\u8BA1\u4FE1\u606F",
      "exit the cli": "\u9000\u51FA\u547D\u4EE4\u884C\u754C\u9762",
      "list configured MCP servers and tools, or authenticate with OAuth-enabled servers": "\u5217\u51FA\u5DF2\u914D\u7F6E\u7684 MCP \u670D\u52A1\u5668\u548C\u5DE5\u5177\uFF0C\u6216\u4F7F\u7528\u652F\u6301 OAuth \u7684\u670D\u52A1\u5668\u8FDB\u884C\u8EAB\u4EFD\u9A8C\u8BC1",
      "Manage workspace directories": "\u7BA1\u7406\u5DE5\u4F5C\u533A\u76EE\u5F55",
      "Add directories to the workspace. Use comma to separate multiple paths": "\u5C06\u76EE\u5F55\u6DFB\u52A0\u5230\u5DE5\u4F5C\u533A\u3002\u4F7F\u7528\u9017\u53F7\u5206\u9694\u591A\u4E2A\u8DEF\u5F84",
      "Show all directories in the workspace": "\u663E\u793A\u5DE5\u4F5C\u533A\u4E2D\u7684\u6240\u6709\u76EE\u5F55",
      "set external editor preference": "\u8BBE\u7F6E\u5916\u90E8\u7F16\u8F91\u5668\u9996\u9009\u9879",
      "Select Editor": "\u9009\u62E9\u7F16\u8F91\u5668",
      "Editor Preference": "\u7F16\u8F91\u5668\u9996\u9009\u9879",
      "These editors are currently supported. Please note that some editors cannot be used in sandbox mode.": "\u5F53\u524D\u652F\u6301\u4EE5\u4E0B\u7F16\u8F91\u5668\u3002\u8BF7\u6CE8\u610F\uFF0C\u67D0\u4E9B\u7F16\u8F91\u5668\u65E0\u6CD5\u5728\u6C99\u7BB1\u6A21\u5F0F\u4E0B\u4F7F\u7528\u3002",
      "Your preferred editor is:": "\u60A8\u7684\u9996\u9009\u7F16\u8F91\u5668\u662F\uFF1A",
      "Manage extensions": "\u7BA1\u7406\u6269\u5C55",
      "List active extensions": "\u5217\u51FA\u6D3B\u52A8\u6269\u5C55",
      "Update extensions. Usage: update <extension-names>|--all": "\u66F4\u65B0\u6269\u5C55\u3002\u7528\u6CD5\uFF1Aupdate <extension-names>|--all",
      "Disable an extension": "\u7981\u7528\u6269\u5C55",
      "Enable an extension": "\u542F\u7528\u6269\u5C55",
      "Install an extension from a git repo or local path": "\u4ECE Git \u4ED3\u5E93\u6216\u672C\u5730\u8DEF\u5F84\u5B89\u88C5\u6269\u5C55",
      "Uninstall an extension": "\u5378\u8F7D\u6269\u5C55",
      "No extensions installed.": "\u672A\u5B89\u88C5\u6269\u5C55\u3002",
      "Usage: /extensions update <extension-names>|--all": "\u7528\u6CD5\uFF1A/extensions update <\u6269\u5C55\u540D>|--all",
      'Extension "{{name}}" not found.': '\u672A\u627E\u5230\u6269\u5C55 "{{name}}"\u3002',
      "No extensions to update.": "\u6CA1\u6709\u53EF\u66F4\u65B0\u7684\u6269\u5C55\u3002",
      "Usage: /extensions install <source>": "\u7528\u6CD5\uFF1A/extensions install <\u6765\u6E90>",
      'Installing extension from "{{source}}"...': '\u6B63\u5728\u4ECE "{{source}}" \u5B89\u88C5\u6269\u5C55...',
      'Extension "{{name}}" installed successfully.': '\u6269\u5C55 "{{name}}" \u5B89\u88C5\u6210\u529F\u3002',
      'Failed to install extension from "{{source}}": {{error}}': '\u4ECE "{{source}}" \u5B89\u88C5\u6269\u5C55\u5931\u8D25\uFF1A{{error}}',
      "Usage: /extensions uninstall <extension-name>": "\u7528\u6CD5\uFF1A/extensions uninstall <\u6269\u5C55\u540D>",
      'Uninstalling extension "{{name}}"...': '\u6B63\u5728\u5378\u8F7D\u6269\u5C55 "{{name}}"...',
      'Extension "{{name}}" uninstalled successfully.': '\u6269\u5C55 "{{name}}" \u5378\u8F7D\u6210\u529F\u3002',
      'Failed to uninstall extension "{{name}}": {{error}}': '\u5378\u8F7D\u6269\u5C55 "{{name}}" \u5931\u8D25\uFF1A{{error}}',
      "Usage: /extensions {{command}} <extension> [--scope=<user|workspace>]": "\u7528\u6CD5\uFF1A/extensions {{command}} <\u6269\u5C55> [--scope=<user|workspace>]",
      'Unsupported scope "{{scope}}", should be one of "user" or "workspace"': '\u4E0D\u652F\u6301\u7684\u4F5C\u7528\u57DF "{{scope}}"\uFF0C\u5E94\u4E3A "user" \u6216 "workspace"',
      'Extension "{{name}}" disabled for scope "{{scope}}"': '\u6269\u5C55 "{{name}}" \u5DF2\u5728\u4F5C\u7528\u57DF "{{scope}}" \u4E2D\u7981\u7528',
      'Extension "{{name}}" enabled for scope "{{scope}}"': '\u6269\u5C55 "{{name}}" \u5DF2\u5728\u4F5C\u7528\u57DF "{{scope}}" \u4E2D\u542F\u7528',
      "Do you want to continue? [Y/n]: ": "\u662F\u5426\u7EE7\u7EED\uFF1F[Y/n]\uFF1A",
      "Do you want to continue?": "\u662F\u5426\u7EE7\u7EED\uFF1F",
      'Installing extension "{{name}}".': '\u6B63\u5728\u5B89\u88C5\u6269\u5C55 "{{name}}"\u3002',
      "**Extensions may introduce unexpected behavior. Ensure you have investigated the extension source and trust the author.**": "**\u6269\u5C55\u53EF\u80FD\u4F1A\u5F15\u5165\u610F\u5916\u884C\u4E3A\u3002\u8BF7\u786E\u4FDD\u60A8\u5DF2\u8C03\u67E5\u8FC7\u6269\u5C55\u6E90\u5E76\u4FE1\u4EFB\u4F5C\u8005\u3002**",
      "This extension will run the following MCP servers:": "\u6B64\u6269\u5C55\u5C06\u8FD0\u884C\u4EE5\u4E0B MCP \u670D\u52A1\u5668\uFF1A",
      local: "\u672C\u5730",
      remote: "\u8FDC\u7A0B",
      "This extension will add the following commands: {{commands}}.": "\u6B64\u6269\u5C55\u5C06\u6DFB\u52A0\u4EE5\u4E0B\u547D\u4EE4\uFF1A{{commands}}\u3002",
      "This extension will append info to your QWEN.md context using {{fileName}}": "\u6B64\u6269\u5C55\u5C06\u4F7F\u7528 {{fileName}} \u5411\u60A8\u7684 QWEN.md \u4E0A\u4E0B\u6587\u8FFD\u52A0\u4FE1\u606F",
      "This extension will exclude the following core tools: {{tools}}": "\u6B64\u6269\u5C55\u5C06\u6392\u9664\u4EE5\u4E0B\u6838\u5FC3\u5DE5\u5177\uFF1A{{tools}}",
      "This extension will install the following skills:": "\u6B64\u6269\u5C55\u5C06\u5B89\u88C5\u4EE5\u4E0B\u6280\u80FD\uFF1A",
      "This extension will install the following subagents:": "\u6B64\u6269\u5C55\u5C06\u5B89\u88C5\u4EE5\u4E0B\u5B50\u667A\u80FD\u4F53\uFF1A",
      'Installation cancelled for "{{name}}".': '\u5DF2\u53D6\u6D88\u5B89\u88C5 "{{name}}"\u3002',
      "You are installing an extension from {{originSource}}. Some features may not work perfectly with Qwen Code.": "\u60A8\u6B63\u5728\u5B89\u88C5\u6765\u81EA {{originSource}} \u7684\u6269\u5C55\u3002\u67D0\u4E9B\u529F\u80FD\u53EF\u80FD\u65E0\u6CD5\u5B8C\u7F8E\u517C\u5BB9 Qwen Code\u3002",
      "--ref and --auto-update are not applicable for marketplace extensions.": "--ref \u548C --auto-update \u4E0D\u9002\u7528\u4E8E\u5E02\u573A\u6269\u5C55\u3002",
      'Extension "{{name}}" installed successfully and enabled.': '\u6269\u5C55 "{{name}}" \u5B89\u88C5\u6210\u529F\u5E76\u5DF2\u542F\u7528\u3002',
      "Installs an extension from a git repository URL, local path, or claude marketplace (marketplace-url:plugin-name).": "\u4ECE Git \u4ED3\u5E93 URL\u3001\u672C\u5730\u8DEF\u5F84\u6216 Claude \u5E02\u573A\uFF08marketplace-url:plugin-name\uFF09\u5B89\u88C5\u6269\u5C55\u3002",
      "The github URL, local path, or marketplace source (marketplace-url:plugin-name) of the extension to install.": "\u8981\u5B89\u88C5\u7684\u6269\u5C55\u7684 GitHub URL\u3001\u672C\u5730\u8DEF\u5F84\u6216\u5E02\u573A\u6E90\uFF08marketplace-url:plugin-name\uFF09\u3002",
      "The git ref to install from.": "\u8981\u5B89\u88C5\u7684 Git \u5F15\u7528\u3002",
      "Enable auto-update for this extension.": "\u4E3A\u6B64\u6269\u5C55\u542F\u7528\u81EA\u52A8\u66F4\u65B0\u3002",
      "Enable pre-release versions for this extension.": "\u4E3A\u6B64\u6269\u5C55\u542F\u7528\u9884\u53D1\u5E03\u7248\u672C\u3002",
      "Acknowledge the security risks of installing an extension and skip the confirmation prompt.": "\u786E\u8BA4\u5B89\u88C5\u6269\u5C55\u7684\u5B89\u5168\u98CE\u9669\u5E76\u8DF3\u8FC7\u786E\u8BA4\u63D0\u793A\u3002",
      "The source argument must be provided.": "\u5FC5\u987B\u63D0\u4F9B\u6765\u6E90\u53C2\u6570\u3002",
      'Extension "{{name}}" successfully uninstalled.': '\u6269\u5C55 "{{name}}" \u5378\u8F7D\u6210\u529F\u3002',
      "Uninstalls an extension.": "\u5378\u8F7D\u6269\u5C55\u3002",
      "The name or source path of the extension to uninstall.": "\u8981\u5378\u8F7D\u7684\u6269\u5C55\u7684\u540D\u79F0\u6216\u6E90\u8DEF\u5F84\u3002",
      "Please include the name of the extension to uninstall as a positional argument.": "\u8BF7\u5C06\u8981\u5378\u8F7D\u7684\u6269\u5C55\u540D\u79F0\u4F5C\u4E3A\u4F4D\u7F6E\u53C2\u6570\u3002",
      "Enables an extension.": "\u542F\u7528\u6269\u5C55\u3002",
      "The name of the extension to enable.": "\u8981\u542F\u7528\u7684\u6269\u5C55\u540D\u79F0\u3002",
      "The scope to enable the extenison in. If not set, will be enabled in all scopes.": "\u542F\u7528\u6269\u5C55\u7684\u4F5C\u7528\u57DF\u3002\u5982\u679C\u672A\u8BBE\u7F6E\uFF0C\u5C06\u5728\u6240\u6709\u4F5C\u7528\u57DF\u4E2D\u542F\u7528\u3002",
      'Extension "{{name}}" successfully enabled for scope "{{scope}}".': '\u6269\u5C55 "{{name}}" \u5DF2\u5728\u4F5C\u7528\u57DF "{{scope}}" \u4E2D\u542F\u7528\u3002',
      'Extension "{{name}}" successfully enabled in all scopes.': '\u6269\u5C55 "{{name}}" \u5DF2\u5728\u6240\u6709\u4F5C\u7528\u57DF\u4E2D\u542F\u7528\u3002',
      "Invalid scope: {{scope}}. Please use one of {{scopes}}.": "\u65E0\u6548\u7684\u4F5C\u7528\u57DF\uFF1A{{scope}}\u3002\u8BF7\u4F7F\u7528 {{scopes}} \u4E4B\u4E00\u3002",
      "Disables an extension.": "\u7981\u7528\u6269\u5C55\u3002",
      "The name of the extension to disable.": "\u8981\u7981\u7528\u7684\u6269\u5C55\u540D\u79F0\u3002",
      "The scope to disable the extenison in.": "\u7981\u7528\u6269\u5C55\u7684\u4F5C\u7528\u57DF\u3002",
      'Extension "{{name}}" successfully disabled for scope "{{scope}}".': '\u6269\u5C55 "{{name}}" \u5DF2\u5728\u4F5C\u7528\u57DF "{{scope}}" \u4E2D\u7981\u7528\u3002',
      'Extension "{{name}}" successfully updated: {{oldVersion}} \u2192 {{newVersion}}.': '\u6269\u5C55 "{{name}}" \u66F4\u65B0\u6210\u529F\uFF1A{{oldVersion}} \u2192 {{newVersion}}\u3002',
      'Unable to install extension "{{name}}" due to missing install metadata': '\u7531\u4E8E\u7F3A\u5C11\u5B89\u88C5\u5143\u6570\u636E\uFF0C\u65E0\u6CD5\u5B89\u88C5\u6269\u5C55 "{{name}}"',
      'Extension "{{name}}" is already up to date.': '\u6269\u5C55 "{{name}}" \u5DF2\u662F\u6700\u65B0\u7248\u672C\u3002',
      "Updates all extensions or a named extension to the latest version.": "\u5C06\u6240\u6709\u6269\u5C55\u6216\u6307\u5B9A\u6269\u5C55\u66F4\u65B0\u5230\u6700\u65B0\u7248\u672C\u3002",
      "The name of the extension to update.": "\u8981\u66F4\u65B0\u7684\u6269\u5C55\u540D\u79F0\u3002",
      "Update all extensions.": "\u66F4\u65B0\u6240\u6709\u6269\u5C55\u3002",
      "Either an extension name or --all must be provided": "\u5FC5\u987B\u63D0\u4F9B\u6269\u5C55\u540D\u79F0\u6216 --all",
      "Lists installed extensions.": "\u5217\u51FA\u5DF2\u5B89\u88C5\u7684\u6269\u5C55\u3002",
      "Path:": "\u8DEF\u5F84\uFF1A",
      "Source:": "\u6765\u6E90\uFF1A",
      "Type:": "\u7C7B\u578B\uFF1A",
      "Ref:": "\u5F15\u7528\uFF1A",
      "Release tag:": "\u53D1\u5E03\u6807\u7B7E\uFF1A",
      "Enabled (User):": "\u5DF2\u542F\u7528\uFF08\u7528\u6237\uFF09\uFF1A",
      "Enabled (Workspace):": "\u5DF2\u542F\u7528\uFF08\u5DE5\u4F5C\u533A\uFF09\uFF1A",
      "Context files:": "\u4E0A\u4E0B\u6587\u6587\u4EF6\uFF1A",
      "Skills:": "\u6280\u80FD\uFF1A",
      "Agents:": "\u667A\u80FD\u4F53\uFF1A",
      "MCP servers:": "MCP \u670D\u52A1\u5668\uFF1A",
      "Link extension failed to install.": "\u94FE\u63A5\u6269\u5C55\u5B89\u88C5\u5931\u8D25\u3002",
      'Extension "{{name}}" linked successfully and enabled.': '\u6269\u5C55 "{{name}}" \u94FE\u63A5\u6210\u529F\u5E76\u5DF2\u542F\u7528\u3002',
      "Links an extension from a local path. Updates made to the local path will always be reflected.": "\u4ECE\u672C\u5730\u8DEF\u5F84\u94FE\u63A5\u6269\u5C55\u3002\u5BF9\u672C\u5730\u8DEF\u5F84\u7684\u66F4\u65B0\u5C06\u59CB\u7EC8\u53CD\u6620\u3002",
      "The name of the extension to link.": "\u8981\u94FE\u63A5\u7684\u6269\u5C55\u540D\u79F0\u3002",
      "Set a specific setting for an extension.": "\u4E3A\u6269\u5C55\u8BBE\u7F6E\u7279\u5B9A\u914D\u7F6E\u3002",
      "Name of the extension to configure.": "\u8981\u914D\u7F6E\u7684\u6269\u5C55\u540D\u79F0\u3002",
      "The setting to configure (name or env var).": "\u8981\u914D\u7F6E\u7684\u8BBE\u7F6E\uFF08\u540D\u79F0\u6216\u73AF\u5883\u53D8\u91CF\uFF09\u3002",
      "The scope to set the setting in.": "\u8BBE\u7F6E\u914D\u7F6E\u7684\u4F5C\u7528\u57DF\u3002",
      "List all settings for an extension.": "\u5217\u51FA\u6269\u5C55\u7684\u6240\u6709\u8BBE\u7F6E\u3002",
      "Name of the extension.": "\u6269\u5C55\u540D\u79F0\u3002",
      'Extension "{{name}}" has no settings to configure.': '\u6269\u5C55 "{{name}}" \u6CA1\u6709\u53EF\u914D\u7F6E\u7684\u8BBE\u7F6E\u3002',
      'Settings for "{{name}}":': '"{{name}}" \u7684\u8BBE\u7F6E\uFF1A',
      "(workspace)": "\uFF08\u5DE5\u4F5C\u533A\uFF09",
      "(user)": "\uFF08\u7528\u6237\uFF09",
      "[not set]": "\uFF3B\u672A\u8BBE\u7F6E\uFF3D",
      "[value stored in keychain]": "\uFF3B\u503C\u5B58\u50A8\u5728\u94A5\u5319\u4E32\u4E2D\uFF3D",
      "Manage extension settings.": "\u7BA1\u7406\u6269\u5C55\u8BBE\u7F6E\u3002",
      "You need to specify a command (set or list).": "\u60A8\u9700\u8981\u6307\u5B9A\u547D\u4EE4\uFF08set \u6216 list\uFF09\u3002",
      // ============================================================================
      // Plugin Choice / Marketplace
      // ============================================================================
      "No plugins available in this marketplace.": "\u6B64\u5E02\u573A\u4E2D\u6CA1\u6709\u53EF\u7528\u7684\u63D2\u4EF6\u3002",
      'Select a plugin to install from marketplace "{{name}}":': '\u4ECE\u5E02\u573A "{{name}}" \u4E2D\u9009\u62E9\u8981\u5B89\u88C5\u7684\u63D2\u4EF6\uFF1A',
      "Plugin selection cancelled.": "\u63D2\u4EF6\u9009\u62E9\u5DF2\u53D6\u6D88\u3002",
      'Select a plugin from "{{name}}"': '\u4ECE "{{name}}" \u4E2D\u9009\u62E9\u63D2\u4EF6',
      "Use \u2191\u2193 or j/k to navigate, Enter to select, Escape to cancel": "\u4F7F\u7528 \u2191\u2193 \u6216 j/k \u5BFC\u822A\uFF0C\u56DE\u8F66\u9009\u62E9\uFF0CEsc \u53D6\u6D88",
      "{{count}} more above": "\u4E0A\u65B9\u8FD8\u6709 {{count}} \u9879",
      "{{count}} more below": "\u4E0B\u65B9\u8FD8\u6709 {{count}} \u9879",
      "manage IDE integration": "\u7BA1\u7406 IDE \u96C6\u6210",
      "check status of IDE integration": "\u68C0\u67E5 IDE \u96C6\u6210\u72B6\u6001",
      "install required IDE companion for {{ideName}}": "\u5B89\u88C5 {{ideName}} \u6240\u9700\u7684 IDE \u914D\u5957\u5DE5\u5177",
      "enable IDE integration": "\u542F\u7528 IDE \u96C6\u6210",
      "disable IDE integration": "\u7981\u7528 IDE \u96C6\u6210",
      "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.": "\u60A8\u5F53\u524D\u73AF\u5883\u4E0D\u652F\u6301 IDE \u96C6\u6210\u3002\u8981\u4F7F\u7528\u6B64\u529F\u80FD\uFF0C\u8BF7\u5728\u4EE5\u4E0B\u652F\u6301\u7684 IDE \u4E4B\u4E00\u4E2D\u8FD0\u884C Qwen Code\uFF1AVS Code \u6216 VS Code \u5206\u652F\u7248\u672C\u3002",
      "Set up GitHub Actions": "\u8BBE\u7F6E GitHub Actions",
      "Configure terminal keybindings for multiline input (VS Code, Cursor, Windsurf, Trae)": "\u914D\u7F6E\u7EC8\u7AEF\u6309\u952E\u7ED1\u5B9A\u4EE5\u652F\u6301\u591A\u884C\u8F93\u5165\uFF08VS Code\u3001Cursor\u3001Windsurf\u3001Trae\uFF09",
      "Please restart your terminal for the changes to take effect.": "\u8BF7\u91CD\u542F\u7EC8\u7AEF\u4EE5\u4F7F\u66F4\u6539\u751F\u6548\u3002",
      "Failed to configure terminal: {{error}}": "\u914D\u7F6E\u7EC8\u7AEF\u5931\u8D25\uFF1A{{error}}",
      "Could not determine {{terminalName}} config path on Windows: APPDATA environment variable is not set.": "\u65E0\u6CD5\u786E\u5B9A {{terminalName}} \u5728 Windows \u4E0A\u7684\u914D\u7F6E\u8DEF\u5F84\uFF1A\u672A\u8BBE\u7F6E APPDATA \u73AF\u5883\u53D8\u91CF\u3002",
      "{{terminalName}} keybindings.json exists but is not a valid JSON array. Please fix the file manually or delete it to allow automatic configuration.": "{{terminalName}} keybindings.json \u5B58\u5728\u4F46\u4E0D\u662F\u6709\u6548\u7684 JSON \u6570\u7EC4\u3002\u8BF7\u624B\u52A8\u4FEE\u590D\u6587\u4EF6\u6216\u5220\u9664\u5B83\u4EE5\u5141\u8BB8\u81EA\u52A8\u914D\u7F6E\u3002",
      "File: {{file}}": "\u6587\u4EF6\uFF1A{{file}}",
      "Failed to parse {{terminalName}} keybindings.json. The file contains invalid JSON. Please fix the file manually or delete it to allow automatic configuration.": "\u89E3\u6790 {{terminalName}} keybindings.json \u5931\u8D25\u3002\u6587\u4EF6\u5305\u542B\u65E0\u6548\u7684 JSON\u3002\u8BF7\u624B\u52A8\u4FEE\u590D\u6587\u4EF6\u6216\u5220\u9664\u5B83\u4EE5\u5141\u8BB8\u81EA\u52A8\u914D\u7F6E\u3002",
      "Error: {{error}}": "\u9519\u8BEF\uFF1A{{error}}",
      "Shift+Enter binding already exists": "Shift+Enter \u7ED1\u5B9A\u5DF2\u5B58\u5728",
      "Ctrl+Enter binding already exists": "Ctrl+Enter \u7ED1\u5B9A\u5DF2\u5B58\u5728",
      "Existing keybindings detected. Will not modify to avoid conflicts.": "\u68C0\u6D4B\u5230\u73B0\u6709\u6309\u952E\u7ED1\u5B9A\u3002\u4E3A\u907F\u514D\u51B2\u7A81\uFF0C\u4E0D\u4F1A\u4FEE\u6539\u3002",
      "Please check and modify manually if needed: {{file}}": "\u5982\u6709\u9700\u8981\uFF0C\u8BF7\u624B\u52A8\u68C0\u67E5\u5E76\u4FEE\u6539\uFF1A{{file}}",
      "Added Shift+Enter and Ctrl+Enter keybindings to {{terminalName}}.": "\u5DF2\u4E3A {{terminalName}} \u6DFB\u52A0 Shift+Enter \u548C Ctrl+Enter \u6309\u952E\u7ED1\u5B9A\u3002",
      "Modified: {{file}}": "\u5DF2\u4FEE\u6539\uFF1A{{file}}",
      "{{terminalName}} keybindings already configured.": "{{terminalName}} \u6309\u952E\u7ED1\u5B9A\u5DF2\u914D\u7F6E\u3002",
      "Failed to configure {{terminalName}}.": "\u914D\u7F6E {{terminalName}} \u5931\u8D25\u3002",
      "Your terminal is already configured for an optimal experience with multiline input (Shift+Enter and Ctrl+Enter).": "\u60A8\u7684\u7EC8\u7AEF\u5DF2\u914D\u7F6E\u4E3A\u652F\u6301\u591A\u884C\u8F93\u5165\uFF08Shift+Enter \u548C Ctrl+Enter\uFF09\u7684\u6700\u4F73\u4F53\u9A8C\u3002",
      "Could not detect terminal type. Supported terminals: VS Code, Cursor, Windsurf, and Trae.": "\u65E0\u6CD5\u68C0\u6D4B\u7EC8\u7AEF\u7C7B\u578B\u3002\u652F\u6301\u7684\u7EC8\u7AEF\uFF1AVS Code\u3001Cursor\u3001Windsurf \u548C Trae\u3002",
      'Terminal "{{terminal}}" is not supported yet.': '\u7EC8\u7AEF "{{terminal}}" \u5C1A\u672A\u652F\u6301\u3002',
      // ============================================================================
      // Commands - Language
      // ============================================================================
      "Invalid language. Available: {{options}}": "\u65E0\u6548\u7684\u8BED\u8A00\u3002\u53EF\u7528\u9009\u9879\uFF1A{{options}}",
      "Language subcommands do not accept additional arguments.": "\u8BED\u8A00\u5B50\u547D\u4EE4\u4E0D\u63A5\u53D7\u989D\u5916\u53C2\u6570",
      "Current UI language: {{lang}}": "\u5F53\u524D UI \u8BED\u8A00\uFF1A{{lang}}",
      "Current LLM output language: {{lang}}": "\u5F53\u524D LLM \u8F93\u51FA\u8BED\u8A00\uFF1A{{lang}}",
      "LLM output language not set": "\u672A\u8BBE\u7F6E LLM \u8F93\u51FA\u8BED\u8A00",
      "Set UI language": "\u8BBE\u7F6E UI \u8BED\u8A00",
      "Set LLM output language": "\u8BBE\u7F6E LLM \u8F93\u51FA\u8BED\u8A00",
      "Usage: /language ui [{{options}}]": "\u7528\u6CD5\uFF1A/language ui [{{options}}]",
      "Usage: /language output <language>": "\u7528\u6CD5\uFF1A/language output <\u8BED\u8A00>",
      "Example: /language output \u4E2D\u6587": "\u793A\u4F8B\uFF1A/language output \u4E2D\u6587",
      "Example: /language output English": "\u793A\u4F8B\uFF1A/language output English",
      "Example: /language output \u65E5\u672C\u8A9E": "\u793A\u4F8B\uFF1A/language output \u65E5\u672C\u8A9E",
      "Example: /language output Portugu\xEAs": "\u793A\u4F8B\uFF1A/language output Portugu\xEAs",
      "UI language changed to {{lang}}": "UI \u8BED\u8A00\u5DF2\u66F4\u6539\u4E3A {{lang}}",
      "LLM output language set to {{lang}}": "LLM \u8F93\u51FA\u8BED\u8A00\u5DF2\u8BBE\u7F6E\u4E3A {{lang}}",
      "LLM output language rule file generated at {{path}}": "LLM \u8F93\u51FA\u8BED\u8A00\u89C4\u5219\u6587\u4EF6\u5DF2\u751F\u6210\u4E8E {{path}}",
      "Please restart the application for the changes to take effect.": "\u8BF7\u91CD\u542F\u5E94\u7528\u7A0B\u5E8F\u4EE5\u4F7F\u66F4\u6539\u751F\u6548\u3002",
      "Failed to generate LLM output language rule file: {{error}}": "\u751F\u6210 LLM \u8F93\u51FA\u8BED\u8A00\u89C4\u5219\u6587\u4EF6\u5931\u8D25\uFF1A{{error}}",
      "Invalid command. Available subcommands:": "\u65E0\u6548\u7684\u547D\u4EE4\u3002\u53EF\u7528\u7684\u5B50\u547D\u4EE4\uFF1A",
      "Available subcommands:": "\u53EF\u7528\u7684\u5B50\u547D\u4EE4\uFF1A",
      "To request additional UI language packs, please open an issue on GitHub.": "\u5982\u9700\u8BF7\u6C42\u5176\u4ED6 UI \u8BED\u8A00\u5305\uFF0C\u8BF7\u5728 GitHub \u4E0A\u63D0\u4EA4 issue",
      "Available options:": "\u53EF\u7528\u9009\u9879\uFF1A",
      "Set UI language to {{name}}": "\u5C06 UI \u8BED\u8A00\u8BBE\u7F6E\u4E3A {{name}}",
      // ============================================================================
      // Commands - Approval Mode
      // ============================================================================
      "Tool Approval Mode": "\u5DE5\u5177\u5BA1\u6279\u6A21\u5F0F",
      "Current approval mode: {{mode}}": "\u5F53\u524D\u5BA1\u6279\u6A21\u5F0F\uFF1A{{mode}}",
      "Available approval modes:": "\u53EF\u7528\u7684\u5BA1\u6279\u6A21\u5F0F\uFF1A",
      "Approval mode changed to: {{mode}}": "\u5BA1\u6279\u6A21\u5F0F\u5DF2\u66F4\u6539\u4E3A\uFF1A{{mode}}",
      "Approval mode changed to: {{mode}} (saved to {{scope}} settings{{location}})": "\u5BA1\u6279\u6A21\u5F0F\u5DF2\u66F4\u6539\u4E3A\uFF1A{{mode}}\uFF08\u5DF2\u4FDD\u5B58\u5230{{scope}}\u8BBE\u7F6E{{location}}\uFF09",
      "Usage: /approval-mode <mode> [--session|--user|--project]": "\u7528\u6CD5\uFF1A/approval-mode <mode> [--session|--user|--project]",
      "Scope subcommands do not accept additional arguments.": "\u4F5C\u7528\u57DF\u5B50\u547D\u4EE4\u4E0D\u63A5\u53D7\u989D\u5916\u53C2\u6570",
      "Plan mode - Analyze only, do not modify files or execute commands": "\u89C4\u5212\u6A21\u5F0F - \u4EC5\u5206\u6790\uFF0C\u4E0D\u4FEE\u6539\u6587\u4EF6\u6216\u6267\u884C\u547D\u4EE4",
      "Default mode - Require approval for file edits or shell commands": "\u9ED8\u8BA4\u6A21\u5F0F - \u9700\u8981\u6279\u51C6\u6587\u4EF6\u7F16\u8F91\u6216 shell \u547D\u4EE4",
      "Auto-edit mode - Automatically approve file edits": "\u81EA\u52A8\u7F16\u8F91\u6A21\u5F0F - \u81EA\u52A8\u6279\u51C6\u6587\u4EF6\u7F16\u8F91",
      "YOLO mode - Automatically approve all tools": "YOLO \u6A21\u5F0F - \u81EA\u52A8\u6279\u51C6\u6240\u6709\u5DE5\u5177",
      "{{mode}} mode": "{{mode}} \u6A21\u5F0F",
      "Settings service is not available; unable to persist the approval mode.": "\u8BBE\u7F6E\u670D\u52A1\u4E0D\u53EF\u7528\uFF1B\u65E0\u6CD5\u6301\u4E45\u5316\u5BA1\u6279\u6A21\u5F0F\u3002",
      "Failed to save approval mode: {{error}}": "\u4FDD\u5B58\u5BA1\u6279\u6A21\u5F0F\u5931\u8D25\uFF1A{{error}}",
      "Failed to change approval mode: {{error}}": "\u66F4\u6539\u5BA1\u6279\u6A21\u5F0F\u5931\u8D25\uFF1A{{error}}",
      "Apply to current session only (temporary)": "\u4EC5\u5E94\u7528\u4E8E\u5F53\u524D\u4F1A\u8BDD\uFF08\u4E34\u65F6\uFF09",
      "Persist for this project/workspace": "\u6301\u4E45\u5316\u5230\u6B64\u9879\u76EE/\u5DE5\u4F5C\u533A",
      "Persist for this user on this machine": "\u6301\u4E45\u5316\u5230\u6B64\u673A\u5668\u4E0A\u7684\u6B64\u7528\u6237",
      "Analyze only, do not modify files or execute commands": "\u4EC5\u5206\u6790\uFF0C\u4E0D\u4FEE\u6539\u6587\u4EF6\u6216\u6267\u884C\u547D\u4EE4",
      "Require approval for file edits or shell commands": "\u9700\u8981\u6279\u51C6\u6587\u4EF6\u7F16\u8F91\u6216 shell \u547D\u4EE4",
      "Automatically approve file edits": "\u81EA\u52A8\u6279\u51C6\u6587\u4EF6\u7F16\u8F91",
      "Automatically approve all tools": "\u81EA\u52A8\u6279\u51C6\u6240\u6709\u5DE5\u5177",
      "Workspace approval mode exists and takes priority. User-level change will have no effect.": "\u5DE5\u4F5C\u533A\u5BA1\u6279\u6A21\u5F0F\u5DF2\u5B58\u5728\u5E76\u5177\u6709\u4F18\u5148\u7EA7\u3002\u7528\u6237\u7EA7\u522B\u7684\u66F4\u6539\u5C06\u65E0\u6548\u3002",
      "Apply To": "\u5E94\u7528\u4E8E",
      "User Settings": "\u7528\u6237\u8BBE\u7F6E",
      "Workspace Settings": "\u5DE5\u4F5C\u533A\u8BBE\u7F6E",
      // ============================================================================
      // Commands - Memory
      // ============================================================================
      "Commands for interacting with memory.": "\u7528\u4E8E\u4E0E\u8BB0\u5FC6\u4EA4\u4E92\u7684\u547D\u4EE4",
      "Show the current memory contents.": "\u663E\u793A\u5F53\u524D\u8BB0\u5FC6\u5185\u5BB9",
      "Show project-level memory contents.": "\u663E\u793A\u9879\u76EE\u7EA7\u8BB0\u5FC6\u5185\u5BB9",
      "Show global memory contents.": "\u663E\u793A\u5168\u5C40\u8BB0\u5FC6\u5185\u5BB9",
      "Add content to project-level memory.": "\u6DFB\u52A0\u5185\u5BB9\u5230\u9879\u76EE\u7EA7\u8BB0\u5FC6",
      "Add content to global memory.": "\u6DFB\u52A0\u5185\u5BB9\u5230\u5168\u5C40\u8BB0\u5FC6",
      "Refresh the memory from the source.": "\u4ECE\u6E90\u5237\u65B0\u8BB0\u5FC6",
      "Usage: /memory add --project <text to remember>": "\u7528\u6CD5\uFF1A/memory add --project <\u8981\u8BB0\u4F4F\u7684\u6587\u672C>",
      "Usage: /memory add --global <text to remember>": "\u7528\u6CD5\uFF1A/memory add --global <\u8981\u8BB0\u4F4F\u7684\u6587\u672C>",
      'Attempting to save to project memory: "{{text}}"': '\u6B63\u5728\u5C1D\u8BD5\u4FDD\u5B58\u5230\u9879\u76EE\u8BB0\u5FC6\uFF1A"{{text}}"',
      'Attempting to save to global memory: "{{text}}"': '\u6B63\u5728\u5C1D\u8BD5\u4FDD\u5B58\u5230\u5168\u5C40\u8BB0\u5FC6\uFF1A"{{text}}"',
      "Current memory content from {{count}} file(s):": "\u6765\u81EA {{count}} \u4E2A\u6587\u4EF6\u7684\u5F53\u524D\u8BB0\u5FC6\u5185\u5BB9\uFF1A",
      "Memory is currently empty.": "\u8BB0\u5FC6\u5F53\u524D\u4E3A\u7A7A",
      "Project memory file not found or is currently empty.": "\u9879\u76EE\u8BB0\u5FC6\u6587\u4EF6\u672A\u627E\u5230\u6216\u5F53\u524D\u4E3A\u7A7A",
      "Global memory file not found or is currently empty.": "\u5168\u5C40\u8BB0\u5FC6\u6587\u4EF6\u672A\u627E\u5230\u6216\u5F53\u524D\u4E3A\u7A7A",
      "Global memory is currently empty.": "\u5168\u5C40\u8BB0\u5FC6\u5F53\u524D\u4E3A\u7A7A",
      "Global memory content:\n\n---\n{{content}}\n---": "\u5168\u5C40\u8BB0\u5FC6\u5185\u5BB9\uFF1A\n\n---\n{{content}}\n---",
      "Project memory content from {{path}}:\n\n---\n{{content}}\n---": "\u9879\u76EE\u8BB0\u5FC6\u5185\u5BB9\u6765\u81EA {{path}}\uFF1A\n\n---\n{{content}}\n---",
      "Project memory is currently empty.": "\u9879\u76EE\u8BB0\u5FC6\u5F53\u524D\u4E3A\u7A7A",
      "Refreshing memory from source files...": "\u6B63\u5728\u4ECE\u6E90\u6587\u4EF6\u5237\u65B0\u8BB0\u5FC6...",
      "Add content to the memory. Use --global for global memory or --project for project memory.": "\u6DFB\u52A0\u5185\u5BB9\u5230\u8BB0\u5FC6\u3002\u4F7F\u7528 --global \u8868\u793A\u5168\u5C40\u8BB0\u5FC6\uFF0C\u4F7F\u7528 --project \u8868\u793A\u9879\u76EE\u8BB0\u5FC6",
      "Usage: /memory add [--global|--project] <text to remember>": "\u7528\u6CD5\uFF1A/memory add [--global|--project] <\u8981\u8BB0\u4F4F\u7684\u6587\u672C>",
      'Attempting to save to memory {{scope}}: "{{fact}}"': '\u6B63\u5728\u5C1D\u8BD5\u4FDD\u5B58\u5230\u8BB0\u5FC6 {{scope}}\uFF1A"{{fact}}"',
      // ============================================================================
      // Commands - MCP
      // ============================================================================
      "Authenticate with an OAuth-enabled MCP server": "\u4F7F\u7528\u652F\u6301 OAuth \u7684 MCP \u670D\u52A1\u5668\u8FDB\u884C\u8BA4\u8BC1",
      "List configured MCP servers and tools": "\u5217\u51FA\u5DF2\u914D\u7F6E\u7684 MCP \u670D\u52A1\u5668\u548C\u5DE5\u5177",
      "Restarts MCP servers.": "\u91CD\u542F MCP \u670D\u52A1\u5668",
      "Config not loaded.": "\u914D\u7F6E\u672A\u52A0\u8F7D",
      "Could not retrieve tool registry.": "\u65E0\u6CD5\u68C0\u7D22\u5DE5\u5177\u6CE8\u518C\u8868",
      "No MCP servers configured with OAuth authentication.": "\u672A\u914D\u7F6E\u652F\u6301 OAuth \u8BA4\u8BC1\u7684 MCP \u670D\u52A1\u5668",
      "MCP servers with OAuth authentication:": "\u652F\u6301 OAuth \u8BA4\u8BC1\u7684 MCP \u670D\u52A1\u5668\uFF1A",
      "Use /mcp auth <server-name> to authenticate.": "\u4F7F\u7528 /mcp auth <server-name> \u8FDB\u884C\u8BA4\u8BC1",
      "MCP server '{{name}}' not found.": "\u672A\u627E\u5230 MCP \u670D\u52A1\u5668 '{{name}}'",
      "Successfully authenticated and refreshed tools for '{{name}}'.": "\u6210\u529F\u8BA4\u8BC1\u5E76\u5237\u65B0\u4E86 '{{name}}' \u7684\u5DE5\u5177",
      "Failed to authenticate with MCP server '{{name}}': {{error}}": "\u8BA4\u8BC1 MCP \u670D\u52A1\u5668 '{{name}}' \u5931\u8D25\uFF1A{{error}}",
      "Re-discovering tools from '{{name}}'...": "\u6B63\u5728\u91CD\u65B0\u53D1\u73B0 '{{name}}' \u7684\u5DE5\u5177...",
      // ============================================================================
      // Commands - Chat
      // ============================================================================
      "Manage conversation history.": "\u7BA1\u7406\u5BF9\u8BDD\u5386\u53F2",
      "List saved conversation checkpoints": "\u5217\u51FA\u5DF2\u4FDD\u5B58\u7684\u5BF9\u8BDD\u68C0\u67E5\u70B9",
      "No saved conversation checkpoints found.": "\u672A\u627E\u5230\u5DF2\u4FDD\u5B58\u7684\u5BF9\u8BDD\u68C0\u67E5\u70B9",
      "List of saved conversations:": "\u5DF2\u4FDD\u5B58\u7684\u5BF9\u8BDD\u5217\u8868\uFF1A",
      "Note: Newest last, oldest first": "\u6CE8\u610F\uFF1A\u6700\u65B0\u7684\u5728\u6700\u540E\uFF0C\u6700\u65E7\u7684\u5728\u6700\u524D",
      "Save the current conversation as a checkpoint. Usage: /chat save <tag>": "\u5C06\u5F53\u524D\u5BF9\u8BDD\u4FDD\u5B58\u4E3A\u68C0\u67E5\u70B9\u3002\u7528\u6CD5\uFF1A/chat save <tag>",
      "Missing tag. Usage: /chat save <tag>": "\u7F3A\u5C11\u6807\u7B7E\u3002\u7528\u6CD5\uFF1A/chat save <tag>",
      "Delete a conversation checkpoint. Usage: /chat delete <tag>": "\u5220\u9664\u5BF9\u8BDD\u68C0\u67E5\u70B9\u3002\u7528\u6CD5\uFF1A/chat delete <tag>",
      "Missing tag. Usage: /chat delete <tag>": "\u7F3A\u5C11\u6807\u7B7E\u3002\u7528\u6CD5\uFF1A/chat delete <tag>",
      "Conversation checkpoint '{{tag}}' has been deleted.": "\u5BF9\u8BDD\u68C0\u67E5\u70B9 '{{tag}}' \u5DF2\u5220\u9664",
      "Error: No checkpoint found with tag '{{tag}}'.": "\u9519\u8BEF\uFF1A\u672A\u627E\u5230\u6807\u7B7E\u4E3A '{{tag}}' \u7684\u68C0\u67E5\u70B9",
      "Resume a conversation from a checkpoint. Usage: /chat resume <tag>": "\u4ECE\u68C0\u67E5\u70B9\u6062\u590D\u5BF9\u8BDD\u3002\u7528\u6CD5\uFF1A/chat resume <tag>",
      "Missing tag. Usage: /chat resume <tag>": "\u7F3A\u5C11\u6807\u7B7E\u3002\u7528\u6CD5\uFF1A/chat resume <tag>",
      "No saved checkpoint found with tag: {{tag}}.": "\u672A\u627E\u5230\u6807\u7B7E\u4E3A {{tag}} \u7684\u5DF2\u4FDD\u5B58\u68C0\u67E5\u70B9",
      "A checkpoint with the tag {{tag}} already exists. Do you want to overwrite it?": "\u6807\u7B7E\u4E3A {{tag}} \u7684\u68C0\u67E5\u70B9\u5DF2\u5B58\u5728\u3002\u60A8\u8981\u8986\u76D6\u5B83\u5417\uFF1F",
      "No chat client available to save conversation.": "\u6CA1\u6709\u53EF\u7528\u7684\u804A\u5929\u5BA2\u6237\u7AEF\u6765\u4FDD\u5B58\u5BF9\u8BDD",
      "Conversation checkpoint saved with tag: {{tag}}.": "\u5BF9\u8BDD\u68C0\u67E5\u70B9\u5DF2\u4FDD\u5B58\uFF0C\u6807\u7B7E\uFF1A{{tag}}",
      "No conversation found to save.": "\u672A\u627E\u5230\u8981\u4FDD\u5B58\u7684\u5BF9\u8BDD",
      "No chat client available to share conversation.": "\u6CA1\u6709\u53EF\u7528\u7684\u804A\u5929\u5BA2\u6237\u7AEF\u6765\u5206\u4EAB\u5BF9\u8BDD",
      "Invalid file format. Only .md and .json are supported.": "\u65E0\u6548\u7684\u6587\u4EF6\u683C\u5F0F\u3002\u4EC5\u652F\u6301 .md \u548C .json \u6587\u4EF6",
      "Error sharing conversation: {{error}}": "\u5206\u4EAB\u5BF9\u8BDD\u65F6\u51FA\u9519\uFF1A{{error}}",
      "Conversation shared to {{filePath}}": "\u5BF9\u8BDD\u5DF2\u5206\u4EAB\u5230 {{filePath}}",
      "No conversation found to share.": "\u672A\u627E\u5230\u8981\u5206\u4EAB\u7684\u5BF9\u8BDD",
      "Share the current conversation to a markdown or json file. Usage: /chat share <file>": "\u5C06\u5F53\u524D\u5BF9\u8BDD\u5206\u4EAB\u5230 markdown \u6216 json \u6587\u4EF6\u3002\u7528\u6CD5\uFF1A/chat share <file>",
      // ============================================================================
      // Commands - Summary
      // ============================================================================
      "Generate a project summary and save it to .qwen/PROJECT_SUMMARY.md": "\u751F\u6210\u9879\u76EE\u6458\u8981\u5E76\u4FDD\u5B58\u5230 .qwen/PROJECT_SUMMARY.md",
      "No chat client available to generate summary.": "\u6CA1\u6709\u53EF\u7528\u7684\u804A\u5929\u5BA2\u6237\u7AEF\u6765\u751F\u6210\u6458\u8981",
      "Already generating summary, wait for previous request to complete": "\u6B63\u5728\u751F\u6210\u6458\u8981\uFF0C\u8BF7\u7B49\u5F85\u4E0A\u4E00\u4E2A\u8BF7\u6C42\u5B8C\u6210",
      "No conversation found to summarize.": "\u672A\u627E\u5230\u8981\u603B\u7ED3\u7684\u5BF9\u8BDD",
      "Failed to generate project context summary: {{error}}": "\u751F\u6210\u9879\u76EE\u4E0A\u4E0B\u6587\u6458\u8981\u5931\u8D25\uFF1A{{error}}",
      "Saved project summary to {{filePathForDisplay}}.": "\u9879\u76EE\u6458\u8981\u5DF2\u4FDD\u5B58\u5230 {{filePathForDisplay}}",
      "Saving project summary...": "\u6B63\u5728\u4FDD\u5B58\u9879\u76EE\u6458\u8981...",
      "Generating project summary...": "\u6B63\u5728\u751F\u6210\u9879\u76EE\u6458\u8981...",
      "Failed to generate summary - no text content received from LLM response": "\u751F\u6210\u6458\u8981\u5931\u8D25 - \u672A\u4ECE LLM \u54CD\u5E94\u4E2D\u63A5\u6536\u5230\u6587\u672C\u5185\u5BB9",
      // ============================================================================
      // Commands - Model
      // ============================================================================
      "Switch the model for this session": "\u5207\u6362\u6B64\u4F1A\u8BDD\u7684\u6A21\u578B",
      "Content generator configuration not available.": "\u5185\u5BB9\u751F\u6210\u5668\u914D\u7F6E\u4E0D\u53EF\u7528",
      "Authentication type not available.": "\u8BA4\u8BC1\u7C7B\u578B\u4E0D\u53EF\u7528",
      "No models available for the current authentication type ({{authType}}).": "\u5F53\u524D\u8BA4\u8BC1\u7C7B\u578B ({{authType}}) \u6CA1\u6709\u53EF\u7528\u7684\u6A21\u578B",
      // ============================================================================
      // Commands - Clear
      // ============================================================================
      "Starting a new session, resetting chat, and clearing terminal.": "\u6B63\u5728\u5F00\u59CB\u65B0\u4F1A\u8BDD\uFF0C\u91CD\u7F6E\u804A\u5929\u5E76\u6E05\u5C4F\u3002",
      "Starting a new session and clearing.": "\u6B63\u5728\u5F00\u59CB\u65B0\u4F1A\u8BDD\u5E76\u6E05\u5C4F\u3002",
      // ============================================================================
      // Commands - Compress
      // ============================================================================
      "Already compressing, wait for previous request to complete": "\u6B63\u5728\u538B\u7F29\u4E2D\uFF0C\u8BF7\u7B49\u5F85\u4E0A\u4E00\u4E2A\u8BF7\u6C42\u5B8C\u6210",
      "Failed to compress chat history.": "\u538B\u7F29\u804A\u5929\u5386\u53F2\u5931\u8D25",
      "Failed to compress chat history: {{error}}": "\u538B\u7F29\u804A\u5929\u5386\u53F2\u5931\u8D25\uFF1A{{error}}",
      "Compressing chat history": "\u6B63\u5728\u538B\u7F29\u804A\u5929\u5386\u53F2",
      "Chat history compressed from {{originalTokens}} to {{newTokens}} tokens.": "\u804A\u5929\u5386\u53F2\u5DF2\u4ECE {{originalTokens}} \u4E2A token \u538B\u7F29\u5230 {{newTokens}} \u4E2A token\u3002",
      "Compression was not beneficial for this history size.": "\u5BF9\u4E8E\u6B64\u5386\u53F2\u8BB0\u5F55\u5927\u5C0F\uFF0C\u538B\u7F29\u6CA1\u6709\u76CA\u5904\u3002",
      "Chat history compression did not reduce size. This may indicate issues with the compression prompt.": "\u804A\u5929\u5386\u53F2\u538B\u7F29\u672A\u80FD\u51CF\u5C0F\u5927\u5C0F\u3002\u8FD9\u53EF\u80FD\u8868\u660E\u538B\u7F29\u63D0\u793A\u5B58\u5728\u95EE\u9898\u3002",
      "Could not compress chat history due to a token counting error.": "\u7531\u4E8E token \u8BA1\u6570\u9519\u8BEF\uFF0C\u65E0\u6CD5\u538B\u7F29\u804A\u5929\u5386\u53F2\u3002",
      "Chat history is already compressed.": "\u804A\u5929\u5386\u53F2\u5DF2\u7ECF\u538B\u7F29\u3002",
      // ============================================================================
      // Commands - Directory
      // ============================================================================
      "Configuration is not available.": "\u914D\u7F6E\u4E0D\u53EF\u7528\u3002",
      "Please provide at least one path to add.": "\u8BF7\u63D0\u4F9B\u81F3\u5C11\u4E00\u4E2A\u8981\u6DFB\u52A0\u7684\u8DEF\u5F84\u3002",
      "The /directory add command is not supported in restrictive sandbox profiles. Please use --include-directories when starting the session instead.": "/directory add \u547D\u4EE4\u5728\u9650\u5236\u6027\u6C99\u7BB1\u914D\u7F6E\u6587\u4EF6\u4E2D\u4E0D\u53D7\u652F\u6301\u3002\u8BF7\u6539\u4E3A\u5728\u542F\u52A8\u4F1A\u8BDD\u65F6\u4F7F\u7528 --include-directories\u3002",
      "Error adding '{{path}}': {{error}}": "\u6DFB\u52A0 '{{path}}' \u65F6\u51FA\u9519\uFF1A{{error}}",
      "Successfully added QWEN.md files from the following directories if there are:\n- {{directories}}": "\u5982\u679C\u5B58\u5728\uFF0C\u5DF2\u6210\u529F\u4ECE\u4EE5\u4E0B\u76EE\u5F55\u6DFB\u52A0 QWEN.md \u6587\u4EF6\uFF1A\n- {{directories}}",
      "Error refreshing memory: {{error}}": "\u5237\u65B0\u5185\u5B58\u65F6\u51FA\u9519\uFF1A{{error}}",
      "Successfully added directories:\n- {{directories}}": "\u6210\u529F\u6DFB\u52A0\u76EE\u5F55\uFF1A\n- {{directories}}",
      "Current workspace directories:\n{{directories}}": "\u5F53\u524D\u5DE5\u4F5C\u533A\u76EE\u5F55\uFF1A\n{{directories}}",
      // ============================================================================
      // Commands - Docs
      // ============================================================================
      "Please open the following URL in your browser to view the documentation:\n{{url}}": "\u8BF7\u5728\u6D4F\u89C8\u5668\u4E2D\u6253\u5F00\u4EE5\u4E0B URL \u4EE5\u67E5\u770B\u6587\u6863\uFF1A\n{{url}}",
      "Opening documentation in your browser: {{url}}": "\u6B63\u5728\u6D4F\u89C8\u5668\u4E2D\u6253\u5F00\u6587\u6863\uFF1A{{url}}",
      // ============================================================================
      // Dialogs - Tool Confirmation
      // ============================================================================
      "Do you want to proceed?": "\u662F\u5426\u7EE7\u7EED\uFF1F",
      "Yes, allow once": "\u662F\uFF0C\u5141\u8BB8\u4E00\u6B21",
      "Allow always": "\u603B\u662F\u5141\u8BB8",
      No: "\u5426",
      "No (esc)": "\u5426 (esc)",
      "Yes, allow always for this session": "\u662F\uFF0C\u672C\u6B21\u4F1A\u8BDD\u603B\u662F\u5141\u8BB8",
      "Modify in progress:": "\u6B63\u5728\u4FEE\u6539\uFF1A",
      "Save and close external editor to continue": "\u4FDD\u5B58\u5E76\u5173\u95ED\u5916\u90E8\u7F16\u8F91\u5668\u4EE5\u7EE7\u7EED",
      "Apply this change?": "\u662F\u5426\u5E94\u7528\u6B64\u66F4\u6539\uFF1F",
      "Yes, allow always": "\u662F\uFF0C\u603B\u662F\u5141\u8BB8",
      "Modify with external editor": "\u4F7F\u7528\u5916\u90E8\u7F16\u8F91\u5668\u4FEE\u6539",
      "No, suggest changes (esc)": "\u5426\uFF0C\u5EFA\u8BAE\u66F4\u6539 (esc)",
      "Allow execution of: '{{command}}'?": "\u5141\u8BB8\u6267\u884C\uFF1A'{{command}}'\uFF1F",
      "Yes, allow always ...": "\u662F\uFF0C\u603B\u662F\u5141\u8BB8 ...",
      "Yes, and auto-accept edits": "\u662F\uFF0C\u5E76\u81EA\u52A8\u63A5\u53D7\u7F16\u8F91",
      "Yes, and manually approve edits": "\u662F\uFF0C\u5E76\u624B\u52A8\u6279\u51C6\u7F16\u8F91",
      "No, keep planning (esc)": "\u5426\uFF0C\u7EE7\u7EED\u89C4\u5212 (esc)",
      "URLs to fetch:": "\u8981\u83B7\u53D6\u7684 URL\uFF1A",
      "MCP Server: {{server}}": "MCP \u670D\u52A1\u5668\uFF1A{{server}}",
      "Tool: {{tool}}": "\u5DE5\u5177\uFF1A{{tool}}",
      'Allow execution of MCP tool "{{tool}}" from server "{{server}}"?': '\u5141\u8BB8\u6267\u884C\u6765\u81EA\u670D\u52A1\u5668 "{{server}}" \u7684 MCP \u5DE5\u5177 "{{tool}}"\uFF1F',
      'Yes, always allow tool "{{tool}}" from server "{{server}}"': '\u662F\uFF0C\u603B\u662F\u5141\u8BB8\u6765\u81EA\u670D\u52A1\u5668 "{{server}}" \u7684\u5DE5\u5177 "{{tool}}"',
      'Yes, always allow all tools from server "{{server}}"': '\u662F\uFF0C\u603B\u662F\u5141\u8BB8\u6765\u81EA\u670D\u52A1\u5668 "{{server}}" \u7684\u6240\u6709\u5DE5\u5177',
      // ============================================================================
      // Dialogs - Shell Confirmation
      // ============================================================================
      "Shell Command Execution": "Shell \u547D\u4EE4\u6267\u884C",
      "A custom command wants to run the following shell commands:": "\u81EA\u5B9A\u4E49\u547D\u4EE4\u60F3\u8981\u8FD0\u884C\u4EE5\u4E0B shell \u547D\u4EE4\uFF1A",
      // ============================================================================
      // Dialogs - Pro Quota
      // ============================================================================
      "Pro quota limit reached for {{model}}.": "{{model}} \u7684 Pro \u914D\u989D\u5DF2\u8FBE\u5230\u4E0A\u9650",
      "Change auth (executes the /auth command)": "\u66F4\u6539\u8BA4\u8BC1\uFF08\u6267\u884C /auth \u547D\u4EE4\uFF09",
      "Continue with {{model}}": "\u4F7F\u7528 {{model}} \u7EE7\u7EED",
      // ============================================================================
      // Dialogs - Welcome Back
      // ============================================================================
      "Current Plan:": "\u5F53\u524D\u8BA1\u5212\uFF1A",
      "Progress: {{done}}/{{total}} tasks completed": "\u8FDB\u5EA6\uFF1A\u5DF2\u5B8C\u6210 {{done}}/{{total}} \u4E2A\u4EFB\u52A1",
      ", {{inProgress}} in progress": "\uFF0C{{inProgress}} \u4E2A\u8FDB\u884C\u4E2D",
      "Pending Tasks:": "\u5F85\u5904\u7406\u4EFB\u52A1\uFF1A",
      "What would you like to do?": "\u60A8\u60F3\u8981\u505A\u4EC0\u4E48\uFF1F",
      "Choose how to proceed with your session:": "\u9009\u62E9\u5982\u4F55\u7EE7\u7EED\u60A8\u7684\u4F1A\u8BDD\uFF1A",
      "Start new chat session": "\u5F00\u59CB\u65B0\u7684\u804A\u5929\u4F1A\u8BDD",
      "Continue previous conversation": "\u7EE7\u7EED\u4E4B\u524D\u7684\u5BF9\u8BDD",
      "\u{1F44B} Welcome back! (Last updated: {{timeAgo}})": "\u{1F44B} \u6B22\u8FCE\u56DE\u6765\uFF01\uFF08\u6700\u540E\u66F4\u65B0\uFF1A{{timeAgo}}\uFF09",
      "\u{1F3AF} Overall Goal:": "\u{1F3AF} \u603B\u4F53\u76EE\u6807\uFF1A",
      // ============================================================================
      // Dialogs - Auth
      // ============================================================================
      "Get started": "\u5F00\u59CB\u4F7F\u7528",
      "How would you like to authenticate for this project?": "\u60A8\u5E0C\u671B\u5982\u4F55\u4E3A\u6B64\u9879\u76EE\u8FDB\u884C\u8EAB\u4EFD\u9A8C\u8BC1\uFF1F",
      "OpenAI API key is required to use OpenAI authentication.": "\u4F7F\u7528 OpenAI \u8BA4\u8BC1\u9700\u8981 OpenAI API \u5BC6\u94A5",
      "You must select an auth method to proceed. Press Ctrl+C again to exit.": "\u60A8\u5FC5\u987B\u9009\u62E9\u8BA4\u8BC1\u65B9\u6CD5\u624D\u80FD\u7EE7\u7EED\u3002\u518D\u6B21\u6309 Ctrl+C \u9000\u51FA",
      "(Use Enter to Set Auth)": "\uFF08\u4F7F\u7528 Enter \u8BBE\u7F6E\u8BA4\u8BC1\uFF09",
      "Terms of Services and Privacy Notice for Qwen Code": "Qwen Code \u7684\u670D\u52A1\u6761\u6B3E\u548C\u9690\u79C1\u58F0\u660E",
      "Qwen OAuth": "Qwen OAuth (\u514D\u8D39)",
      "Login with QwenChat account to use daily free quota.": "\u4F7F\u7528 QwenChat \u8D26\u53F7\u767B\u5F55\uFF0C\u4EAB\u53D7\u6BCF\u65E5\u514D\u8D39\u989D\u5EA6\u3002",
      "Use coding plan credentials or your own api-keys/providers.": "\u4F7F\u7528 Coding Plan \u51ED\u8BC1\u6216\u60A8\u81EA\u5DF1\u7684 API \u5BC6\u94A5/\u63D0\u4F9B\u5546\u3002",
      OpenAI: "OpenAI",
      "Failed to login. Message: {{message}}": "\u767B\u5F55\u5931\u8D25\u3002\u6D88\u606F\uFF1A{{message}}",
      "Authentication is enforced to be {{enforcedType}}, but you are currently using {{currentType}}.": "\u8BA4\u8BC1\u65B9\u5F0F\u88AB\u5F3A\u5236\u8BBE\u7F6E\u4E3A {{enforcedType}}\uFF0C\u4F46\u60A8\u5F53\u524D\u4F7F\u7528\u7684\u662F {{currentType}}",
      "Qwen OAuth authentication timed out. Please try again.": "Qwen OAuth \u8BA4\u8BC1\u8D85\u65F6\u3002\u8BF7\u91CD\u8BD5",
      "Qwen OAuth authentication cancelled.": "Qwen OAuth \u8BA4\u8BC1\u5DF2\u53D6\u6D88",
      "Qwen OAuth Authentication": "Qwen OAuth \u8BA4\u8BC1",
      "Please visit this URL to authorize:": "\u8BF7\u8BBF\u95EE\u6B64 URL \u8FDB\u884C\u6388\u6743\uFF1A",
      "Or scan the QR code below:": "\u6216\u626B\u63CF\u4E0B\u65B9\u7684\u4E8C\u7EF4\u7801\uFF1A",
      "Waiting for authorization": "\u7B49\u5F85\u6388\u6743\u4E2D",
      "Time remaining:": "\u5269\u4F59\u65F6\u95F4\uFF1A",
      "(Press ESC or CTRL+C to cancel)": "\uFF08\u6309 ESC \u6216 CTRL+C \u53D6\u6D88\uFF09",
      "Qwen OAuth Authentication Timeout": "Qwen OAuth \u8BA4\u8BC1\u8D85\u65F6",
      "OAuth token expired (over {{seconds}} seconds). Please select authentication method again.": "OAuth \u4EE4\u724C\u5DF2\u8FC7\u671F\uFF08\u8D85\u8FC7 {{seconds}} \u79D2\uFF09\u3002\u8BF7\u91CD\u65B0\u9009\u62E9\u8BA4\u8BC1\u65B9\u6CD5",
      "Press any key to return to authentication type selection.": "\u6309\u4EFB\u610F\u952E\u8FD4\u56DE\u8BA4\u8BC1\u7C7B\u578B\u9009\u62E9",
      "Waiting for Qwen OAuth authentication...": "\u6B63\u5728\u7B49\u5F85 Qwen OAuth \u8BA4\u8BC1...",
      "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.": "\u6CE8\u610F\uFF1A\u4F7F\u7528 Qwen OAuth \u65F6\uFF0Csettings.json \u4E2D\u73B0\u6709\u7684 API \u5BC6\u94A5\u4E0D\u4F1A\u88AB\u6E05\u9664\u3002\u5982\u679C\u9700\u8981\uFF0C\u60A8\u53EF\u4EE5\u7A0D\u540E\u5207\u6362\u56DE OpenAI \u8BA4\u8BC1\u3002",
      "Authentication timed out. Please try again.": "\u8BA4\u8BC1\u8D85\u65F6\u3002\u8BF7\u91CD\u8BD5\u3002",
      "Waiting for auth... (Press ESC or CTRL+C to cancel)": "\u6B63\u5728\u7B49\u5F85\u8BA4\u8BC1...\uFF08\u6309 ESC \u6216 CTRL+C \u53D6\u6D88\uFF09",
      "Missing API key for OpenAI-compatible auth. Set settings.security.auth.apiKey, or set the {{envKeyHint}} environment variable.": "\u7F3A\u5C11 OpenAI \u517C\u5BB9\u8BA4\u8BC1\u7684 API \u5BC6\u94A5\u3002\u8BF7\u8BBE\u7F6E settings.security.auth.apiKey \u6216\u8BBE\u7F6E {{envKeyHint}} \u73AF\u5883\u53D8\u91CF\u3002",
      "{{envKeyHint}} environment variable not found.": "\u672A\u627E\u5230 {{envKeyHint}} \u73AF\u5883\u53D8\u91CF\u3002",
      "{{envKeyHint}} environment variable not found. Please set it in your .env file or environment variables.": "\u672A\u627E\u5230 {{envKeyHint}} \u73AF\u5883\u53D8\u91CF\u3002\u8BF7\u5728 .env \u6587\u4EF6\u6216\u7CFB\u7EDF\u73AF\u5883\u53D8\u91CF\u4E2D\u8FDB\u884C\u8BBE\u7F6E\u3002",
      "{{envKeyHint}} environment variable not found (or set settings.security.auth.apiKey). Please set it in your .env file or environment variables.": "\u672A\u627E\u5230 {{envKeyHint}} \u73AF\u5883\u53D8\u91CF\uFF08\u6216\u8BBE\u7F6E settings.security.auth.apiKey\uFF09\u3002\u8BF7\u5728 .env \u6587\u4EF6\u6216\u7CFB\u7EDF\u73AF\u5883\u53D8\u91CF\u4E2D\u8FDB\u884C\u8BBE\u7F6E\u3002",
      "Missing API key for OpenAI-compatible auth. Set the {{envKeyHint}} environment variable.": "\u7F3A\u5C11 OpenAI \u517C\u5BB9\u8BA4\u8BC1\u7684 API \u5BC6\u94A5\u3002\u8BF7\u8BBE\u7F6E {{envKeyHint}} \u73AF\u5883\u53D8\u91CF\u3002",
      "Anthropic provider missing required baseUrl in modelProviders[].baseUrl.": "Anthropic \u63D0\u4F9B\u5546\u7F3A\u5C11\u5FC5\u9700\u7684 baseUrl\uFF0C\u8BF7\u5728 modelProviders[].baseUrl \u4E2D\u914D\u7F6E\u3002",
      "ANTHROPIC_BASE_URL environment variable not found.": "\u672A\u627E\u5230 ANTHROPIC_BASE_URL \u73AF\u5883\u53D8\u91CF\u3002",
      "Invalid auth method selected.": "\u9009\u62E9\u4E86\u65E0\u6548\u7684\u8BA4\u8BC1\u65B9\u5F0F\u3002",
      "Failed to authenticate. Message: {{message}}": "\u8BA4\u8BC1\u5931\u8D25\u3002\u6D88\u606F\uFF1A{{message}}",
      "Authenticated successfully with {{authType}} credentials.": "\u4F7F\u7528 {{authType}} \u51ED\u636E\u6210\u529F\u8BA4\u8BC1\u3002",
      'Invalid QWEN_DEFAULT_AUTH_TYPE value: "{{value}}". Valid values are: {{validValues}}': '\u65E0\u6548\u7684 QWEN_DEFAULT_AUTH_TYPE \u503C\uFF1A"{{value}}"\u3002\u6709\u6548\u503C\u4E3A\uFF1A{{validValues}}',
      "OpenAI Configuration Required": "\u9700\u8981\u914D\u7F6E OpenAI",
      "Please enter your OpenAI configuration. You can get an API key from": "\u8BF7\u8F93\u5165\u60A8\u7684 OpenAI \u914D\u7F6E\u3002\u60A8\u53EF\u4EE5\u4ECE\u4EE5\u4E0B\u5730\u5740\u83B7\u53D6 API \u5BC6\u94A5\uFF1A",
      "API Key:": "API \u5BC6\u94A5\uFF1A",
      "Invalid credentials: {{errorMessage}}": "\u51ED\u636E\u65E0\u6548\uFF1A{{errorMessage}}",
      "Failed to validate credentials": "\u9A8C\u8BC1\u51ED\u636E\u5931\u8D25",
      "Press Enter to continue, Tab/\u2191\u2193 to navigate, Esc to cancel": "\u6309 Enter \u7EE7\u7EED\uFF0CTab/\u2191\u2193 \u5BFC\u822A\uFF0CEsc \u53D6\u6D88",
      // ============================================================================
      // Dialogs - Model
      // ============================================================================
      "Select Model": "\u9009\u62E9\u6A21\u578B",
      "(Press Esc to close)": "\uFF08\u6309 Esc \u5173\u95ED\uFF09",
      "Current (effective) configuration": "\u5F53\u524D\uFF08\u5B9E\u9645\u751F\u6548\uFF09\u914D\u7F6E",
      AuthType: "\u8BA4\u8BC1\u65B9\u5F0F",
      "API Key": "API \u5BC6\u94A5",
      unset: "\u672A\u8BBE\u7F6E",
      "(default)": "(\u9ED8\u8BA4)",
      "(set)": "(\u5DF2\u8BBE\u7F6E)",
      "(not set)": "(\u672A\u8BBE\u7F6E)",
      "Failed to switch model to '{{modelId}}'.\n\n{{error}}": "\u65E0\u6CD5\u5207\u6362\u5230\u6A21\u578B '{{modelId}}'.\n\n{{error}}",
      "Qwen 3.5 Plus \u2014 efficient hybrid model with leading coding performance": "Qwen 3.5 Plus \u2014 \u9AD8\u6548\u6DF7\u5408\u67B6\u6784\uFF0C\u7F16\u7A0B\u6027\u80FD\u4E1A\u754C\u9886\u5148",
      "The latest Qwen Vision model from Alibaba Cloud ModelStudio (version: qwen3-vl-plus-2025-09-23)": "\u6765\u81EA\u963F\u91CC\u4E91 ModelStudio \u7684\u6700\u65B0 Qwen Vision \u6A21\u578B\uFF08\u7248\u672C\uFF1Aqwen3-vl-plus-2025-09-23\uFF09",
      // ============================================================================
      // Dialogs - Permissions
      // ============================================================================
      "Manage folder trust settings": "\u7BA1\u7406\u6587\u4EF6\u5939\u4FE1\u4EFB\u8BBE\u7F6E",
      // ============================================================================
      // Status Bar
      // ============================================================================
      "Using:": "\u5DF2\u52A0\u8F7D: ",
      "{{count}} open file": "{{count}} \u4E2A\u6253\u5F00\u7684\u6587\u4EF6",
      "{{count}} open files": "{{count}} \u4E2A\u6253\u5F00\u7684\u6587\u4EF6",
      "(ctrl+g to view)": "\uFF08\u6309 ctrl+g \u67E5\u770B\uFF09",
      "{{count}} {{name}} file": "{{count}} \u4E2A {{name}} \u6587\u4EF6",
      "{{count}} {{name}} files": "{{count}} \u4E2A {{name}} \u6587\u4EF6",
      "{{count}} MCP server": "{{count}} \u4E2A MCP \u670D\u52A1\u5668",
      "{{count}} MCP servers": "{{count}} \u4E2A MCP \u670D\u52A1\u5668",
      "{{count}} Blocked": "{{count}} \u4E2A\u5DF2\u963B\u6B62",
      "(ctrl+t to view)": "\uFF08\u6309 ctrl+t \u67E5\u770B\uFF09",
      "(ctrl+t to toggle)": "\uFF08\u6309 ctrl+t \u5207\u6362\uFF09",
      "Press Ctrl+C again to exit.": "\u518D\u6B21\u6309 Ctrl+C \u9000\u51FA",
      "Press Ctrl+D again to exit.": "\u518D\u6B21\u6309 Ctrl+D \u9000\u51FA",
      "Press Esc again to clear.": "\u518D\u6B21\u6309 Esc \u6E05\u9664",
      // ============================================================================
      // MCP Status
      // ============================================================================
      "No MCP servers configured.": "\u672A\u914D\u7F6E MCP \u670D\u52A1\u5668",
      "\u23F3 MCP servers are starting up ({{count}} initializing)...": "\u23F3 MCP \u670D\u52A1\u5668\u6B63\u5728\u542F\u52A8\uFF08{{count}} \u4E2A\u6B63\u5728\u521D\u59CB\u5316\uFF09...",
      "Note: First startup may take longer. Tool availability will update automatically.": "\u6CE8\u610F\uFF1A\u9996\u6B21\u542F\u52A8\u53EF\u80FD\u9700\u8981\u66F4\u957F\u65F6\u95F4\u3002\u5DE5\u5177\u53EF\u7528\u6027\u5C06\u81EA\u52A8\u66F4\u65B0",
      "Configured MCP servers:": "\u5DF2\u914D\u7F6E\u7684 MCP \u670D\u52A1\u5668\uFF1A",
      Ready: "\u5C31\u7EEA",
      "Starting... (first startup may take longer)": "\u6B63\u5728\u542F\u52A8...\uFF08\u9996\u6B21\u542F\u52A8\u53EF\u80FD\u9700\u8981\u66F4\u957F\u65F6\u95F4\uFF09",
      Disconnected: "\u5DF2\u65AD\u5F00\u8FDE\u63A5",
      "{{count}} tool": "{{count}} \u4E2A\u5DE5\u5177",
      "{{count}} tools": "{{count}} \u4E2A\u5DE5\u5177",
      "{{count}} prompt": "{{count}} \u4E2A\u63D0\u793A",
      "{{count}} prompts": "{{count}} \u4E2A\u63D0\u793A",
      "(from {{extensionName}})": "\uFF08\u6765\u81EA {{extensionName}}\uFF09",
      OAuth: "OAuth",
      "OAuth expired": "OAuth \u5DF2\u8FC7\u671F",
      "OAuth not authenticated": "OAuth \u672A\u8BA4\u8BC1",
      "tools and prompts will appear when ready": "\u5DE5\u5177\u548C\u63D0\u793A\u5C06\u5728\u5C31\u7EEA\u65F6\u663E\u793A",
      "{{count}} tools cached": "{{count}} \u4E2A\u5DE5\u5177\u5DF2\u7F13\u5B58",
      "Tools:": "\u5DE5\u5177\uFF1A",
      "Parameters:": "\u53C2\u6570\uFF1A",
      "Prompts:": "\u63D0\u793A\uFF1A",
      Blocked: "\u5DF2\u963B\u6B62",
      "\u{1F4A1} Tips:": "\u{1F4A1} \u63D0\u793A\uFF1A",
      Use: "\u4F7F\u7528",
      "to show server and tool descriptions": "\u663E\u793A\u670D\u52A1\u5668\u548C\u5DE5\u5177\u63CF\u8FF0",
      "to show tool parameter schemas": "\u663E\u793A\u5DE5\u5177\u53C2\u6570\u67B6\u6784",
      "to hide descriptions": "\u9690\u85CF\u63CF\u8FF0",
      "to authenticate with OAuth-enabled servers": "\u4F7F\u7528\u652F\u6301 OAuth \u7684\u670D\u52A1\u5668\u8FDB\u884C\u8BA4\u8BC1",
      Press: "\u6309",
      "to toggle tool descriptions on/off": "\u5207\u6362\u5DE5\u5177\u63CF\u8FF0\u5F00\u5173",
      "Starting OAuth authentication for MCP server '{{name}}'...": "\u6B63\u5728\u4E3A MCP \u670D\u52A1\u5668 '{{name}}' \u542F\u52A8 OAuth \u8BA4\u8BC1...",
      "Restarting MCP servers...": "\u6B63\u5728\u91CD\u542F MCP \u670D\u52A1\u5668...",
      // ============================================================================
      // Startup Tips
      // ============================================================================
      "Tips:": "\u63D0\u793A\uFF1A",
      "Use /compress when the conversation gets long to summarize history and free up context.": "\u5BF9\u8BDD\u53D8\u957F\u65F6\u7528 /compress\uFF0C\u603B\u7ED3\u5386\u53F2\u5E76\u91CA\u653E\u4E0A\u4E0B\u6587\u3002",
      "Start a fresh idea with /clear or /new; the previous session stays available in history.": "\u7528 /clear \u6216 /new \u5F00\u542F\u65B0\u601D\u8DEF\uFF1B\u4E4B\u524D\u7684\u4F1A\u8BDD\u4F1A\u4FDD\u7559\u5728\u5386\u53F2\u8BB0\u5F55\u4E2D\u3002",
      "Use /bug to submit issues to the maintainers when something goes off.": "\u9047\u5230\u95EE\u9898\u65F6\uFF0C\u7528 /bug \u5C06\u95EE\u9898\u63D0\u4EA4\u7ED9\u7EF4\u62A4\u8005\u3002",
      "Switch auth type quickly with /auth.": "\u7528 /auth \u5FEB\u901F\u5207\u6362\u8BA4\u8BC1\u65B9\u5F0F\u3002",
      "You can run any shell commands from Qwen Code using ! (e.g. !ls).": "\u5728 Qwen Code \u4E2D\u4F7F\u7528 ! \u53EF\u8FD0\u884C\u4EFB\u610F shell \u547D\u4EE4\uFF08\u4F8B\u5982 !ls\uFF09\u3002",
      "Type / to open the command popup; Tab autocompletes slash commands and saved prompts.": "\u8F93\u5165 / \u6253\u5F00\u547D\u4EE4\u5F39\u7A97\uFF1B\u6309 Tab \u81EA\u52A8\u8865\u5168\u659C\u6760\u547D\u4EE4\u548C\u4FDD\u5B58\u7684\u63D0\u793A\u8BCD\u3002",
      "You can resume a previous conversation by running qwen --continue or qwen --resume.": "\u8FD0\u884C qwen --continue \u6216 qwen --resume \u53EF\u7EE7\u7EED\u4E4B\u524D\u7684\u4F1A\u8BDD\u3002",
      "You can switch permission mode quickly with Shift+Tab or /approval-mode.": "\u6309 Shift+Tab \u6216\u8F93\u5165 /approval-mode \u53EF\u5FEB\u901F\u5207\u6362\u6743\u9650\u6A21\u5F0F\u3002",
      "You can switch permission mode quickly with Tab or /approval-mode.": "\u6309 Tab \u6216\u8F93\u5165 /approval-mode \u53EF\u5FEB\u901F\u5207\u6362\u6743\u9650\u6A21\u5F0F\u3002",
      "Try /insight to generate personalized insights from your chat history.": "\u8BD5\u8BD5 /insight\uFF0C\u4ECE\u804A\u5929\u8BB0\u5F55\u4E2D\u751F\u6210\u4E2A\u6027\u5316\u6D1E\u5BDF\u3002",
      // ============================================================================
      // Exit Screen / Stats
      // ============================================================================
      "Agent powering down. Goodbye!": "Qwen Code \u6B63\u5728\u5173\u95ED\uFF0C\u518D\u89C1\uFF01",
      "To continue this session, run": "\u8981\u7EE7\u7EED\u6B64\u4F1A\u8BDD\uFF0C\u8BF7\u8FD0\u884C",
      "Interaction Summary": "\u4EA4\u4E92\u6458\u8981",
      "Session ID:": "\u4F1A\u8BDD ID\uFF1A",
      "Tool Calls:": "\u5DE5\u5177\u8C03\u7528\uFF1A",
      "Success Rate:": "\u6210\u529F\u7387\uFF1A",
      "User Agreement:": "\u7528\u6237\u540C\u610F\u7387\uFF1A",
      reviewed: "\u5DF2\u5BA1\u6838",
      "Code Changes:": "\u4EE3\u7801\u53D8\u66F4\uFF1A",
      Performance: "\u6027\u80FD",
      "Wall Time:": "\u603B\u8017\u65F6\uFF1A",
      "Agent Active:": "\u667A\u80FD\u4F53\u6D3B\u8DC3\u65F6\u95F4\uFF1A",
      "API Time:": "API \u65F6\u95F4\uFF1A",
      "Tool Time:": "\u5DE5\u5177\u65F6\u95F4\uFF1A",
      "Session Stats": "\u4F1A\u8BDD\u7EDF\u8BA1",
      "Model Usage": "\u6A21\u578B\u4F7F\u7528\u60C5\u51B5",
      Reqs: "\u8BF7\u6C42\u6570",
      "Input Tokens": "\u8F93\u5165 token \u6570",
      "Output Tokens": "\u8F93\u51FA token \u6570",
      "Savings Highlight:": "\u8282\u7701\u4EAE\u70B9\uFF1A",
      "of input tokens were served from the cache, reducing costs.": "\u4ECE\u7F13\u5B58\u8F7D\u5165 token \uFF0C\u964D\u4F4E\u4E86\u6210\u672C",
      "Tip: For a full token breakdown, run `/stats model`.": "\u63D0\u793A\uFF1A\u8981\u67E5\u770B\u5B8C\u6574\u7684\u4EE4\u724C\u660E\u7EC6\uFF0C\u8BF7\u8FD0\u884C `/stats model`",
      "Model Stats For Nerds": "\u6A21\u578B\u7EDF\u8BA1\uFF08\u6280\u672F\u7EC6\u8282\uFF09",
      "Tool Stats For Nerds": "\u5DE5\u5177\u7EDF\u8BA1\uFF08\u6280\u672F\u7EC6\u8282\uFF09",
      Metric: "\u6307\u6807",
      API: "API",
      Requests: "\u8BF7\u6C42\u6570",
      Errors: "\u9519\u8BEF\u6570",
      "Avg Latency": "\u5E73\u5747\u5EF6\u8FDF",
      Tokens: "\u4EE4\u724C",
      Total: "\u603B\u8BA1",
      Prompt: "\u63D0\u793A",
      Cached: "\u7F13\u5B58",
      Thoughts: "\u601D\u8003",
      Tool: "\u5DE5\u5177",
      Output: "\u8F93\u51FA",
      "No API calls have been made in this session.": "\u672C\u6B21\u4F1A\u8BDD\u4E2D\u672A\u8FDB\u884C\u4EFB\u4F55 API \u8C03\u7528",
      "Tool Name": "\u5DE5\u5177\u540D\u79F0",
      Calls: "\u8C03\u7528\u6B21\u6570",
      "Success Rate": "\u6210\u529F\u7387",
      "Avg Duration": "\u5E73\u5747\u8017\u65F6",
      "User Decision Summary": "\u7528\u6237\u51B3\u7B56\u6458\u8981",
      "Total Reviewed Suggestions:": "\u5DF2\u5BA1\u6838\u5EFA\u8BAE\u603B\u6570\uFF1A",
      " \xBB Accepted:": " \xBB \u5DF2\u63A5\u53D7\uFF1A",
      " \xBB Rejected:": " \xBB \u5DF2\u62D2\u7EDD\uFF1A",
      " \xBB Modified:": " \xBB \u5DF2\u4FEE\u6539\uFF1A",
      " Overall Agreement Rate:": " \u603B\u4F53\u540C\u610F\u7387\uFF1A",
      "No tool calls have been made in this session.": "\u672C\u6B21\u4F1A\u8BDD\u4E2D\u672A\u8FDB\u884C\u4EFB\u4F55\u5DE5\u5177\u8C03\u7528",
      "Session start time is unavailable, cannot calculate stats.": "\u4F1A\u8BDD\u5F00\u59CB\u65F6\u95F4\u4E0D\u53EF\u7528\uFF0C\u65E0\u6CD5\u8BA1\u7B97\u7EDF\u8BA1\u4FE1\u606F",
      // ============================================================================
      // Command Format Migration
      // ============================================================================
      "Command Format Migration": "\u547D\u4EE4\u683C\u5F0F\u8FC1\u79FB",
      "Found {{count}} TOML command file:": "\u53D1\u73B0 {{count}} \u4E2A TOML \u547D\u4EE4\u6587\u4EF6\uFF1A",
      "Found {{count}} TOML command files:": "\u53D1\u73B0 {{count}} \u4E2A TOML \u547D\u4EE4\u6587\u4EF6\uFF1A",
      "... and {{count}} more": "... \u4EE5\u53CA\u5176\u4ED6 {{count}} \u4E2A",
      "The TOML format is deprecated. Would you like to migrate them to Markdown format?": "TOML \u683C\u5F0F\u5DF2\u5F03\u7528\u3002\u662F\u5426\u5C06\u5B83\u4EEC\u8FC1\u79FB\u5230 Markdown \u683C\u5F0F\uFF1F",
      "(Backups will be created and original files will be preserved)": "\uFF08\u5C06\u521B\u5EFA\u5907\u4EFD\uFF0C\u539F\u59CB\u6587\u4EF6\u5C06\u4FDD\u7559\uFF09",
      // ============================================================================
      // Loading Phrases
      // ============================================================================
      "Waiting for user confirmation...": "\u7B49\u5F85\u7528\u6237\u786E\u8BA4...",
      "(esc to cancel, {{time}})": "\uFF08\u6309 esc \u53D6\u6D88\uFF0C{{time}}\uFF09",
      WITTY_LOADING_PHRASES: [
        // --- 职场搬砖系列 ---
        "\u6B63\u5728\u52AA\u529B\u642C\u7816\uFF0C\u8BF7\u7A0D\u5019...",
        "\u8001\u677F\u5728\u8EAB\u540E\uFF0C\u5FEB\u52A0\u8F7D\u554A\uFF01",
        "\u5934\u53D1\u6389\u5149\u524D\uFF0C\u4E00\u5B9A\u80FD\u52A0\u8F7D\u5B8C...",
        "\u670D\u52A1\u5668\u6B63\u5728\u6DF1\u547C\u5438\uFF0C\u51C6\u5907\u653E\u5927\u62DB...",
        "\u6B63\u5728\u5411\u670D\u52A1\u5668\u6295\u5582\u5496\u5561...",
        // --- 大厂黑话系列 ---
        "\u6B63\u5728\u8D4B\u80FD\u5168\u94FE\u8DEF\uFF0C\u5BFB\u627E\u5173\u952E\u6293\u624B...",
        "\u6B63\u5728\u964D\u672C\u589E\u6548\uFF0C\u4F18\u5316\u52A0\u8F7D\u8DEF\u5F84...",
        "\u6B63\u5728\u6253\u7834\u90E8\u95E8\u58C1\u5792\uFF0C\u6C89\u6DC0\u65B9\u6CD5\u8BBA...",
        "\u6B63\u5728\u62E5\u62B1\u53D8\u5316\uFF0C\u8FED\u4EE3\u6838\u5FC3\u4EF7\u503C...",
        "\u6B63\u5728\u5BF9\u9F50\u9897\u7C92\u5EA6\uFF0C\u6253\u78E8\u5E95\u5C42\u903B\u8F91...",
        "\u5927\u529B\u51FA\u5947\u8FF9\uFF0C\u6B63\u5728\u5F3A\u884C\u52A0\u8F7D...",
        // --- 程序员自嘲系列 ---
        "\u53EA\u8981\u6211\u4E0D\u5199\u4EE3\u7801\uFF0C\u4EE3\u7801\u5C31\u6CA1\u6709 Bug...",
        "\u6B63\u5728\u628A Bug \u8F6C\u5316\u4E3A Feature...",
        "\u53EA\u8981\u6211\u4E0D\u5C34\u5C2C\uFF0CBug \u5C31\u8FFD\u4E0D\u4E0A\u6211...",
        "\u6B63\u5728\u8BD5\u56FE\u7406\u89E3\u53BB\u5E74\u7684\u81EA\u5DF1\u5199\u4E86\u4EC0\u4E48...",
        "\u6B63\u5728\u733F\u529B\u89C9\u9192\u4E2D\uFF0C\u8BF7\u8010\u5FC3\u7B49\u5F85...",
        // --- 合作愉快系列 ---
        "\u6B63\u5728\u8BE2\u95EE\u4EA7\u54C1\u7ECF\u7406\uFF1A\u8FD9\u9700\u6C42\u662F\u771F\u7684\u5417\uFF1F",
        "\u6B63\u5728\u7ED9\u4EA7\u54C1\u7ECF\u7406\u753B\u997C\uFF0C\u8BF7\u7A0D\u7B49...",
        // --- 温暖治愈系列 ---
        "\u6BCF\u4E00\u884C\u4EE3\u7801\uFF0C\u90FD\u5728\u52AA\u529B\u8BA9\u4E16\u754C\u53D8\u5F97\u66F4\u597D\u4E00\u70B9\u70B9...",
        "\u6BCF\u4E00\u4E2A\u4F1F\u5927\u7684\u60F3\u6CD5\uFF0C\u90FD\u503C\u5F97\u8FD9\u4EFD\u8010\u5FC3\u7684\u7B49\u5F85...",
        "\u522B\u6025\uFF0C\u7F8E\u597D\u7684\u4E8B\u7269\u603B\u662F\u9700\u8981\u4E00\u70B9\u65F6\u95F4\u53BB\u915D\u917F...",
        "\u613F\u4F60\u7684\u4EE3\u7801\u6C38\u65E0 Bug\uFF0C\u613F\u4F60\u7684\u68A6\u60F3\u7EC8\u5C06\u6210\u771F...",
        "\u54EA\u6015\u53EA\u6709 0.1% \u7684\u8FDB\u5EA6\uFF0C\u4E5F\u662F\u5728\u5411\u76EE\u6807\u9760\u8FD1...",
        "\u52A0\u8F7D\u7684\u662F\u5B57\u8282\uFF0C\u627F\u8F7D\u7684\u662F\u5BF9\u6280\u672F\u7684\u70ED\u7231..."
      ],
      // ============================================================================
      // Extension Settings Input
      // ============================================================================
      "Enter value...": "\u8BF7\u8F93\u5165\u503C...",
      "Enter sensitive value...": "\u8BF7\u8F93\u5165\u654F\u611F\u503C...",
      "Press Enter to submit, Escape to cancel": "\u6309 Enter \u63D0\u4EA4\uFF0CEscape \u53D6\u6D88",
      // ============================================================================
      // Command Migration Tool
      // ============================================================================
      "Markdown file already exists: {{filename}}": "Markdown \u6587\u4EF6\u5DF2\u5B58\u5728\uFF1A{{filename}}",
      "TOML Command Format Deprecation Notice": "TOML \u547D\u4EE4\u683C\u5F0F\u5F03\u7528\u901A\u77E5",
      "Found {{count}} command file(s) in TOML format:": "\u53D1\u73B0 {{count}} \u4E2A TOML \u683C\u5F0F\u7684\u547D\u4EE4\u6587\u4EF6\uFF1A",
      "The TOML format for commands is being deprecated in favor of Markdown format.": "\u547D\u4EE4\u7684 TOML \u683C\u5F0F\u6B63\u5728\u88AB\u5F03\u7528\uFF0C\u63A8\u8350\u4F7F\u7528 Markdown \u683C\u5F0F\u3002",
      "Markdown format is more readable and easier to edit.": "Markdown \u683C\u5F0F\u66F4\u6613\u8BFB\u3001\u66F4\u6613\u7F16\u8F91\u3002",
      "You can migrate these files automatically using:": "\u60A8\u53EF\u4EE5\u4F7F\u7528\u4EE5\u4E0B\u547D\u4EE4\u81EA\u52A8\u8FC1\u79FB\u8FD9\u4E9B\u6587\u4EF6\uFF1A",
      "Or manually convert each file:": "\u6216\u624B\u52A8\u8F6C\u6362\u6BCF\u4E2A\u6587\u4EF6\uFF1A",
      'TOML: prompt = "..." / description = "..."': 'TOML\uFF1Aprompt = "..." / description = "..."',
      "Markdown: YAML frontmatter + content": "Markdown\uFF1AYAML frontmatter + \u5185\u5BB9",
      "The migration tool will:": "\u8FC1\u79FB\u5DE5\u5177\u5C06\uFF1A",
      "Convert TOML files to Markdown": "\u5C06 TOML \u6587\u4EF6\u8F6C\u6362\u4E3A Markdown",
      "Create backups of original files": "\u521B\u5EFA\u539F\u59CB\u6587\u4EF6\u7684\u5907\u4EFD",
      "Preserve all command functionality": "\u4FDD\u7559\u6240\u6709\u547D\u4EE4\u529F\u80FD",
      "TOML format will continue to work for now, but migration is recommended.": "TOML \u683C\u5F0F\u76EE\u524D\u4ECD\u53EF\u4F7F\u7528\uFF0C\u4F46\u5EFA\u8BAE\u8FC1\u79FB\u3002",
      // ============================================================================
      // Extensions - Explore Command
      // ============================================================================
      "Open extensions page in your browser": "\u5728\u6D4F\u89C8\u5668\u4E2D\u6253\u5F00\u6269\u5C55\u5E02\u573A\u9875\u9762",
      "Unknown extensions source: {{source}}.": "\u672A\u77E5\u7684\u6269\u5C55\u6765\u6E90\uFF1A{{source}}\u3002",
      "Would open extensions page in your browser: {{url}} (skipped in test environment)": "\u5C06\u5728\u6D4F\u89C8\u5668\u4E2D\u6253\u5F00\u6269\u5C55\u9875\u9762\uFF1A{{url}}\uFF08\u6D4B\u8BD5\u73AF\u5883\u4E2D\u5DF2\u8DF3\u8FC7\uFF09",
      "View available extensions at {{url}}": "\u5728 {{url}} \u67E5\u770B\u53EF\u7528\u6269\u5C55",
      "Opening extensions page in your browser: {{url}}": "\u6B63\u5728\u6D4F\u89C8\u5668\u4E2D\u6253\u5F00\u6269\u5C55\u9875\u9762\uFF1A{{url}}",
      "Failed to open browser. Check out the extensions gallery at {{url}}": "\u6253\u5F00\u6D4F\u89C8\u5668\u5931\u8D25\u3002\u8BF7\u8BBF\u95EE\u6269\u5C55\u5E02\u573A\uFF1A{{url}}",
      // ============================================================================
      // Retry / Rate Limit
      // ============================================================================
      "Rate limit error: {{reason}}": "\u89E6\u53D1\u9650\u6D41\uFF1A{{reason}}",
      "Retrying in {{seconds}} seconds\u2026 (attempt {{attempt}}/{{maxRetries}})": "\u5C06\u4E8E {{seconds}} \u79D2\u540E\u91CD\u8BD5\u2026\uFF08\u7B2C {{attempt}}/{{maxRetries}} \u6B21\uFF09",
      // ============================================================================
      // Coding Plan Authentication
      // ============================================================================
      "Please enter your API key:": "\u8BF7\u8F93\u5165\u60A8\u7684 API Key\uFF1A",
      "API key cannot be empty.": "API Key \u4E0D\u80FD\u4E3A\u7A7A\u3002",
      "You can get your exclusive Coding Plan API-KEY here:": "\u60A8\u53EF\u4EE5\u5728\u8FD9\u91CC\u83B7\u53D6\u4E13\u5C5E\u7684 Coding Plan API-KEY\uFF1A",
      "API key is stored in settings.env. You can migrate it to a .env file for better security.": "API Key \u5DF2\u5B58\u50A8\u5728 settings.env \u4E2D\u3002\u60A8\u53EF\u4EE5\u5C06\u5176\u8FC1\u79FB\u5230 .env \u6587\u4EF6\u4EE5\u83B7\u5F97\u66F4\u597D\u7684\u5B89\u5168\u6027\u3002",
      "New model configurations are available for Bailian Coding Plan. Update now?": "\u767E\u70BC Coding Plan \u6709\u65B0\u6A21\u578B\u914D\u7F6E\u53EF\u7528\u3002\u662F\u5426\u7ACB\u5373\u66F4\u65B0\uFF1F",
      "Coding Plan configuration updated successfully. New models are now available.": "Coding Plan \u914D\u7F6E\u66F4\u65B0\u6210\u529F\u3002\u65B0\u6A21\u578B\u73B0\u5DF2\u53EF\u7528\u3002",
      "Coding Plan API key not found. Please re-authenticate with Coding Plan.": "\u672A\u627E\u5230 Coding Plan API Key\u3002\u8BF7\u91CD\u65B0\u901A\u8FC7 Coding Plan \u8BA4\u8BC1\u3002",
      "Failed to update Coding Plan configuration: {{message}}": "\u66F4\u65B0 Coding Plan \u914D\u7F6E\u5931\u8D25\uFF1A{{message}}",
      // ============================================================================
      // Custom API-KEY Configuration
      // ============================================================================
      "For advanced users who want to configure models manually.": "\u9002\u5408\u9700\u8981\u624B\u52A8\u914D\u7F6E\u6A21\u578B\u7684\u9AD8\u7EA7\u7528\u6237\u3002",
      "Please configure your models in settings.json:": "\u8BF7\u5728 settings.json \u4E2D\u914D\u7F6E\u60A8\u7684\u6A21\u578B\uFF1A",
      "Set API key via environment variable (e.g., OPENAI_API_KEY)": "\u901A\u8FC7\u73AF\u5883\u53D8\u91CF\u8BBE\u7F6E API Key\uFF08\u4F8B\u5982\uFF1AOPENAI_API_KEY\uFF09",
      "Add model configuration to modelProviders['openai'] (or other auth types)": "\u5C06\u6A21\u578B\u914D\u7F6E\u6DFB\u52A0\u5230 modelProviders['openai']\uFF08\u6216\u5176\u4ED6\u8BA4\u8BC1\u7C7B\u578B\uFF09",
      "Each provider needs: id, envKey (required), plus optional baseUrl, generationConfig": "\u6BCF\u4E2A\u63D0\u4F9B\u5546\u9700\u8981\uFF1Aid\u3001envKey\uFF08\u5FC5\u9700\uFF09\uFF0C\u4EE5\u53CA\u53EF\u9009\u7684 baseUrl\u3001generationConfig",
      "Use /model command to select your preferred model from the configured list": "\u4F7F\u7528 /model \u547D\u4EE4\u4ECE\u914D\u7F6E\u5217\u8868\u4E2D\u9009\u62E9\u60A8\u504F\u597D\u7684\u6A21\u578B",
      "Supported auth types: openai, anthropic, gemini, vertex-ai, etc.": "\u652F\u6301\u7684\u8BA4\u8BC1\u7C7B\u578B\uFF1Aopenai\u3001anthropic\u3001gemini\u3001vertex-ai \u7B49",
      "More instructions please check:": "\u66F4\u591A\u8BF4\u660E\u8BF7\u67E5\u770B\uFF1A",
      // ============================================================================
      // Auth Dialog - View Titles and Labels
      // ============================================================================
      "API-KEY": "API-KEY",
      "Coding Plan": "Coding Plan",
      "Coding Plan (Bailian, China)": "Coding Plan (\u767E\u70BC, \u4E2D\u56FD)",
      "Coding Plan (Bailian, Global/Intl)": "Coding Plan (\u767E\u70BC, \u5168\u7403/\u56FD\u9645)",
      "Paste your api key of Bailian Coding Plan and you're all set!": "\u7C98\u8D34\u60A8\u7684\u767E\u70BC Coding Plan API Key\uFF0C\u5373\u53EF\u5B8C\u6210\u8BBE\u7F6E\uFF01",
      "Paste your api key of Coding Plan (Bailian, Global/Intl) and you're all set!": "\u7C98\u8D34\u60A8\u7684 Coding Plan (\u767E\u70BC, \u5168\u7403/\u56FD\u9645) API Key\uFF0C\u5373\u53EF\u5B8C\u6210\u8BBE\u7F6E\uFF01",
      Custom: "\u81EA\u5B9A\u4E49",
      "More instructions about configuring `modelProviders` manually.": "\u5173\u4E8E\u624B\u52A8\u914D\u7F6E `modelProviders` \u7684\u66F4\u591A\u8BF4\u660E\u3002",
      "Select API-KEY configuration mode:": "\u9009\u62E9 API-KEY \u914D\u7F6E\u6A21\u5F0F\uFF1A",
      "(Press Escape to go back)": "(\u6309 Escape \u952E\u8FD4\u56DE)",
      "(Press Enter to submit, Escape to cancel)": "(\u6309 Enter \u63D0\u4EA4\uFF0CEscape \u53D6\u6D88)",
      // ============================================================================
      // Coding Plan International Updates
      // ============================================================================
      "New model configurations are available for {{region}}. Update now?": "{{region}} \u6709\u65B0\u7684\u6A21\u578B\u914D\u7F6E\u53EF\u7528\u3002\u662F\u5426\u7ACB\u5373\u66F4\u65B0\uFF1F",
      "New model configurations are available for Bailian Coding Plan (China). Update now?": "\u767E\u70BC Coding Plan (\u4E2D\u56FD) \u6709\u65B0\u7684\u6A21\u578B\u914D\u7F6E\u53EF\u7528\u3002\u662F\u5426\u7ACB\u5373\u66F4\u65B0\uFF1F",
      "New model configurations are available for Coding Plan (Bailian, Global/Intl). Update now?": "Coding Plan (\u767E\u70BC, \u5168\u7403/\u56FD\u9645) \u6709\u65B0\u7684\u6A21\u578B\u914D\u7F6E\u53EF\u7528\u3002\u662F\u5426\u7ACB\u5373\u66F4\u65B0\uFF1F",
      '{{region}} configuration updated successfully. Model switched to "{{model}}".': '{{region}} \u914D\u7F6E\u66F4\u65B0\u6210\u529F\u3002\u6A21\u578B\u5DF2\u5207\u6362\u81F3 "{{model}}"\u3002',
      "Authenticated successfully with {{region}}. API key and model configs saved to settings.json (backed up).": "\u6210\u529F\u901A\u8FC7 {{region}} \u8BA4\u8BC1\u3002API Key \u548C\u6A21\u578B\u914D\u7F6E\u5DF2\u4FDD\u5B58\u81F3 settings.json\uFF08\u5DF2\u5907\u4EFD\uFF09\u3002"
    };
  }
});

// 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 r5 = rgb[0] / 255;
      const g2 = rgb[1] / 255;
      const b2 = rgb[2] / 255;
      const min = Math.min(r5, g2, b2);
      const max = Math.max(r5, g2, b2);
      const delta = max - min;
      let h3;
      let s5;
      if (max === min) {
        h3 = 0;
      } else if (r5 === max) {
        h3 = (g2 - b2) / delta;
      } else if (g2 === max) {
        h3 = 2 + (b2 - r5) / delta;
      } else if (b2 === max) {
        h3 = 4 + (r5 - g2) / delta;
      }
      h3 = Math.min(h3 * 60, 360);
      if (h3 < 0) {
        h3 += 360;
      }
      const l3 = (min + max) / 2;
      if (max === min) {
        s5 = 0;
      } else if (l3 <= 0.5) {
        s5 = delta / (max + min);
      } else {
        s5 = delta / (2 - max - min);
      }
      return [h3, s5 * 100, l3 * 100];
    };
    convert2.rgb.hsv = function(rgb) {
      let rdif;
      let gdif;
      let bdif;
      let h3;
      let s5;
      const r5 = rgb[0] / 255;
      const g2 = rgb[1] / 255;
      const b2 = rgb[2] / 255;
      const v2 = Math.max(r5, g2, b2);
      const diff4 = v2 - Math.min(r5, g2, b2);
      const diffc = /* @__PURE__ */ __name(function(c4) {
        return (v2 - c4) / 6 / diff4 + 1 / 2;
      }, "diffc");
      if (diff4 === 0) {
        h3 = 0;
        s5 = 0;
      } else {
        s5 = diff4 / v2;
        rdif = diffc(r5);
        gdif = diffc(g2);
        bdif = diffc(b2);
        if (r5 === v2) {
          h3 = bdif - gdif;
        } else if (g2 === v2) {
          h3 = 1 / 3 + rdif - bdif;
        } else if (b2 === v2) {
          h3 = 2 / 3 + gdif - rdif;
        }
        if (h3 < 0) {
          h3 += 1;
        } else if (h3 > 1) {
          h3 -= 1;
        }
      }
      return [
        h3 * 360,
        s5 * 100,
        v2 * 100
      ];
    };
    convert2.rgb.hwb = function(rgb) {
      const r5 = rgb[0];
      const g2 = rgb[1];
      let b2 = rgb[2];
      const h3 = convert2.rgb.hsl(rgb)[0];
      const w2 = 1 / 255 * Math.min(r5, Math.min(g2, b2));
      b2 = 1 - 1 / 255 * Math.max(r5, Math.max(g2, b2));
      return [h3, w2 * 100, b2 * 100];
    };
    convert2.rgb.cmyk = function(rgb) {
      const r5 = rgb[0] / 255;
      const g2 = rgb[1] / 255;
      const b2 = rgb[2] / 255;
      const k2 = Math.min(1 - r5, 1 - g2, 1 - b2);
      const c4 = (1 - r5 - k2) / (1 - k2) || 0;
      const m3 = (1 - g2 - k2) / (1 - k2) || 0;
      const y2 = (1 - b2 - k2) / (1 - k2) || 0;
      return [c4 * 100, m3 * 100, y2 * 100, k2 * 100];
    };
    function comparativeDistance(x3, y2) {
      return (x3[0] - y2[0]) ** 2 + (x3[1] - y2[1]) ** 2 + (x3[2] - y2[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 r5 = rgb[0] / 255;
      let g2 = rgb[1] / 255;
      let b2 = rgb[2] / 255;
      r5 = r5 > 0.04045 ? ((r5 + 0.055) / 1.055) ** 2.4 : r5 / 12.92;
      g2 = g2 > 0.04045 ? ((g2 + 0.055) / 1.055) ** 2.4 : g2 / 12.92;
      b2 = b2 > 0.04045 ? ((b2 + 0.055) / 1.055) ** 2.4 : b2 / 12.92;
      const x3 = r5 * 0.4124 + g2 * 0.3576 + b2 * 0.1805;
      const y2 = r5 * 0.2126 + g2 * 0.7152 + b2 * 0.0722;
      const z2 = r5 * 0.0193 + g2 * 0.1192 + b2 * 0.9505;
      return [x3 * 100, y2 * 100, z2 * 100];
    };
    convert2.rgb.lab = function(rgb) {
      const xyz = convert2.rgb.xyz(rgb);
      let x3 = xyz[0];
      let y2 = xyz[1];
      let z2 = xyz[2];
      x3 /= 95.047;
      y2 /= 100;
      z2 /= 108.883;
      x3 = x3 > 8856e-6 ? x3 ** (1 / 3) : 7.787 * x3 + 16 / 116;
      y2 = y2 > 8856e-6 ? y2 ** (1 / 3) : 7.787 * y2 + 16 / 116;
      z2 = z2 > 8856e-6 ? z2 ** (1 / 3) : 7.787 * z2 + 16 / 116;
      const l3 = 116 * y2 - 16;
      const a2 = 500 * (x3 - y2);
      const b2 = 200 * (y2 - z2);
      return [l3, a2, b2];
    };
    convert2.hsl.rgb = function(hsl) {
      const h3 = hsl[0] / 360;
      const s5 = hsl[1] / 100;
      const l3 = hsl[2] / 100;
      let t22;
      let t32;
      let val;
      if (s5 === 0) {
        val = l3 * 255;
        return [val, val, val];
      }
      if (l3 < 0.5) {
        t22 = l3 * (1 + s5);
      } else {
        t22 = l3 + s5 - l3 * s5;
      }
      const t1 = 2 * l3 - t22;
      const rgb = [0, 0, 0];
      for (let i3 = 0; i3 < 3; i3++) {
        t32 = h3 + 1 / 3 * -(i3 - 1);
        if (t32 < 0) {
          t32++;
        }
        if (t32 > 1) {
          t32--;
        }
        if (6 * t32 < 1) {
          val = t1 + (t22 - t1) * 6 * t32;
        } else if (2 * t32 < 1) {
          val = t22;
        } else if (3 * t32 < 2) {
          val = t1 + (t22 - t1) * (2 / 3 - t32) * 6;
        } else {
          val = t1;
        }
        rgb[i3] = val * 255;
      }
      return rgb;
    };
    convert2.hsl.hsv = function(hsl) {
      const h3 = hsl[0];
      let s5 = hsl[1] / 100;
      let l3 = hsl[2] / 100;
      let smin = s5;
      const lmin = Math.max(l3, 0.01);
      l3 *= 2;
      s5 *= l3 <= 1 ? l3 : 2 - l3;
      smin *= lmin <= 1 ? lmin : 2 - lmin;
      const v2 = (l3 + s5) / 2;
      const sv = l3 === 0 ? 2 * smin / (lmin + smin) : 2 * s5 / (l3 + s5);
      return [h3, sv * 100, v2 * 100];
    };
    convert2.hsv.rgb = function(hsv) {
      const h3 = hsv[0] / 60;
      const s5 = hsv[1] / 100;
      let v2 = hsv[2] / 100;
      const hi = Math.floor(h3) % 6;
      const f5 = h3 - Math.floor(h3);
      const p2 = 255 * v2 * (1 - s5);
      const q2 = 255 * v2 * (1 - s5 * f5);
      const t5 = 255 * v2 * (1 - s5 * (1 - f5));
      v2 *= 255;
      switch (hi) {
        case 0:
          return [v2, t5, p2];
        case 1:
          return [q2, v2, p2];
        case 2:
          return [p2, v2, t5];
        case 3:
          return [p2, q2, v2];
        case 4:
          return [t5, p2, v2];
        case 5:
          return [v2, p2, q2];
      }
    };
    convert2.hsv.hsl = function(hsv) {
      const h3 = hsv[0];
      const s5 = hsv[1] / 100;
      const v2 = hsv[2] / 100;
      const vmin = Math.max(v2, 0.01);
      let sl;
      let l3;
      l3 = (2 - s5) * v2;
      const lmin = (2 - s5) * vmin;
      sl = s5 * vmin;
      sl /= lmin <= 1 ? lmin : 2 - lmin;
      sl = sl || 0;
      l3 /= 2;
      return [h3, sl * 100, l3 * 100];
    };
    convert2.hwb.rgb = function(hwb) {
      const h3 = hwb[0] / 360;
      let wh = hwb[1] / 100;
      let bl = hwb[2] / 100;
      const ratio = wh + bl;
      let f5;
      if (ratio > 1) {
        wh /= ratio;
        bl /= ratio;
      }
      const i3 = Math.floor(6 * h3);
      const v2 = 1 - bl;
      f5 = 6 * h3 - i3;
      if ((i3 & 1) !== 0) {
        f5 = 1 - f5;
      }
      const n3 = wh + f5 * (v2 - wh);
      let r5;
      let g2;
      let b2;
      switch (i3) {
        default:
        case 6:
        case 0:
          r5 = v2;
          g2 = n3;
          b2 = wh;
          break;
        case 1:
          r5 = n3;
          g2 = v2;
          b2 = wh;
          break;
        case 2:
          r5 = wh;
          g2 = v2;
          b2 = n3;
          break;
        case 3:
          r5 = wh;
          g2 = n3;
          b2 = v2;
          break;
        case 4:
          r5 = n3;
          g2 = wh;
          b2 = v2;
          break;
        case 5:
          r5 = v2;
          g2 = wh;
          b2 = n3;
          break;
      }
      return [r5 * 255, g2 * 255, b2 * 255];
    };
    convert2.cmyk.rgb = function(cmyk) {
      const c4 = cmyk[0] / 100;
      const m3 = cmyk[1] / 100;
      const y2 = cmyk[2] / 100;
      const k2 = cmyk[3] / 100;
      const r5 = 1 - Math.min(1, c4 * (1 - k2) + k2);
      const g2 = 1 - Math.min(1, m3 * (1 - k2) + k2);
      const b2 = 1 - Math.min(1, y2 * (1 - k2) + k2);
      return [r5 * 255, g2 * 255, b2 * 255];
    };
    convert2.xyz.rgb = function(xyz) {
      const x3 = xyz[0] / 100;
      const y2 = xyz[1] / 100;
      const z2 = xyz[2] / 100;
      let r5;
      let g2;
      let b2;
      r5 = x3 * 3.2406 + y2 * -1.5372 + z2 * -0.4986;
      g2 = x3 * -0.9689 + y2 * 1.8758 + z2 * 0.0415;
      b2 = x3 * 0.0557 + y2 * -0.204 + z2 * 1.057;
      r5 = r5 > 31308e-7 ? 1.055 * r5 ** (1 / 2.4) - 0.055 : r5 * 12.92;
      g2 = g2 > 31308e-7 ? 1.055 * g2 ** (1 / 2.4) - 0.055 : g2 * 12.92;
      b2 = b2 > 31308e-7 ? 1.055 * b2 ** (1 / 2.4) - 0.055 : b2 * 12.92;
      r5 = Math.min(Math.max(0, r5), 1);
      g2 = Math.min(Math.max(0, g2), 1);
      b2 = Math.min(Math.max(0, b2), 1);
      return [r5 * 255, g2 * 255, b2 * 255];
    };
    convert2.xyz.lab = function(xyz) {
      let x3 = xyz[0];
      let y2 = xyz[1];
      let z2 = xyz[2];
      x3 /= 95.047;
      y2 /= 100;
      z2 /= 108.883;
      x3 = x3 > 8856e-6 ? x3 ** (1 / 3) : 7.787 * x3 + 16 / 116;
      y2 = y2 > 8856e-6 ? y2 ** (1 / 3) : 7.787 * y2 + 16 / 116;
      z2 = z2 > 8856e-6 ? z2 ** (1 / 3) : 7.787 * z2 + 16 / 116;
      const l3 = 116 * y2 - 16;
      const a2 = 500 * (x3 - y2);
      const b2 = 200 * (y2 - z2);
      return [l3, a2, b2];
    };
    convert2.lab.xyz = function(lab) {
      const l3 = lab[0];
      const a2 = lab[1];
      const b2 = lab[2];
      let x3;
      let y2;
      let z2;
      y2 = (l3 + 16) / 116;
      x3 = a2 / 500 + y2;
      z2 = y2 - b2 / 200;
      const y22 = y2 ** 3;
      const x22 = x3 ** 3;
      const z22 = z2 ** 3;
      y2 = y22 > 8856e-6 ? y22 : (y2 - 16 / 116) / 7.787;
      x3 = x22 > 8856e-6 ? x22 : (x3 - 16 / 116) / 7.787;
      z2 = z22 > 8856e-6 ? z22 : (z2 - 16 / 116) / 7.787;
      x3 *= 95.047;
      y2 *= 100;
      z2 *= 108.883;
      return [x3, y2, z2];
    };
    convert2.lab.lch = function(lab) {
      const l3 = lab[0];
      const a2 = lab[1];
      const b2 = lab[2];
      let h3;
      const hr3 = Math.atan2(b2, a2);
      h3 = hr3 * 360 / 2 / Math.PI;
      if (h3 < 0) {
        h3 += 360;
      }
      const c4 = Math.sqrt(a2 * a2 + b2 * b2);
      return [l3, c4, h3];
    };
    convert2.lch.lab = function(lch) {
      const l3 = lch[0];
      const c4 = lch[1];
      const h3 = lch[2];
      const hr3 = h3 / 360 * 2 * Math.PI;
      const a2 = c4 * Math.cos(hr3);
      const b2 = c4 * Math.sin(hr3);
      return [l3, a2, b2];
    };
    convert2.rgb.ansi16 = function(args, saturation = null) {
      const [r5, g2, b2] = 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(b2 / 255) << 2 | Math.round(g2 / 255) << 1 | Math.round(r5 / 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 r5 = args[0];
      const g2 = args[1];
      const b2 = args[2];
      if (r5 === g2 && g2 === b2) {
        if (r5 < 8) {
          return 16;
        }
        if (r5 > 248) {
          return 231;
        }
        return Math.round((r5 - 8) / 247 * 24) + 232;
      }
      const ansi2 = 16 + 36 * Math.round(r5 / 255 * 5) + 6 * Math.round(g2 / 255 * 5) + Math.round(b2 / 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 r5 = (color & 1) * mult * 255;
      const g2 = (color >> 1 & 1) * mult * 255;
      const b2 = (color >> 2 & 1) * mult * 255;
      return [r5, g2, b2];
    };
    convert2.ansi256.rgb = function(args) {
      if (args >= 232) {
        const c4 = (args - 232) * 10 + 8;
        return [c4, c4, c4];
      }
      args -= 16;
      let rem;
      const r5 = Math.floor(args / 36) / 5 * 255;
      const g2 = Math.floor((rem = args % 36) / 6) / 5 * 255;
      const b2 = rem % 6 / 5 * 255;
      return [r5, g2, b2];
    };
    convert2.rgb.hex = function(args) {
      const integer2 = ((Math.round(args[0]) & 255) << 16) + ((Math.round(args[1]) & 255) << 8) + (Math.round(args[2]) & 255);
      const string4 = integer2.toString(16).toUpperCase();
      return "000000".substring(string4.length) + string4;
    };
    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 integer2 = parseInt(colorString, 16);
      const r5 = integer2 >> 16 & 255;
      const g2 = integer2 >> 8 & 255;
      const b2 = integer2 & 255;
      return [r5, g2, b2];
    };
    convert2.rgb.hcg = function(rgb) {
      const r5 = rgb[0] / 255;
      const g2 = rgb[1] / 255;
      const b2 = rgb[2] / 255;
      const max = Math.max(Math.max(r5, g2), b2);
      const min = Math.min(Math.min(r5, g2), b2);
      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 === r5) {
        hue = (g2 - b2) / chroma % 6;
      } else if (max === g2) {
        hue = 2 + (b2 - r5) / chroma;
      } else {
        hue = 4 + (r5 - g2) / chroma;
      }
      hue /= 6;
      hue %= 1;
      return [hue * 360, chroma * 100, grayscale * 100];
    };
    convert2.hsl.hcg = function(hsl) {
      const s5 = hsl[1] / 100;
      const l3 = hsl[2] / 100;
      const c4 = l3 < 0.5 ? 2 * s5 * l3 : 2 * s5 * (1 - l3);
      let f5 = 0;
      if (c4 < 1) {
        f5 = (l3 - 0.5 * c4) / (1 - c4);
      }
      return [hsl[0], c4 * 100, f5 * 100];
    };
    convert2.hsv.hcg = function(hsv) {
      const s5 = hsv[1] / 100;
      const v2 = hsv[2] / 100;
      const c4 = s5 * v2;
      let f5 = 0;
      if (c4 < 1) {
        f5 = (v2 - c4) / (1 - c4);
      }
      return [hsv[0], c4 * 100, f5 * 100];
    };
    convert2.hcg.rgb = function(hcg) {
      const h3 = hcg[0] / 360;
      const c4 = hcg[1] / 100;
      const g2 = hcg[2] / 100;
      if (c4 === 0) {
        return [g2 * 255, g2 * 255, g2 * 255];
      }
      const pure = [0, 0, 0];
      const hi = h3 % 1 * 6;
      const v2 = hi % 1;
      const w2 = 1 - v2;
      let mg = 0;
      switch (Math.floor(hi)) {
        case 0:
          pure[0] = 1;
          pure[1] = v2;
          pure[2] = 0;
          break;
        case 1:
          pure[0] = w2;
          pure[1] = 1;
          pure[2] = 0;
          break;
        case 2:
          pure[0] = 0;
          pure[1] = 1;
          pure[2] = v2;
          break;
        case 3:
          pure[0] = 0;
          pure[1] = w2;
          pure[2] = 1;
          break;
        case 4:
          pure[0] = v2;
          pure[1] = 0;
          pure[2] = 1;
          break;
        default:
          pure[0] = 1;
          pure[1] = 0;
          pure[2] = w2;
      }
      mg = (1 - c4) * g2;
      return [
        (c4 * pure[0] + mg) * 255,
        (c4 * pure[1] + mg) * 255,
        (c4 * pure[2] + mg) * 255
      ];
    };
    convert2.hcg.hsv = function(hcg) {
      const c4 = hcg[1] / 100;
      const g2 = hcg[2] / 100;
      const v2 = c4 + g2 * (1 - c4);
      let f5 = 0;
      if (v2 > 0) {
        f5 = c4 / v2;
      }
      return [hcg[0], f5 * 100, v2 * 100];
    };
    convert2.hcg.hsl = function(hcg) {
      const c4 = hcg[1] / 100;
      const g2 = hcg[2] / 100;
      const l3 = g2 * (1 - c4) + 0.5 * c4;
      let s5 = 0;
      if (l3 > 0 && l3 < 0.5) {
        s5 = c4 / (2 * l3);
      } else if (l3 >= 0.5 && l3 < 1) {
        s5 = c4 / (2 * (1 - l3));
      }
      return [hcg[0], s5 * 100, l3 * 100];
    };
    convert2.hcg.hwb = function(hcg) {
      const c4 = hcg[1] / 100;
      const g2 = hcg[2] / 100;
      const v2 = c4 + g2 * (1 - c4);
      return [hcg[0], (v2 - c4) * 100, (1 - v2) * 100];
    };
    convert2.hwb.hcg = function(hwb) {
      const w2 = hwb[1] / 100;
      const b2 = hwb[2] / 100;
      const v2 = 1 - b2;
      const c4 = v2 - w2;
      let g2 = 0;
      if (c4 < 1) {
        g2 = (v2 - c4) / (1 - c4);
      }
      return [hwb[0], c4 * 100, g2 * 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 integer2 = (val << 16) + (val << 8) + val;
      const string4 = integer2.toString(16).toUpperCase();
      return "000000".substring(string4.length) + string4;
    };
    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, i3 = 0; i3 < len; i3++) {
        graph[models[i3]] = {
          // 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, i3 = 0; i3 < len; i3++) {
          const adjacent = adjacents[i3];
          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 path125 = [graph[toModel].parent, toModel];
      let fn = conversions[graph[toModel].parent][toModel];
      let cur = graph[toModel].parent;
      while (graph[cur].parent) {
        path125.unshift(graph[cur].parent);
        fn = link3(conversions[graph[cur].parent][cur], fn);
        cur = graph[cur].parent;
      }
      fn.conversion = path125;
      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, i3 = 0; i3 < len; i3++) {
        const toModel = models[i3];
        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, i3 = 0; i3 < len; i3++) {
            result[i3] = Math.round(result[i3]);
          }
        }
        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((n3) => n3, "ansi2ansi");
    var rgb2rgb = /* @__PURE__ */ __name((r5, g2, b2) => [r5, g2, b2], "rgb2rgb");
    var setLazyProperty = /* @__PURE__ */ __name((object3, property, get4) => {
      Object.defineProperty(object3, property, {
        get: /* @__PURE__ */ __name(() => {
          const value = get4();
          Object.defineProperty(object3, 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 os47 = __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 = os47.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_util20 = __commonJS({
  "node_modules/chalk/source/util.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var stringReplaceAll3 = /* @__PURE__ */ __name((string4, substring, replacer) => {
      let index = string4.indexOf(substring);
      if (index === -1) {
        return string4;
      }
      const substringLength = substring.length;
      let endIndex = 0;
      let returnValue = "";
      do {
        returnValue += string4.substr(endIndex, index - endIndex) + substring + replacer;
        endIndex = index + substringLength;
        index = string4.indexOf(substring, endIndex);
      } while (index !== -1);
      returnValue += string4.substr(endIndex);
      return returnValue;
    }, "stringReplaceAll");
    var stringEncaseCRLFWithFirstIndex3 = /* @__PURE__ */ __name((string4, prefix, postfix, index) => {
      let endIndex = 0;
      let returnValue = "";
      do {
        const gotCR = string4[index - 1] === "\r";
        returnValue += string4.substr(endIndex, (gotCR ? index - 1 : index) - endIndex) + prefix + (gotCR ? "\r\n" : "\n") + postfix;
        endIndex = index + 1;
        index = string4.indexOf("\n", endIndex);
      } while (index !== -1);
      returnValue += string4.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(c4) {
      const u2 = c4[0] === "u";
      const bracket = c4[1] === "{";
      if (u2 && !bracket && c4.length === 5 || c4[0] === "x" && c4.length === 3) {
        return String.fromCharCode(parseInt(c4.slice(1), 16));
      }
      if (u2 && bracket) {
        return String.fromCodePoint(parseInt(c4.slice(2, -1), 16));
      }
      return ESCAPES5.get(c4) || c4;
    }
    __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 number4 = Number(chunk);
        if (!Number.isNaN(number4)) {
          results.push(number4);
        } else if (matches = chunk.match(STRING_REGEX)) {
          results.push(matches[2].replace(ESCAPE_REGEX, (m3, 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(chalk9, styles10) {
      const enabled = {};
      for (const layer2 of styles10) {
        for (const style of layer2.styles) {
          enabled[style[0]] = layer2.inverse ? null : style.slice(1);
        }
      }
      let current = chalk9;
      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 = (chalk9, temporary) => {
      const styles10 = [];
      const chunks = [];
      let chunk = [];
      temporary.replace(TEMPLATE_REGEX, (m3, escapeCharacter, inverse, style, close, character) => {
        if (escapeCharacter) {
          chunk.push(unescape4(escapeCharacter));
        } else if (style) {
          const string4 = chunk.join("");
          chunk = [];
          chunks.push(styles10.length === 0 ? string4 : buildStyle(chalk9, styles10)(string4));
          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(chalk9, 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_util20();
    var { isArray: isArray2 } = Array;
    var levelMapping3 = [
      "ansi",
      "ansi",
      "ansi256",
      "ansi16m"
    ];
    var styles10 = /* @__PURE__ */ Object.create(null);
    var applyOptions3 = /* @__PURE__ */ __name((object3, 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;
      object3.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 chalk10 = {};
      applyOptions3(chalk10, options2);
      chalk10.template = (...arguments_) => chalkTag(chalk10.template, ...arguments_);
      Object.setPrototypeOf(chalk10, Chalk.prototype);
      Object.setPrototypeOf(chalk10.template, chalk10);
      chalk10.template.constructor = () => {
        throw new Error("`chalk.constructor()` is deprecated. Use `new chalk.Instance()` instead.");
      };
      chalk10.template.Instance = ChalkClass;
      return chalk10.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((open4, close, parent) => {
      let openAll;
      let closeAll;
      if (parent === void 0) {
        openAll = open4;
        closeAll = close;
      } else {
        openAll = parent.openAll + open4;
        closeAll = close + parent.closeAll;
      }
      return {
        open: open4,
        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, string4) => {
      if (self2.level <= 0 || !string4) {
        return self2._isEmpty ? "" : string4;
      }
      let styler = self2._styler;
      if (styler === void 0) {
        return string4;
      }
      const { openAll, closeAll } = styler;
      if (string4.indexOf("\x1B") !== -1) {
        while (styler !== void 0) {
          string4 = stringReplaceAll3(string4, styler.close, styler.open);
          styler = styler.parent;
        }
      }
      const lfIndex = string4.indexOf("\n");
      if (lfIndex !== -1) {
        string4 = stringEncaseCRLFWithFirstIndex3(string4, closeAll, openAll, lfIndex);
      }
      return openAll + string4 + closeAll;
    }, "applyStyle");
    var template;
    var chalkTag = /* @__PURE__ */ __name((chalk10, ...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 i3 = 1; i3 < firstString.length; i3++) {
        parts.push(
          String(arguments_[i3 - 1]).replace(/[{}\\]/g, "\\$&"),
          String(firstString.raw[i3])
        );
      }
      if (template === void 0) {
        template = require_templates();
      }
      return template(chalk10, parts.join(""));
    }, "chalkTag");
    Object.defineProperties(Chalk.prototype, styles10);
    var chalk9 = Chalk();
    chalk9.supportsColor = stdoutColor3;
    chalk9.stderr = Chalk({ level: stderrColor3 ? stderrColor3.level : 0 });
    chalk9.stderr.supportsColor = stderrColor3;
    module2.exports = chalk9;
  }
});

// node_modules/picocolors/picocolors.js
var require_picocolors = __commonJS({
  "node_modules/picocolors/picocolors.js"(exports2, module2) {
    init_esbuild_shims();
    var p2 = process || {};
    var argv = p2.argv || [];
    var env7 = p2.env || {};
    var isColorSupported = !(!!env7.NO_COLOR || argv.includes("--no-color")) && (!!env7.FORCE_COLOR || argv.includes("--color") || p2.platform === "win32" || (p2.stdout || {}).isTTY && env7.TERM !== "dumb" || !!env7.CI);
    var formatter = /* @__PURE__ */ __name((open4, close, replace2 = open4) => (input) => {
      let string4 = "" + input, index = string4.indexOf(close, open4.length);
      return ~index ? open4 + replaceClose(string4, close, replace2, index) + close : open4 + string4 + close;
    }, "formatter");
    var replaceClose = /* @__PURE__ */ __name((string4, close, replace2, index) => {
      let result = "", cursor = 0;
      do {
        result += string4.substring(cursor, index) + replace2;
        cursor = index + close.length;
        index = string4.indexOf(close, cursor);
      } while (~index);
      return result + string4.substring(cursor);
    }, "replaceClose");
    var createColors = /* @__PURE__ */ __name((enabled = isColorSupported) => {
      let f5 = enabled ? formatter : () => String;
      return {
        isColorSupported: enabled,
        reset: f5("\x1B[0m", "\x1B[0m"),
        bold: f5("\x1B[1m", "\x1B[22m", "\x1B[22m\x1B[1m"),
        dim: f5("\x1B[2m", "\x1B[22m", "\x1B[22m\x1B[2m"),
        italic: f5("\x1B[3m", "\x1B[23m"),
        underline: f5("\x1B[4m", "\x1B[24m"),
        inverse: f5("\x1B[7m", "\x1B[27m"),
        hidden: f5("\x1B[8m", "\x1B[28m"),
        strikethrough: f5("\x1B[9m", "\x1B[29m"),
        black: f5("\x1B[30m", "\x1B[39m"),
        red: f5("\x1B[31m", "\x1B[39m"),
        green: f5("\x1B[32m", "\x1B[39m"),
        yellow: f5("\x1B[33m", "\x1B[39m"),
        blue: f5("\x1B[34m", "\x1B[39m"),
        magenta: f5("\x1B[35m", "\x1B[39m"),
        cyan: f5("\x1B[36m", "\x1B[39m"),
        white: f5("\x1B[37m", "\x1B[39m"),
        gray: f5("\x1B[90m", "\x1B[39m"),
        bgBlack: f5("\x1B[40m", "\x1B[49m"),
        bgRed: f5("\x1B[41m", "\x1B[49m"),
        bgGreen: f5("\x1B[42m", "\x1B[49m"),
        bgYellow: f5("\x1B[43m", "\x1B[49m"),
        bgBlue: f5("\x1B[44m", "\x1B[49m"),
        bgMagenta: f5("\x1B[45m", "\x1B[49m"),
        bgCyan: f5("\x1B[46m", "\x1B[49m"),
        bgWhite: f5("\x1B[47m", "\x1B[49m"),
        blackBright: f5("\x1B[90m", "\x1B[39m"),
        redBright: f5("\x1B[91m", "\x1B[39m"),
        greenBright: f5("\x1B[92m", "\x1B[39m"),
        yellowBright: f5("\x1B[93m", "\x1B[39m"),
        blueBright: f5("\x1B[94m", "\x1B[39m"),
        magentaBright: f5("\x1B[95m", "\x1B[39m"),
        cyanBright: f5("\x1B[96m", "\x1B[39m"),
        whiteBright: f5("\x1B[97m", "\x1B[39m"),
        bgBlackBright: f5("\x1B[100m", "\x1B[49m"),
        bgRedBright: f5("\x1B[101m", "\x1B[49m"),
        bgGreenBright: f5("\x1B[102m", "\x1B[49m"),
        bgYellowBright: f5("\x1B[103m", "\x1B[49m"),
        bgBlueBright: f5("\x1B[104m", "\x1B[49m"),
        bgMagentaBright: f5("\x1B[105m", "\x1B[49m"),
        bgCyanBright: f5("\x1B[106m", "\x1B[49m"),
        bgWhiteBright: f5("\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-\u088F\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\u0C5C\u0C5D\u0C60\u0C61\u0C80\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDC-\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-\uA7DC\uA7F1-\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-\u1ADD\u1AE0-\u1AEB\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, 7, 25, 39, 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, 5, 57, 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, 24, 43, 261, 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, 33, 24, 3, 24, 45, 74, 6, 0, 67, 12, 65, 1, 2, 0, 15, 4, 10, 7381, 42, 31, 98, 114, 8702, 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, 208, 30, 2, 2, 2, 1, 2, 6, 3, 4, 10, 1, 225, 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, 4381, 3, 5773, 3, 7472, 16, 621, 2467, 541, 1507, 4938, 6, 8489];
    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, 78, 5, 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, 199, 7, 137, 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, 55, 9, 266, 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, 233, 0, 3, 0, 8, 1, 6, 0, 475, 6, 110, 6, 6, 9, 4759, 9, 787719, 239];
    function isInAstralSet(code2, set) {
      let pos2 = 65536;
      for (let i3 = 0, length = set.length; i3 < length; i3 += 2) {
        pos2 += set[i3];
        if (pos2 > code2) return false;
        pos2 += set[i3 + 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 i3 = 0; i3 < name3.length; i3++) {
        let cp3 = name3.charCodeAt(i3);
        if ((cp3 & 64512) === 55296 && i3 + 1 < name3.length) {
          const trail = name3.charCodeAt(++i3);
          if ((trail & 64512) === 56320) {
            cp3 = 65536 + ((cp3 & 1023) << 10) + (trail & 1023);
          }
        }
        if (isFirst) {
          isFirst = false;
          if (!isIdentifierStart(cp3)) {
            return false;
          }
        } else if (!isIdentifierChar(cp3)) {
          return false;
        }
      }
      return !isFirst;
    }
    __name(isIdentifierName, "isIdentifierName");
  }
});

// node_modules/@babel/helper-validator-identifier/lib/keyword.js
var require_keyword3 = __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_lib5 = __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_keyword3();
  }
});

// node_modules/@babel/code-frame/lib/index.js
var require_lib6 = __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_lib5();
    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((f5, g2) => (v2) => f5(g2(v2)), "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 tokenize5;
    var JSX_TAG = /^[a-z][\w-]*$/i;
    var getTokenType = /* @__PURE__ */ __name(function(token2, offset, text) {
      if (token2.type === "name") {
        const tokenValue = token2.value;
        if (helperValidatorIdentifier.isKeyword(tokenValue) || helperValidatorIdentifier.isStrictReservedWord(tokenValue, true) || sometimesKeywords.has(tokenValue)) {
          return "keyword";
        }
        if (JSX_TAG.test(tokenValue) && (text[offset - 1] === "<" || text.slice(offset - 2, offset) === "</")) {
          return "jsxIdentifier";
        }
        const firstChar = String.fromCodePoint(tokenValue.codePointAt(0));
        if (firstChar !== firstChar.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");
    tokenize5 = /* @__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 tokenize5(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 i3 = 0; i3 <= lineDiff2; i3++) {
          const lineNumber = i3 + startLine;
          if (!startColumn) {
            markerLines[lineNumber] = true;
          } else if (i3 === 0) {
            const sourceLength = source2[lineNumber - 1].length;
            markerLines[lineNumber] = [startColumn, sourceLength - startColumn + 1];
          } else if (i3 === lineDiff2) {
            markerLines[lineNumber] = [0, endColumn];
          } else {
            const sourceLength = source2[lineNumber - i3].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 number4 = start + 1 + index2;
        const paddedNumber = ` ${number4}`.slice(-numberMaxWidth);
        const gutter = ` ${paddedNumber} |`;
        const hasMarker = markerLines[number4];
        const lastMarkerLine = !markerLines[number4 + 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 debug3 = typeof process === "object" && process.env && process.env.NODE_DEBUG && /\bsemver\b/i.test(process.env.NODE_DEBUG) ? (...args) => console.error("SEMVER", ...args) : () => {
    };
    module2.exports = debug3;
  }
});

// node_modules/semver/internal/constants.js
var require_constants13 = __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_constants13();
    var debug3 = require_debug();
    exports2 = module2.exports = {};
    var re3 = exports2.re = [];
    var safeRe = exports2.safeRe = [];
    var src = exports2.src = [];
    var safeSrc = exports2.safeSrc = [];
    var t5 = exports2.t = {};
    var R2 = 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 = R2++;
      debug3(name3, index, value);
      t5[name3] = index;
      src[index] = value;
      safeSrc[index] = safe;
      re3[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[t5.NUMERICIDENTIFIER]})\\.(${src[t5.NUMERICIDENTIFIER]})\\.(${src[t5.NUMERICIDENTIFIER]})`);
    createToken("MAINVERSIONLOOSE", `(${src[t5.NUMERICIDENTIFIERLOOSE]})\\.(${src[t5.NUMERICIDENTIFIERLOOSE]})\\.(${src[t5.NUMERICIDENTIFIERLOOSE]})`);
    createToken("PRERELEASEIDENTIFIER", `(?:${src[t5.NONNUMERICIDENTIFIER]}|${src[t5.NUMERICIDENTIFIER]})`);
    createToken("PRERELEASEIDENTIFIERLOOSE", `(?:${src[t5.NONNUMERICIDENTIFIER]}|${src[t5.NUMERICIDENTIFIERLOOSE]})`);
    createToken("PRERELEASE", `(?:-(${src[t5.PRERELEASEIDENTIFIER]}(?:\\.${src[t5.PRERELEASEIDENTIFIER]})*))`);
    createToken("PRERELEASELOOSE", `(?:-?(${src[t5.PRERELEASEIDENTIFIERLOOSE]}(?:\\.${src[t5.PRERELEASEIDENTIFIERLOOSE]})*))`);
    createToken("BUILDIDENTIFIER", `${LETTERDASHNUMBER}+`);
    createToken("BUILD", `(?:\\+(${src[t5.BUILDIDENTIFIER]}(?:\\.${src[t5.BUILDIDENTIFIER]})*))`);
    createToken("FULLPLAIN", `v?${src[t5.MAINVERSION]}${src[t5.PRERELEASE]}?${src[t5.BUILD]}?`);
    createToken("FULL", `^${src[t5.FULLPLAIN]}$`);
    createToken("LOOSEPLAIN", `[v=\\s]*${src[t5.MAINVERSIONLOOSE]}${src[t5.PRERELEASELOOSE]}?${src[t5.BUILD]}?`);
    createToken("LOOSE", `^${src[t5.LOOSEPLAIN]}$`);
    createToken("GTLT", "((?:<|>)?=?)");
    createToken("XRANGEIDENTIFIERLOOSE", `${src[t5.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`);
    createToken("XRANGEIDENTIFIER", `${src[t5.NUMERICIDENTIFIER]}|x|X|\\*`);
    createToken("XRANGEPLAIN", `[v=\\s]*(${src[t5.XRANGEIDENTIFIER]})(?:\\.(${src[t5.XRANGEIDENTIFIER]})(?:\\.(${src[t5.XRANGEIDENTIFIER]})(?:${src[t5.PRERELEASE]})?${src[t5.BUILD]}?)?)?`);
    createToken("XRANGEPLAINLOOSE", `[v=\\s]*(${src[t5.XRANGEIDENTIFIERLOOSE]})(?:\\.(${src[t5.XRANGEIDENTIFIERLOOSE]})(?:\\.(${src[t5.XRANGEIDENTIFIERLOOSE]})(?:${src[t5.PRERELEASELOOSE]})?${src[t5.BUILD]}?)?)?`);
    createToken("XRANGE", `^${src[t5.GTLT]}\\s*${src[t5.XRANGEPLAIN]}$`);
    createToken("XRANGELOOSE", `^${src[t5.GTLT]}\\s*${src[t5.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[t5.COERCEPLAIN]}(?:$|[^\\d])`);
    createToken("COERCEFULL", src[t5.COERCEPLAIN] + `(?:${src[t5.PRERELEASE]})?(?:${src[t5.BUILD]})?(?:$|[^\\d])`);
    createToken("COERCERTL", src[t5.COERCE], true);
    createToken("COERCERTLFULL", src[t5.COERCEFULL], true);
    createToken("LONETILDE", "(?:~>?)");
    createToken("TILDETRIM", `(\\s*)${src[t5.LONETILDE]}\\s+`, true);
    exports2.tildeTrimReplace = "$1~";
    createToken("TILDE", `^${src[t5.LONETILDE]}${src[t5.XRANGEPLAIN]}$`);
    createToken("TILDELOOSE", `^${src[t5.LONETILDE]}${src[t5.XRANGEPLAINLOOSE]}$`);
    createToken("LONECARET", "(?:\\^)");
    createToken("CARETTRIM", `(\\s*)${src[t5.LONECARET]}\\s+`, true);
    exports2.caretTrimReplace = "$1^";
    createToken("CARET", `^${src[t5.LONECARET]}${src[t5.XRANGEPLAIN]}$`);
    createToken("CARETLOOSE", `^${src[t5.LONECARET]}${src[t5.XRANGEPLAINLOOSE]}$`);
    createToken("COMPARATORLOOSE", `^${src[t5.GTLT]}\\s*(${src[t5.LOOSEPLAIN]})$|^$`);
    createToken("COMPARATOR", `^${src[t5.GTLT]}\\s*(${src[t5.FULLPLAIN]})$|^$`);
    createToken("COMPARATORTRIM", `(\\s*)${src[t5.GTLT]}\\s*(${src[t5.LOOSEPLAIN]}|${src[t5.XRANGEPLAIN]})`, true);
    exports2.comparatorTrimReplace = "$1$2$3";
    createToken("HYPHENRANGE", `^\\s*(${src[t5.XRANGEPLAIN]})\\s+-\\s+(${src[t5.XRANGEPLAIN]})\\s*$`);
    createToken("HYPHENRANGELOOSE", `^\\s*(${src[t5.XRANGEPLAINLOOSE]})\\s+-\\s+(${src[t5.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((a2, b2) => {
      if (typeof a2 === "number" && typeof b2 === "number") {
        return a2 === b2 ? 0 : a2 < b2 ? -1 : 1;
      }
      const anum = numeric.test(a2);
      const bnum = numeric.test(b2);
      if (anum && bnum) {
        a2 = +a2;
        b2 = +b2;
      }
      return a2 === b2 ? 0 : anum && !bnum ? -1 : bnum && !anum ? 1 : a2 < b2 ? -1 : 1;
    }, "compareIdentifiers");
    var rcompareIdentifiers = /* @__PURE__ */ __name((a2, b2) => compareIdentifiers(b2, a2), "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 debug3 = require_debug();
    var { MAX_LENGTH, MAX_SAFE_INTEGER } = require_constants13();
    var { safeRe: re3, t: t5 } = 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`
          );
        }
        debug3("SemVer", version2, options2);
        this.options = options2;
        this.loose = !!options2.loose;
        this.includePrerelease = !!options2.includePrerelease;
        const m3 = version2.trim().match(options2.loose ? re3[t5.LOOSE] : re3[t5.FULL]);
        if (!m3) {
          throw new TypeError(`Invalid Version: ${version2}`);
        }
        this.raw = version2;
        this.major = +m3[1];
        this.minor = +m3[2];
        this.patch = +m3[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 (!m3[4]) {
          this.prerelease = [];
        } else {
          this.prerelease = m3[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 = m3[5] ? m3[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) {
        debug3("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);
        }
        if (this.major < other2.major) {
          return -1;
        }
        if (this.major > other2.major) {
          return 1;
        }
        if (this.minor < other2.minor) {
          return -1;
        }
        if (this.minor > other2.minor) {
          return 1;
        }
        if (this.patch < other2.patch) {
          return -1;
        }
        if (this.patch > other2.patch) {
          return 1;
        }
        return 0;
      }
      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 i3 = 0;
        do {
          const a2 = this.prerelease[i3];
          const b2 = other2.prerelease[i3];
          debug3("prerelease compare", i3, a2, b2);
          if (a2 === void 0 && b2 === void 0) {
            return 0;
          } else if (b2 === void 0) {
            return 1;
          } else if (a2 === void 0) {
            return -1;
          } else if (a2 === b2) {
            continue;
          } else {
            return compareIdentifiers(a2, b2);
          }
        } while (++i3);
      }
      compareBuild(other2) {
        if (!(other2 instanceof _SemVer)) {
          other2 = new _SemVer(other2, this.options);
        }
        let i3 = 0;
        do {
          const a2 = this.build[i3];
          const b2 = other2.build[i3];
          debug3("build compare", i3, a2, b2);
          if (a2 === void 0 && b2 === void 0) {
            return 0;
          } else if (b2 === void 0) {
            return 1;
          } else if (a2 === void 0) {
            return -1;
          } else if (a2 === b2) {
            continue;
          } else {
            return compareIdentifiers(a2, b2);
          }
        } while (++i3);
      }
      // 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 ? re3[t5.PRERELEASELOOSE] : re3[t5.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 i3 = this.prerelease.length;
              while (--i3 >= 0) {
                if (typeof this.prerelease[i3] === "number") {
                  this.prerelease[i3]++;
                  i3 = -2;
                }
              }
              if (i3 === -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_parse9 = __commonJS({
  "node_modules/semver/functions/parse.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var SemVer = require_semver2();
    var parse14 = /* @__PURE__ */ __name((version2, options2, throwErrors = false) => {
      if (version2 instanceof SemVer) {
        return version2;
      }
      try {
        return new SemVer(version2, options2);
      } catch (er2) {
        if (!throwErrors) {
          return null;
        }
        throw er2;
      }
    }, "parse");
    module2.exports = parse14;
  }
});

// node_modules/semver/functions/valid.js
var require_valid = __commonJS({
  "node_modules/semver/functions/valid.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var parse14 = require_parse9();
    var valid = /* @__PURE__ */ __name((version2, options2) => {
      const v2 = parse14(version2, options2);
      return v2 ? v2.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 parse14 = require_parse9();
    var clean = /* @__PURE__ */ __name((version2, options2) => {
      const s5 = parse14(version2.trim().replace(/^[=v]+/, ""), options2);
      return s5 ? s5.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 read3(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(read3, "read");
      function skipWhitespace() {
        read3(/[ ]*/);
      }
      __name(skipWhitespace, "skipWhitespace");
      function operator2() {
        var string4;
        var possibilities = ["WITH", "AND", "OR", "(", ")", ":", "+"];
        for (var i3 = 0; i3 < possibilities.length; i3++) {
          string4 = read3(possibilities[i3]);
          if (string4) {
            break;
          }
        }
        if (string4 === "+" && index > 1 && source2[index - 2] === " ") {
          throw new Error("Space before `+`");
        }
        return string4 && {
          type: "OPERATOR",
          string: string4
        };
      }
      __name(operator2, "operator");
      function idstring() {
        return read3(/[A-Za-z0-9-.]+/);
      }
      __name(idstring, "idstring");
      function expectIdstring() {
        var string4 = idstring();
        if (!string4) {
          throw new Error("Expected idstring at offset " + index);
        }
        return string4;
      }
      __name(expectIdstring, "expectIdstring");
      function documentRef() {
        if (read3("DocumentRef-")) {
          var string4 = expectIdstring();
          return { type: "DOCUMENTREF", string: string4 };
        }
      }
      __name(documentRef, "documentRef");
      function licenseRef() {
        if (read3("LicenseRef-")) {
          var string4 = expectIdstring();
          return { type: "LICENSEREF", string: string4 };
        }
      }
      __name(licenseRef, "licenseRef");
      function identifier2() {
        var begin = index;
        var string4 = idstring();
        if (licenses.indexOf(string4) !== -1) {
          return {
            type: "LICENSE",
            string: string4
          };
        } else if (exceptions.indexOf(string4) !== -1) {
          return {
            type: "EXCEPTION",
            string: string4
          };
        }
        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_parse10 = __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 t5 = token2();
        if (t5 && t5.type === "OPERATOR" && operator2 === t5.string) {
          next();
          return t5.string;
        }
      }
      __name(parseOperator, "parseOperator");
      function parseWith() {
        if (parseOperator("WITH")) {
          var t5 = token2();
          if (t5 && t5.type === "EXCEPTION") {
            next();
            return t5.string;
          }
          throw new Error("Expected exception after `WITH`");
        }
      }
      __name(parseWith, "parseWith");
      function parseLicenseRef() {
        var begin = index;
        var string4 = "";
        var t5 = token2();
        if (t5.type === "DOCUMENTREF") {
          next();
          string4 += "DocumentRef-" + t5.string + ":";
          if (!parseOperator(":")) {
            throw new Error("Expected `:` after `DocumentRef-...`");
          }
        }
        t5 = token2();
        if (t5.type === "LICENSEREF") {
          next();
          string4 += "LicenseRef-" + t5.string;
          return { license: string4 };
        }
        index = begin;
      }
      __name(parseLicenseRef, "parseLicenseRef");
      function parseLicense() {
        var t5 = token2();
        if (t5 && t5.type === "LICENSE") {
          next();
          var node2 = { license: t5.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 parse14 = require_parse10();
    module2.exports = function(source2) {
      return parse14(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 parse14 = require_spdx_expression_parse();
    var spdxLicenseIds = require_spdx_license_ids();
    function valid(string4) {
      try {
        parse14(string4);
        return true;
      } catch (error2) {
        return false;
      }
    }
    __name(valid, "valid");
    function sortTranspositions(a2, b2) {
      var length = b2[0].length - a2[0].length;
      if (length !== 0) return length;
      return a2[0].toUpperCase().localeCompare(b2[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 i3 = 0; i3 < transforms.length; i3++) {
        var transformed = transforms[i3](identifier2).trim();
        if (transformed !== identifier2 && valid(transformed)) {
          return transformed;
        }
      }
      return null;
    }, "validTransformation");
    var validLastResort = /* @__PURE__ */ __name(function(identifier2) {
      var upperCased = identifier2.toUpperCase();
      for (var i3 = 0; i3 < lastResorts.length; i3++) {
        var lastResort = lastResorts[i3];
        if (upperCased.indexOf(lastResort[SUBSTRING]) > -1) {
          return lastResort[IDENTIFIER2];
        }
      }
      return null;
    }, "validLastResort");
    var anyCorrection = /* @__PURE__ */ __name(function(identifier2, check2) {
      for (var i3 = 0; i3 < transpositions.length; i3++) {
        var transposition = transpositions[i3];
        var transposed = transposition[TRANSPOSED];
        if (identifier2.indexOf(transposed) > -1) {
          var corrected = identifier2.replace(
            transposed,
            transposition[CORRECT]
          );
          var checked = check2(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 parse14 = 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, string4) {
      return string4.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 = parse14(argument);
      } catch (e4) {
        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(_2, 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((n3) => n3 && n3 === Math.floor(n3) && n3 > 0 && isFinite(n3), "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 s5 = new _Stack(max, HeapCls);
        _Stack.#constructing = false;
        return s5;
      }
      constructor(max, HeapCls) {
        if (!_Stack.#constructing) {
          throw new TypeError("instantiate Stack using Stack.create(n)");
        }
        this.heap = new HeapCls(max);
        this.length = 0;
      }
      push(n3) {
        this.heap[this.length++] = n3;
      }
      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(c4) {
        return {
          // properties
          starts: c4.#starts,
          ttls: c4.#ttls,
          sizes: c4.#sizes,
          keyMap: c4.#keyMap,
          keyList: c4.#keyList,
          valList: c4.#valList,
          next: c4.#next,
          prev: c4.#prev,
          get head() {
            return c4.#head;
          },
          get tail() {
            return c4.#tail;
          },
          free: c4.#free,
          // methods
          isBackgroundFetch: /* @__PURE__ */ __name((p2) => c4.#isBackgroundFetch(p2), "isBackgroundFetch"),
          backgroundFetch: /* @__PURE__ */ __name((k2, index, options2, context2) => c4.#backgroundFetch(k2, index, options2, context2), "backgroundFetch"),
          moveToTail: /* @__PURE__ */ __name((index) => c4.#moveToTail(index), "moveToTail"),
          indexes: /* @__PURE__ */ __name((options2) => c4.#indexes(options2), "indexes"),
          rindexes: /* @__PURE__ */ __name((options2) => c4.#rindexes(options2), "rindexes"),
          isStale: /* @__PURE__ */ __name((index) => c4.#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 t5 = setTimeout(() => {
              if (this.#isStale(index)) {
                this.#delete(this.#keyList[index], "expire");
              }
            }, ttl + 1);
            if (t5.unref) {
              t5.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 n3 = perf2.now();
          if (this.ttlResolution > 0) {
            cachedNow = n3;
            const t5 = setTimeout(() => cachedNow = 0, this.ttlResolution);
            if (t5.unref) {
              t5.unref();
            }
          }
          return n3;
        }, "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 s5 = starts[index];
          const t5 = ttls[index];
          return !!t5 && !!s5 && (cachedNow || getNow()) - s5 > t5;
        };
      }
      // 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 = (k2, v2, size, sizeCalculation) => {
          if (this.#isBackgroundFetch(v2)) {
            return 0;
          }
          if (!isPosInt2(size)) {
            if (sizeCalculation) {
              if (typeof sizeCalculation !== "function") {
                throw new TypeError("sizeCalculation must be a function");
              }
              size = sizeCalculation(v2, k2);
              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 i3 = this.#tail; true; ) {
            if (!this.#isValidIndex(i3)) {
              break;
            }
            if (allowStale || !this.#isStale(i3)) {
              yield i3;
            }
            if (i3 === this.#head) {
              break;
            } else {
              i3 = this.#prev[i3];
            }
          }
        }
      }
      *#rindexes({ allowStale = this.allowStale } = {}) {
        if (this.#size) {
          for (let i3 = this.#head; true; ) {
            if (!this.#isValidIndex(i3)) {
              break;
            }
            if (allowStale || !this.#isStale(i3)) {
              yield i3;
            }
            if (i3 === this.#tail) {
              break;
            } else {
              i3 = this.#next[i3];
            }
          }
        }
      }
      #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 i3 of this.#indexes()) {
          if (this.#valList[i3] !== void 0 && this.#keyList[i3] !== void 0 && !this.#isBackgroundFetch(this.#valList[i3])) {
            yield [this.#keyList[i3], this.#valList[i3]];
          }
        }
      }
      /**
       * 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 i3 of this.#rindexes()) {
          if (this.#valList[i3] !== void 0 && this.#keyList[i3] !== void 0 && !this.#isBackgroundFetch(this.#valList[i3])) {
            yield [this.#keyList[i3], this.#valList[i3]];
          }
        }
      }
      /**
       * Return a generator yielding the keys in the cache,
       * in order from most recently used to least recently used.
       */
      *keys() {
        for (const i3 of this.#indexes()) {
          const k2 = this.#keyList[i3];
          if (k2 !== void 0 && !this.#isBackgroundFetch(this.#valList[i3])) {
            yield k2;
          }
        }
      }
      /**
       * 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 i3 of this.#rindexes()) {
          const k2 = this.#keyList[i3];
          if (k2 !== void 0 && !this.#isBackgroundFetch(this.#valList[i3])) {
            yield k2;
          }
        }
      }
      /**
       * Return a generator yielding the values in the cache,
       * in order from most recently used to least recently used.
       */
      *values() {
        for (const i3 of this.#indexes()) {
          const v2 = this.#valList[i3];
          if (v2 !== void 0 && !this.#isBackgroundFetch(this.#valList[i3])) {
            yield this.#valList[i3];
          }
        }
      }
      /**
       * 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 i3 of this.#rindexes()) {
          const v2 = this.#valList[i3];
          if (v2 !== void 0 && !this.#isBackgroundFetch(this.#valList[i3])) {
            yield this.#valList[i3];
          }
        }
      }
      /**
       * 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 i3 of this.#indexes()) {
          const v2 = this.#valList[i3];
          const value = this.#isBackgroundFetch(v2) ? v2.__staleWhileFetching : v2;
          if (value === void 0)
            continue;
          if (fn(value, this.#keyList[i3], this)) {
            return this.get(this.#keyList[i3], 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 i3 of this.#indexes()) {
          const v2 = this.#valList[i3];
          const value = this.#isBackgroundFetch(v2) ? v2.__staleWhileFetching : v2;
          if (value === void 0)
            continue;
          fn.call(thisp, value, this.#keyList[i3], 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 i3 of this.#rindexes()) {
          const v2 = this.#valList[i3];
          const value = this.#isBackgroundFetch(v2) ? v2.__staleWhileFetching : v2;
          if (value === void 0)
            continue;
          fn.call(thisp, value, this.#keyList[i3], this);
        }
      }
      /**
       * Delete any stale entries. Returns true if anything was removed,
       * false otherwise.
       */
      purgeStale() {
        let deleted = false;
        for (const i3 of this.#rindexes({ allowStale: true })) {
          if (this.#isStale(i3)) {
            this.#delete(this.#keyList[i3], "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 i3 = this.#keyMap.get(key);
        if (i3 === void 0)
          return void 0;
        const v2 = this.#valList[i3];
        const value = this.#isBackgroundFetch(v2) ? v2.__staleWhileFetching : v2;
        if (value === void 0)
          return void 0;
        const entry = { value };
        if (this.#ttls && this.#starts) {
          const ttl = this.#ttls[i3];
          const start = this.#starts[i3];
          if (ttl && start) {
            const remain = ttl - (perf2.now() - start);
            entry.ttl = remain;
            entry.start = Date.now();
          }
        }
        if (this.#sizes) {
          entry.size = this.#sizes[i3];
        }
        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 i3 of this.#indexes({ allowStale: true })) {
          const key = this.#keyList[i3];
          const v2 = this.#valList[i3];
          const value = this.#isBackgroundFetch(v2) ? v2.__staleWhileFetching : v2;
          if (value === void 0 || key === void 0)
            continue;
          const entry = { value };
          if (this.#ttls && this.#starts) {
            entry.ttl = this.#ttls[i3];
            const age = perf2.now() - this.#starts[i3];
            entry.start = Math.floor(Date.now() - age);
          }
          if (this.#sizes) {
            entry.size = this.#sizes[i3];
          }
          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(k2, v2, setOptions2 = {}) {
        if (v2 === void 0) {
          this.delete(k2);
          return this;
        }
        const { ttl = this.ttl, start, noDisposeOnSet = this.noDisposeOnSet, sizeCalculation = this.sizeCalculation, status } = setOptions2;
        let { noUpdateTTL = this.noUpdateTTL } = setOptions2;
        const size = this.#requireSize(k2, v2, setOptions2.size || 0, sizeCalculation);
        if (this.maxEntrySize && size > this.maxEntrySize) {
          if (status) {
            status.set = "miss";
            status.maxEntrySizeExceeded = true;
          }
          this.#delete(k2, "set");
          return this;
        }
        let index = this.#size === 0 ? void 0 : this.#keyMap.get(k2);
        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] = k2;
          this.#valList[index] = v2;
          this.#keyMap.set(k2, 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 (v2 !== oldVal) {
            if (this.#hasFetchMethod && this.#isBackgroundFetch(oldVal)) {
              oldVal.__abortController.abort(new Error("replaced"));
              const { __staleWhileFetching: s5 } = oldVal;
              if (s5 !== void 0 && !noDisposeOnSet) {
                if (this.#hasDispose) {
                  this.#dispose?.(s5, k2, "set");
                }
                if (this.#hasDisposeAfter) {
                  this.#disposed?.push([s5, k2, "set"]);
                }
              }
            } else if (!noDisposeOnSet) {
              if (this.#hasDispose) {
                this.#dispose?.(oldVal, k2, "set");
              }
              if (this.#hasDisposeAfter) {
                this.#disposed?.push([oldVal, k2, "set"]);
              }
            }
            this.#removeItemSize(index);
            this.#addItemSize(index, size, status);
            this.#valList[index] = v2;
            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 dt2 = this.#disposed;
          let task;
          while (task = dt2?.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 dt2 = this.#disposed;
            let task;
            while (task = dt2?.shift()) {
              this.#disposeAfter?.(...task);
            }
          }
        }
      }
      #evict(free) {
        const head = this.#head;
        const k2 = this.#keyList[head];
        const v2 = this.#valList[head];
        if (this.#hasFetchMethod && this.#isBackgroundFetch(v2)) {
          v2.__abortController.abort(new Error("evicted"));
        } else if (this.#hasDispose || this.#hasDisposeAfter) {
          if (this.#hasDispose) {
            this.#dispose?.(v2, k2, "evict");
          }
          if (this.#hasDisposeAfter) {
            this.#disposed?.push([v2, k2, "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(k2);
        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(k2, hasOptions = {}) {
        const { updateAgeOnHas = this.updateAgeOnHas, status } = hasOptions;
        const index = this.#keyMap.get(k2);
        if (index !== void 0) {
          const v2 = this.#valList[index];
          if (this.#isBackgroundFetch(v2) && v2.__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(k2, peekOptions = {}) {
        const { allowStale = this.allowStale } = peekOptions;
        const index = this.#keyMap.get(k2);
        if (index === void 0 || !allowStale && this.#isStale(index)) {
          return;
        }
        const v2 = this.#valList[index];
        return this.#isBackgroundFetch(v2) ? v2.__staleWhileFetching : v2;
      }
      #backgroundFetch(k2, index, options2, context2) {
        const v2 = index === void 0 ? void 0 : this.#valList[index];
        if (this.#isBackgroundFetch(v2)) {
          return v2;
        }
        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((v3, updateCache = false) => {
          const { aborted: aborted2 } = ac.signal;
          const ignoreAbort = options2.ignoreFetchAbort && v3 !== void 0;
          if (options2.status) {
            if (aborted2 && !updateCache) {
              options2.status.fetchAborted = true;
              options2.status.fetchError = ac.signal.reason;
              if (ignoreAbort)
                options2.status.fetchAbortIgnored = true;
            } else {
              options2.status.fetchResolved = true;
            }
          }
          if (aborted2 && !ignoreAbort && !updateCache) {
            return fetchFail(ac.signal.reason);
          }
          const bf2 = p2;
          if (this.#valList[index] === p2) {
            if (v3 === void 0) {
              if (bf2.__staleWhileFetching) {
                this.#valList[index] = bf2.__staleWhileFetching;
              } else {
                this.#delete(k2, "fetch");
              }
            } else {
              if (options2.status)
                options2.status.fetchUpdated = true;
              this.set(k2, v3, fetchOpts.options);
            }
          }
          return v3;
        }, "cb");
        const eb = /* @__PURE__ */ __name((er2) => {
          if (options2.status) {
            options2.status.fetchRejected = true;
            options2.status.fetchError = er2;
          }
          return fetchFail(er2);
        }, "eb");
        const fetchFail = /* @__PURE__ */ __name((er2) => {
          const { aborted: aborted2 } = ac.signal;
          const allowStaleAborted = aborted2 && options2.allowStaleOnFetchAbort;
          const allowStale = allowStaleAborted || options2.allowStaleOnFetchRejection;
          const noDelete = allowStale || options2.noDeleteOnFetchRejection;
          const bf2 = p2;
          if (this.#valList[index] === p2) {
            const del = !noDelete || bf2.__staleWhileFetching === void 0;
            if (del) {
              this.#delete(k2, "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 er2;
          }
        }, "fetchFail");
        const pcall = /* @__PURE__ */ __name((res, rej) => {
          const fmp = this.#fetchMethod?.(k2, v2, fetchOpts);
          if (fmp && fmp instanceof Promise) {
            fmp.then((v3) => res(v3 === void 0 ? void 0 : v3), rej);
          }
          ac.signal.addEventListener("abort", () => {
            if (!options2.ignoreFetchAbort || options2.allowStaleOnFetchAbort) {
              res(void 0);
              if (options2.allowStaleOnFetchAbort) {
                res = /* @__PURE__ */ __name((v3) => cb(v3, true), "res");
              }
            }
          });
        }, "pcall");
        if (options2.status)
          options2.status.fetchDispatched = true;
        const p2 = new Promise(pcall).then(cb, eb);
        const bf = Object.assign(p2, {
          __abortController: ac,
          __staleWhileFetching: v2,
          __returned: void 0
        });
        if (index === void 0) {
          this.set(k2, bf, { ...fetchOpts.options, status: void 0 });
          index = this.#keyMap.get(k2);
        } else {
          this.#valList[index] = bf;
        }
        return bf;
      }
      #isBackgroundFetch(p2) {
        if (!this.#hasFetchMethod)
          return false;
        const b2 = p2;
        return !!b2 && b2 instanceof Promise && b2.hasOwnProperty("__staleWhileFetching") && b2.__abortController instanceof AC2;
      }
      async fetch(k2, 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(k2, {
            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(k2);
        if (index === void 0) {
          if (status)
            status.fetch = "miss";
          const p2 = this.#backgroundFetch(k2, index, options2, context2);
          return p2.__returned = p2;
        } else {
          const v2 = this.#valList[index];
          if (this.#isBackgroundFetch(v2)) {
            const stale = allowStale && v2.__staleWhileFetching !== void 0;
            if (status) {
              status.fetch = "inflight";
              if (stale)
                status.returnedStale = true;
            }
            return stale ? v2.__staleWhileFetching : v2.__returned = v2;
          }
          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 v2;
          }
          const p2 = this.#backgroundFetch(k2, index, options2, context2);
          const hasStale = p2.__staleWhileFetching !== void 0;
          const staleVal = hasStale && allowStale;
          if (status) {
            status.fetch = isStale ? "stale" : "refresh";
            if (staleVal && isStale)
              status.returnedStale = true;
          }
          return staleVal ? p2.__staleWhileFetching : p2.__returned = p2;
        }
      }
      async forceFetch(k2, fetchOptions = {}) {
        const v2 = await this.fetch(k2, fetchOptions);
        if (v2 === void 0)
          throw new Error("fetch() returned undefined");
        return v2;
      }
      memo(k2, memoOptions = {}) {
        const memoMethod = this.#memoMethod;
        if (!memoMethod) {
          throw new Error("no memoMethod provided to constructor");
        }
        const { context: context2, forceRefresh, ...options2 } = memoOptions;
        const v2 = this.get(k2, options2);
        if (!forceRefresh && v2 !== void 0)
          return v2;
        const vv = memoMethod(k2, v2, {
          options: options2,
          context: context2
        });
        this.set(k2, 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(k2, getOptions2 = {}) {
        const { allowStale = this.allowStale, updateAgeOnGet = this.updateAgeOnGet, noDeleteOnStaleGet = this.noDeleteOnStaleGet, status } = getOptions2;
        const index = this.#keyMap.get(k2);
        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(k2, "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(p2, n3) {
        this.#prev[n3] = p2;
        this.#next[p2] = n3;
      }
      #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(k2) {
        return this.#delete(k2, "delete");
      }
      #delete(k2, reason) {
        let deleted = false;
        if (this.#size !== 0) {
          const index = this.#keyMap.get(k2);
          if (index !== void 0) {
            deleted = true;
            if (this.#size === 1) {
              this.#clear(reason);
            } else {
              this.#removeItemSize(index);
              const v2 = this.#valList[index];
              if (this.#isBackgroundFetch(v2)) {
                v2.__abortController.abort(new Error("deleted"));
              } else if (this.#hasDispose || this.#hasDisposeAfter) {
                if (this.#hasDispose) {
                  this.#dispose?.(v2, k2, reason);
                }
                if (this.#hasDisposeAfter) {
                  this.#disposed?.push([v2, k2, reason]);
                }
              }
              this.#keyMap.delete(k2);
              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 dt2 = this.#disposed;
          let task;
          while (task = dt2?.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 v2 = this.#valList[index];
          if (this.#isBackgroundFetch(v2)) {
            v2.__abortController.abort(new Error("deleted"));
          } else {
            const k2 = this.#keyList[index];
            if (this.#hasDispose) {
              this.#dispose?.(v2, k2, reason);
            }
            if (this.#hasDisposeAfter) {
              this.#disposed?.push([v2, k2, 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 dt2 = this.#disposed;
          let task;
          while (task = dt2?.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((f5) => f5.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: path125 }) => `https://${domain}/${user}/${project}${maybeJoin("/", editpath, "/", maybeEncode(committish || "HEAD"), "/", path125)}`, "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: path125, fragment, hashformat }) => `https://${domain}/${user}/${project}/${treepath}/${maybeEncode(committish || "HEAD")}/${path125}${maybeJoin("#", hashformat(fragment || ""))}`, "browsetreetemplate"),
      browseblobtemplate: /* @__PURE__ */ __name(({ domain, user, project, committish, blobpath, path: path125, fragment, hashformat }) => `https://${domain}/${user}/${project}/${blobpath}/${maybeEncode(committish || "HEAD")}/${path125}${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: path125 }) => `https://${domain}/${user}/${project}/raw/${maybeEncode(committish || "HEAD")}/${path125}`, "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: path125 }) => `https://${maybeJoin(auth2, "@")}raw.githubusercontent.com/${user}/${project}/${maybeEncode(committish || "HEAD")}/${path125}`, "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: path125, editpath }) => `https://${domain}/${user}/${project}${maybeJoin("/", treepath, "/", maybeEncode(committish || "HEAD"), "/", path125, 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 path125 = url2.pathname.slice(1);
        if (path125.includes("/-/") || path125.includes("/archive.tar.gz")) {
          return;
        }
        const segments = path125.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: path125, hashformat }) => `https://${domain}/${project}${maybeJoin("/", maybeEncode(committish))}${maybeJoin("#", hashformat(path125))}`, "browsetreetemplate"),
      browseblobtemplate: /* @__PURE__ */ __name(({ domain, project, committish, path: path125, hashformat }) => `https://${domain}/${project}${maybeJoin("/", maybeEncode(committish))}${maybeJoin("#", hashformat(path125))}`, "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: path125 }) => `https://gist.githubusercontent.com/${user}/${project}/raw${maybeJoin("/", maybeEncode(committish))}/${path125}`, "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: path125 }) => `https://${domain}/${user}/${project}/blob/${maybeEncode(committish) || "HEAD"}/${path125}`, "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((u2) => {
      try {
        return new url2.URL(u2);
      } 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_lib7 = __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(path125, ...args) {
        if (typeof path125 !== "string") {
          return this.#fill(this.browsetemplate, path125);
        }
        if (typeof args[0] !== "string") {
          return this.#fill(this.browsetreetemplate, { ...args[0], path: path125 });
        }
        return this.#fill(this.browsetreetemplate, { ...args[1], fragment: args[0], path: path125 });
      }
      // 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(path125, ...args) {
        if (typeof args[0] !== "string") {
          return this.#fill(this.browseblobtemplate, { ...args[0], path: path125 });
        }
        return this.#fill(this.browseblobtemplate, { ...args[1], fragment: args[0], path: path125 });
      }
      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(path125, opts) {
        return this.#fill(this.filetemplate, { ...opts, path: path125 });
      }
      edit(path125, opts) {
        return this.#fill(this.edittemplate, { ...opts, path: path125 });
      }
      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(d2) {
      if (!d2) {
        return;
      }
      if (d2 === "ERROR: No README data found!") {
        return;
      }
      d2 = d2.trim().split("\n");
      let s5 = 0;
      while (d2[s5] && d2[s5].trim().match(/^(#|$)/)) {
        s5++;
      }
      const l3 = d2.length;
      let e4 = s5 + 1;
      while (e4 < l3 && d2[e4].trim()) {
        e4++;
      }
      return d2.slice(s5, e4).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_lib7();
    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 r5 = data.repository.url || "";
        if (r5) {
          var hosted = hostedGitInfo.fromUrl(r5);
          if (hosted) {
            r5 = data.repository.url = hosted.getDefaultRepresentation() === "shortcut" ? hosted.https() : hosted.toString();
          }
        }
        if (r5.match(/github.com\/[^/]+\/[^/]+\.git\.git$/)) {
          this.warn("brokenGitUrl", r5);
        }
      }, "fixRepositoryField"),
      fixTypos: /* @__PURE__ */ __name(function(data) {
        Object.keys(typos.topLevel).forEach(function(d2) {
          if (Object.prototype.hasOwnProperty.call(data, d2)) {
            this.warn("typo", d2, typos.topLevel[d2]);
          }
        }, 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(k2) {
          if (typeof data.scripts[k2] !== "string") {
            this.warn("nonStringScript");
            delete data.scripts[k2];
          } else if (typos.script[k2] && !data.scripts[typos.script[k2]]) {
            this.warn("typo", k2, typos.script[k2], "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 b2 = {};
          var match2;
          if (match2 = data.name.match(/^@[^/]+[/](.*)$/)) {
            b2[match2[1]] = data.bin;
          } else {
            b2[data.name] = data.bin;
          }
          data.bin = b2;
        }
      }, "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(d2) {
            var r5 = data[deps][d2];
            if (typeof r5 !== "string") {
              this.warn("nonStringDependency", d2, JSON.stringify(r5));
              delete data[deps][d2];
            }
            var hosted = hostedGitInfo.fromUrl(data[deps][d2]);
            if (hosted) {
              data[deps][d2] = 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 u2 = person.url || person.web;
      var wrappedUrl = u2 ? " (" + u2 + ")" : "";
      var e4 = person.email || person.mail;
      var wrappedEmail = e4 ? " <" + e4 + ">" : "";
      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 o3 = data.optionalDependencies;
      if (!o3) {
        return;
      }
      var d2 = data.dependencies || {};
      Object.keys(o3).forEach(function(k2) {
        d2[k2] = o3[k2];
      });
      data.dependencies = d2;
    }
    __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 o3 = {};
      deps.filter(function(d2) {
        return typeof d2 === "string";
      }).forEach(function(d2) {
        d2 = d2.trim().split(/(:?[@\s><=])/);
        var dn = d2.shift();
        var dv = d2.join("");
        dv = dv.trim();
        dv = dv.replace(/^@/, "");
        o3[dn] = dv;
      });
      return o3;
    }
    __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(k2) {
        if (typos.bugs[k2]) {
          warn("typo", k2, typos.bugs[k2], "bugs");
          bugs[typos.bugs[k2]] = bugs[k2];
          delete bugs[k2];
        }
      });
    }
    __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 util3 = __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 util3.format.apply(null, args);
      }
    };
    function makeTypoWarning(providedName, probableName, field) {
      if (field) {
        providedName = field + "['" + providedName + "']";
        probableName = field + "['" + probableName + "']";
      }
      return util3.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 = normalize12;
    var fixer = require_fixer();
    normalize12.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 normalize12(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(normalize12, "normalize");
    function ucFirst(string4) {
      return string4.charAt(0).toUpperCase() + string4.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 execSync9 = __require("child_process").execSync;
    var fs113 = __require("fs");
    var path125 = __require("path");
    var access8 = fs113.access;
    var accessSync2 = fs113.accessSync;
    var constants4 = fs113.constants || fs113;
    var isUsingWindows = process.platform == "win32";
    var fileNotExists = /* @__PURE__ */ __name(function(commandName, callback) {
      access8(
        commandName,
        constants4.F_OK,
        function(err) {
          callback(!err);
        }
      );
    }, "fileNotExists");
    var fileNotExistsSync = /* @__PURE__ */ __name(function(commandName) {
      try {
        accessSync2(commandName, constants4.F_OK);
        return false;
      } catch (e4) {
        return true;
      }
    }, "fileNotExistsSync");
    var localExecutable = /* @__PURE__ */ __name(function(commandName, callback) {
      access8(
        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 (e4) {
        return false;
      }
    }, "localExecutableSync");
    var commandExistsUnix = /* @__PURE__ */ __name(function(commandName, cleanedCommandName, callback) {
      fileNotExists(commandName, function(isFile3) {
        if (!isFile3) {
          var child = exec5(
            "command -v " + cleanedCommandName + " 2>/dev/null && { echo >&1 " + cleanedCommandName + "; exit 0; }",
            function(error2, 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(error2) {
          if (error2 !== null) {
            callback(null, false);
          } else {
            callback(null, true);
          }
        }
      );
    }, "commandExistsWindows");
    var commandExistsUnixSync = /* @__PURE__ */ __name(function(commandName, cleanedCommandName) {
      if (fileNotExistsSync(commandName)) {
        try {
          var stdout = execSync9(
            "command -v " + cleanedCommandName + " 2>/dev/null && { echo >&1 " + cleanedCommandName + "; exit 0; }"
          );
          return !!stdout;
        } catch (error2) {
          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 = execSync9("where " + cleanedCommandName, { stdio: [] });
        return !!stdout;
      } catch (error2) {
        return false;
      }
    }, "commandExistsWindowsSync");
    var cleanInput = /* @__PURE__ */ __name(function(s5) {
      if (/[^A-Za-z0-9_\/:=-]/.test(s5)) {
        s5 = "'" + s5.replace(/'/g, "'\\''") + "'";
        s5 = s5.replace(/^(?:'')+/g, "").replace(/\\'''/g, "\\'");
      }
      return s5;
    }, "cleanInput");
    if (isUsingWindows) {
      cleanInput = /* @__PURE__ */ __name(function(s5) {
        var isPathName = /[\\]/.test(s5);
        if (isPathName) {
          var dirname26 = '"' + path125.dirname(s5) + '"';
          var basename26 = '"' + path125.basename(s5) + '"';
          return dirname26 + ":" + basename26;
        }
        return '"' + s5 + '"';
      }, "cleanInput");
    }
    module2.exports = /* @__PURE__ */ __name(function commandExists4(commandName, callback) {
      var cleanedCommandName = cleanInput(commandName);
      if (!callback && typeof Promise !== "undefined") {
        return new Promise(function(resolve30, reject) {
          commandExists4(commandName, function(error2, output) {
            if (output) {
              resolve30(commandName);
            } else {
              reject(error2);
            }
          });
        });
      }
      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();
  }
});

// packages/cli/node_modules/ajv/dist/compile/codegen/code.js
var require_code5 = __commonJS({
  "packages/cli/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(s5) {
        super();
        if (!exports2.IDENTIFIER.test(s5))
          throw new Error("CodeGen: name must be a valid identifier");
        this.str = s5;
      }
      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 _a7;
        return (_a7 = this._str) !== null && _a7 !== void 0 ? _a7 : this._str = this._items.reduce((s5, c4) => `${s5}${c4}`, "");
      }
      get names() {
        var _a7;
        return (_a7 = this._names) !== null && _a7 !== void 0 ? _a7 : this._names = this._items.reduce((names, c4) => {
          if (c4 instanceof Name)
            names[c4.str] = (names[c4.str] || 0) + 1;
          return names;
        }, {});
      }
    };
    exports2._Code = _Code;
    exports2.nil = new _Code("");
    function _2(strs, ...args) {
      const code2 = [strs[0]];
      let i3 = 0;
      while (i3 < args.length) {
        addCodeArg(code2, args[i3]);
        code2.push(strs[++i3]);
      }
      return new _Code(code2);
    }
    __name(_2, "_");
    exports2._ = _2;
    var plus = new _Code("+");
    function str2(strs, ...args) {
      const expr = [safeStringify(strs[0])];
      let i3 = 0;
      while (i3 < args.length) {
        expr.push(plus);
        addCodeArg(expr, args[i3]);
        expr.push(plus, safeStringify(strs[++i3]));
      }
      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(interpolate2(arg));
    }
    __name(addCodeArg, "addCodeArg");
    exports2.addCodeArg = addCodeArg;
    function optimize(expr) {
      let i3 = 1;
      while (i3 < expr.length - 1) {
        if (expr[i3] === plus) {
          const res = mergeExprItems(expr[i3 - 1], expr[i3 + 1]);
          if (res !== void 0) {
            expr.splice(i3 - 1, 3, res);
            continue;
          }
          expr[i3++] = "+";
        }
        i3++;
      }
    }
    __name(optimize, "optimize");
    function mergeExprItems(a2, b2) {
      if (b2 === '""')
        return a2;
      if (a2 === '""')
        return b2;
      if (typeof a2 == "string") {
        if (b2 instanceof Name || a2[a2.length - 1] !== '"')
          return;
        if (typeof b2 != "string")
          return `${a2.slice(0, -1)}${b2}"`;
        if (b2[0] === '"')
          return a2.slice(0, -1) + b2.slice(1);
        return;
      }
      if (typeof b2 == "string" && b2[0] === '"' && !(a2 instanceof Name))
        return `"${a2}${b2.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 interpolate2(x3) {
      return typeof x3 == "number" || typeof x3 == "boolean" || x3 === null ? x3 : safeStringify(Array.isArray(x3) ? x3.join(",") : x3);
    }
    __name(interpolate2, "interpolate");
    function stringify4(x3) {
      return new _Code(safeStringify(x3));
    }
    __name(stringify4, "stringify");
    exports2.stringify = stringify4;
    function safeStringify(x3) {
      return JSON.stringify(x3).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}`) : _2`[${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/cli/node_modules/ajv/dist/compile/codegen/scope.js
var require_scope3 = __commonJS({
  "packages/cli/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_code5();
    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 _a7, _b2;
        if (((_b2 = (_a7 = this._parent) === null || _a7 === void 0 ? void 0 : _a7._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 _a7;
        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 = (_a7 = value.key) !== null && _a7 !== void 0 ? _a7 : 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 s5 = this._scope[prefix] || (this._scope[prefix] = []);
        const itemIndex = s5.length;
        s5[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 c4 = valueCode(name3);
            if (c4) {
              const def2 = this.opts.es5 ? exports2.varKinds.var : exports2.varKinds.const;
              code2 = (0, code_1._)`${code2}${def2} ${name3} = ${c4};${this.opts._n}`;
            } else if (c4 = getCode === null || getCode === void 0 ? void 0 : getCode(name3)) {
              code2 = (0, code_1._)`${code2}${c4}${this.opts._n}`;
            } else {
              throw new ValueError(name3);
            }
            nameSet.set(name3, UsedValueState.Completed);
          });
        }
        return code2;
      }
    };
    exports2.ValueScope = ValueScope;
  }
});

// packages/cli/node_modules/ajv/dist/compile/codegen/index.js
var require_codegen4 = __commonJS({
  "packages/cli/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_code5();
    var scope_1 = require_scope3();
    var code_2 = require_code5();
    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_scope3();
    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 Node5 = class {
      static {
        __name(this, "Node");
      }
      optimizeNodes() {
        return this;
      }
      optimizeNames(_names, _constants) {
        return this;
      }
    };
    var Def = class extends Node5 {
      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 Node5 {
      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 Node5 {
      static {
        __name(this, "Label");
      }
      constructor(label) {
        super();
        this.label = label;
        this.names = {};
      }
      render({ _n }) {
        return `${this.label}:` + _n;
      }
    };
    var Break = class extends Node5 {
      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 Node5 {
      static {
        __name(this, "Throw");
      }
      constructor(error2) {
        super();
        this.error = error2;
      }
      render({ _n }) {
        return `throw ${this.error};` + _n;
      }
      get names() {
        return this.error.names;
      }
    };
    var AnyCode = class extends Node5 {
      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 Node5 {
      static {
        __name(this, "ParentNode");
      }
      constructor(nodes = []) {
        super();
        this.nodes = nodes;
      }
      render(opts) {
        return this.nodes.reduce((code2, n3) => code2 + n3.render(opts), "");
      }
      optimizeNodes() {
        const { nodes } = this;
        let i3 = nodes.length;
        while (i3--) {
          const n3 = nodes[i3].optimizeNodes();
          if (Array.isArray(n3))
            nodes.splice(i3, 1, ...n3);
          else if (n3)
            nodes[i3] = n3;
          else
            nodes.splice(i3, 1);
        }
        return nodes.length > 0 ? this : void 0;
      }
      optimizeNames(names, constants4) {
        const { nodes } = this;
        let i3 = nodes.length;
        while (i3--) {
          const n3 = nodes[i3];
          if (n3.optimizeNames(names, constants4))
            continue;
          subtractNames(names, n3.names);
          nodes.splice(i3, 1);
        }
        return nodes.length > 0 ? this : void 0;
      }
      get names() {
        return this.nodes.reduce((names, n3) => addNames(names, n3.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 e4 = this.else;
        if (e4) {
          const ns = e4.optimizeNodes();
          e4 = this.else = Array.isArray(ns) ? new Else(ns) : ns;
        }
        if (e4) {
          if (cond === false)
            return e4 instanceof _If ? e4 : e4.nodes;
          if (this.nodes.length)
            return this;
          return new _If(not(cond), e4 instanceof _If ? [e4] : e4.nodes);
        }
        if (cond === false || !this.nodes.length)
          return void 0;
        return this;
      }
      optimizeNames(names, constants4) {
        var _a7;
        this.else = (_a7 = this.else) === null || _a7 === void 0 ? void 0 : _a7.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 _a7, _b2;
        super.optimizeNodes();
        (_a7 = this.catch) === null || _a7 === void 0 ? void 0 : _a7.optimizeNodes();
        (_b2 = this.finally) === null || _b2 === void 0 ? void 0 : _b2.optimizeNodes();
        return this;
      }
      optimizeNames(names, constants4) {
        var _a7, _b2;
        super.optimizeNames(names, constants4);
        (_a7 = this.catch) === null || _a7 === void 0 ? void 0 : _a7.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(error2) {
        super();
        this.error = error2;
      }
      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(c4) {
        if (typeof c4 == "function")
          c4();
        else if (c4 !== code_1.nil)
          this._leafNode(new AnyCode(c4));
        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`, (i3) => {
            this.var(name3, (0, code_1._)`${arr}[${i3}]`);
            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 error2 = this.name("e");
          this._currNode = node.catch = new Catch(error2);
          catchCode(error2);
        }
        if (finallyCode) {
          this._currNode = node.finally = new Finally();
          this.code(finallyCode);
        }
        return this._endBlockNode(Catch, Finally);
      }
      // `throw` statement
      throw(error2) {
        return this._leafNode(new Throw(error2));
      }
      // start self-balancing block
      block(body, nodeCount) {
        this._blockStarts.push(this._nodes.length);
        if (body)
          this.code(body).endBlock(nodeCount);
        return this;
      }
      // end the current self-balancing block
      endBlock(nodeCount) {
        const 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(n3 = 1) {
        while (n3-- > 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 n3 = this._currNode;
        if (n3 instanceof N1 || N2 && n3 instanceof N2) {
          this._nodes.pop();
          return this;
        }
        throw new Error(`CodeGen: not in block "${N2 ? `${N1.kind}/${N2.kind}` : N1.kind}"`);
      }
      _elseNode(node) {
        const n3 = this._currNode;
        if (!(n3 instanceof If)) {
          throw new Error('CodeGen: "else" without "if"');
        }
        this._currNode = n3.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 n3 in from)
        names[n3] = (names[n3] || 0) + (from[n3] || 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, c4) => {
        if (c4 instanceof code_1.Name)
          c4 = replaceName(c4);
        if (c4 instanceof code_1._Code)
          items.push(...c4._items);
        else
          items.push(c4);
        return items;
      }, []));
      function replaceName(n3) {
        const c4 = constants4[n3.str];
        if (c4 === void 0 || names[n3.str] !== 1)
          return n3;
        delete names[n3.str];
        return c4;
      }
      __name(replaceName, "replaceName");
      function canOptimize(e4) {
        return e4 instanceof code_1._Code && e4._items.some((c4) => c4 instanceof code_1.Name && names[c4.str] === 1 && constants4[c4.str] !== void 0);
      }
      __name(canOptimize, "canOptimize");
    }
    __name(optimizeExpr, "optimizeExpr");
    function subtractNames(names, from) {
      for (const n3 in from)
        names[n3] = (names[n3] || 0) - (from[n3] || 0);
    }
    __name(subtractNames, "subtractNames");
    function not(x3) {
      return typeof x3 == "boolean" || typeof x3 == "number" || x3 === null ? !x3 : (0, code_1._)`!${par(x3)}`;
    }
    __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 or2(...args) {
      return args.reduce(orCode);
    }
    __name(or2, "or");
    exports2.or = or2;
    function mappend(op) {
      return (x3, y2) => x3 === code_1.nil ? y2 : y2 === code_1.nil ? x3 : (0, code_1._)`${par(x3)} ${op} ${par(y2)}`;
    }
    __name(mappend, "mappend");
    function par(x3) {
      return x3 instanceof code_1.Name ? x3 : (0, code_1._)`(${x3})`;
    }
    __name(par, "par");
  }
});

// packages/cli/node_modules/ajv/dist/compile/util.js
var require_util21 = __commonJS({
  "packages/cli/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_codegen4();
    var code_1 = require_code5();
    function toHash(arr) {
      const hash = {};
      for (const item of arr)
        hash[item] = true;
      return hash;
    }
    __name(toHash, "toHash");
    exports2.toHash = toHash;
    function alwaysValidSchema(it2, schema) {
      if (typeof schema == "boolean")
        return schema;
      if (Object.keys(schema).length === 0)
        return true;
      checkUnknownRules(it2, schema);
      return !schemaHasRules(schema, it2.self.RULES.all);
    }
    __name(alwaysValidSchema, "alwaysValidSchema");
    exports2.alwaysValidSchema = alwaysValidSchema;
    function checkUnknownRules(it2, schema = it2.schema) {
      const { opts, self: self2 } = it2;
      if (!opts.strictSchema)
        return;
      if (typeof schema === "boolean")
        return;
      const rules = self2.RULES.keywords;
      for (const key in schema) {
        if (!rules[key])
          checkStrictMode(it2, `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, f5) {
      if (Array.isArray(xs)) {
        for (const x3 of xs)
          f5(x3);
      } else {
        f5(xs);
      }
    }
    __name(eachItem, "eachItem");
    exports2.eachItem = eachItem;
    function makeMergeEvaluated({ mergeNames, mergeToName, mergeValues: mergeValues3, 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) : mergeValues3(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((p2) => gen.assign((0, codegen_1._)`${props}${(0, codegen_1.getProperty)(p2)}`, true));
    }
    __name(setEvaluated, "setEvaluated");
    exports2.setEvaluated = setEvaluated;
    var snippets = {};
    function useFunc(gen, f5) {
      return gen.scopeValue("func", {
        ref: f5,
        code: snippets[f5.code] || (snippets[f5.code] = new code_1._Code(f5.code))
      });
    }
    __name(useFunc, "useFunc");
    exports2.useFunc = useFunc;
    var Type3;
    (function(Type4) {
      Type4[Type4["Num"] = 0] = "Num";
      Type4[Type4["Str"] = 1] = "Str";
    })(Type3 || (exports2.Type = Type3 = {}));
    function getErrorPath(dataProp, dataPropType, jsPropertySyntax) {
      if (dataProp instanceof codegen_1.Name) {
        const isNumber3 = dataPropType === Type3.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(it2, msg, mode = it2.opts.strictSchema) {
      if (!mode)
        return;
      msg = `strict mode: ${msg}`;
      if (mode === true)
        throw new Error(msg);
      it2.self.logger.warn(msg);
    }
    __name(checkStrictMode, "checkStrictMode");
    exports2.checkStrictMode = checkStrictMode;
  }
});

// packages/cli/node_modules/ajv/dist/compile/names.js
var require_names3 = __commonJS({
  "packages/cli/node_modules/ajv/dist/compile/names.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    var codegen_1 = require_codegen4();
    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/cli/node_modules/ajv/dist/compile/errors.js
var require_errors4 = __commonJS({
  "packages/cli/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_codegen4();
    var util_1 = require_util21();
    var names_1 = require_names3();
    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, error2 = exports2.keywordError, errorPaths, overrideAllErrors) {
      const { it: it2 } = cxt;
      const { gen, compositeRule, allErrors } = it2;
      const errObj = errorObjectCode(cxt, error2, errorPaths);
      if (overrideAllErrors !== null && overrideAllErrors !== void 0 ? overrideAllErrors : compositeRule || allErrors) {
        addError(gen, errObj);
      } else {
        returnErrors(it2, (0, codegen_1._)`[${errObj}]`);
      }
    }
    __name(reportError3, "reportError");
    exports2.reportError = reportError3;
    function reportExtraError(cxt, error2 = exports2.keywordError, errorPaths) {
      const { it: it2 } = cxt;
      const { gen, compositeRule, allErrors } = it2;
      const errObj = errorObjectCode(cxt, error2, errorPaths);
      addError(gen, errObj);
      if (!(compositeRule || allErrors)) {
        returnErrors(it2, names_1.default.vErrors);
      }
    }
    __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: it2 }) {
      if (errsCount === void 0)
        throw new Error("ajv implementation error");
      const err = gen.name("err");
      gen.forRange("i", errsCount, names_1.default.errors, (i3) => {
        gen.const(err, (0, codegen_1._)`${names_1.default.vErrors}[${i3}]`);
        gen.if((0, codegen_1._)`${err}.instancePath === undefined`, () => gen.assign((0, codegen_1._)`${err}.instancePath`, (0, codegen_1.strConcat)(names_1.default.instancePath, it2.errorPath)));
        gen.assign((0, codegen_1._)`${err}.schemaPath`, (0, codegen_1.str)`${it2.errSchemaPath}/${keyword}`);
        if (it2.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(it2, errs) {
      const { gen, validateName: validateName2, schemaEnv } = it2;
      if (schemaEnv.$async) {
        gen.throw((0, codegen_1._)`new ${it2.ValidationError}(${errs})`);
      } else {
        gen.assign((0, codegen_1._)`${validateName2}.errors`, errs);
        gen.return(false);
      }
    }
    __name(returnErrors, "returnErrors");
    var E2 = {
      keyword: new codegen_1.Name("keyword"),
      schemaPath: new codegen_1.Name("schemaPath"),
      // also used in JTD errors
      params: new codegen_1.Name("params"),
      propertyName: new codegen_1.Name("propertyName"),
      message: new codegen_1.Name("message"),
      schema: new codegen_1.Name("schema"),
      parentSchema: new codegen_1.Name("parentSchema")
    };
    function errorObjectCode(cxt, error2, errorPaths) {
      const { createErrors } = cxt.it;
      if (createErrors === false)
        return (0, codegen_1._)`{}`;
      return errorObject(cxt, error2, errorPaths);
    }
    __name(errorObjectCode, "errorObjectCode");
    function errorObject(cxt, error2, errorPaths = {}) {
      const { gen, it: it2 } = cxt;
      const keyValues = [
        errorInstancePath(it2, errorPaths),
        errorSchemaPath(cxt, errorPaths)
      ];
      extraErrorProps(cxt, error2, keyValues);
      return gen.object(...keyValues);
    }
    __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 [E2.schemaPath, schPath];
    }
    __name(errorSchemaPath, "errorSchemaPath");
    function extraErrorProps(cxt, { params, message }, keyValues) {
      const { keyword, data, schemaValue, it: it2 } = cxt;
      const { opts, propertyName, topSchemaRef, schemaPath } = it2;
      keyValues.push([E2.keyword, keyword], [E2.params, typeof params == "function" ? params(cxt) : params || (0, codegen_1._)`{}`]);
      if (opts.messages) {
        keyValues.push([E2.message, typeof message == "function" ? message(cxt) : message]);
      }
      if (opts.verbose) {
        keyValues.push([E2.schema, schemaValue], [E2.parentSchema, (0, codegen_1._)`${topSchemaRef}${schemaPath}`], [names_1.default.data, data]);
      }
      if (propertyName)
        keyValues.push([E2.propertyName, propertyName]);
    }
    __name(extraErrorProps, "extraErrorProps");
  }
});

// packages/cli/node_modules/ajv/dist/compile/validate/boolSchema.js
var require_boolSchema3 = __commonJS({
  "packages/cli/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_errors4();
    var codegen_1 = require_codegen4();
    var names_1 = require_names3();
    var boolError = {
      message: "boolean schema is false"
    };
    function topBoolOrEmptySchema(it2) {
      const { gen, schema, validateName: validateName2 } = it2;
      if (schema === false) {
        falseSchemaError(it2, false);
      } else if (typeof schema == "object" && schema.$async === true) {
        gen.return(names_1.default.data);
      } else {
        gen.assign((0, codegen_1._)`${validateName2}.errors`, null);
        gen.return(true);
      }
    }
    __name(topBoolOrEmptySchema, "topBoolOrEmptySchema");
    exports2.topBoolOrEmptySchema = topBoolOrEmptySchema;
    function boolOrEmptySchema(it2, valid) {
      const { gen, schema } = it2;
      if (schema === false) {
        gen.var(valid, false);
        falseSchemaError(it2);
      } else {
        gen.var(valid, true);
      }
    }
    __name(boolOrEmptySchema, "boolOrEmptySchema");
    exports2.boolOrEmptySchema = boolOrEmptySchema;
    function falseSchemaError(it2, overrideAllErrors) {
      const { gen, data } = it2;
      const cxt = {
        gen,
        keyword: "false schema",
        data,
        schema: false,
        schemaCode: false,
        schemaValue: false,
        params: {},
        it: it2
      };
      (0, errors_1.reportError)(cxt, boolError, void 0, overrideAllErrors);
    }
    __name(falseSchemaError, "falseSchemaError");
  }
});

// packages/cli/node_modules/ajv/dist/compile/rules.js
var require_rules3 = __commonJS({
  "packages/cli/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(x3) {
      return typeof x3 == "string" && jsonTypes.has(x3);
    }
    __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/cli/node_modules/ajv/dist/compile/validate/applicability.js
var require_applicability3 = __commonJS({
  "packages/cli/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 _a7;
      return schema[rule.keyword] !== void 0 || ((_a7 = rule.definition.implements) === null || _a7 === void 0 ? void 0 : _a7.some((kwd) => schema[kwd] !== void 0));
    }
    __name(shouldUseRule, "shouldUseRule");
    exports2.shouldUseRule = shouldUseRule;
  }
});

// packages/cli/node_modules/ajv/dist/compile/validate/dataType.js
var require_dataType3 = __commonJS({
  "packages/cli/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_rules3();
    var applicability_1 = require_applicability3();
    var errors_1 = require_errors4();
    var codegen_1 = require_codegen4();
    var util_1 = require_util21();
    var DataType;
    (function(DataType2) {
      DataType2[DataType2["Correct"] = 0] = "Correct";
      DataType2[DataType2["Wrong"] = 1] = "Wrong";
    })(DataType || (exports2.DataType = DataType = {}));
    function getSchemaTypes(schema) {
      const types7 = getJSONTypes(schema.type);
      const hasNull = types7.includes("null");
      if (hasNull) {
        if (schema.nullable === false)
          throw new Error("type: null contradicts nullable: false");
      } else {
        if (!types7.length && schema.nullable !== void 0) {
          throw new Error('"nullable" cannot be used without "type"');
        }
        if (schema.nullable === true)
          types7.push("null");
      }
      return types7;
    }
    __name(getSchemaTypes, "getSchemaTypes");
    exports2.getSchemaTypes = getSchemaTypes;
    function getJSONTypes(ts) {
      const types7 = Array.isArray(ts) ? ts : ts ? [ts] : [];
      if (types7.every(rules_1.isJSONType))
        return types7;
      throw new Error("type must be JSONType or JSONType[]: " + types7.join(","));
    }
    __name(getJSONTypes, "getJSONTypes");
    exports2.getJSONTypes = getJSONTypes;
    function coerceAndCheckDataType(it2, types7) {
      const { gen, data, opts } = it2;
      const coerceTo = coerceToTypes(types7, opts.coerceTypes);
      const checkTypes = types7.length > 0 && !(coerceTo.length === 0 && types7.length === 1 && (0, applicability_1.schemaHasRulesForType)(it2, types7[0]));
      if (checkTypes) {
        const wrongType = checkDataTypes(types7, data, opts.strictNumbers, DataType.Wrong);
        gen.if(wrongType, () => {
          if (coerceTo.length)
            coerceData(it2, types7, coerceTo);
          else
            reportTypeError(it2);
        });
      }
      return checkTypes;
    }
    __name(coerceAndCheckDataType, "coerceAndCheckDataType");
    exports2.coerceAndCheckDataType = coerceAndCheckDataType;
    var COERCIBLE = /* @__PURE__ */ new Set(["string", "number", "integer", "boolean", "null"]);
    function coerceToTypes(types7, coerceTypes) {
      return coerceTypes ? types7.filter((t5) => COERCIBLE.has(t5) || coerceTypes === "array" && t5 === "array") : [];
    }
    __name(coerceToTypes, "coerceToTypes");
    function coerceData(it2, types7, coerceTo) {
      const { gen, data, opts } = it2;
      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(types7, data, opts.strictNumbers), () => gen.assign(coerced, data)));
      }
      gen.if((0, codegen_1._)`${coerced} !== undefined`);
      for (const t5 of coerceTo) {
        if (COERCIBLE.has(t5) || t5 === "array" && opts.coerceTypes === "array") {
          coerceSpecificType(t5);
        }
      }
      gen.else();
      reportTypeError(it2);
      gen.endIf();
      gen.if((0, codegen_1._)`${coerced} !== undefined`, () => {
        gen.assign(data, coerced);
        assignParentData(it2, coerced);
      });
      function coerceSpecificType(t5) {
        switch (t5) {
          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 types7 = (0, util_1.toHash)(dataTypes);
      if (types7.array && types7.object) {
        const notObj = (0, codegen_1._)`typeof ${data} != "object"`;
        cond = types7.null ? notObj : (0, codegen_1._)`!${data} || ${notObj}`;
        delete types7.null;
        delete types7.array;
        delete types7.object;
      } else {
        cond = codegen_1.nil;
      }
      if (types7.number)
        delete types7.integer;
      for (const t5 in types7)
        cond = (0, codegen_1.and)(cond, checkDataType(t5, 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(it2) {
      const cxt = getTypeErrorContext(it2);
      (0, errors_1.reportError)(cxt, typeError);
    }
    __name(reportTypeError, "reportTypeError");
    exports2.reportTypeError = reportTypeError;
    function getTypeErrorContext(it2) {
      const { gen, data, schema } = it2;
      const schemaCode = (0, util_1.schemaRefOrVal)(it2, schema, "type");
      return {
        gen,
        keyword: "type",
        data,
        schema: schema.type,
        schemaCode,
        schemaValue: schemaCode,
        parentSchema: schema,
        params: {},
        it: it2
      };
    }
    __name(getTypeErrorContext, "getTypeErrorContext");
  }
});

// packages/cli/node_modules/ajv/dist/compile/validate/defaults.js
var require_defaults3 = __commonJS({
  "packages/cli/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_codegen4();
    var util_1 = require_util21();
    function assignDefaults(it2, ty) {
      const { properties, items } = it2.schema;
      if (ty === "object" && properties) {
        for (const key in properties) {
          assignDefault(it2, key, properties[key].default);
        }
      } else if (ty === "array" && Array.isArray(items)) {
        items.forEach((sch, i3) => assignDefault(it2, i3, sch.default));
      }
    }
    __name(assignDefaults, "assignDefaults");
    exports2.assignDefaults = assignDefaults;
    function assignDefault(it2, prop, defaultValue) {
      const { gen, compositeRule, data, opts } = it2;
      if (defaultValue === void 0)
        return;
      const childData = (0, codegen_1._)`${data}${(0, codegen_1.getProperty)(prop)}`;
      if (compositeRule) {
        (0, util_1.checkStrictMode)(it2, `default is ignored for: ${childData}`);
        return;
      }
      let condition = (0, codegen_1._)`${childData} === undefined`;
      if (opts.useDefaults === "empty") {
        condition = (0, codegen_1._)`${condition} || ${childData} === null || ${childData} === ""`;
      }
      gen.if(condition, (0, codegen_1._)`${childData} = ${(0, codegen_1.stringify)(defaultValue)}`);
    }
    __name(assignDefault, "assignDefault");
  }
});

// packages/cli/node_modules/ajv/dist/vocabularies/code.js
var require_code6 = __commonJS({
  "packages/cli/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_codegen4();
    var util_1 = require_util21();
    var names_1 = require_names3();
    var util_2 = require_util21();
    function checkReportMissingProp(cxt, prop) {
      const { gen, data, it: it2 } = cxt;
      gen.if(noPropertyInData(gen, data, prop, it2.opts.ownProperties), () => {
        cxt.setParams({ missingProperty: (0, codegen_1._)`${prop}` }, true);
        cxt.error();
      });
    }
    __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((p2) => p2 !== "__proto__") : [];
    }
    __name(allSchemaProperties, "allSchemaProperties");
    exports2.allSchemaProperties = allSchemaProperties;
    function schemaProperties(it2, schemaMap) {
      return allSchemaProperties(schemaMap).filter((p2) => !(0, util_1.alwaysValidSchema)(it2, schemaMap[p2]));
    }
    __name(schemaProperties, "schemaProperties");
    exports2.schemaProperties = schemaProperties;
    function callValidateCode({ schemaCode, data, it: { gen, topSchemaRef, schemaPath, errorPath }, it: it2 }, 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, it2.parentData],
        [names_1.default.parentDataProperty, it2.parentDataProperty],
        [names_1.default.rootData, names_1.default.rootData]
      ];
      if (it2.opts.dynamicRef)
        valCxt.push([names_1.default.dynamicAnchors, names_1.default.dynamicAnchors]);
      const args = (0, codegen_1._)`${dataAndSchema}, ${gen.object(...valCxt)}`;
      return 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 u2 = opts.unicodeRegExp ? "u" : "";
      const { regExp } = opts.code;
      const rx = regExp(pattern, u2);
      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}, ${u2})`
      });
    }
    __name(usePattern, "usePattern");
    exports2.usePattern = usePattern;
    function validateArray(cxt) {
      const { gen, data, keyword, it: it2 } = cxt;
      const valid = gen.name("valid");
      if (it2.allErrors) {
        const validArr = gen.let("valid", true);
        validateItems(() => gen.assign(validArr, false));
        return validArr;
      }
      gen.var(valid, true);
      validateItems(() => gen.break());
      return valid;
      function validateItems(notValid) {
        const len = gen.const("len", (0, codegen_1._)`${data}.length`);
        gen.forRange("i", 0, len, (i3) => {
          cxt.subschema({
            keyword,
            dataProp: i3,
            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: it2 } = cxt;
      if (!Array.isArray(schema))
        throw new Error("ajv implementation error");
      const alwaysValid = schema.some((sch) => (0, util_1.alwaysValidSchema)(it2, sch));
      if (alwaysValid && !it2.opts.unevaluated)
        return;
      const valid = gen.let("valid", false);
      const schValid = gen.name("_valid");
      gen.block(() => schema.forEach((_sch, i3) => {
        const schCxt = cxt.subschema({
          keyword,
          schemaProp: i3,
          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/cli/node_modules/ajv/dist/compile/validate/keyword.js
var require_keyword4 = __commonJS({
  "packages/cli/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_codegen4();
    var names_1 = require_names3();
    var code_1 = require_code6();
    var errors_1 = require_errors4();
    function macroKeywordCode(cxt, def2) {
      const { gen, keyword, schema, parentSchema, it: it2 } = cxt;
      const macroSchema = def2.macro.call(it2.self, schema, parentSchema, it2);
      const schemaRef = useKeyword(gen, keyword, macroSchema);
      if (it2.opts.validateSchema !== false)
        it2.self.validateSchema(macroSchema, true);
      const valid = gen.name("valid");
      cxt.subschema({
        schema: macroSchema,
        schemaPath: codegen_1.nil,
        errSchemaPath: `${it2.errSchemaPath}/${keyword}`,
        topSchemaRef: schemaRef,
        compositeRule: true
      }, valid);
      cxt.pass(valid, () => cxt.error(true));
    }
    __name(macroKeywordCode, "macroKeywordCode");
    exports2.macroKeywordCode = macroKeywordCode;
    function funcKeywordCode(cxt, def2) {
      var _a7;
      const { gen, keyword, schema, parentSchema, $data, it: it2 } = cxt;
      checkAsyncKeyword(it2, def2);
      const validate3 = !$data && def2.compile ? def2.compile.call(it2.self, schema, parentSchema, it2) : def2.validate;
      const validateRef = useKeyword(gen, keyword, validate3);
      const valid = gen.let("valid");
      cxt.block$data(valid, validateKeyword);
      cxt.ok((_a7 = def2.valid) !== null && _a7 !== void 0 ? _a7 : 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 `), (e4) => gen.assign(valid, false).if((0, codegen_1._)`${e4} instanceof ${it2.ValidationError}`, () => gen.assign(ruleErrs, (0, codegen_1._)`${e4}.errors`), () => gen.throw(e4)));
        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 = it2.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 _a8;
        gen.if((0, codegen_1.not)((_a8 = def2.valid) !== null && _a8 !== void 0 ? _a8 : valid), errors);
      }
      __name(reportErrs, "reportErrs");
    }
    __name(funcKeywordCode, "funcKeywordCode");
    exports2.funcKeywordCode = funcKeywordCode;
    function modifyData(cxt) {
      const { gen, data, it: it2 } = cxt;
      gen.if(it2.parentData, () => gen.assign(data, (0, codegen_1._)`${it2.parentData}[${it2.parentDataProperty}]`));
    }
    __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((st2) => st2 === "array" ? Array.isArray(schema) : st2 === "object" ? schema && typeof schema == "object" && !Array.isArray(schema) : typeof schema == st2 || 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/cli/node_modules/ajv/dist/compile/validate/subschema.js
var require_subschema3 = __commonJS({
  "packages/cli/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_codegen4();
    var util_1 = require_util21();
    function getSubschema(it2, { 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 = it2.schema[keyword];
        return schemaProp === void 0 ? {
          schema: sch,
          schemaPath: (0, codegen_1._)`${it2.schemaPath}${(0, codegen_1.getProperty)(keyword)}`,
          errSchemaPath: `${it2.errSchemaPath}/${keyword}`
        } : {
          schema: sch[schemaProp],
          schemaPath: (0, codegen_1._)`${it2.schemaPath}${(0, codegen_1.getProperty)(keyword)}${(0, codegen_1.getProperty)(schemaProp)}`,
          errSchemaPath: `${it2.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, it2, { dataProp, dataPropType: dpType, data, dataTypes, propertyName }) {
      if (data !== void 0 && dataProp !== void 0) {
        throw new Error('both "data" and "dataProp" passed, only one allowed');
      }
      const { gen } = it2;
      if (dataProp !== void 0) {
        const { errorPath, dataPathArr, opts } = it2;
        const nextData = gen.let("data", (0, codegen_1._)`${it2.data}${(0, codegen_1.getProperty)(dataProp)}`, true);
        dataContextProps(nextData);
        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 = it2.dataLevel + 1;
        subschema.dataTypes = [];
        it2.definedProperties = /* @__PURE__ */ new Set();
        subschema.parentData = it2.data;
        subschema.dataNames = [...it2.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;
  }
});

// packages/cli/node_modules/json-schema-traverse/index.js
var require_json_schema_traverse3 = __commonJS({
  "packages/cli/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 i3 = 0; i3 < sch.length; i3++)
                _traverse(opts, pre, post, sch[i3], jsonPtr + "/" + key + "/" + i3, rootSchema, jsonPtr, key, schema, i3);
            }
          } 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/cli/node_modules/ajv/dist/compile/resolve.js
var require_resolve4 = __commonJS({
  "packages/cli/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_util21();
    var equal = require_fast_deep_equal();
    var traverse = require_json_schema_traverse3();
    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 = "", normalize12) {
      if (normalize12 !== false)
        id = normalizeId(id);
      const p2 = resolver.parse(id);
      return _getFullPath(resolver, p2);
    }
    __name(getFullPath, "getFullPath");
    exports2.getFullPath = getFullPath;
    function _getFullPath(resolver, p2) {
      const serialized = resolver.serialize(p2);
      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, _2, 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/cli/node_modules/ajv/dist/compile/validate/index.js
var require_validate3 = __commonJS({
  "packages/cli/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_boolSchema3();
    var dataType_1 = require_dataType3();
    var applicability_1 = require_applicability3();
    var dataType_2 = require_dataType3();
    var defaults_1 = require_defaults3();
    var keyword_1 = require_keyword4();
    var subschema_1 = require_subschema3();
    var codegen_1 = require_codegen4();
    var names_1 = require_names3();
    var resolve_1 = require_resolve4();
    var util_1 = require_util21();
    var errors_1 = require_errors4();
    function validateFunctionCode(it2) {
      if (isSchemaObj(it2)) {
        checkKeywords(it2);
        if (schemaCxtHasRules(it2)) {
          topSchemaObjCode(it2);
          return;
        }
      }
      validateFunction(it2, () => (0, boolSchema_1.topBoolOrEmptySchema)(it2));
    }
    __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(it2) {
      const { schema, opts, gen } = it2;
      validateFunction(it2, () => {
        if (opts.$comment && schema.$comment)
          commentKeyword(it2);
        checkNoDefault(it2);
        gen.let(names_1.default.vErrors, null);
        gen.let(names_1.default.errors, 0);
        if (opts.unevaluated)
          resetEvaluated(it2);
        typeAndKeywords(it2);
        returnResults(it2);
      });
      return;
    }
    __name(topSchemaObjCode, "topSchemaObjCode");
    function resetEvaluated(it2) {
      const { gen, validateName: validateName2 } = it2;
      it2.evaluated = gen.const("evaluated", (0, codegen_1._)`${validateName2}.evaluated`);
      gen.if((0, codegen_1._)`${it2.evaluated}.dynamicProps`, () => gen.assign((0, codegen_1._)`${it2.evaluated}.props`, (0, codegen_1._)`undefined`));
      gen.if((0, codegen_1._)`${it2.evaluated}.dynamicItems`, () => gen.assign((0, codegen_1._)`${it2.evaluated}.items`, (0, codegen_1._)`undefined`));
    }
    __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(it2, valid) {
      if (isSchemaObj(it2)) {
        checkKeywords(it2);
        if (schemaCxtHasRules(it2)) {
          subSchemaObjCode(it2, valid);
          return;
        }
      }
      (0, boolSchema_1.boolOrEmptySchema)(it2, 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(it2) {
      return typeof it2.schema != "boolean";
    }
    __name(isSchemaObj, "isSchemaObj");
    function subSchemaObjCode(it2, valid) {
      const { schema, gen, opts } = it2;
      if (opts.$comment && schema.$comment)
        commentKeyword(it2);
      updateContext(it2);
      checkAsyncSchema(it2);
      const errsCount = gen.const("_errs", names_1.default.errors);
      typeAndKeywords(it2, errsCount);
      gen.var(valid, (0, codegen_1._)`${errsCount} === ${names_1.default.errors}`);
    }
    __name(subSchemaObjCode, "subSchemaObjCode");
    function checkKeywords(it2) {
      (0, util_1.checkUnknownRules)(it2);
      checkRefsAndKeywords(it2);
    }
    __name(checkKeywords, "checkKeywords");
    function typeAndKeywords(it2, errsCount) {
      if (it2.opts.jtd)
        return schemaKeywords(it2, [], false, errsCount);
      const types7 = (0, dataType_1.getSchemaTypes)(it2.schema);
      const checkedTypes = (0, dataType_1.coerceAndCheckDataType)(it2, types7);
      schemaKeywords(it2, types7, !checkedTypes, errsCount);
    }
    __name(typeAndKeywords, "typeAndKeywords");
    function checkRefsAndKeywords(it2) {
      const { schema, errSchemaPath, opts, self: self2 } = it2;
      if (schema.$ref && opts.ignoreKeywordsWithRef && (0, util_1.schemaHasRulesButRef)(schema, self2.RULES)) {
        self2.logger.warn(`$ref: keywords ignored in schema at path "${errSchemaPath}"`);
      }
    }
    __name(checkRefsAndKeywords, "checkRefsAndKeywords");
    function checkNoDefault(it2) {
      const { schema, opts } = it2;
      if (schema.default !== void 0 && opts.useDefaults && opts.strictSchema) {
        (0, util_1.checkStrictMode)(it2, "default is ignored in the schema root");
      }
    }
    __name(checkNoDefault, "checkNoDefault");
    function updateContext(it2) {
      const schId = it2.schema[it2.opts.schemaId];
      if (schId)
        it2.baseId = (0, resolve_1.resolveUrl)(it2.opts.uriResolver, it2.baseId, schId);
    }
    __name(updateContext, "updateContext");
    function checkAsyncSchema(it2) {
      if (it2.schema.$async && !it2.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(it2) {
      const { gen, schemaEnv, validateName: validateName2, ValidationError, opts } = it2;
      if (schemaEnv.$async) {
        gen.if((0, codegen_1._)`${names_1.default.errors} === 0`, () => gen.return(names_1.default.data), () => gen.throw((0, codegen_1._)`new ${ValidationError}(${names_1.default.vErrors})`));
      } else {
        gen.assign((0, codegen_1._)`${validateName2}.errors`, names_1.default.vErrors);
        if (opts.unevaluated)
          assignEvaluated(it2);
        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(it2, types7, typeErrors, errsCount) {
      const { gen, schema, data, allErrors, opts, self: self2 } = it2;
      const { RULES } = self2;
      if (schema.$ref && (opts.ignoreKeywordsWithRef || !(0, util_1.schemaHasRulesButRef)(schema, RULES))) {
        gen.block(() => keywordCode(it2, "$ref", RULES.all.$ref.definition));
        return;
      }
      if (!opts.jtd)
        checkStrictTypes(it2, types7);
      gen.block(() => {
        for (const group of RULES.rules)
          groupKeywords(group);
        groupKeywords(RULES.post);
      });
      function groupKeywords(group) {
        if (!(0, applicability_1.shouldUseGroup)(schema, group))
          return;
        if (group.type) {
          gen.if((0, dataType_2.checkDataType)(group.type, data, opts.strictNumbers));
          iterateKeywords(it2, group);
          if (types7.length === 1 && types7[0] === group.type && typeErrors) {
            gen.else();
            (0, dataType_2.reportTypeError)(it2);
          }
          gen.endIf();
        } else {
          iterateKeywords(it2, group);
        }
        if (!allErrors)
          gen.if((0, codegen_1._)`${names_1.default.errors} === ${errsCount || 0}`);
      }
      __name(groupKeywords, "groupKeywords");
    }
    __name(schemaKeywords, "schemaKeywords");
    function iterateKeywords(it2, group) {
      const { gen, schema, opts: { useDefaults } } = it2;
      if (useDefaults)
        (0, defaults_1.assignDefaults)(it2, group.type);
      gen.block(() => {
        for (const rule of group.rules) {
          if ((0, applicability_1.shouldUseRule)(schema, rule)) {
            keywordCode(it2, rule.keyword, rule.definition, group.type);
          }
        }
      });
    }
    __name(iterateKeywords, "iterateKeywords");
    function checkStrictTypes(it2, types7) {
      if (it2.schemaEnv.meta || !it2.opts.strictTypes)
        return;
      checkContextTypes(it2, types7);
      if (!it2.opts.allowUnionTypes)
        checkMultipleTypes(it2, types7);
      checkKeywordTypes(it2, it2.dataTypes);
    }
    __name(checkStrictTypes, "checkStrictTypes");
    function checkContextTypes(it2, types7) {
      if (!types7.length)
        return;
      if (!it2.dataTypes.length) {
        it2.dataTypes = types7;
        return;
      }
      types7.forEach((t5) => {
        if (!includesType(it2.dataTypes, t5)) {
          strictTypesError(it2, `type "${t5}" not allowed by context "${it2.dataTypes.join(",")}"`);
        }
      });
      narrowSchemaTypes(it2, types7);
    }
    __name(checkContextTypes, "checkContextTypes");
    function checkMultipleTypes(it2, ts) {
      if (ts.length > 1 && !(ts.length === 2 && ts.includes("null"))) {
        strictTypesError(it2, "use allowUnionTypes to allow union type keyword");
      }
    }
    __name(checkMultipleTypes, "checkMultipleTypes");
    function checkKeywordTypes(it2, ts) {
      const rules = it2.self.RULES.all;
      for (const keyword in rules) {
        const rule = rules[keyword];
        if (typeof rule == "object" && (0, applicability_1.shouldUseRule)(it2.schema, rule)) {
          const { type } = rule.definition;
          if (type.length && !type.some((t5) => hasApplicableType(ts, t5))) {
            strictTypesError(it2, `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, t5) {
      return ts.includes(t5) || t5 === "integer" && ts.includes("number");
    }
    __name(includesType, "includesType");
    function narrowSchemaTypes(it2, withTypes) {
      const ts = [];
      for (const t5 of it2.dataTypes) {
        if (includesType(withTypes, t5))
          ts.push(t5);
        else if (withTypes.includes("integer") && t5 === "number")
          ts.push("integer");
      }
      it2.dataTypes = ts;
    }
    __name(narrowSchemaTypes, "narrowSchemaTypes");
    function strictTypesError(it2, msg) {
      const schemaPath = it2.schemaEnv.baseId + it2.errSchemaPath;
      msg += ` at "${schemaPath}" (strictTypes)`;
      (0, util_1.checkStrictMode)(it2, msg, it2.opts.strictTypes);
    }
    __name(strictTypesError, "strictTypesError");
    var KeywordCxt = class {
      static {
        __name(this, "KeywordCxt");
      }
      constructor(it2, def2, keyword) {
        (0, keyword_1.validateKeywordUsage)(it2, def2, keyword);
        this.gen = it2.gen;
        this.allErrors = it2.allErrors;
        this.keyword = keyword;
        this.data = it2.data;
        this.schema = it2.schema[keyword];
        this.$data = def2.$data && it2.opts.$data && this.schema && this.schema.$data;
        this.schemaValue = (0, util_1.schemaRefOrVal)(it2, this.schema, keyword, this.$data);
        this.schemaType = def2.schemaType;
        this.parentSchema = it2.schema;
        this.params = {};
        this.it = it2;
        this.def = def2;
        if (this.$data) {
          this.schemaCode = it2.gen.const("vSchema", getData(this.$data, it2));
        } else {
          this.schemaCode = this.schemaValue;
          if (!(0, keyword_1.validSchemaType)(this.schema, 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 = it2.gen.const("_errs", names_1.default.errors);
        }
      }
      result(condition, successAction, failAction) {
        this.failResult((0, codegen_1.not)(condition), successAction, failAction);
      }
      failResult(condition, successAction, failAction) {
        this.gen.if(condition);
        if (failAction)
          failAction();
        else
          this.error();
        if (successAction) {
          this.gen.else();
          successAction();
          if (this.allErrors)
            this.gen.endIf();
        } else {
          if (this.allErrors)
            this.gen.endIf();
          else
            this.gen.else();
        }
      }
      pass(condition, failAction) {
        this.failResult((0, codegen_1.not)(condition), void 0, failAction);
      }
      fail(condition) {
        if (condition === void 0) {
          this.error();
          if (!this.allErrors)
            this.gen.if(false);
          return;
        }
        this.gen.if(condition);
        this.error();
        if (this.allErrors)
          this.gen.endIf();
        else
          this.gen.else();
      }
      fail$data(condition) {
        if (!this.$data)
          return this.fail(condition);
        const { schemaCode } = this;
        this.fail((0, codegen_1._)`${schemaCode} !== undefined && (${(0, codegen_1.or)(this.invalid$data(), condition)})`);
      }
      error(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: it2 } = this;
        return (0, codegen_1.or)(wrong$DataType(), invalid$DataSchema());
        function wrong$DataType() {
          if (schemaType.length) {
            if (!(schemaCode instanceof codegen_1.Name))
              throw new Error("ajv implementation error");
            const st2 = Array.isArray(schemaType) ? schemaType : [schemaType];
            return (0, codegen_1._)`${(0, dataType_2.checkDataTypes)(st2, schemaCode, it2.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: it2, gen } = this;
        if (!it2.opts.unevaluated)
          return;
        if (it2.props !== true && schemaCxt.props !== void 0) {
          it2.props = util_1.mergeEvaluated.props(gen, schemaCxt.props, it2.props, toName);
        }
        if (it2.items !== true && schemaCxt.items !== void 0) {
          it2.items = util_1.mergeEvaluated.items(gen, schemaCxt.items, it2.items, toName);
        }
      }
      mergeValidEvaluated(schemaCxt, valid) {
        const { it: it2, gen } = this;
        if (it2.opts.unevaluated && (it2.props !== true || it2.items !== true)) {
          gen.if(valid, () => this.mergeEvaluated(schemaCxt, codegen_1.Name));
          return true;
        }
      }
    };
    exports2.KeywordCxt = KeywordCxt;
    function keywordCode(it2, keyword, def2, ruleType) {
      const cxt = new KeywordCxt(it2, 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/cli/node_modules/ajv/dist/runtime/validation_error.js
var require_validation_error3 = __commonJS({
  "packages/cli/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/cli/node_modules/ajv/dist/compile/ref_error.js
var require_ref_error3 = __commonJS({
  "packages/cli/node_modules/ajv/dist/compile/ref_error.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    var resolve_1 = require_resolve4();
    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/cli/node_modules/ajv/dist/compile/index.js
var require_compile3 = __commonJS({
  "packages/cli/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_codegen4();
    var validation_error_1 = require_validation_error3();
    var names_1 = require_names3();
    var resolve_1 = require_resolve4();
    var util_1 = require_util21();
    var validate_1 = require_validate3();
    var SchemaEnv = class {
      static {
        __name(this, "SchemaEnv");
      }
      constructor(env7) {
        var _a7;
        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 = (_a7 = env7.baseId) !== null && _a7 !== void 0 ? _a7 : (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 validate3 = makeValidate(this, this.scope.get());
        this.scope.value(validateName2, { ref: validate3 });
        validate3.errors = null;
        validate3.schema = sch.schema;
        validate3.schemaEnv = sch;
        if (sch.$async)
          validate3.$async = true;
        if (this.opts.code.source === true) {
          validate3.source = { validateName: validateName2, validateCode, scopeValues: gen._values };
        }
        if (this.opts.unevaluated) {
          const { props, items } = schemaCxt;
          validate3.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 (validate3.source)
            validate3.source.evaluated = (0, codegen_1.stringify)(validate3.evaluated);
        }
        sch.validate = validate3;
        return sch;
      } catch (e4) {
        delete sch.validate;
        delete sch.validateName;
        if (sourceCode)
          this.logger.error("Error compiling schema, function code:", sourceCode);
        throw e4;
      } finally {
        this._compilations.delete(sch);
      }
    }
    __name(compileSchema, "compileSchema");
    exports2.compileSchema = compileSchema;
    function resolveRef(root, baseId, ref) {
      var _a7;
      ref = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, ref);
      const schOrFunc = root.refs[ref];
      if (schOrFunc)
        return schOrFunc;
      let _sch = resolve30.call(this, root, ref);
      if (_sch === void 0) {
        const schema = (_a7 = root.localRefs) === null || _a7 === void 0 ? void 0 : _a7[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, s22) {
      return s1.schema === s22.schema && s1.root === s22.root && s1.baseId === s22.baseId;
    }
    __name(sameSchemaEnv, "sameSchemaEnv");
    function resolve30(root, ref) {
      let sch;
      while (typeof (sch = this.refs[ref]) == "string")
        ref = sch;
      return sch || this.schemas[ref] || resolveSchema.call(this, root, ref);
    }
    __name(resolve30, "resolve");
    function resolveSchema(root, ref) {
      const p2 = this.opts.uriResolver.parse(ref);
      const refPath = (0, resolve_1._getFullPath)(this.opts.uriResolver, p2);
      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, p2, 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, p2, 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, p2, 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 _a7;
      if (((_a7 = parsedRef.fragment) === null || _a7 === void 0 ? void 0 : _a7[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/cli/node_modules/ajv/dist/refs/data.json
var require_data3 = __commonJS({
  "packages/cli/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
    };
  }
});

// packages/cli/node_modules/ajv/dist/runtime/uri.js
var require_uri3 = __commonJS({
  "packages/cli/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/cli/node_modules/ajv/dist/core.js
var require_core9 = __commonJS({
  "packages/cli/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_validate3();
    Object.defineProperty(exports2, "KeywordCxt", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return validate_1.KeywordCxt;
    }, "get") });
    var codegen_1 = require_codegen4();
    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_error3();
    var ref_error_1 = require_ref_error3();
    var rules_1 = require_rules3();
    var compile_1 = require_compile3();
    var codegen_2 = require_codegen4();
    var resolve_1 = require_resolve4();
    var dataType_1 = require_dataType3();
    var util_1 = require_util21();
    var $dataRefSchema = require_data3();
    var uri_1 = require_uri3();
    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(o3) {
      var _a7, _b2, _c2, _d, _e2, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r2, _s, _t2, _u, _v, _w, _x, _y, _z, _0;
      const s5 = o3.strict;
      const _optz = (_a7 = o3.code) === null || _a7 === void 0 ? void 0 : _a7.optimize;
      const optimize = _optz === true || _optz === void 0 ? 1 : _optz || 0;
      const regExp = (_c2 = (_b2 = o3.code) === null || _b2 === void 0 ? void 0 : _b2.regExp) !== null && _c2 !== void 0 ? _c2 : defaultRegExp;
      const uriResolver = (_d = o3.uriResolver) !== null && _d !== void 0 ? _d : uri_1.default;
      return {
        strictSchema: (_f = (_e2 = o3.strictSchema) !== null && _e2 !== void 0 ? _e2 : s5) !== null && _f !== void 0 ? _f : true,
        strictNumbers: (_h = (_g = o3.strictNumbers) !== null && _g !== void 0 ? _g : s5) !== null && _h !== void 0 ? _h : true,
        strictTypes: (_k = (_j = o3.strictTypes) !== null && _j !== void 0 ? _j : s5) !== null && _k !== void 0 ? _k : "log",
        strictTuples: (_m = (_l = o3.strictTuples) !== null && _l !== void 0 ? _l : s5) !== null && _m !== void 0 ? _m : "log",
        strictRequired: (_p = (_o = o3.strictRequired) !== null && _o !== void 0 ? _o : s5) !== null && _p !== void 0 ? _p : false,
        code: o3.code ? { ...o3.code, optimize, regExp } : { optimize, regExp },
        loopRequired: (_q = o3.loopRequired) !== null && _q !== void 0 ? _q : MAX_EXPRESSION,
        loopEnum: (_r2 = o3.loopEnum) !== null && _r2 !== void 0 ? _r2 : MAX_EXPRESSION,
        meta: (_s = o3.meta) !== null && _s !== void 0 ? _s : true,
        messages: (_t2 = o3.messages) !== null && _t2 !== void 0 ? _t2 : true,
        inlineRefs: (_u = o3.inlineRefs) !== null && _u !== void 0 ? _u : true,
        schemaId: (_v = o3.schemaId) !== null && _v !== void 0 ? _v : "$id",
        addUsedSchema: (_w = o3.addUsedSchema) !== null && _w !== void 0 ? _w : true,
        validateSchema: (_x = o3.validateSchema) !== null && _x !== void 0 ? _x : true,
        validateFormats: (_y = o3.validateFormats) !== null && _y !== void 0 ? _y : true,
        unicodeRegExp: (_z = o3.unicodeRegExp) !== null && _z !== void 0 ? _z : true,
        int32range: (_0 = o3.int32range) !== null && _0 !== void 0 ? _0 : true,
        uriResolver
      };
    }
    __name(requiredOptions, "requiredOptions");
    var Ajv3 = 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 v2;
        if (typeof schemaKeyRef == "string") {
          v2 = this.getSchema(schemaKeyRef);
          if (!v2)
            throw new Error(`no schema with key or ref "${schemaKeyRef}"`);
        } else {
          v2 = this.compile(schemaKeyRef);
        }
        const valid = v2(data);
        if (!("$async" in v2))
          this.errors = v2.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 (e4) {
            if (!(e4 instanceof ref_error_1.default))
              throw e4;
            checkLoaded.call(this, e4);
            await loadMissingSchema.call(this, e4.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 p2 = this._loading[ref];
          if (p2)
            return p2;
          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 ? (k2) => addRule.call(this, k2, definition) : (k2) => definition.type.forEach((t5) => addRule.call(this, k2, definition, t5)));
        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 i3 = group.rules.findIndex((rule) => rule.keyword === keyword);
          if (i3 >= 0)
            group.rules.splice(i3, 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((e4) => `${dataVar}${e4.instancePath} ${e4.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;
        }
      }
    };
    Ajv3.ValidationError = validation_error_1.default;
    Ajv3.MissingRefError = ref_error_1.default;
    exports2.default = Ajv3;
    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 _a7;
      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: t5 }) => t5 === 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;
      (_a7 = definition.implements) === null || _a7 === void 0 ? void 0 : _a7.forEach((kwd) => this.addKeyword(kwd));
    }
    __name(addRule, "addRule");
    function addBeforeRule(ruleGroup, rule, before) {
      const i3 = ruleGroup.rules.findIndex((_rule) => _rule.keyword === before);
      if (i3 >= 0) {
        ruleGroup.rules.splice(i3, 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/cli/node_modules/ajv/dist/vocabularies/core/id.js
var require_id3 = __commonJS({
  "packages/cli/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/cli/node_modules/ajv/dist/vocabularies/core/ref.js
var require_ref3 = __commonJS({
  "packages/cli/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_error3();
    var code_1 = require_code6();
    var codegen_1 = require_codegen4();
    var names_1 = require_names3();
    var compile_1 = require_compile3();
    var util_1 = require_util21();
    var def2 = {
      keyword: "$ref",
      schemaType: "string",
      code(cxt) {
        const { gen, schema: $ref, it: it2 } = cxt;
        const { baseId, schemaEnv: env7, validateName: validateName2, opts, self: self2 } = it2;
        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(it2.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 v2 = getValidate(cxt, sch);
          callRef(cxt, v2, 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, v2, sch, $async) {
      const { gen, it: it2 } = cxt;
      const { allErrors, schemaEnv: env7, opts } = it2;
      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, v2, passCxt)}`);
          addEvaluatedFrom(v2);
          if (!allErrors)
            gen.assign(valid, true);
        }, (e4) => {
          gen.if((0, codegen_1._)`!(${e4} instanceof ${it2.ValidationError})`, () => gen.throw(e4));
          addErrorsFrom(e4);
          if (!allErrors)
            gen.assign(valid, false);
        });
        cxt.ok(valid);
      }
      __name(callAsyncRef, "callAsyncRef");
      function callSyncRef() {
        cxt.result((0, code_1.callValidateCode)(cxt, v2, passCxt), () => addEvaluatedFrom(v2), () => addErrorsFrom(v2));
      }
      __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 _a7;
        if (!it2.opts.unevaluated)
          return;
        const schEvaluated = (_a7 = sch === null || sch === void 0 ? void 0 : sch.validate) === null || _a7 === void 0 ? void 0 : _a7.evaluated;
        if (it2.props !== true) {
          if (schEvaluated && !schEvaluated.dynamicProps) {
            if (schEvaluated.props !== void 0) {
              it2.props = util_1.mergeEvaluated.props(gen, schEvaluated.props, it2.props);
            }
          } else {
            const props = gen.var("props", (0, codegen_1._)`${source2}.evaluated.props`);
            it2.props = util_1.mergeEvaluated.props(gen, props, it2.props, codegen_1.Name);
          }
        }
        if (it2.items !== true) {
          if (schEvaluated && !schEvaluated.dynamicItems) {
            if (schEvaluated.items !== void 0) {
              it2.items = util_1.mergeEvaluated.items(gen, schEvaluated.items, it2.items);
            }
          } else {
            const items = gen.var("items", (0, codegen_1._)`${source2}.evaluated.items`);
            it2.items = util_1.mergeEvaluated.items(gen, items, it2.items, codegen_1.Name);
          }
        }
      }
      __name(addEvaluatedFrom, "addEvaluatedFrom");
    }
    __name(callRef, "callRef");
    exports2.callRef = callRef;
    exports2.default = def2;
  }
});

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

// packages/cli/node_modules/ajv/dist/vocabularies/validation/limitNumber.js
var require_limitNumber3 = __commonJS({
  "packages/cli/node_modules/ajv/dist/vocabularies/validation/limitNumber.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    var codegen_1 = require_codegen4();
    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 error2 = {
      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: error2,
      code(cxt) {
        const { keyword, data, schemaCode } = cxt;
        cxt.fail$data((0, codegen_1._)`${data} ${KWDs[keyword].fail} ${schemaCode} || isNaN(${data})`);
      }
    };
    exports2.default = def2;
  }
});

// packages/cli/node_modules/ajv/dist/vocabularies/validation/multipleOf.js
var require_multipleOf3 = __commonJS({
  "packages/cli/node_modules/ajv/dist/vocabularies/validation/multipleOf.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    var codegen_1 = require_codegen4();
    var error2 = {
      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: error2,
      code(cxt) {
        const { gen, data, schemaCode, it: it2 } = cxt;
        const prec = it2.opts.multipleOfPrecision;
        const res = gen.let("res");
        const invalid = prec ? (0, codegen_1._)`Math.abs(Math.round(${res}) - ${res}) > 1e-${prec}` : (0, codegen_1._)`${res} !== parseInt(${res})`;
        cxt.fail$data((0, codegen_1._)`(${schemaCode} === 0 || (${res} = ${data}/${schemaCode}, ${invalid}))`);
      }
    };
    exports2.default = def2;
  }
});

// packages/cli/node_modules/ajv/dist/runtime/ucs2length.js
var require_ucs2length3 = __commonJS({
  "packages/cli/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/cli/node_modules/ajv/dist/vocabularies/validation/limitLength.js
var require_limitLength3 = __commonJS({
  "packages/cli/node_modules/ajv/dist/vocabularies/validation/limitLength.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    var codegen_1 = require_codegen4();
    var util_1 = require_util21();
    var ucs2length_1 = require_ucs2length3();
    var error2 = {
      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: error2,
      code(cxt) {
        const { keyword, data, schemaCode, it: it2 } = cxt;
        const op = keyword === "maxLength" ? codegen_1.operators.GT : codegen_1.operators.LT;
        const len = it2.opts.unicode === false ? (0, codegen_1._)`${data}.length` : (0, codegen_1._)`${(0, util_1.useFunc)(cxt.gen, ucs2length_1.default)}(${data})`;
        cxt.fail$data((0, codegen_1._)`${len} ${op} ${schemaCode}`);
      }
    };
    exports2.default = def2;
  }
});

// packages/cli/node_modules/ajv/dist/vocabularies/validation/pattern.js
var require_pattern3 = __commonJS({
  "packages/cli/node_modules/ajv/dist/vocabularies/validation/pattern.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    var code_1 = require_code6();
    var codegen_1 = require_codegen4();
    var error2 = {
      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: error2,
      code(cxt) {
        const { data, $data, schema, schemaCode, it: it2 } = cxt;
        const u2 = it2.opts.unicodeRegExp ? "u" : "";
        const regExp = $data ? (0, codegen_1._)`(new RegExp(${schemaCode}, ${u2}))` : (0, code_1.usePattern)(cxt, schema);
        cxt.fail$data((0, codegen_1._)`!${regExp}.test(${data})`);
      }
    };
    exports2.default = def2;
  }
});

// packages/cli/node_modules/ajv/dist/vocabularies/validation/limitProperties.js
var require_limitProperties3 = __commonJS({
  "packages/cli/node_modules/ajv/dist/vocabularies/validation/limitProperties.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    var codegen_1 = require_codegen4();
    var error2 = {
      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: error2,
      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/cli/node_modules/ajv/dist/vocabularies/validation/required.js
var require_required3 = __commonJS({
  "packages/cli/node_modules/ajv/dist/vocabularies/validation/required.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    var code_1 = require_code6();
    var codegen_1 = require_codegen4();
    var util_1 = require_util21();
    var error2 = {
      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: error2,
      code(cxt) {
        const { gen, schema, schemaCode, data, $data, it: it2 } = cxt;
        const { opts } = it2;
        if (!$data && schema.length === 0)
          return;
        const useLoop = schema.length >= opts.loopRequired;
        if (it2.allErrors)
          allErrorsMode();
        else
          exitOnErrorMode();
        if (opts.strictRequired) {
          const props = cxt.parentSchema.properties;
          const { definedProperties } = cxt.it;
          for (const requiredKey of schema) {
            if ((props === null || props === void 0 ? void 0 : props[requiredKey]) === void 0 && !definedProperties.has(requiredKey)) {
              const schemaPath = it2.schemaEnv.baseId + it2.errSchemaPath;
              const msg = `required property "${requiredKey}" is not defined at "${schemaPath}" (strictRequired)`;
              (0, util_1.checkStrictMode)(it2, msg, it2.opts.strictRequired);
            }
          }
        }
        function allErrorsMode() {
          if (useLoop || $data) {
            cxt.block$data(codegen_1.nil, loopAllRequired);
          } else {
            for (const prop of schema) {
              (0, code_1.checkReportMissingProp)(cxt, prop);
            }
          }
        }
        __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/cli/node_modules/ajv/dist/vocabularies/validation/limitItems.js
var require_limitItems3 = __commonJS({
  "packages/cli/node_modules/ajv/dist/vocabularies/validation/limitItems.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    var codegen_1 = require_codegen4();
    var error2 = {
      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: error2,
      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/cli/node_modules/ajv/dist/runtime/equal.js
var require_equal3 = __commonJS({
  "packages/cli/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/cli/node_modules/ajv/dist/vocabularies/validation/uniqueItems.js
var require_uniqueItems3 = __commonJS({
  "packages/cli/node_modules/ajv/dist/vocabularies/validation/uniqueItems.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    var dataType_1 = require_dataType3();
    var codegen_1 = require_codegen4();
    var util_1 = require_util21();
    var equal_1 = require_equal3();
    var error2 = {
      message: /* @__PURE__ */ __name(({ params: { i: i3, j: j2 } }) => (0, codegen_1.str)`must NOT have duplicate items (items ## ${j2} and ${i3} are identical)`, "message"),
      params: /* @__PURE__ */ __name(({ params: { i: i3, j: j2 } }) => (0, codegen_1._)`{i: ${i3}, j: ${j2}}`, "params")
    };
    var def2 = {
      keyword: "uniqueItems",
      type: "array",
      schemaType: "boolean",
      $data: true,
      error: error2,
      code(cxt) {
        const { gen, data, $data, schema, parentSchema, schemaCode, it: it2 } = cxt;
        if (!$data && !schema)
          return;
        const valid = gen.let("valid");
        const itemTypes = parentSchema.items ? (0, dataType_1.getSchemaTypes)(parentSchema.items) : [];
        cxt.block$data(valid, validateUniqueItems, (0, codegen_1._)`${schemaCode} === false`);
        cxt.ok(valid);
        function validateUniqueItems() {
          const i3 = gen.let("i", (0, codegen_1._)`${data}.length`);
          const j2 = gen.let("j");
          cxt.setParams({ i: i3, j: j2 });
          gen.assign(valid, true);
          gen.if((0, codegen_1._)`${i3} > 1`, () => (canOptimize() ? loopN : loopN2)(i3, j2));
        }
        __name(validateUniqueItems, "validateUniqueItems");
        function canOptimize() {
          return itemTypes.length > 0 && !itemTypes.some((t5) => t5 === "object" || t5 === "array");
        }
        __name(canOptimize, "canOptimize");
        function loopN(i3, j2) {
          const item = gen.name("item");
          const wrongType = (0, dataType_1.checkDataTypes)(itemTypes, item, it2.opts.strictNumbers, dataType_1.DataType.Wrong);
          const indices = gen.const("indices", (0, codegen_1._)`{}`);
          gen.for((0, codegen_1._)`;${i3}--;`, () => {
            gen.let(item, (0, codegen_1._)`${data}[${i3}]`);
            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(j2, (0, codegen_1._)`${indices}[${item}]`);
              cxt.error();
              gen.assign(valid, false).break();
            }).code((0, codegen_1._)`${indices}[${item}] = ${i3}`);
          });
        }
        __name(loopN, "loopN");
        function loopN2(i3, j2) {
          const eql = (0, util_1.useFunc)(gen, equal_1.default);
          const outer = gen.name("outer");
          gen.label(outer).for((0, codegen_1._)`;${i3}--;`, () => gen.for((0, codegen_1._)`${j2} = ${i3}; ${j2}--;`, () => gen.if((0, codegen_1._)`${eql}(${data}[${i3}], ${data}[${j2}])`, () => {
            cxt.error();
            gen.assign(valid, false).break(outer);
          })));
        }
        __name(loopN2, "loopN2");
      }
    };
    exports2.default = def2;
  }
});

// packages/cli/node_modules/ajv/dist/vocabularies/validation/const.js
var require_const3 = __commonJS({
  "packages/cli/node_modules/ajv/dist/vocabularies/validation/const.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    var codegen_1 = require_codegen4();
    var util_1 = require_util21();
    var equal_1 = require_equal3();
    var error2 = {
      message: "must be equal to constant",
      params: /* @__PURE__ */ __name(({ schemaCode }) => (0, codegen_1._)`{allowedValue: ${schemaCode}}`, "params")
    };
    var def2 = {
      keyword: "const",
      $data: true,
      error: error2,
      code(cxt) {
        const { gen, data, $data, schemaCode, schema } = cxt;
        if ($data || schema && typeof schema == "object") {
          cxt.fail$data((0, codegen_1._)`!${(0, util_1.useFunc)(gen, equal_1.default)}(${data}, ${schemaCode})`);
        } else {
          cxt.fail((0, codegen_1._)`${schema} !== ${data}`);
        }
      }
    };
    exports2.default = def2;
  }
});

// packages/cli/node_modules/ajv/dist/vocabularies/validation/enum.js
var require_enum4 = __commonJS({
  "packages/cli/node_modules/ajv/dist/vocabularies/validation/enum.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    var codegen_1 = require_codegen4();
    var util_1 = require_util21();
    var equal_1 = require_equal3();
    var error2 = {
      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: error2,
      code(cxt) {
        const { gen, data, $data, schema, schemaCode, it: it2 } = cxt;
        if (!$data && schema.length === 0)
          throw new Error("enum must have non-empty array");
        const useLoop = schema.length >= it2.opts.loopEnum;
        let eql;
        const getEql = /* @__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, i3) => equalCode(vSchema, i3)));
        }
        cxt.pass(valid);
        function loopEnum() {
          gen.assign(valid, false);
          gen.forOf("v", schemaCode, (v2) => gen.if((0, codegen_1._)`${getEql()}(${data}, ${v2})`, () => gen.assign(valid, true).break()));
        }
        __name(loopEnum, "loopEnum");
        function equalCode(vSchema, i3) {
          const sch = schema[i3];
          return typeof sch === "object" && sch !== null ? (0, codegen_1._)`${getEql()}(${data}, ${vSchema}[${i3}])` : (0, codegen_1._)`${data} === ${sch}`;
        }
        __name(equalCode, "equalCode");
      }
    };
    exports2.default = def2;
  }
});

// packages/cli/node_modules/ajv/dist/vocabularies/validation/index.js
var require_validation5 = __commonJS({
  "packages/cli/node_modules/ajv/dist/vocabularies/validation/index.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    var limitNumber_1 = require_limitNumber3();
    var multipleOf_1 = require_multipleOf3();
    var limitLength_1 = require_limitLength3();
    var pattern_1 = require_pattern3();
    var limitProperties_1 = require_limitProperties3();
    var required_1 = require_required3();
    var limitItems_1 = require_limitItems3();
    var uniqueItems_1 = require_uniqueItems3();
    var const_1 = require_const3();
    var enum_1 = require_enum4();
    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/cli/node_modules/ajv/dist/vocabularies/applicator/additionalItems.js
var require_additionalItems3 = __commonJS({
  "packages/cli/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_codegen4();
    var util_1 = require_util21();
    var error2 = {
      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: error2,
      code(cxt) {
        const { parentSchema, it: it2 } = cxt;
        const { items } = parentSchema;
        if (!Array.isArray(items)) {
          (0, util_1.checkStrictMode)(it2, '"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: it2 } = cxt;
      it2.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)(it2, 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, (i3) => {
          cxt.subschema({ keyword, dataProp: i3, dataPropType: util_1.Type.Num }, valid);
          if (!it2.allErrors)
            gen.if((0, codegen_1.not)(valid), () => gen.break());
        });
      }
      __name(validateItems, "validateItems");
    }
    __name(validateAdditionalItems, "validateAdditionalItems");
    exports2.validateAdditionalItems = validateAdditionalItems;
    exports2.default = def2;
  }
});

// packages/cli/node_modules/ajv/dist/vocabularies/applicator/items.js
var require_items3 = __commonJS({
  "packages/cli/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_codegen4();
    var util_1 = require_util21();
    var code_1 = require_code6();
    var def2 = {
      keyword: "items",
      type: "array",
      schemaType: ["object", "array", "boolean"],
      before: "uniqueItems",
      code(cxt) {
        const { schema, it: it2 } = cxt;
        if (Array.isArray(schema))
          return validateTuple(cxt, "additionalItems", schema);
        it2.items = true;
        if ((0, util_1.alwaysValidSchema)(it2, schema))
          return;
        cxt.ok((0, code_1.validateArray)(cxt));
      }
    };
    function validateTuple(cxt, extraItems, schArr = cxt.schema) {
      const { gen, parentSchema, data, keyword, it: it2 } = cxt;
      checkStrictTuple(parentSchema);
      if (it2.opts.unevaluated && schArr.length && it2.items !== true) {
        it2.items = util_1.mergeEvaluated.items(gen, schArr.length, it2.items);
      }
      const valid = gen.name("valid");
      const len = gen.const("len", (0, codegen_1._)`${data}.length`);
      schArr.forEach((sch, i3) => {
        if ((0, util_1.alwaysValidSchema)(it2, sch))
          return;
        gen.if((0, codegen_1._)`${len} > ${i3}`, () => cxt.subschema({
          keyword,
          schemaProp: i3,
          dataProp: i3
        }, valid));
        cxt.ok(valid);
      });
      function checkStrictTuple(sch) {
        const { opts, errSchemaPath } = it2;
        const l3 = schArr.length;
        const fullTuple = l3 === sch.minItems && (l3 === sch.maxItems || sch[extraItems] === false);
        if (opts.strictTuples && !fullTuple) {
          const msg = `"${keyword}" is ${l3}-tuple, but minItems or maxItems/${extraItems} are not specified or different at path "${errSchemaPath}"`;
          (0, util_1.checkStrictMode)(it2, msg, opts.strictTuples);
        }
      }
      __name(checkStrictTuple, "checkStrictTuple");
    }
    __name(validateTuple, "validateTuple");
    exports2.validateTuple = validateTuple;
    exports2.default = def2;
  }
});

// packages/cli/node_modules/ajv/dist/vocabularies/applicator/prefixItems.js
var require_prefixItems3 = __commonJS({
  "packages/cli/node_modules/ajv/dist/vocabularies/applicator/prefixItems.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    var items_1 = require_items3();
    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/cli/node_modules/ajv/dist/vocabularies/applicator/items2020.js
var require_items20203 = __commonJS({
  "packages/cli/node_modules/ajv/dist/vocabularies/applicator/items2020.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    var codegen_1 = require_codegen4();
    var util_1 = require_util21();
    var code_1 = require_code6();
    var additionalItems_1 = require_additionalItems3();
    var error2 = {
      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: error2,
      code(cxt) {
        const { schema, parentSchema, it: it2 } = cxt;
        const { prefixItems } = parentSchema;
        it2.items = true;
        if ((0, util_1.alwaysValidSchema)(it2, schema))
          return;
        if (prefixItems)
          (0, additionalItems_1.validateAdditionalItems)(cxt, prefixItems);
        else
          cxt.ok((0, code_1.validateArray)(cxt));
      }
    };
    exports2.default = def2;
  }
});

// packages/cli/node_modules/ajv/dist/vocabularies/applicator/contains.js
var require_contains3 = __commonJS({
  "packages/cli/node_modules/ajv/dist/vocabularies/applicator/contains.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    var codegen_1 = require_codegen4();
    var util_1 = require_util21();
    var error2 = {
      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: error2,
      code(cxt) {
        const { gen, schema, parentSchema, data, it: it2 } = cxt;
        let min;
        let max;
        const { minContains, maxContains } = parentSchema;
        if (it2.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)(it2, `"minContains" == 0 without "maxContains": "contains" keyword ignored`);
          return;
        }
        if (max !== void 0 && min > max) {
          (0, util_1.checkStrictMode)(it2, `"minContains" > "maxContains" is always invalid`);
          cxt.fail();
          return;
        }
        if ((0, util_1.alwaysValidSchema)(it2, schema)) {
          let cond = (0, codegen_1._)`${len} >= ${min}`;
          if (max !== void 0)
            cond = (0, codegen_1._)`${cond} && ${len} <= ${max}`;
          cxt.pass(cond);
          return;
        }
        it2.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, (i3) => {
            cxt.subschema({
              keyword: "contains",
              dataProp: i3,
              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/cli/node_modules/ajv/dist/vocabularies/applicator/dependencies.js
var require_dependencies3 = __commonJS({
  "packages/cli/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_codegen4();
    var util_1 = require_util21();
    var code_1 = require_code6();
    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: it2 } = cxt;
      if (Object.keys(propertyDeps).length === 0)
        return;
      const missing = gen.let("missing");
      for (const prop in propertyDeps) {
        const deps = propertyDeps[prop];
        if (deps.length === 0)
          continue;
        const hasProperty2 = (0, code_1.propertyInData)(gen, data, prop, it2.opts.ownProperties);
        cxt.setParams({
          property: prop,
          depsCount: deps.length,
          deps: deps.join(", ")
        });
        if (it2.allErrors) {
          gen.if(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: it2 } = cxt;
      const valid = gen.name("valid");
      for (const prop in schemaDeps) {
        if ((0, util_1.alwaysValidSchema)(it2, schemaDeps[prop]))
          continue;
        gen.if(
          (0, code_1.propertyInData)(gen, data, prop, it2.opts.ownProperties),
          () => {
            const schCxt = cxt.subschema({ keyword, 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/cli/node_modules/ajv/dist/vocabularies/applicator/propertyNames.js
var require_propertyNames3 = __commonJS({
  "packages/cli/node_modules/ajv/dist/vocabularies/applicator/propertyNames.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    var codegen_1 = require_codegen4();
    var util_1 = require_util21();
    var error2 = {
      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: error2,
      code(cxt) {
        const { gen, schema, data, it: it2 } = cxt;
        if ((0, util_1.alwaysValidSchema)(it2, schema))
          return;
        const valid = gen.name("valid");
        gen.forIn("key", data, (key) => {
          cxt.setParams({ propertyName: key });
          cxt.subschema({
            keyword: "propertyNames",
            data: key,
            dataTypes: ["string"],
            propertyName: key,
            compositeRule: true
          }, valid);
          gen.if((0, codegen_1.not)(valid), () => {
            cxt.error(true);
            if (!it2.allErrors)
              gen.break();
          });
        });
        cxt.ok(valid);
      }
    };
    exports2.default = def2;
  }
});

// packages/cli/node_modules/ajv/dist/vocabularies/applicator/additionalProperties.js
var require_additionalProperties3 = __commonJS({
  "packages/cli/node_modules/ajv/dist/vocabularies/applicator/additionalProperties.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    var code_1 = require_code6();
    var codegen_1 = require_codegen4();
    var names_1 = require_names3();
    var util_1 = require_util21();
    var error2 = {
      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: error2,
      code(cxt) {
        const { gen, schema, parentSchema, data, errsCount, it: it2 } = cxt;
        if (!errsCount)
          throw new Error("ajv implementation error");
        const { allErrors, opts } = it2;
        it2.props = true;
        if (opts.removeAdditional !== "all" && (0, util_1.alwaysValidSchema)(it2, schema))
          return;
        const props = (0, code_1.allSchemaProperties)(parentSchema.properties);
        const patProps = (0, code_1.allSchemaProperties)(parentSchema.patternProperties);
        checkAdditionalProperties();
        cxt.ok((0, codegen_1._)`${errsCount} === ${names_1.default.errors}`);
        function checkAdditionalProperties() {
          gen.forIn("key", data, (key) => {
            if (!props.length && !patProps.length)
              additionalPropertyCode(key);
            else
              gen.if(isAdditional(key), () => additionalPropertyCode(key));
          });
        }
        __name(checkAdditionalProperties, "checkAdditionalProperties");
        function isAdditional(key) {
          let definedProp;
          if (props.length > 8) {
            const propsSchema = (0, util_1.schemaRefOrVal)(it2, parentSchema.properties, "properties");
            definedProp = (0, code_1.isOwnProperty)(gen, propsSchema, key);
          } else if (props.length) {
            definedProp = (0, codegen_1.or)(...props.map((p2) => (0, codegen_1._)`${key} === ${p2}`));
          } else {
            definedProp = codegen_1.nil;
          }
          if (patProps.length) {
            definedProp = (0, codegen_1.or)(definedProp, ...patProps.map((p2) => (0, codegen_1._)`${(0, code_1.usePattern)(cxt, p2)}.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)(it2, schema)) {
            const valid = gen.name("valid");
            if (opts.removeAdditional === "failing") {
              applyAdditionalSchema(key, valid, false);
              gen.if((0, codegen_1.not)(valid), () => {
                cxt.reset();
                deleteAdditional(key);
              });
            } else {
              applyAdditionalSchema(key, valid);
              if (!allErrors)
                gen.if((0, codegen_1.not)(valid), () => gen.break());
            }
          }
        }
        __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/cli/node_modules/ajv/dist/vocabularies/applicator/properties.js
var require_properties3 = __commonJS({
  "packages/cli/node_modules/ajv/dist/vocabularies/applicator/properties.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    var validate_1 = require_validate3();
    var code_1 = require_code6();
    var util_1 = require_util21();
    var additionalProperties_1 = require_additionalProperties3();
    var def2 = {
      keyword: "properties",
      type: "object",
      schemaType: "object",
      code(cxt) {
        const { gen, schema, parentSchema, data, it: it2 } = cxt;
        if (it2.opts.removeAdditional === "all" && parentSchema.additionalProperties === void 0) {
          additionalProperties_1.default.code(new validate_1.KeywordCxt(it2, additionalProperties_1.default, "additionalProperties"));
        }
        const allProps = (0, code_1.allSchemaProperties)(schema);
        for (const prop of allProps) {
          it2.definedProperties.add(prop);
        }
        if (it2.opts.unevaluated && allProps.length && it2.props !== true) {
          it2.props = util_1.mergeEvaluated.props(gen, (0, util_1.toHash)(allProps), it2.props);
        }
        const properties = allProps.filter((p2) => !(0, util_1.alwaysValidSchema)(it2, schema[p2]));
        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, it2.opts.ownProperties));
            applyPropertySchema(prop);
            if (!it2.allErrors)
              gen.else().var(valid, true);
            gen.endIf();
          }
          cxt.it.definedProperties.add(prop);
          cxt.ok(valid);
        }
        function hasDefault(prop) {
          return it2.opts.useDefaults && !it2.compositeRule && schema[prop].default !== void 0;
        }
        __name(hasDefault, "hasDefault");
        function applyPropertySchema(prop) {
          cxt.subschema({
            keyword: "properties",
            schemaProp: prop,
            dataProp: prop
          }, valid);
        }
        __name(applyPropertySchema, "applyPropertySchema");
      }
    };
    exports2.default = def2;
  }
});

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

// packages/cli/node_modules/ajv/dist/vocabularies/applicator/not.js
var require_not3 = __commonJS({
  "packages/cli/node_modules/ajv/dist/vocabularies/applicator/not.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    var util_1 = require_util21();
    var def2 = {
      keyword: "not",
      schemaType: ["object", "boolean"],
      trackErrors: true,
      code(cxt) {
        const { gen, schema, it: it2 } = cxt;
        if ((0, util_1.alwaysValidSchema)(it2, schema)) {
          cxt.fail();
          return;
        }
        const valid = gen.name("valid");
        cxt.subschema({
          keyword: "not",
          compositeRule: true,
          createErrors: false,
          allErrors: false
        }, valid);
        cxt.failResult(valid, () => cxt.reset(), () => cxt.error());
      },
      error: { message: "must NOT be valid" }
    };
    exports2.default = def2;
  }
});

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

// packages/cli/node_modules/ajv/dist/vocabularies/applicator/oneOf.js
var require_oneOf3 = __commonJS({
  "packages/cli/node_modules/ajv/dist/vocabularies/applicator/oneOf.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    var codegen_1 = require_codegen4();
    var util_1 = require_util21();
    var error2 = {
      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: error2,
      code(cxt) {
        const { gen, schema, parentSchema, it: it2 } = cxt;
        if (!Array.isArray(schema))
          throw new Error("ajv implementation error");
        if (it2.opts.discriminator && parentSchema.discriminator)
          return;
        const schArr = schema;
        const valid = gen.let("valid", false);
        const passing = gen.let("passing", null);
        const schValid = gen.name("_valid");
        cxt.setParams({ passing });
        gen.block(validateOneOf);
        cxt.result(valid, () => cxt.reset(), () => cxt.error(true));
        function validateOneOf() {
          schArr.forEach((sch, i3) => {
            let schCxt;
            if ((0, util_1.alwaysValidSchema)(it2, sch)) {
              gen.var(schValid, true);
            } else {
              schCxt = cxt.subschema({
                keyword: "oneOf",
                schemaProp: i3,
                compositeRule: true
              }, schValid);
            }
            if (i3 > 0) {
              gen.if((0, codegen_1._)`${schValid} && ${valid}`).assign(valid, false).assign(passing, (0, codegen_1._)`[${passing}, ${i3}]`).else();
            }
            gen.if(schValid, () => {
              gen.assign(valid, true);
              gen.assign(passing, i3);
              if (schCxt)
                cxt.mergeEvaluated(schCxt, codegen_1.Name);
            });
          });
        }
        __name(validateOneOf, "validateOneOf");
      }
    };
    exports2.default = def2;
  }
});

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

// packages/cli/node_modules/ajv/dist/vocabularies/applicator/if.js
var require_if3 = __commonJS({
  "packages/cli/node_modules/ajv/dist/vocabularies/applicator/if.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    var codegen_1 = require_codegen4();
    var util_1 = require_util21();
    var error2 = {
      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: error2,
      code(cxt) {
        const { gen, parentSchema, it: it2 } = cxt;
        if (parentSchema.then === void 0 && parentSchema.else === void 0) {
          (0, util_1.checkStrictMode)(it2, '"if" without "then" and "else" is ignored');
        }
        const hasThen = hasSchema(it2, "then");
        const hasElse = hasSchema(it2, "else");
        if (!hasThen && !hasElse)
          return;
        const valid = gen.let("valid", true);
        const schValid = gen.name("_valid");
        validateIf();
        cxt.reset();
        if (hasThen && hasElse) {
          const ifClause = gen.let("ifClause");
          cxt.setParams({ ifClause });
          gen.if(schValid, validateClause("then", ifClause), validateClause("else", ifClause));
        } else if (hasThen) {
          gen.if(schValid, validateClause("then"));
        } else {
          gen.if((0, codegen_1.not)(schValid), validateClause("else"));
        }
        cxt.pass(valid, () => cxt.error(true));
        function validateIf() {
          const schCxt = cxt.subschema({
            keyword: "if",
            compositeRule: true,
            createErrors: false,
            allErrors: false
          }, schValid);
          cxt.mergeEvaluated(schCxt);
        }
        __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(it2, keyword) {
      const schema = it2.schema[keyword];
      return schema !== void 0 && !(0, util_1.alwaysValidSchema)(it2, schema);
    }
    __name(hasSchema, "hasSchema");
    exports2.default = def2;
  }
});

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

// packages/cli/node_modules/ajv/dist/vocabularies/applicator/index.js
var require_applicator4 = __commonJS({
  "packages/cli/node_modules/ajv/dist/vocabularies/applicator/index.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    var additionalItems_1 = require_additionalItems3();
    var prefixItems_1 = require_prefixItems3();
    var items_1 = require_items3();
    var items2020_1 = require_items20203();
    var contains_1 = require_contains3();
    var dependencies_1 = require_dependencies3();
    var propertyNames_1 = require_propertyNames3();
    var additionalProperties_1 = require_additionalProperties3();
    var properties_1 = require_properties3();
    var patternProperties_1 = require_patternProperties3();
    var not_1 = require_not3();
    var anyOf_1 = require_anyOf3();
    var oneOf_1 = require_oneOf3();
    var allOf_1 = require_allOf3();
    var if_1 = require_if3();
    var thenElse_1 = require_thenElse3();
    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/cli/node_modules/ajv/dist/vocabularies/format/format.js
var require_format5 = __commonJS({
  "packages/cli/node_modules/ajv/dist/vocabularies/format/format.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    var codegen_1 = require_codegen4();
    var error2 = {
      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: error2,
      code(cxt, ruleType) {
        const { gen, data, $data, schema, schemaCode, it: it2 } = cxt;
        const { opts, errSchemaPath, schemaEnv, self: self2 } = it2;
        if (!opts.validateFormats)
          return;
        if ($data)
          validate$DataFormat();
        else
          validateFormat();
        function validate$DataFormat() {
          const fmts = gen.scopeValue("formats", {
            ref: self2.formats,
            code: opts.code.formats
          });
          const fDef = gen.const("fDef", (0, codegen_1._)`${fmts}[${schemaCode}]`);
          const fType = gen.let("fType");
          const 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/cli/node_modules/ajv/dist/vocabularies/format/index.js
var require_format6 = __commonJS({
  "packages/cli/node_modules/ajv/dist/vocabularies/format/index.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    var format_1 = require_format5();
    var format4 = [format_1.default];
    exports2.default = format4;
  }
});

// packages/cli/node_modules/ajv/dist/vocabularies/metadata.js
var require_metadata4 = __commonJS({
  "packages/cli/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/cli/node_modules/ajv/dist/vocabularies/draft7.js
var require_draft73 = __commonJS({
  "packages/cli/node_modules/ajv/dist/vocabularies/draft7.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    var core_1 = require_core10();
    var validation_1 = require_validation5();
    var applicator_1 = require_applicator4();
    var format_1 = require_format6();
    var metadata_1 = require_metadata4();
    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/cli/node_modules/ajv/dist/vocabularies/discriminator/types.js
var require_types9 = __commonJS({
  "packages/cli/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/cli/node_modules/ajv/dist/vocabularies/discriminator/index.js
var require_discriminator3 = __commonJS({
  "packages/cli/node_modules/ajv/dist/vocabularies/discriminator/index.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    var codegen_1 = require_codegen4();
    var types_1 = require_types9();
    var compile_1 = require_compile3();
    var ref_error_1 = require_ref_error3();
    var util_1 = require_util21();
    var error2 = {
      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: error2,
      code(cxt) {
        const { gen, data, schema, parentSchema, it: it2 } = cxt;
        const { oneOf } = parentSchema;
        if (!it2.opts.discriminator) {
          throw new Error("discriminator: requires discriminator option");
        }
        const tagName = schema.propertyName;
        if (typeof tagName != "string")
          throw new Error("discriminator: requires propertyName");
        if (schema.mapping)
          throw new Error("discriminator: mapping is not supported");
        if (!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 _a7;
          const oneOfMapping = {};
          const topRequired = hasRequired(parentSchema);
          let tagRequired = true;
          for (let i3 = 0; i3 < oneOf.length; i3++) {
            let sch = oneOf[i3];
            if ((sch === null || sch === void 0 ? void 0 : sch.$ref) && !(0, util_1.schemaHasRulesButRef)(sch, it2.self.RULES)) {
              const ref = sch.$ref;
              sch = compile_1.resolveRef.call(it2.self, it2.schemaEnv.root, it2.baseId, ref);
              if (sch instanceof compile_1.SchemaEnv)
                sch = sch.schema;
              if (sch === void 0)
                throw new ref_error_1.default(it2.opts.uriResolver, it2.baseId, ref);
            }
            const propSch = (_a7 = sch === null || sch === void 0 ? void 0 : sch.properties) === null || _a7 === void 0 ? void 0 : _a7[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, i3);
          }
          if (!tagRequired)
            throw new Error(`discriminator: "${tagName}" must be required`);
          return oneOfMapping;
          function hasRequired({ required: required2 }) {
            return Array.isArray(required2) && required2.includes(tagName);
          }
          __name(hasRequired, "hasRequired");
          function addMappings(sch, i3) {
            if (sch.const) {
              addMapping(sch.const, i3);
            } else if (sch.enum) {
              for (const tagValue of sch.enum) {
                addMapping(tagValue, i3);
              }
            } else {
              throw new Error(`discriminator: "properties/${tagName}" must have "const" or "enum"`);
            }
          }
          __name(addMappings, "addMappings");
          function addMapping(tagValue, i3) {
            if (typeof tagValue != "string" || tagValue in oneOfMapping) {
              throw new Error(`discriminator: "${tagName}" values must be unique strings`);
            }
            oneOfMapping[tagValue] = i3;
          }
          __name(addMapping, "addMapping");
        }
        __name(getMapping, "getMapping");
      }
    };
    exports2.default = def2;
  }
});

// packages/cli/node_modules/ajv/dist/refs/json-schema-draft-07.json
var require_json_schema_draft_073 = __commonJS({
  "packages/cli/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/cli/node_modules/ajv/dist/ajv.js
var require_ajv3 = __commonJS({
  "packages/cli/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_core9();
    var draft7_1 = require_draft73();
    var discriminator_1 = require_discriminator3();
    var draft7MetaSchema = require_json_schema_draft_073();
    var META_SUPPORT_DATA = ["/properties"];
    var META_SCHEMA_ID = "http://json-schema.org/draft-07/schema";
    var Ajv3 = class extends core_1.default {
      static {
        __name(this, "Ajv");
      }
      _addVocabularies() {
        super._addVocabularies();
        draft7_1.default.forEach((v2) => this.addVocabulary(v2));
        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 = Ajv3;
    module2.exports = exports2 = Ajv3;
    module2.exports.Ajv = Ajv3;
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.default = Ajv3;
    var validate_1 = require_validate3();
    Object.defineProperty(exports2, "KeywordCxt", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return validate_1.KeywordCxt;
    }, "get") });
    var codegen_1 = require_codegen4();
    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_error3();
    Object.defineProperty(exports2, "ValidationError", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return validation_error_1.default;
    }, "get") });
    var ref_error_1 = require_ref_error3();
    Object.defineProperty(exports2, "MissingRefError", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return ref_error_1.default;
    }, "get") });
  }
});

// packages/cli/node_modules/undici/lib/core/symbols.js
var require_symbols6 = __commonJS({
  "packages/cli/node_modules/undici/lib/core/symbols.js"(exports2, module2) {
    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"),
      kInterceptors: Symbol("dispatch interceptors"),
      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")
    };
  }
});

// packages/cli/node_modules/undici/lib/core/errors.js
var require_errors5 = __commonJS({
  "packages/cli/node_modules/undici/lib/core/errors.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var kUndiciError = Symbol.for("undici.error.UND_ERR");
    var UndiciError = class extends Error {
      static {
        __name(this, "UndiciError");
      }
      constructor(message) {
        super(message);
        this.name = "UndiciError";
        this.code = "UND_ERR";
      }
      static [Symbol.hasInstance](instance) {
        return instance && instance[kUndiciError] === true;
      }
      [kUndiciError] = true;
    };
    var kConnectTimeoutError = Symbol.for("undici.error.UND_ERR_CONNECT_TIMEOUT");
    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";
      }
      static [Symbol.hasInstance](instance) {
        return instance && instance[kConnectTimeoutError] === true;
      }
      [kConnectTimeoutError] = true;
    };
    var kHeadersTimeoutError = Symbol.for("undici.error.UND_ERR_HEADERS_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";
      }
      static [Symbol.hasInstance](instance) {
        return instance && instance[kHeadersTimeoutError] === true;
      }
      [kHeadersTimeoutError] = true;
    };
    var kHeadersOverflowError = Symbol.for("undici.error.UND_ERR_HEADERS_OVERFLOW");
    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";
      }
      static [Symbol.hasInstance](instance) {
        return instance && instance[kHeadersOverflowError] === true;
      }
      [kHeadersOverflowError] = true;
    };
    var kBodyTimeoutError = Symbol.for("undici.error.UND_ERR_BODY_TIMEOUT");
    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";
      }
      static [Symbol.hasInstance](instance) {
        return instance && instance[kBodyTimeoutError] === true;
      }
      [kBodyTimeoutError] = true;
    };
    var kResponseStatusCodeError = Symbol.for("undici.error.UND_ERR_RESPONSE_STATUS_CODE");
    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;
      }
      static [Symbol.hasInstance](instance) {
        return instance && instance[kResponseStatusCodeError] === true;
      }
      [kResponseStatusCodeError] = true;
    };
    var kInvalidArgumentError = Symbol.for("undici.error.UND_ERR_INVALID_ARG");
    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";
      }
      static [Symbol.hasInstance](instance) {
        return instance && instance[kInvalidArgumentError] === true;
      }
      [kInvalidArgumentError] = true;
    };
    var kInvalidReturnValueError = Symbol.for("undici.error.UND_ERR_INVALID_RETURN_VALUE");
    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";
      }
      static [Symbol.hasInstance](instance) {
        return instance && instance[kInvalidReturnValueError] === true;
      }
      [kInvalidReturnValueError] = true;
    };
    var kAbortError = Symbol.for("undici.error.UND_ERR_ABORT");
    var AbortError4 = class extends UndiciError {
      static {
        __name(this, "AbortError");
      }
      constructor(message) {
        super(message);
        this.name = "AbortError";
        this.message = message || "The operation was aborted";
        this.code = "UND_ERR_ABORT";
      }
      static [Symbol.hasInstance](instance) {
        return instance && instance[kAbortError] === true;
      }
      [kAbortError] = true;
    };
    var kRequestAbortedError = Symbol.for("undici.error.UND_ERR_ABORTED");
    var RequestAbortedError = class extends AbortError4 {
      static {
        __name(this, "RequestAbortedError");
      }
      constructor(message) {
        super(message);
        this.name = "AbortError";
        this.message = message || "Request aborted";
        this.code = "UND_ERR_ABORTED";
      }
      static [Symbol.hasInstance](instance) {
        return instance && instance[kRequestAbortedError] === true;
      }
      [kRequestAbortedError] = true;
    };
    var kInformationalError = Symbol.for("undici.error.UND_ERR_INFO");
    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";
      }
      static [Symbol.hasInstance](instance) {
        return instance && instance[kInformationalError] === true;
      }
      [kInformationalError] = true;
    };
    var kRequestContentLengthMismatchError = Symbol.for("undici.error.UND_ERR_REQ_CONTENT_LENGTH_MISMATCH");
    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";
      }
      static [Symbol.hasInstance](instance) {
        return instance && instance[kRequestContentLengthMismatchError] === true;
      }
      [kRequestContentLengthMismatchError] = true;
    };
    var kResponseContentLengthMismatchError = Symbol.for("undici.error.UND_ERR_RES_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";
      }
      static [Symbol.hasInstance](instance) {
        return instance && instance[kResponseContentLengthMismatchError] === true;
      }
      [kResponseContentLengthMismatchError] = true;
    };
    var kClientDestroyedError = Symbol.for("undici.error.UND_ERR_DESTROYED");
    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";
      }
      static [Symbol.hasInstance](instance) {
        return instance && instance[kClientDestroyedError] === true;
      }
      [kClientDestroyedError] = true;
    };
    var kClientClosedError = Symbol.for("undici.error.UND_ERR_CLOSED");
    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";
      }
      static [Symbol.hasInstance](instance) {
        return instance && instance[kClientClosedError] === true;
      }
      [kClientClosedError] = true;
    };
    var kSocketError = Symbol.for("undici.error.UND_ERR_SOCKET");
    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;
      }
      static [Symbol.hasInstance](instance) {
        return instance && instance[kSocketError] === true;
      }
      [kSocketError] = true;
    };
    var kNotSupportedError = Symbol.for("undici.error.UND_ERR_NOT_SUPPORTED");
    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";
      }
      static [Symbol.hasInstance](instance) {
        return instance && instance[kNotSupportedError] === true;
      }
      [kNotSupportedError] = true;
    };
    var kBalancedPoolMissingUpstreamError = Symbol.for("undici.error.UND_ERR_BPL_MISSING_UPSTREAM");
    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";
      }
      static [Symbol.hasInstance](instance) {
        return instance && instance[kBalancedPoolMissingUpstreamError] === true;
      }
      [kBalancedPoolMissingUpstreamError] = true;
    };
    var kHTTPParserError = Symbol.for("undici.error.UND_ERR_HTTP_PARSER");
    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;
      }
      static [Symbol.hasInstance](instance) {
        return instance && instance[kHTTPParserError] === true;
      }
      [kHTTPParserError] = true;
    };
    var kResponseExceededMaxSizeError = Symbol.for("undici.error.UND_ERR_RES_EXCEEDED_MAX_SIZE");
    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";
      }
      static [Symbol.hasInstance](instance) {
        return instance && instance[kResponseExceededMaxSizeError] === true;
      }
      [kResponseExceededMaxSizeError] = true;
    };
    var kRequestRetryError = Symbol.for("undici.error.UND_ERR_REQ_RETRY");
    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;
      }
      static [Symbol.hasInstance](instance) {
        return instance && instance[kRequestRetryError] === true;
      }
      [kRequestRetryError] = true;
    };
    var kResponseError = Symbol.for("undici.error.UND_ERR_RESPONSE");
    var ResponseError = class extends UndiciError {
      static {
        __name(this, "ResponseError");
      }
      constructor(message, code2, { headers, data }) {
        super(message);
        this.name = "ResponseError";
        this.message = message || "Response error";
        this.code = "UND_ERR_RESPONSE";
        this.statusCode = code2;
        this.data = data;
        this.headers = headers;
      }
      static [Symbol.hasInstance](instance) {
        return instance && instance[kResponseError] === true;
      }
      [kResponseError] = true;
    };
    var kSecureProxyConnectionError = Symbol.for("undici.error.UND_ERR_PRX_TLS");
    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;
      }
      static [Symbol.hasInstance](instance) {
        return instance && instance[kSecureProxyConnectionError] === true;
      }
      [kSecureProxyConnectionError] = true;
    };
    module2.exports = {
      AbortError: AbortError4,
      HTTPParserError,
      UndiciError,
      HeadersTimeoutError,
      HeadersOverflowError,
      BodyTimeoutError,
      RequestContentLengthMismatchError,
      ConnectTimeoutError,
      ResponseStatusCodeError,
      InvalidArgumentError,
      InvalidReturnValueError,
      RequestAbortedError,
      ClientDestroyedError,
      ClientClosedError,
      InformationalError,
      SocketError,
      NotSupportedError,
      ResponseContentLengthMismatchError,
      BalancedPoolMissingUpstreamError,
      ResponseExceededMaxSizeError,
      RequestRetryError,
      ResponseError,
      SecureProxyConnectionError
    };
  }
});

// packages/cli/node_modules/undici/lib/core/constants.js
var require_constants14 = __commonJS({
  "packages/cli/node_modules/undici/lib/core/constants.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var headerNameLowerCasedRecord = {};
    var wellknownHeaderNames = [
      "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"
    ];
    for (let i3 = 0; i3 < wellknownHeaderNames.length; ++i3) {
      const key = wellknownHeaderNames[i3];
      const lowerCasedKey = key.toLowerCase();
      headerNameLowerCasedRecord[key] = headerNameLowerCasedRecord[lowerCasedKey] = lowerCasedKey;
    }
    Object.setPrototypeOf(headerNameLowerCasedRecord, null);
    module2.exports = {
      wellknownHeaderNames,
      headerNameLowerCasedRecord
    };
  }
});

// packages/cli/node_modules/undici/lib/core/tree.js
var require_tree2 = __commonJS({
  "packages/cli/node_modules/undici/lib/core/tree.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var {
      wellknownHeaderNames,
      headerNameLowerCasedRecord
    } = require_constants14();
    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
       */
      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
       * @return {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
       * */
      insert(key, value) {
        if (this.node === null) {
          this.node = new TstNode(key, value, 0);
        } else {
          this.node.add(key, value);
        }
      }
      /**
       * @param {Uint8Array} key
       * @return {any}
       */
      lookup(key) {
        return this.node?.search(key)?.value ?? null;
      }
    };
    var tree = new TernarySearchTree();
    for (let i3 = 0; i3 < wellknownHeaderNames.length; ++i3) {
      const key = headerNameLowerCasedRecord[wellknownHeaderNames[i3]];
      tree.insert(key, key);
    }
    module2.exports = {
      TernarySearchTree,
      tree
    };
  }
});

// packages/cli/node_modules/undici/lib/core/util.js
var require_util22 = __commonJS({
  "packages/cli/node_modules/undici/lib/core/util.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var assert4 = __require("node:assert");
    var { kDestroyed, kBodyUsed, kListeners, kBody } = require_symbols6();
    var { IncomingMessage } = __require("node:http");
    var stream2 = __require("node:stream");
    var net2 = __require("node:net");
    var { Blob: Blob6 } = __require("node:buffer");
    var nodeUtil = __require("node:util");
    var { stringify: stringify4 } = __require("node:querystring");
    var { EventEmitter: EE3 } = __require("node:events");
    var { InvalidArgumentError } = require_errors5();
    var { headerNameLowerCasedRecord } = require_constants14();
    var { tree } = require_tree2();
    var [nodeMajor, nodeMinor] = process.versions.node.split(".").map((v2) => Number(v2));
    var BodyAsyncIterable = class {
      static {
        __name(this, "BodyAsyncIterable");
      }
      constructor(body) {
        this[kBody] = body;
        this[kBodyUsed] = false;
      }
      async *[Symbol.asyncIterator]() {
        assert4(!this[kBodyUsed], "disturbed");
        this[kBodyUsed] = true;
        yield* this[kBody];
      }
    };
    function wrapRequestBody(body) {
      if (isStream2(body)) {
        if (bodyLength(body) === 0) {
          body.on("data", function() {
            assert4(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 nop() {
    }
    __name(nop, "nop");
    function isStream2(obj) {
      return obj && typeof obj === "object" && typeof obj.pipe === "function" && typeof obj.on === "function";
    }
    __name(isStream2, "isStream");
    function isBlobLike3(object3) {
      if (object3 === null) {
        return false;
      } else if (object3 instanceof Blob6) {
        return true;
      } else if (typeof object3 !== "object") {
        return false;
      } else {
        const sTag = object3[Symbol.toStringTag];
        return (sTag === "Blob" || sTag === "File") && ("stream" in object3 && typeof object3.stream === "function" || "arrayBuffer" in object3 && typeof object3.arrayBuffer === "function");
      }
    }
    __name(isBlobLike3, "isBlobLike");
    function buildURL(url2, queryParams) {
      if (url2.includes("?") || url2.includes("#")) {
        throw new Error('Query params cannot be passed when url already contains "?" or "#".');
      }
      const stringified = stringify4(queryParams);
      if (stringified) {
        url2 += "?" + stringified;
      }
      return url2;
    }
    __name(buildURL, "buildURL");
    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 path125 = url2.path != null ? url2.path : `${url2.pathname || ""}${url2.search || ""}`;
        if (origin[origin.length - 1] === "/") {
          origin = origin.slice(0, origin.length - 1);
        }
        if (path125 && path125[0] !== "/") {
          path125 = `/${path125}`;
        }
        return new URL(`${origin}${path125}`);
      }
      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("]");
        assert4(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;
      }
      assert4(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 (isBlobLike3(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 m3 = val.toString().match(KEEPALIVE_TIMEOUT_EXPR);
      return m3 ? parseInt(m3[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 i3 = 0; i3 < headers.length; i3 += 2) {
        const key = headerNameToString(headers[i3]);
        let val = obj[key];
        if (val) {
          if (typeof val === "string") {
            val = [val];
            obj[key] = val;
          }
          val.push(headers[i3 + 1].toString("utf8"));
        } else {
          const headersValue = headers[i3 + 1];
          if (typeof headersValue === "string") {
            obj[key] = headersValue;
          } else {
            obj[key] = Array.isArray(headersValue) ? headersValue.map((x3) => x3.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 len = headers.length;
      const ret = new Array(len);
      let hasContentLength = false;
      let contentDispositionIdx = -1;
      let key;
      let val;
      let kLen = 0;
      for (let n3 = 0; n3 < headers.length; n3 += 2) {
        key = headers[n3];
        val = headers[n3 + 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 = n3 + 1;
        }
        ret[n3] = key;
        ret[n3 + 1] = val;
      }
      if (hasContentLength && contentDispositionIdx !== -1) {
        ret[contentDispositionIdx] = Buffer.from(ret[contentDispositionIdx]).toString("latin1");
      }
      return ret;
    }
    __name(parseRawHeaders, "parseRawHeaders");
    function isBuffer(buffer) {
      return buffer instanceof Uint8Array || Buffer.isBuffer(buffer);
    }
    __name(isBuffer, "isBuffer");
    function validateHandler(handler, method, upgrade) {
      if (!handler || typeof handler !== "object") {
        throw new InvalidArgumentError("handler must be an object");
      }
      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(validateHandler, "validateHandler");
    function isDisturbed(body) {
      return !!(body && (stream2.isDisturbed(body) || body[kBodyUsed]));
    }
    __name(isDisturbed, "isDisturbed");
    function isErrored(body) {
      return !!(body && stream2.isErrored(body));
    }
    __name(isErrored, "isErrored");
    function isReadable2(body) {
      return !!(body && stream2.isReadable(body));
    }
    __name(isReadable2, "isReadable");
    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]();
          },
          async pull(controller) {
            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));
              }
            }
            return controller.desiredSize > 0;
          },
          async cancel(reason) {
            await iterator.return();
          },
          type: "bytes"
        }
      );
    }
    __name(ReadableStreamFrom2, "ReadableStreamFrom");
    function isFormDataLike(object3) {
      return object3 && typeof object3 === "object" && typeof object3.append === "function" && typeof object3.delete === "function" && typeof object3.get === "function" && typeof object3.getAll === "function" && typeof object3.has === "function" && typeof object3.set === "function" && object3[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.addListener("abort", listener);
      return () => signal.removeListener("abort", listener);
    }
    __name(addAbortListener, "addAbortListener");
    var hasToWellFormed = typeof String.prototype.toWellFormed === "function";
    var hasIsWellFormed = typeof String.prototype.isWellFormed === "function";
    function toUSVString(val) {
      return hasToWellFormed ? `${val}`.toWellFormed() : nodeUtil.toUSVString(val);
    }
    __name(toUSVString, "toUSVString");
    function isUSVString(val) {
      return hasIsWellFormed ? `${val}`.isWellFormed() : toUSVString(val) === `${val}`;
    }
    __name(isUSVString, "isUSVString");
    function isTokenCharCode(c4) {
      switch (c4) {
        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 c4 >= 33 && c4 <= 126;
      }
    }
    __name(isTokenCharCode, "isTokenCharCode");
    function isValidHTTPToken(characters) {
      if (characters.length === 0) {
        return false;
      }
      for (let i3 = 0; i3 < characters.length; ++i3) {
        if (!isTokenCharCode(characters.charCodeAt(i3))) {
          return false;
        }
      }
      return true;
    }
    __name(isValidHTTPToken, "isValidHTTPToken");
    var headerCharRegex = /[^\t\x20-\x7e\x80-\xff]/;
    function isValidHeaderValue(characters) {
      return !headerCharRegex.test(characters);
    }
    __name(isValidHeaderValue, "isValidHeaderValue");
    function parseRangeHeader(range) {
      if (range == null || range === "") return { start: 0, end: null, size: null };
      const m3 = range ? range.match(/^bytes (\d+)-(\d+)\/(\d+)?$/) : null;
      return m3 ? {
        start: parseInt(m3[1]),
        end: m3[2] ? parseInt(m3[2]) : null,
        size: m3[3] ? parseInt(m3[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) {
      for (const [name3, listener] of obj[kListeners] ?? []) {
        obj.removeListener(name3, listener);
      }
      obj[kListeners] = null;
    }
    __name(removeAllListeners, "removeAllListeners");
    function errorRequest(client, request4, err) {
      try {
        request4.onError(err);
        assert4(request4.aborted);
      } catch (err2) {
        client.emit("error", err2);
      }
    }
    __name(errorRequest, "errorRequest");
    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,
      nop,
      isDisturbed,
      isErrored,
      isReadable: isReadable2,
      toUSVString,
      isUSVString,
      isBlobLike: isBlobLike3,
      parseOrigin,
      parseURL,
      getServerName,
      isStream: isStream2,
      isIterable,
      isAsyncIterable: isAsyncIterable2,
      isDestroyed,
      headerNameToString,
      bufferToLowerCasedHeaderName,
      addListener,
      removeAllListeners,
      errorRequest,
      parseRawHeaders,
      parseHeaders,
      parseKeepAliveTimeout,
      destroy,
      bodyLength,
      deepClone,
      ReadableStreamFrom: ReadableStreamFrom2,
      isBuffer,
      validateHandler,
      getSocketInfo,
      isFormDataLike,
      buildURL,
      addAbortListener,
      isValidHTTPToken,
      isValidHeaderValue,
      isTokenCharCode,
      parseRangeHeader,
      normalizedMethodRecordsBase,
      normalizedMethodRecords,
      isValidPort,
      isHttpOrHttpsPrefixed,
      nodeMajor,
      nodeMinor,
      safeHTTPMethods: ["GET", "HEAD", "OPTIONS", "TRACE"],
      wrapRequestBody
    };
  }
});

// packages/cli/node_modules/undici/lib/core/diagnostics.js
var require_diagnostics2 = __commonJS({
  "packages/cli/node_modules/undici/lib/core/diagnostics.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var diagnosticsChannel = __require("node:diagnostics_channel");
    var util3 = __require("node:util");
    var undiciDebugLog = util3.debuglog("undici");
    var fetchDebuglog = util3.debuglog("fetch");
    var websocketDebuglog = util3.debuglog("websocket");
    var isClientSet = false;
    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"),
      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")
    };
    if (undiciDebugLog.enabled || fetchDebuglog.enabled) {
      const debuglog = fetchDebuglog.enabled ? fetchDebuglog : undiciDebugLog;
      diagnosticsChannel.channel("undici:client:beforeConnect").subscribe((evt) => {
        const {
          connectParams: { version: version2, protocol, port, host }
        } = evt;
        debuglog(
          "connecting to %s using %s%s",
          `${host}${port ? `:${port}` : ""}`,
          protocol,
          version2
        );
      });
      diagnosticsChannel.channel("undici:client:connected").subscribe((evt) => {
        const {
          connectParams: { version: version2, protocol, port, host }
        } = evt;
        debuglog(
          "connected to %s using %s%s",
          `${host}${port ? `:${port}` : ""}`,
          protocol,
          version2
        );
      });
      diagnosticsChannel.channel("undici:client:connectError").subscribe((evt) => {
        const {
          connectParams: { version: version2, protocol, port, host },
          error: error2
        } = evt;
        debuglog(
          "connection to %s using %s%s errored - %s",
          `${host}${port ? `:${port}` : ""}`,
          protocol,
          version2,
          error2.message
        );
      });
      diagnosticsChannel.channel("undici:client:sendHeaders").subscribe((evt) => {
        const {
          request: { method, path: path125, origin }
        } = evt;
        debuglog("sending request to %s %s/%s", method, origin, path125);
      });
      diagnosticsChannel.channel("undici:request:headers").subscribe((evt) => {
        const {
          request: { method, path: path125, origin },
          response: { statusCode }
        } = evt;
        debuglog(
          "received response to %s %s/%s - HTTP %d",
          method,
          origin,
          path125,
          statusCode
        );
      });
      diagnosticsChannel.channel("undici:request:trailers").subscribe((evt) => {
        const {
          request: { method, path: path125, origin }
        } = evt;
        debuglog("trailers received from %s %s/%s", method, origin, path125);
      });
      diagnosticsChannel.channel("undici:request:error").subscribe((evt) => {
        const {
          request: { method, path: path125, origin },
          error: error2
        } = evt;
        debuglog(
          "request to %s %s/%s errored - %s",
          method,
          origin,
          path125,
          error2.message
        );
      });
      isClientSet = true;
    }
    if (websocketDebuglog.enabled) {
      if (!isClientSet) {
        const debuglog = undiciDebugLog.enabled ? undiciDebugLog : websocketDebuglog;
        diagnosticsChannel.channel("undici:client:beforeConnect").subscribe((evt) => {
          const {
            connectParams: { version: version2, protocol, port, host }
          } = evt;
          debuglog(
            "connecting to %s%s using %s%s",
            host,
            port ? `:${port}` : "",
            protocol,
            version2
          );
        });
        diagnosticsChannel.channel("undici:client:connected").subscribe((evt) => {
          const {
            connectParams: { version: version2, protocol, port, host }
          } = evt;
          debuglog(
            "connected to %s%s using %s%s",
            host,
            port ? `:${port}` : "",
            protocol,
            version2
          );
        });
        diagnosticsChannel.channel("undici:client:connectError").subscribe((evt) => {
          const {
            connectParams: { version: version2, protocol, port, host },
            error: error2
          } = evt;
          debuglog(
            "connection to %s%s using %s%s errored - %s",
            host,
            port ? `:${port}` : "",
            protocol,
            version2,
            error2.message
          );
        });
        diagnosticsChannel.channel("undici:client:sendHeaders").subscribe((evt) => {
          const {
            request: { method, path: path125, origin }
          } = evt;
          debuglog("sending request to %s %s/%s", method, origin, path125);
        });
      }
      diagnosticsChannel.channel("undici:websocket:open").subscribe((evt) => {
        const {
          address: { address, port }
        } = evt;
        websocketDebuglog("connection opened %s%s", address, port ? `:${port}` : "");
      });
      diagnosticsChannel.channel("undici:websocket:close").subscribe((evt) => {
        const { websocket, code: code2, reason } = evt;
        websocketDebuglog(
          "closed connection to %s - %s %s",
          websocket.url,
          code2,
          reason
        );
      });
      diagnosticsChannel.channel("undici:websocket:socket_error").subscribe((err) => {
        websocketDebuglog("connection errored - %s", err.message);
      });
      diagnosticsChannel.channel("undici:websocket:ping").subscribe((evt) => {
        websocketDebuglog("ping received");
      });
      diagnosticsChannel.channel("undici:websocket:pong").subscribe((evt) => {
        websocketDebuglog("pong received");
      });
    }
    module2.exports = {
      channels
    };
  }
});

// packages/cli/node_modules/undici/lib/core/request.js
var require_request3 = __commonJS({
  "packages/cli/node_modules/undici/lib/core/request.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var {
      InvalidArgumentError,
      NotSupportedError
    } = require_errors5();
    var assert4 = __require("node:assert");
    var {
      isValidHTTPToken,
      isValidHeaderValue,
      isStream: isStream2,
      destroy,
      isBuffer,
      isFormDataLike,
      isIterable,
      isBlobLike: isBlobLike3,
      buildURL,
      validateHandler,
      getServerName,
      normalizedMethodRecords
    } = require_util22();
    var { channels } = require_diagnostics2();
    var { headerNameLowerCasedRecord } = require_constants14();
    var invalidPathRegex = /[^\u0021-\u00ff]/;
    var kHandler = Symbol("handler");
    var Request6 = class {
      static {
        __name(this, "Request");
      }
      constructor(origin, {
        path: path125,
        method,
        body,
        headers,
        query,
        idempotent,
        blocking,
        upgrade,
        headersTimeout,
        bodyTimeout,
        reset,
        throwOnError,
        expectContinue,
        servername
      }, handler) {
        if (typeof path125 !== "string") {
          throw new InvalidArgumentError("path must be a string");
        } else if (path125[0] !== "/" && !(path125.startsWith("http://") || path125.startsWith("https://")) && method !== "CONNECT") {
          throw new InvalidArgumentError("path must be an absolute URL or start with a slash");
        } else if (invalidPathRegex.test(path125)) {
          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");
        }
        this.headersTimeout = headersTimeout;
        this.bodyTimeout = bodyTimeout;
        this.throwOnError = throwOnError === true;
        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) || isBlobLike3(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 ? buildURL(path125, query) : path125;
        this.origin = origin;
        this.idempotent = idempotent == null ? method === "HEAD" || method === "GET" : idempotent;
        this.blocking = blocking == null ? false : blocking;
        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 i3 = 0; i3 < headers.length; i3 += 2) {
            processHeader(this, headers[i3], headers[i3 + 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 i3 = 0; i3 < keys.length; ++i3) {
              processHeader(this, keys[i3], headers[keys[i3]]);
            }
          }
        } else if (headers != null) {
          throw new InvalidArgumentError("headers must be an object or an array");
        }
        validateHandler(handler, method, upgrade);
        this.servername = servername || getServerName(this.host);
        this[kHandler] = handler;
        if (channels.create.hasSubscribers) {
          channels.create.publish({ request: this });
        }
      }
      onBodySent(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) {
        assert4(!this.aborted);
        assert4(!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) {
        assert4(!this.aborted);
        assert4(!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) {
        assert4(!this.aborted);
        assert4(!this.completed);
        try {
          return this[kHandler].onData(chunk);
        } catch (err) {
          this.abort(err);
          return false;
        }
      }
      onUpgrade(statusCode, headers, socket) {
        assert4(!this.aborted);
        assert4(!this.completed);
        return this[kHandler].onUpgrade(statusCode, headers, socket);
      }
      onComplete(trailers) {
        this.onFinally();
        assert4(!this.aborted);
        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(error2) {
        this.onFinally();
        if (channels.error.hasSubscribers) {
          channels.error.publish({ request: this, error: error2 });
        }
        if (this.aborted) {
          return;
        }
        this.aborted = true;
        return this[kHandler].onError(error2);
      }
      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 i3 = 0; i3 < val.length; i3++) {
          if (typeof val[i3] === "string") {
            if (!isValidHeaderValue(val[i3])) {
              throw new InvalidArgumentError(`invalid ${key} header`);
            }
            arr.push(val[i3]);
          } else if (val[i3] === null) {
            arr.push("");
          } else if (typeof val[i3] === "object") {
            throw new InvalidArgumentError(`invalid ${key} header`);
          } else {
            arr.push(`${val[i3]}`);
          }
        }
        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 = Request6;
  }
});

// packages/cli/node_modules/undici/lib/dispatcher/dispatcher.js
var require_dispatcher2 = __commonJS({
  "packages/cli/node_modules/undici/lib/dispatcher/dispatcher.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var EventEmitter11 = __require("node:events");
    var Dispatcher = class extends EventEmitter11 {
      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);
          if (dispatch == null || typeof dispatch !== "function" || dispatch.length !== 2) {
            throw new TypeError("invalid interceptor");
          }
        }
        return new ComposedDispatcher(this, dispatch);
      }
    };
    var ComposedDispatcher = class extends Dispatcher {
      static {
        __name(this, "ComposedDispatcher");
      }
      #dispatcher = null;
      #dispatch = null;
      constructor(dispatcher, dispatch) {
        super();
        this.#dispatcher = dispatcher;
        this.#dispatch = dispatch;
      }
      dispatch(...args) {
        this.#dispatch(...args);
      }
      close(...args) {
        return this.#dispatcher.close(...args);
      }
      destroy(...args) {
        return this.#dispatcher.destroy(...args);
      }
    };
    module2.exports = Dispatcher;
  }
});

// packages/cli/node_modules/undici/lib/dispatcher/dispatcher-base.js
var require_dispatcher_base2 = __commonJS({
  "packages/cli/node_modules/undici/lib/dispatcher/dispatcher-base.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var Dispatcher = require_dispatcher2();
    var {
      ClientDestroyedError,
      ClientClosedError,
      InvalidArgumentError
    } = require_errors5();
    var { kDestroy, kClose, kClosed, kDestroyed, kDispatch, kInterceptors } = require_symbols6();
    var kOnDestroyed = Symbol("onDestroyed");
    var kOnClosed = Symbol("onClosed");
    var kInterceptedDispatch = Symbol("Intercepted Dispatch");
    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];
      }
      get interceptors() {
        return this[kInterceptors];
      }
      set interceptors(newInterceptors) {
        if (newInterceptors) {
          for (let i3 = newInterceptors.length - 1; i3 >= 0; i3--) {
            const interceptor = this[kInterceptors][i3];
            if (typeof interceptor !== "function") {
              throw new InvalidArgumentError("interceptor must be an function");
            }
          }
        }
        this[kInterceptors] = newInterceptors;
      }
      close(callback) {
        if (callback === void 0) {
          return new Promise((resolve30, reject) => {
            this.close((err, data) => {
              return err ? reject(err) : resolve30(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 i3 = 0; i3 < callbacks.length; i3++) {
            callbacks[i3](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((resolve30, reject) => {
            this.destroy(err, (err2, data) => {
              return err2 ? (
                /* istanbul ignore next: should never error */
                reject(err2)
              ) : resolve30(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 i3 = 0; i3 < callbacks.length; i3++) {
            callbacks[i3](null, null);
          }
        }, "onDestroyed");
        this[kDestroy](err).then(() => {
          queueMicrotask(onDestroyed);
        });
      }
      [kInterceptedDispatch](opts, handler) {
        if (!this[kInterceptors] || this[kInterceptors].length === 0) {
          this[kInterceptedDispatch] = this[kDispatch];
          return this[kDispatch](opts, handler);
        }
        let dispatch = this[kDispatch].bind(this);
        for (let i3 = this[kInterceptors].length - 1; i3 >= 0; i3--) {
          dispatch = this[kInterceptors][i3](dispatch);
        }
        this[kInterceptedDispatch] = dispatch;
        return dispatch(opts, handler);
      }
      dispatch(opts, handler) {
        if (!handler || typeof handler !== "object") {
          throw new InvalidArgumentError("handler must be an object");
        }
        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[kInterceptedDispatch](opts, handler);
        } catch (err) {
          if (typeof handler.onError !== "function") {
            throw new InvalidArgumentError("invalid onError method");
          }
          handler.onError(err);
          return false;
        }
      }
    };
    module2.exports = DispatcherBase;
  }
});

// packages/cli/node_modules/undici/lib/util/timers.js
var require_timers2 = __commonJS({
  "packages/cli/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) {
        fastNowTimeout.refresh();
      } else {
        clearTimeout(fastNowTimeout);
        fastNowTimeout = setTimeout(onTick, TICK_MS);
        if (fastNowTimeout.unref) {
          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
    };
  }
});

// packages/cli/node_modules/undici/lib/core/connect.js
var require_connect2 = __commonJS({
  "packages/cli/node_modules/undici/lib/core/connect.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var net2 = __require("node:net");
    var assert4 = __require("node:assert");
    var util3 = require_util22();
    var { InvalidArgumentError, ConnectTimeoutError } = require_errors5();
    var timers = require_timers2();
    function noop8() {
    }
    __name(noop8, "noop");
    var tls;
    var SessionCache;
    if (globalThis.FinalizationRegistry && !(process.env.NODE_V8_COVERAGE || process.env.UNDICI_NO_FG)) {
      SessionCache = class WeakSessionCache {
        static {
          __name(this, "WeakSessionCache");
        }
        constructor(maxCachedSessions) {
          this._maxCachedSessions = maxCachedSessions;
          this._sessionCache = /* @__PURE__ */ new Map();
          this._sessionRegistry = new globalThis.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);
        }
      };
    } else {
      SessionCache = class SimpleSessionCache {
        static {
          __name(this, "SimpleSessionCache");
        }
        constructor(maxCachedSessions) {
          this._maxCachedSessions = maxCachedSessions;
          this._sessionCache = /* @__PURE__ */ new Map();
        }
        get(sessionKey) {
          return this._sessionCache.get(sessionKey);
        }
        set(sessionKey, session) {
          if (this._maxCachedSessions === 0) {
            return;
          }
          if (this._sessionCache.size >= this._maxCachedSessions) {
            const { value: oldestKey } = this._sessionCache.keys().next();
            this._sessionCache.delete(oldestKey);
          }
          this._sessionCache.set(sessionKey, session);
        }
      };
    }
    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: hostname4, host, protocol, port, servername, localAddress, httpSocket }, callback) {
        let socket;
        if (protocol === "https:") {
          if (!tls) {
            tls = __require("node:tls");
          }
          servername = servername || options2.servername || util3.getServerName(host) || null;
          const sessionKey = servername || hostname4;
          assert4(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,
            // TODO(HTTP/2): Add support for h2c
            ALPNProtocols: allowH2 ? ["http/1.1", "h2"] : ["http/1.1"],
            socket: httpSocket,
            // upgrade socket connection
            port,
            host: hostname4
          });
          socket.on("session", function(session2) {
            sessionCache.set(sessionKey, session2);
          });
        } else {
          assert4(!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: hostname4
          });
        }
        if (options2.keepAlive == null || options2.keepAlive) {
          const keepAliveInitialDelay = options2.keepAliveInitialDelay === void 0 ? 6e4 : options2.keepAliveInitialDelay;
          socket.setKeepAlive(true, keepAliveInitialDelay);
        }
        const clearConnectTimeout = setupConnectTimeout(new WeakRef(socket), { timeout: timeout2, hostname: hostname4, 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");
    var setupConnectTimeout = process.platform === "win32" ? (socketWeakRef, opts) => {
      if (!opts.timeout) {
        return noop8;
      }
      let s1 = null;
      let s22 = null;
      const fastTimer = timers.setFastTimeout(() => {
        s1 = setImmediate(() => {
          s22 = setImmediate(() => onConnectTimeout(socketWeakRef.deref(), opts));
        });
      }, opts.timeout);
      return () => {
        timers.clearFastTimeout(fastTimer);
        clearImmediate(s1);
        clearImmediate(s22);
      };
    } : (socketWeakRef, opts) => {
      if (!opts.timeout) {
        return noop8;
      }
      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)`;
      util3.destroy(socket, new ConnectTimeoutError(message));
    }
    __name(onConnectTimeout, "onConnectTimeout");
    module2.exports = buildConnector;
  }
});

// packages/cli/node_modules/undici/lib/llhttp/utils.js
var require_utils16 = __commonJS({
  "packages/cli/node_modules/undici/lib/llhttp/utils.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.enumToMap = void 0;
    function enumToMap(obj) {
      const res = {};
      Object.keys(obj).forEach((key) => {
        const value = obj[key];
        if (typeof value === "number") {
          res[key] = value;
        }
      });
      return res;
    }
    __name(enumToMap, "enumToMap");
    exports2.enumToMap = enumToMap;
  }
});

// packages/cli/node_modules/undici/lib/llhttp/constants.js
var require_constants15 = __commonJS({
  "packages/cli/node_modules/undici/lib/llhttp/constants.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.SPECIAL_HEADERS = exports2.HEADER_STATE = exports2.MINOR = exports2.MAJOR = exports2.CONNECTION_TOKEN_CHARS = exports2.HEADER_CHARS = exports2.TOKEN = exports2.STRICT_TOKEN = exports2.HEX = exports2.URL_CHAR = exports2.STRICT_URL_CHAR = exports2.USERINFO_CHARS = exports2.MARK = exports2.ALPHANUM = exports2.NUM = exports2.HEX_MAP = exports2.NUM_MAP = exports2.ALPHA = exports2.FINISH = exports2.H_METHOD_MAP = exports2.METHOD_MAP = exports2.METHODS_RTSP = exports2.METHODS_ICE = exports2.METHODS_HTTP = exports2.METHODS = exports2.LENIENT_FLAGS = exports2.FLAGS = exports2.TYPE = exports2.ERROR = void 0;
    var utils_1 = require_utils16();
    var ERROR2;
    (function(ERROR3) {
      ERROR3[ERROR3["OK"] = 0] = "OK";
      ERROR3[ERROR3["INTERNAL"] = 1] = "INTERNAL";
      ERROR3[ERROR3["STRICT"] = 2] = "STRICT";
      ERROR3[ERROR3["LF_EXPECTED"] = 3] = "LF_EXPECTED";
      ERROR3[ERROR3["UNEXPECTED_CONTENT_LENGTH"] = 4] = "UNEXPECTED_CONTENT_LENGTH";
      ERROR3[ERROR3["CLOSED_CONNECTION"] = 5] = "CLOSED_CONNECTION";
      ERROR3[ERROR3["INVALID_METHOD"] = 6] = "INVALID_METHOD";
      ERROR3[ERROR3["INVALID_URL"] = 7] = "INVALID_URL";
      ERROR3[ERROR3["INVALID_CONSTANT"] = 8] = "INVALID_CONSTANT";
      ERROR3[ERROR3["INVALID_VERSION"] = 9] = "INVALID_VERSION";
      ERROR3[ERROR3["INVALID_HEADER_TOKEN"] = 10] = "INVALID_HEADER_TOKEN";
      ERROR3[ERROR3["INVALID_CONTENT_LENGTH"] = 11] = "INVALID_CONTENT_LENGTH";
      ERROR3[ERROR3["INVALID_CHUNK_SIZE"] = 12] = "INVALID_CHUNK_SIZE";
      ERROR3[ERROR3["INVALID_STATUS"] = 13] = "INVALID_STATUS";
      ERROR3[ERROR3["INVALID_EOF_STATE"] = 14] = "INVALID_EOF_STATE";
      ERROR3[ERROR3["INVALID_TRANSFER_ENCODING"] = 15] = "INVALID_TRANSFER_ENCODING";
      ERROR3[ERROR3["CB_MESSAGE_BEGIN"] = 16] = "CB_MESSAGE_BEGIN";
      ERROR3[ERROR3["CB_HEADERS_COMPLETE"] = 17] = "CB_HEADERS_COMPLETE";
      ERROR3[ERROR3["CB_MESSAGE_COMPLETE"] = 18] = "CB_MESSAGE_COMPLETE";
      ERROR3[ERROR3["CB_CHUNK_HEADER"] = 19] = "CB_CHUNK_HEADER";
      ERROR3[ERROR3["CB_CHUNK_COMPLETE"] = 20] = "CB_CHUNK_COMPLETE";
      ERROR3[ERROR3["PAUSED"] = 21] = "PAUSED";
      ERROR3[ERROR3["PAUSED_UPGRADE"] = 22] = "PAUSED_UPGRADE";
      ERROR3[ERROR3["PAUSED_H2_UPGRADE"] = 23] = "PAUSED_H2_UPGRADE";
      ERROR3[ERROR3["USER"] = 24] = "USER";
    })(ERROR2 = exports2.ERROR || (exports2.ERROR = {}));
    var TYPE2;
    (function(TYPE3) {
      TYPE3[TYPE3["BOTH"] = 0] = "BOTH";
      TYPE3[TYPE3["REQUEST"] = 1] = "REQUEST";
      TYPE3[TYPE3["RESPONSE"] = 2] = "RESPONSE";
    })(TYPE2 = exports2.TYPE || (exports2.TYPE = {}));
    var FLAGS;
    (function(FLAGS2) {
      FLAGS2[FLAGS2["CONNECTION_KEEP_ALIVE"] = 1] = "CONNECTION_KEEP_ALIVE";
      FLAGS2[FLAGS2["CONNECTION_CLOSE"] = 2] = "CONNECTION_CLOSE";
      FLAGS2[FLAGS2["CONNECTION_UPGRADE"] = 4] = "CONNECTION_UPGRADE";
      FLAGS2[FLAGS2["CHUNKED"] = 8] = "CHUNKED";
      FLAGS2[FLAGS2["UPGRADE"] = 16] = "UPGRADE";
      FLAGS2[FLAGS2["CONTENT_LENGTH"] = 32] = "CONTENT_LENGTH";
      FLAGS2[FLAGS2["SKIPBODY"] = 64] = "SKIPBODY";
      FLAGS2[FLAGS2["TRAILING"] = 128] = "TRAILING";
      FLAGS2[FLAGS2["TRANSFER_ENCODING"] = 512] = "TRANSFER_ENCODING";
    })(FLAGS = exports2.FLAGS || (exports2.FLAGS = {}));
    var LENIENT_FLAGS;
    (function(LENIENT_FLAGS2) {
      LENIENT_FLAGS2[LENIENT_FLAGS2["HEADERS"] = 1] = "HEADERS";
      LENIENT_FLAGS2[LENIENT_FLAGS2["CHUNKED_LENGTH"] = 2] = "CHUNKED_LENGTH";
      LENIENT_FLAGS2[LENIENT_FLAGS2["KEEP_ALIVE"] = 4] = "KEEP_ALIVE";
    })(LENIENT_FLAGS = exports2.LENIENT_FLAGS || (exports2.LENIENT_FLAGS = {}));
    var METHODS;
    (function(METHODS2) {
      METHODS2[METHODS2["DELETE"] = 0] = "DELETE";
      METHODS2[METHODS2["GET"] = 1] = "GET";
      METHODS2[METHODS2["HEAD"] = 2] = "HEAD";
      METHODS2[METHODS2["POST"] = 3] = "POST";
      METHODS2[METHODS2["PUT"] = 4] = "PUT";
      METHODS2[METHODS2["CONNECT"] = 5] = "CONNECT";
      METHODS2[METHODS2["OPTIONS"] = 6] = "OPTIONS";
      METHODS2[METHODS2["TRACE"] = 7] = "TRACE";
      METHODS2[METHODS2["COPY"] = 8] = "COPY";
      METHODS2[METHODS2["LOCK"] = 9] = "LOCK";
      METHODS2[METHODS2["MKCOL"] = 10] = "MKCOL";
      METHODS2[METHODS2["MOVE"] = 11] = "MOVE";
      METHODS2[METHODS2["PROPFIND"] = 12] = "PROPFIND";
      METHODS2[METHODS2["PROPPATCH"] = 13] = "PROPPATCH";
      METHODS2[METHODS2["SEARCH"] = 14] = "SEARCH";
      METHODS2[METHODS2["UNLOCK"] = 15] = "UNLOCK";
      METHODS2[METHODS2["BIND"] = 16] = "BIND";
      METHODS2[METHODS2["REBIND"] = 17] = "REBIND";
      METHODS2[METHODS2["UNBIND"] = 18] = "UNBIND";
      METHODS2[METHODS2["ACL"] = 19] = "ACL";
      METHODS2[METHODS2["REPORT"] = 20] = "REPORT";
      METHODS2[METHODS2["MKACTIVITY"] = 21] = "MKACTIVITY";
      METHODS2[METHODS2["CHECKOUT"] = 22] = "CHECKOUT";
      METHODS2[METHODS2["MERGE"] = 23] = "MERGE";
      METHODS2[METHODS2["M-SEARCH"] = 24] = "M-SEARCH";
      METHODS2[METHODS2["NOTIFY"] = 25] = "NOTIFY";
      METHODS2[METHODS2["SUBSCRIBE"] = 26] = "SUBSCRIBE";
      METHODS2[METHODS2["UNSUBSCRIBE"] = 27] = "UNSUBSCRIBE";
      METHODS2[METHODS2["PATCH"] = 28] = "PATCH";
      METHODS2[METHODS2["PURGE"] = 29] = "PURGE";
      METHODS2[METHODS2["MKCALENDAR"] = 30] = "MKCALENDAR";
      METHODS2[METHODS2["LINK"] = 31] = "LINK";
      METHODS2[METHODS2["UNLINK"] = 32] = "UNLINK";
      METHODS2[METHODS2["SOURCE"] = 33] = "SOURCE";
      METHODS2[METHODS2["PRI"] = 34] = "PRI";
      METHODS2[METHODS2["DESCRIBE"] = 35] = "DESCRIBE";
      METHODS2[METHODS2["ANNOUNCE"] = 36] = "ANNOUNCE";
      METHODS2[METHODS2["SETUP"] = 37] = "SETUP";
      METHODS2[METHODS2["PLAY"] = 38] = "PLAY";
      METHODS2[METHODS2["PAUSE"] = 39] = "PAUSE";
      METHODS2[METHODS2["TEARDOWN"] = 40] = "TEARDOWN";
      METHODS2[METHODS2["GET_PARAMETER"] = 41] = "GET_PARAMETER";
      METHODS2[METHODS2["SET_PARAMETER"] = 42] = "SET_PARAMETER";
      METHODS2[METHODS2["REDIRECT"] = 43] = "REDIRECT";
      METHODS2[METHODS2["RECORD"] = 44] = "RECORD";
      METHODS2[METHODS2["FLUSH"] = 45] = "FLUSH";
    })(METHODS = exports2.METHODS || (exports2.METHODS = {}));
    exports2.METHODS_HTTP = [
      METHODS.DELETE,
      METHODS.GET,
      METHODS.HEAD,
      METHODS.POST,
      METHODS.PUT,
      METHODS.CONNECT,
      METHODS.OPTIONS,
      METHODS.TRACE,
      METHODS.COPY,
      METHODS.LOCK,
      METHODS.MKCOL,
      METHODS.MOVE,
      METHODS.PROPFIND,
      METHODS.PROPPATCH,
      METHODS.SEARCH,
      METHODS.UNLOCK,
      METHODS.BIND,
      METHODS.REBIND,
      METHODS.UNBIND,
      METHODS.ACL,
      METHODS.REPORT,
      METHODS.MKACTIVITY,
      METHODS.CHECKOUT,
      METHODS.MERGE,
      METHODS["M-SEARCH"],
      METHODS.NOTIFY,
      METHODS.SUBSCRIBE,
      METHODS.UNSUBSCRIBE,
      METHODS.PATCH,
      METHODS.PURGE,
      METHODS.MKCALENDAR,
      METHODS.LINK,
      METHODS.UNLINK,
      METHODS.PRI,
      // TODO(indutny): should we allow it with HTTP?
      METHODS.SOURCE
    ];
    exports2.METHODS_ICE = [
      METHODS.SOURCE
    ];
    exports2.METHODS_RTSP = [
      METHODS.OPTIONS,
      METHODS.DESCRIBE,
      METHODS.ANNOUNCE,
      METHODS.SETUP,
      METHODS.PLAY,
      METHODS.PAUSE,
      METHODS.TEARDOWN,
      METHODS.GET_PARAMETER,
      METHODS.SET_PARAMETER,
      METHODS.REDIRECT,
      METHODS.RECORD,
      METHODS.FLUSH,
      // For AirPlay
      METHODS.GET,
      METHODS.POST
    ];
    exports2.METHOD_MAP = utils_1.enumToMap(METHODS);
    exports2.H_METHOD_MAP = {};
    Object.keys(exports2.METHOD_MAP).forEach((key) => {
      if (/^H/.test(key)) {
        exports2.H_METHOD_MAP[key] = exports2.METHOD_MAP[key];
      }
    });
    var FINISH;
    (function(FINISH2) {
      FINISH2[FINISH2["SAFE"] = 0] = "SAFE";
      FINISH2[FINISH2["SAFE_WITH_CB"] = 1] = "SAFE_WITH_CB";
      FINISH2[FINISH2["UNSAFE"] = 2] = "UNSAFE";
    })(FINISH = exports2.FINISH || (exports2.FINISH = {}));
    exports2.ALPHA = [];
    for (let i3 = "A".charCodeAt(0); i3 <= "Z".charCodeAt(0); i3++) {
      exports2.ALPHA.push(String.fromCharCode(i3));
      exports2.ALPHA.push(String.fromCharCode(i3 + 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.STRICT_URL_CHAR = [
      "!",
      '"',
      "$",
      "%",
      "&",
      "'",
      "(",
      ")",
      "*",
      "+",
      ",",
      "-",
      ".",
      "/",
      ":",
      ";",
      "<",
      "=",
      ">",
      "@",
      "[",
      "\\",
      "]",
      "^",
      "_",
      "`",
      "{",
      "|",
      "}",
      "~"
    ].concat(exports2.ALPHANUM);
    exports2.URL_CHAR = exports2.STRICT_URL_CHAR.concat(["	", "\f"]);
    for (let i3 = 128; i3 <= 255; i3++) {
      exports2.URL_CHAR.push(i3);
    }
    exports2.HEX = exports2.NUM.concat(["a", "b", "c", "d", "e", "f", "A", "B", "C", "D", "E", "F"]);
    exports2.STRICT_TOKEN = [
      "!",
      "#",
      "$",
      "%",
      "&",
      "'",
      "*",
      "+",
      "-",
      ".",
      "^",
      "_",
      "`",
      "|",
      "~"
    ].concat(exports2.ALPHANUM);
    exports2.TOKEN = exports2.STRICT_TOKEN.concat([" "]);
    exports2.HEADER_CHARS = ["	"];
    for (let i3 = 32; i3 <= 255; i3++) {
      if (i3 !== 127) {
        exports2.HEADER_CHARS.push(i3);
      }
    }
    exports2.CONNECTION_TOKEN_CHARS = exports2.HEADER_CHARS.filter((c4) => c4 !== 44);
    exports2.MAJOR = exports2.NUM_MAP;
    exports2.MINOR = exports2.MAJOR;
    var HEADER_STATE;
    (function(HEADER_STATE2) {
      HEADER_STATE2[HEADER_STATE2["GENERAL"] = 0] = "GENERAL";
      HEADER_STATE2[HEADER_STATE2["CONNECTION"] = 1] = "CONNECTION";
      HEADER_STATE2[HEADER_STATE2["CONTENT_LENGTH"] = 2] = "CONTENT_LENGTH";
      HEADER_STATE2[HEADER_STATE2["TRANSFER_ENCODING"] = 3] = "TRANSFER_ENCODING";
      HEADER_STATE2[HEADER_STATE2["UPGRADE"] = 4] = "UPGRADE";
      HEADER_STATE2[HEADER_STATE2["CONNECTION_KEEP_ALIVE"] = 5] = "CONNECTION_KEEP_ALIVE";
      HEADER_STATE2[HEADER_STATE2["CONNECTION_CLOSE"] = 6] = "CONNECTION_CLOSE";
      HEADER_STATE2[HEADER_STATE2["CONNECTION_UPGRADE"] = 7] = "CONNECTION_UPGRADE";
      HEADER_STATE2[HEADER_STATE2["TRANSFER_ENCODING_CHUNKED"] = 8] = "TRANSFER_ENCODING_CHUNKED";
    })(HEADER_STATE = exports2.HEADER_STATE || (exports2.HEADER_STATE = {}));
    exports2.SPECIAL_HEADERS = {
      "connection": HEADER_STATE.CONNECTION,
      "content-length": HEADER_STATE.CONTENT_LENGTH,
      "proxy-connection": HEADER_STATE.CONNECTION,
      "transfer-encoding": HEADER_STATE.TRANSFER_ENCODING,
      "upgrade": HEADER_STATE.UPGRADE
    };
  }
});

// packages/cli/node_modules/undici/lib/llhttp/llhttp-wasm.js
var require_llhttp_wasm2 = __commonJS({
  "packages/cli/node_modules/undici/lib/llhttp/llhttp-wasm.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var { Buffer: Buffer9 } = __require("node:buffer");
    module2.exports = Buffer9.from(" ", "base64");
  }
});

// packages/cli/node_modules/undici/lib/llhttp/llhttp_simd-wasm.js
var require_llhttp_simd_wasm2 = __commonJS({
  "packages/cli/node_modules/undici/lib/llhttp/llhttp_simd-wasm.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var { Buffer: Buffer9 } = __require("node:buffer");
    module2.exports = Buffer9.from(" ", "base64");
  }
});

// packages/cli/node_modules/undici/lib/web/fetch/constants.js
var require_constants16 = __commonJS({
  "packages/cli/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 redirectStatus3 = (
      /** @type {const} */
      [301, 302, 303, 307, 308]
    );
    var redirectStatusSet = new Set(redirectStatus3);
    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 referrerPolicy = (
      /** @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 referrerPolicySet = new Set(referrerPolicy);
    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: redirectStatus3,
      corsSafeListedMethods,
      nullBodyStatus,
      safeMethods,
      badPorts,
      requestDuplex,
      subresourceSet,
      badPortsSet,
      redirectStatusSet,
      corsSafeListedMethodsSet,
      safeMethodsSet,
      forbiddenMethodsSet,
      referrerPolicySet
    };
  }
});

// packages/cli/node_modules/undici/lib/web/fetch/global.js
var require_global3 = __commonJS({
  "packages/cli/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
    };
  }
});

// packages/cli/node_modules/undici/lib/web/fetch/data-url.js
var require_data_url2 = __commonJS({
  "packages/cli/node_modules/undici/lib/web/fetch/data-url.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var assert4 = __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) {
      assert4(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 j2 = 0;
      for (let i3 = 0; i3 < length; ++i3) {
        const byte = input[i3];
        if (byte !== 37) {
          output[j2++] = byte;
        } else if (byte === 37 && !(isHexCharByte(input[i3 + 1]) && isHexCharByte(input[i3 + 2]))) {
          output[j2++] = 37;
        } else {
          output[j2++] = hexByteToNumber(input[i3 + 1]) << 4 | hexByteToNumber(input[i3 + 2]);
          i3 += 2;
        }
      }
      return length === j2 ? output : output.subarray(0, j2);
    }
    __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) {
      const positionStart = position.position;
      let value = "";
      assert4(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 {
          assert4(quoteOrBackslash === '"');
          break;
        }
      }
      if (extractValue) {
        return value;
      }
      return input.slice(positionStart, position.position);
    }
    __name(collectAnHTTPQuotedString, "collectAnHTTPQuotedString");
    function serializeAMimeType(mimeType) {
      assert4(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 i3 = 0;
      let addition = (2 << 15) - 1;
      while (i3 < length) {
        if (i3 + addition > length) {
          addition = length - i3;
        }
        result += String.fromCharCode.apply(null, input.subarray(i3, i3 += 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
    };
  }
});

// packages/cli/node_modules/undici/lib/web/fetch/webidl.js
var require_webidl2 = __commonJS({
  "packages/cli/node_modules/undici/lib/web/fetch/webidl.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var { types: types7, inspect: inspect3 } = __require("node:util");
    var { markAsUncloneable } = __require("node:worker_threads");
    var { toUSVString } = require_util22();
    var webidl = {};
    webidl.converters = {};
    webidl.util = {};
    webidl.errors = {};
    webidl.errors.exception = function(message) {
      return new TypeError(`${message.header}: ${message.message}`);
    };
    webidl.errors.conversionFailed = function(context2) {
      const plural = context2.types.length === 1 ? "" : " one of";
      const message = `${context2.argument} could not be converted to${plural}: ${context2.types.join(", ")}.`;
      return webidl.errors.exception({
        header: context2.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(V3, I3, opts) {
      if (opts?.strict !== false) {
        if (!(V3 instanceof I3)) {
          const err = new TypeError("Illegal invocation");
          err.code = "ERR_INVALID_THIS";
          throw err;
        }
      } else {
        if (V3?.[Symbol.toStringTag] !== I3.prototype[Symbol.toStringTag]) {
          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.Type = function(V3) {
      switch (typeof V3) {
        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 (V3 === null) {
            return "Null";
          }
          return "Object";
        }
      }
    };
    webidl.util.markAsUncloneable = markAsUncloneable || (() => {
    });
    webidl.util.ConvertToInt = function(V3, 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 x3 = Number(V3);
      if (x3 === 0) {
        x3 = 0;
      }
      if (opts?.enforceRange === true) {
        if (Number.isNaN(x3) || x3 === Number.POSITIVE_INFINITY || x3 === Number.NEGATIVE_INFINITY) {
          throw webidl.errors.exception({
            header: "Integer conversion",
            message: `Could not convert ${webidl.util.Stringify(V3)} to an integer.`
          });
        }
        x3 = webidl.util.IntegerPart(x3);
        if (x3 < lowerBound || x3 > upperBound) {
          throw webidl.errors.exception({
            header: "Integer conversion",
            message: `Value must be between ${lowerBound}-${upperBound}, got ${x3}.`
          });
        }
        return x3;
      }
      if (!Number.isNaN(x3) && opts?.clamp === true) {
        x3 = Math.min(Math.max(x3, lowerBound), upperBound);
        if (Math.floor(x3) % 2 === 0) {
          x3 = Math.floor(x3);
        } else {
          x3 = Math.ceil(x3);
        }
        return x3;
      }
      if (Number.isNaN(x3) || x3 === 0 && Object.is(0, x3) || x3 === Number.POSITIVE_INFINITY || x3 === Number.NEGATIVE_INFINITY) {
        return 0;
      }
      x3 = webidl.util.IntegerPart(x3);
      x3 = x3 % Math.pow(2, bitLength);
      if (signedness === "signed" && x3 >= Math.pow(2, bitLength) - 1) {
        return x3 - Math.pow(2, bitLength);
      }
      return x3;
    };
    webidl.util.IntegerPart = function(n3) {
      const r5 = Math.floor(Math.abs(n3));
      if (n3 < 0) {
        return -1 * r5;
      }
      return r5;
    };
    webidl.util.Stringify = function(V3) {
      const type = webidl.util.Type(V3);
      switch (type) {
        case "Symbol":
          return `Symbol(${V3.description})`;
        case "Object":
          return inspect3(V3);
        case "String":
          return `"${V3}"`;
        default:
          return `${V3}`;
      }
    };
    webidl.sequenceConverter = function(converter) {
      return (V3, prefix, argument, Iterable) => {
        if (webidl.util.Type(V3) !== "Object") {
          throw webidl.errors.exception({
            header: prefix,
            message: `${argument} (${webidl.util.Stringify(V3)}) is not iterable.`
          });
        }
        const method = typeof Iterable === "function" ? Iterable() : V3?.[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 (O2, prefix, argument) => {
        if (webidl.util.Type(O2) !== "Object") {
          throw webidl.errors.exception({
            header: prefix,
            message: `${argument} ("${webidl.util.Type(O2)}") is not an Object.`
          });
        }
        const result = {};
        if (!types7.isProxy(O2)) {
          const keys2 = [...Object.getOwnPropertyNames(O2), ...Object.getOwnPropertySymbols(O2)];
          for (const key of keys2) {
            const typedKey = keyConverter(key, prefix, argument);
            const typedValue = valueConverter(O2[key], prefix, argument);
            result[typedKey] = typedValue;
          }
          return result;
        }
        const keys = Reflect.ownKeys(O2);
        for (const key of keys) {
          const desc2 = Reflect.getOwnPropertyDescriptor(O2, key);
          if (desc2?.enumerable) {
            const typedKey = keyConverter(key, prefix, argument);
            const typedValue = valueConverter(O2[key], prefix, argument);
            result[typedKey] = typedValue;
          }
        }
        return result;
      };
    };
    webidl.interfaceConverter = function(i3) {
      return (V3, prefix, argument, opts) => {
        if (opts?.strict !== false && !(V3 instanceof i3)) {
          throw webidl.errors.exception({
            header: prefix,
            message: `Expected ${argument} ("${webidl.util.Stringify(V3)}") to be an instance of ${i3.name}.`
          });
        }
        return V3;
      };
    };
    webidl.dictionaryConverter = function(converters) {
      return (dictionary, prefix, argument) => {
        const type = webidl.util.Type(dictionary);
        const dict = {};
        if (type === "Null" || type === "Undefined") {
          return dict;
        } else if (type !== "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: required2, converter } = options2;
          if (required2 === true) {
            if (!Object.hasOwn(dictionary, key)) {
              throw webidl.errors.exception({
                header: prefix,
                message: `Missing required key "${key}".`
              });
            }
          }
          let value = dictionary[key];
          const hasDefault = Object.hasOwn(options2, "defaultValue");
          if (hasDefault && value !== null) {
            value ??= defaultValue();
          }
          if (required2 || 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 (V3, prefix, argument) => {
        if (V3 === null) {
          return V3;
        }
        return converter(V3, prefix, argument);
      };
    };
    webidl.converters.DOMString = function(V3, prefix, argument, opts) {
      if (V3 === null && opts?.legacyNullToEmptyString) {
        return "";
      }
      if (typeof V3 === "symbol") {
        throw webidl.errors.exception({
          header: prefix,
          message: `${argument} is a symbol, which cannot be converted to a DOMString.`
        });
      }
      return String(V3);
    };
    webidl.converters.ByteString = function(V3, prefix, argument) {
      const x3 = webidl.converters.DOMString(V3, prefix, argument);
      for (let index = 0; index < x3.length; index++) {
        if (x3.charCodeAt(index) > 255) {
          throw new TypeError(
            `Cannot convert argument to a ByteString because the character at index ${index} has a value of ${x3.charCodeAt(index)} which is greater than 255.`
          );
        }
      }
      return x3;
    };
    webidl.converters.USVString = toUSVString;
    webidl.converters.boolean = function(V3) {
      const x3 = Boolean(V3);
      return x3;
    };
    webidl.converters.any = function(V3) {
      return V3;
    };
    webidl.converters["long long"] = function(V3, prefix, argument) {
      const x3 = webidl.util.ConvertToInt(V3, 64, "signed", void 0, prefix, argument);
      return x3;
    };
    webidl.converters["unsigned long long"] = function(V3, prefix, argument) {
      const x3 = webidl.util.ConvertToInt(V3, 64, "unsigned", void 0, prefix, argument);
      return x3;
    };
    webidl.converters["unsigned long"] = function(V3, prefix, argument) {
      const x3 = webidl.util.ConvertToInt(V3, 32, "unsigned", void 0, prefix, argument);
      return x3;
    };
    webidl.converters["unsigned short"] = function(V3, prefix, argument, opts) {
      const x3 = webidl.util.ConvertToInt(V3, 16, "unsigned", opts, prefix, argument);
      return x3;
    };
    webidl.converters.ArrayBuffer = function(V3, prefix, argument, opts) {
      if (webidl.util.Type(V3) !== "Object" || !types7.isAnyArrayBuffer(V3)) {
        throw webidl.errors.conversionFailed({
          prefix,
          argument: `${argument} ("${webidl.util.Stringify(V3)}")`,
          types: ["ArrayBuffer"]
        });
      }
      if (opts?.allowShared === false && types7.isSharedArrayBuffer(V3)) {
        throw webidl.errors.exception({
          header: "ArrayBuffer",
          message: "SharedArrayBuffer is not allowed."
        });
      }
      if (V3.resizable || V3.growable) {
        throw webidl.errors.exception({
          header: "ArrayBuffer",
          message: "Received a resizable ArrayBuffer."
        });
      }
      return V3;
    };
    webidl.converters.TypedArray = function(V3, T2, prefix, name3, opts) {
      if (webidl.util.Type(V3) !== "Object" || !types7.isTypedArray(V3) || V3.constructor.name !== T2.name) {
        throw webidl.errors.conversionFailed({
          prefix,
          argument: `${name3} ("${webidl.util.Stringify(V3)}")`,
          types: [T2.name]
        });
      }
      if (opts?.allowShared === false && types7.isSharedArrayBuffer(V3.buffer)) {
        throw webidl.errors.exception({
          header: "ArrayBuffer",
          message: "SharedArrayBuffer is not allowed."
        });
      }
      if (V3.buffer.resizable || V3.buffer.growable) {
        throw webidl.errors.exception({
          header: "ArrayBuffer",
          message: "Received a resizable ArrayBuffer."
        });
      }
      return V3;
    };
    webidl.converters.DataView = function(V3, prefix, name3, opts) {
      if (webidl.util.Type(V3) !== "Object" || !types7.isDataView(V3)) {
        throw webidl.errors.exception({
          header: prefix,
          message: `${name3} is not a DataView.`
        });
      }
      if (opts?.allowShared === false && types7.isSharedArrayBuffer(V3.buffer)) {
        throw webidl.errors.exception({
          header: "ArrayBuffer",
          message: "SharedArrayBuffer is not allowed."
        });
      }
      if (V3.buffer.resizable || V3.buffer.growable) {
        throw webidl.errors.exception({
          header: "ArrayBuffer",
          message: "Received a resizable ArrayBuffer."
        });
      }
      return V3;
    };
    webidl.converters.BufferSource = function(V3, prefix, name3, opts) {
      if (types7.isAnyArrayBuffer(V3)) {
        return webidl.converters.ArrayBuffer(V3, prefix, name3, { ...opts, allowShared: false });
      }
      if (types7.isTypedArray(V3)) {
        return webidl.converters.TypedArray(V3, V3.constructor, prefix, name3, { ...opts, allowShared: false });
      }
      if (types7.isDataView(V3)) {
        return webidl.converters.DataView(V3, prefix, name3, { ...opts, allowShared: false });
      }
      throw webidl.errors.conversionFailed({
        prefix,
        argument: `${name3} ("${webidl.util.Stringify(V3)}")`,
        types: ["BufferSource"]
      });
    };
    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
    );
    module2.exports = {
      webidl
    };
  }
});

// packages/cli/node_modules/undici/lib/web/fetch/util.js
var require_util23 = __commonJS({
  "packages/cli/node_modules/undici/lib/web/fetch/util.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var { Transform: Transform2 } = __require("node:stream");
    var zlib4 = __require("node:zlib");
    var { redirectStatusSet, referrerPolicySet: referrerPolicyTokens, badPortsSet } = require_constants16();
    var { getGlobalOrigin } = require_global3();
    var { collectASequenceOfCodePoints, collectAnHTTPQuotedString, removeChars, parseMIMEType } = require_data_url2();
    var { performance: performance2 } = __require("node:perf_hooks");
    var { isBlobLike: isBlobLike3, ReadableStreamFrom: ReadableStreamFrom2, isValidHTTPToken, normalizedMethodRecordsBase } = require_util22();
    var assert4 = __require("node:assert");
    var { isUint8Array } = __require("node:util/types");
    var { webidl } = require_webidl2();
    var supportedHashes = [];
    var crypto14;
    try {
      crypto14 = __require("node:crypto");
      const possibleRelevantHashes = ["sha256", "sha384", "sha512"];
      supportedHashes = crypto14.getHashes().filter((hash) => possibleRelevantHashes.includes(hash));
    } catch {
    }
    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 i3 = 0; i3 < url2.length; ++i3) {
        const code2 = url2.charCodeAt(i3);
        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(object3) {
      return object3 instanceof Error || (object3?.constructor?.name === "Error" || object3?.constructor?.name === "DOMException");
    }
    __name(isErrorLike, "isErrorLike");
    function isValidReasonPhrase(statusText) {
      for (let i3 = 0; i3 < statusText.length; ++i3) {
        const c4 = statusText.charCodeAt(i3);
        if (!(c4 === 9 || // HTAB
        c4 >= 32 && c4 <= 126 || // SP / VCHAR
        c4 >= 128 && c4 <= 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 setRequestReferrerPolicyOnRedirect(request4, actualResponse) {
      const { headersList } = actualResponse;
      const policyHeader = (headersList.get("referrer-policy", true) ?? "").split(",");
      let policy = "";
      if (policyHeader.length > 0) {
        for (let i3 = policyHeader.length; i3 !== 0; i3--) {
          const token2 = policyHeader[i3 - 1].trim();
          if (referrerPolicyTokens.has(token2)) {
            policy = token2;
            break;
          }
        }
      }
      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 determineRequestsReferrer3(request4) {
      const policy = request4.referrerPolicy;
      assert4(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 (request4.referrer instanceof URL) {
        referrerSource = request4.referrer;
      }
      let referrerURL = stripURLForReferrer(referrerSource);
      const referrerOrigin = stripURLForReferrer(referrerSource, true);
      if (referrerURL.toString().length > 4096) {
        referrerURL = referrerOrigin;
      }
      const areSameOrigin = sameOrigin(request4, referrerURL);
      const isNonPotentiallyTrustWorthy = isURLPotentiallyTrustworthy(referrerURL) && !isURLPotentiallyTrustworthy(request4.url);
      switch (policy) {
        case "origin":
          return referrerOrigin != null ? referrerOrigin : stripURLForReferrer(referrerSource, true);
        case "unsafe-url":
          return referrerURL;
        case "same-origin":
          return areSameOrigin ? referrerOrigin : "no-referrer";
        case "origin-when-cross-origin":
          return areSameOrigin ? referrerURL : 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 "strict-origin":
        // eslint-disable-line
        /**
           * 1. If referrerURL is a potentially trustworthy URL and
           * request’s current URL is not a potentially trustworthy URL,
           * then return no referrer.
           * 2. Return referrerOrigin
          */
        case "no-referrer-when-downgrade":
        // eslint-disable-line
        /**
         * 1. If referrerURL is a potentially trustworthy URL and
         * request’s current URL is not a potentially trustworthy URL,
         * then return no referrer.
         * 2. Return referrerOrigin
        */
        default:
          return isNonPotentiallyTrustWorthy ? "no-referrer" : referrerOrigin;
      }
    }
    __name(determineRequestsReferrer3, "determineRequestsReferrer");
    function stripURLForReferrer(url2, originOnly) {
      assert4(url2 instanceof URL);
      url2 = new URL(url2);
      if (url2.protocol === "file:" || url2.protocol === "about:" || url2.protocol === "blank:") {
        return "no-referrer";
      }
      url2.username = "";
      url2.password = "";
      url2.hash = "";
      if (originOnly) {
        url2.pathname = "";
        url2.search = "";
      }
      return url2;
    }
    __name(stripURLForReferrer, "stripURLForReferrer");
    function isURLPotentiallyTrustworthy(url2) {
      if (!(url2 instanceof URL)) {
        return false;
      }
      if (url2.href === "about:blank" || url2.href === "about:srcdoc") {
        return true;
      }
      if (url2.protocol === "data:") return true;
      if (url2.protocol === "file:") return true;
      return isOriginPotentiallyTrustworthy3(url2.origin);
      function isOriginPotentiallyTrustworthy3(origin) {
        if (origin == null || origin === "null") return false;
        const originAsURL = new URL(origin);
        if (originAsURL.protocol === "https:" || originAsURL.protocol === "wss:") {
          return true;
        }
        if (/^127(?:\.[0-9]+){0,2}\.[0-9]+$|^\[(?:0*:)*?:?0*1\]$/.test(originAsURL.hostname) || (originAsURL.hostname === "localhost" || originAsURL.hostname.includes("localhost.")) || originAsURL.hostname.endsWith(".localhost")) {
          return true;
        }
        return false;
      }
      __name(isOriginPotentiallyTrustworthy3, "isOriginPotentiallyTrustworthy");
    }
    __name(isURLPotentiallyTrustworthy, "isURLPotentiallyTrustworthy");
    function bytesMatch(bytes, metadataList) {
      if (crypto14 === void 0) {
        return true;
      }
      const parsedMetadata = parseMetadata(metadataList);
      if (parsedMetadata === "no metadata") {
        return true;
      }
      if (parsedMetadata.length === 0) {
        return true;
      }
      const strongest = getStrongestMetadata(parsedMetadata);
      const metadata = filterMetadataListByAlgorithm(parsedMetadata, strongest);
      for (const item of metadata) {
        const algorithm = item.algo;
        const expectedValue = item.hash;
        let actualValue = crypto14.createHash(algorithm).update(bytes).digest("base64");
        if (actualValue[actualValue.length - 1] === "=") {
          if (actualValue[actualValue.length - 2] === "=") {
            actualValue = actualValue.slice(0, -2);
          } else {
            actualValue = actualValue.slice(0, -1);
          }
        }
        if (compareBase64Mixed(actualValue, expectedValue)) {
          return true;
        }
      }
      return false;
    }
    __name(bytesMatch, "bytesMatch");
    var parseHashWithOptions = /(?<algo>sha256|sha384|sha512)-((?<hash>[A-Za-z0-9+/]+|[A-Za-z0-9_-]+)={0,2}(?:\s|$)( +[!-~]*)?)?/i;
    function parseMetadata(metadata) {
      const result = [];
      let empty = true;
      for (const token2 of metadata.split(" ")) {
        empty = false;
        const parsedToken = parseHashWithOptions.exec(token2);
        if (parsedToken === null || parsedToken.groups === void 0 || parsedToken.groups.algo === void 0) {
          continue;
        }
        const algorithm = parsedToken.groups.algo.toLowerCase();
        if (supportedHashes.includes(algorithm)) {
          result.push(parsedToken.groups);
        }
      }
      if (empty === true) {
        return "no metadata";
      }
      return result;
    }
    __name(parseMetadata, "parseMetadata");
    function getStrongestMetadata(metadataList) {
      let algorithm = metadataList[0].algo;
      if (algorithm[3] === "5") {
        return algorithm;
      }
      for (let i3 = 1; i3 < metadataList.length; ++i3) {
        const metadata = metadataList[i3];
        if (metadata.algo[3] === "5") {
          algorithm = "sha512";
          break;
        } else if (algorithm[3] === "3") {
          continue;
        } else if (metadata.algo[3] === "3") {
          algorithm = "sha384";
        }
      }
      return algorithm;
    }
    __name(getStrongestMetadata, "getStrongestMetadata");
    function filterMetadataListByAlgorithm(metadataList, algorithm) {
      if (metadataList.length === 1) {
        return metadataList;
      }
      let pos2 = 0;
      for (let i3 = 0; i3 < metadataList.length; ++i3) {
        if (metadataList[i3].algo === algorithm) {
          metadataList[pos2++] = metadataList[i3];
        }
      }
      metadataList.length = pos2;
      return metadataList;
    }
    __name(filterMetadataListByAlgorithm, "filterMetadataListByAlgorithm");
    function compareBase64Mixed(actualValue, expectedValue) {
      if (actualValue.length !== expectedValue.length) {
        return false;
      }
      for (let i3 = 0; i3 < actualValue.length; ++i3) {
        if (actualValue[i3] !== expectedValue[i3]) {
          if (actualValue[i3] === "+" && expectedValue[i3] === "-" || actualValue[i3] === "/" && expectedValue[i3] === "_") {
            continue;
          }
          return false;
        }
      }
      return true;
    }
    __name(compareBase64Mixed, "compareBase64Mixed");
    function tryUpgradeRequestToAPotentiallyTrustworthyURL(request4) {
    }
    __name(tryUpgradeRequestToAPotentiallyTrustworthyURL, "tryUpgradeRequestToAPotentiallyTrustworthyURL");
    function sameOrigin(A4, B2) {
      if (A4.origin === B2.origin && A4.origin === "null") {
        return true;
      }
      if (A4.protocol === B2.protocol && A4.hostname === B2.hostname && A4.port === B2.port) {
        return true;
      }
      return false;
    }
    __name(sameOrigin, "sameOrigin");
    function createDeferredPromise() {
      let res;
      let rej;
      const promise = new Promise((resolve30, reject) => {
        res = resolve30;
        rej = reject;
      });
      return { promise, resolve: res, reject: rej };
    }
    __name(createDeferredPromise, "createDeferredPromise");
    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");
      }
      assert4(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, kind2) {
          this.#target = target;
          this.#kind = kind2;
          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 = this.#target[kInternalIterator];
          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, kind2) {
        return new FastIterableIterator(target, kind2);
      };
    }
    __name(createIterator, "createIterator");
    function iteratorMixin(name3, object3, 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, object3);
            return makeIterator(this, "key");
          }, "keys")
        },
        values: {
          writable: true,
          enumerable: true,
          configurable: true,
          value: /* @__PURE__ */ __name(function values() {
            webidl.brandCheck(this, object3);
            return makeIterator(this, "value");
          }, "values")
        },
        entries: {
          writable: true,
          enumerable: true,
          configurable: true,
          value: /* @__PURE__ */ __name(function entries() {
            webidl.brandCheck(this, object3);
            return makeIterator(this, "key+value");
          }, "entries")
        },
        forEach: {
          writable: true,
          enumerable: true,
          configurable: true,
          value: /* @__PURE__ */ __name(function forEach2(callbackfn, thisArg = globalThis) {
            webidl.brandCheck(this, object3);
            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(object3.prototype, {
        ...properties,
        [Symbol.iterator]: {
          writable: true,
          enumerable: false,
          configurable: true,
          value: properties.entries.value
        }
      });
    }
    __name(iteratorMixin, "iteratorMixin");
    async function fullyReadBody(body, processBody, processBodyError) {
      const successSteps = processBody;
      const errorSteps = processBodyError;
      let reader;
      try {
        reader = body.stream.getReader();
      } catch (e4) {
        errorSteps(e4);
        return;
      }
      try {
        successSteps(await readAllBytes(reader));
      } catch (e4) {
        errorSteps(e4);
      }
    }
    __name(fullyReadBody, "fullyReadBody");
    function isReadableStreamLike(stream2) {
      return stream2 instanceof ReadableStream || stream2[Symbol.toStringTag] === "ReadableStream" && typeof stream2.tee === "function";
    }
    __name(isReadableStreamLike, "isReadableStreamLike");
    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) {
      assert4(!invalidIsomorphicEncodeValueRegex.test(input));
      return input;
    }
    __name(isomorphicEncode, "isomorphicEncode");
    async function readAllBytes(reader) {
      const bytes = [];
      let byteLength = 0;
      while (true) {
        const { done, value: chunk } = await reader.read();
        if (done) {
          return Buffer.concat(bytes, byteLength);
        }
        if (!isUint8Array(chunk)) {
          throw new TypeError("Received non-Uint8Array chunk");
        }
        bytes.push(chunk);
        byteLength += chunk.length;
      }
    }
    __name(readAllBytes, "readAllBytes");
    function urlIsLocal(url2) {
      assert4("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) {
      assert4("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 ? zlib4.createInflate(this.#zlibOptions) : zlib4.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 {
            assert4(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,
      createDeferredPromise,
      ReadableStreamFrom: ReadableStreamFrom2,
      tryUpgradeRequestToAPotentiallyTrustworthyURL,
      clampAndCoarsenConnectionTimingInfo,
      coarsenedSharedCurrentTime,
      determineRequestsReferrer: determineRequestsReferrer3,
      makePolicyContainer,
      clonePolicyContainer,
      appendFetchMetadata,
      appendRequestOriginHeader,
      TAOCheck,
      corsCheck,
      crossOriginResourcePolicyCheck,
      createOpaqueTimingInfo,
      setRequestReferrerPolicyOnRedirect,
      isValidHTTPToken,
      requestBadPort,
      requestCurrentURL,
      responseURL,
      responseLocationURL,
      isBlobLike: isBlobLike3,
      isURLPotentiallyTrustworthy,
      isValidReasonPhrase,
      sameOrigin,
      normalizeMethod,
      serializeJavascriptValueToJSONString,
      iteratorMixin,
      createIterator,
      isValidHeaderName,
      isValidHeaderValue,
      isErrorLike,
      fullyReadBody,
      bytesMatch,
      isReadableStreamLike,
      readableStreamClose,
      isomorphicEncode,
      urlIsLocal,
      urlHasHttpsScheme,
      urlIsHttpHttpsScheme,
      readAllBytes,
      simpleRangeHeaderValue,
      buildContentRange,
      parseMetadata,
      createInflate,
      extractMimeType,
      getDecodeSplit,
      utf8DecodeBytes,
      environmentSettingsObject
    };
  }
});

// packages/cli/node_modules/undici/lib/web/fetch/symbols.js
var require_symbols7 = __commonJS({
  "packages/cli/node_modules/undici/lib/web/fetch/symbols.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    module2.exports = {
      kUrl: Symbol("url"),
      kHeaders: Symbol("headers"),
      kSignal: Symbol("signal"),
      kState: Symbol("state"),
      kDispatcher: Symbol("dispatcher")
    };
  }
});

// packages/cli/node_modules/undici/lib/web/fetch/file.js
var require_file2 = __commonJS({
  "packages/cli/node_modules/undici/lib/web/fetch/file.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var { Blob: Blob6, File: File6 } = __require("node:buffer");
    var { kState } = require_symbols7();
    var { webidl } = require_webidl2();
    var FileLike = class _FileLike {
      static {
        __name(this, "FileLike");
      }
      constructor(blobLike, fileName, options2 = {}) {
        const n3 = fileName;
        const t5 = options2.type;
        const d2 = options2.lastModified ?? Date.now();
        this[kState] = {
          blobLike,
          name: n3,
          type: t5,
          lastModified: d2
        };
      }
      stream(...args) {
        webidl.brandCheck(this, _FileLike);
        return this[kState].blobLike.stream(...args);
      }
      arrayBuffer(...args) {
        webidl.brandCheck(this, _FileLike);
        return this[kState].blobLike.arrayBuffer(...args);
      }
      slice(...args) {
        webidl.brandCheck(this, _FileLike);
        return this[kState].blobLike.slice(...args);
      }
      text(...args) {
        webidl.brandCheck(this, _FileLike);
        return this[kState].blobLike.text(...args);
      }
      get size() {
        webidl.brandCheck(this, _FileLike);
        return this[kState].blobLike.size;
      }
      get type() {
        webidl.brandCheck(this, _FileLike);
        return this[kState].blobLike.type;
      }
      get name() {
        webidl.brandCheck(this, _FileLike);
        return this[kState].name;
      }
      get lastModified() {
        webidl.brandCheck(this, _FileLike);
        return this[kState].lastModified;
      }
      get [Symbol.toStringTag]() {
        return "File";
      }
    };
    webidl.converters.Blob = webidl.interfaceConverter(Blob6);
    function isFileLike4(object3) {
      return object3 instanceof File6 || object3 && (typeof object3.stream === "function" || typeof object3.arrayBuffer === "function") && object3[Symbol.toStringTag] === "File";
    }
    __name(isFileLike4, "isFileLike");
    module2.exports = { FileLike, isFileLike: isFileLike4 };
  }
});

// packages/cli/node_modules/undici/lib/web/fetch/formdata.js
var require_formdata2 = __commonJS({
  "packages/cli/node_modules/undici/lib/web/fetch/formdata.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var { isBlobLike: isBlobLike3, iteratorMixin } = require_util23();
    var { kState } = require_symbols7();
    var { kEnumerableProperty } = require_util22();
    var { FileLike, isFileLike: isFileLike4 } = require_file2();
    var { webidl } = require_webidl2();
    var { File: NativeFile } = __require("node:buffer");
    var nodeUtil = __require("node:util");
    var File6 = globalThis.File ?? NativeFile;
    var FormData6 = class _FormData {
      static {
        __name(this, "FormData");
      }
      constructor(form) {
        webidl.util.markAsUncloneable(this);
        if (form !== void 0) {
          throw webidl.errors.conversionFailed({
            prefix: "FormData constructor",
            argument: "Argument 1",
            types: ["undefined"]
          });
        }
        this[kState] = [];
      }
      append(name3, value, filename = void 0) {
        webidl.brandCheck(this, _FormData);
        const prefix = "FormData.append";
        webidl.argumentLengthCheck(arguments, 2, prefix);
        if (arguments.length === 3 && !isBlobLike3(value)) {
          throw new TypeError(
            "Failed to execute 'append' on 'FormData': parameter 2 is not of type 'Blob'"
          );
        }
        name3 = webidl.converters.USVString(name3, prefix, "name");
        value = isBlobLike3(value) ? webidl.converters.Blob(value, prefix, "value", { strict: false }) : webidl.converters.USVString(value, prefix, "value");
        filename = arguments.length === 3 ? webidl.converters.USVString(filename, prefix, "filename") : void 0;
        const entry = makeEntry(name3, value, filename);
        this[kState].push(entry);
      }
      delete(name3) {
        webidl.brandCheck(this, _FormData);
        const prefix = "FormData.delete";
        webidl.argumentLengthCheck(arguments, 1, prefix);
        name3 = webidl.converters.USVString(name3, prefix, "name");
        this[kState] = this[kState].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, prefix, "name");
        const idx = this[kState].findIndex((entry) => entry.name === name3);
        if (idx === -1) {
          return null;
        }
        return this[kState][idx].value;
      }
      getAll(name3) {
        webidl.brandCheck(this, _FormData);
        const prefix = "FormData.getAll";
        webidl.argumentLengthCheck(arguments, 1, prefix);
        name3 = webidl.converters.USVString(name3, prefix, "name");
        return this[kState].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, prefix, "name");
        return this[kState].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);
        if (arguments.length === 3 && !isBlobLike3(value)) {
          throw new TypeError(
            "Failed to execute 'set' on 'FormData': parameter 2 is not of type 'Blob'"
          );
        }
        name3 = webidl.converters.USVString(name3, prefix, "name");
        value = isBlobLike3(value) ? webidl.converters.Blob(value, prefix, "name", { strict: false }) : webidl.converters.USVString(value, prefix, "name");
        filename = arguments.length === 3 ? webidl.converters.USVString(filename, prefix, "name") : void 0;
        const entry = makeEntry(name3, value, filename);
        const idx = this[kState].findIndex((entry2) => entry2.name === name3);
        if (idx !== -1) {
          this[kState] = [
            ...this[kState].slice(0, idx),
            entry,
            ...this[kState].slice(idx + 1).filter((entry2) => entry2.name !== name3)
          ];
        } else {
          this[kState].push(entry);
        }
      }
      [nodeUtil.inspect.custom](depth, options2) {
        const state = this[kState].reduce((a2, b2) => {
          if (a2[b2.name]) {
            if (Array.isArray(a2[b2.name])) {
              a2[b2.name].push(b2.value);
            } else {
              a2[b2.name] = [a2[b2.name], b2.value];
            }
          } else {
            a2[b2.name] = b2.value;
          }
          return a2;
        }, { __proto__: null });
        options2.depth ??= depth;
        options2.colors ??= true;
        const output = nodeUtil.formatWithOptions(options2, state);
        return `FormData ${output.slice(output.indexOf("]") + 2)}`;
      }
    };
    iteratorMixin("FormData", FormData6, kState, "name", "value");
    Object.defineProperties(FormData6.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 (!isFileLike4(value)) {
          value = value instanceof Blob ? new File6([value], "blob", { type: value.type }) : new FileLike(value, "blob", { type: value.type });
        }
        if (filename !== void 0) {
          const options2 = {
            type: value.type,
            lastModified: value.lastModified
          };
          value = value instanceof NativeFile ? new File6([value], filename, options2) : new FileLike(value, filename, options2);
        }
      }
      return { name: name3, value };
    }
    __name(makeEntry, "makeEntry");
    module2.exports = { FormData: FormData6, makeEntry };
  }
});

// packages/cli/node_modules/undici/lib/web/fetch/formdata-parser.js
var require_formdata_parser2 = __commonJS({
  "packages/cli/node_modules/undici/lib/web/fetch/formdata-parser.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var { isUSVString, bufferToLowerCasedHeaderName } = require_util22();
    var { utf8DecodeBytes } = require_util23();
    var { HTTP_TOKEN_CODEPOINTS, isomorphicDecode } = require_data_url2();
    var { isFileLike: isFileLike4 } = require_file2();
    var { makeEntry } = require_formdata2();
    var assert4 = __require("node:assert");
    var { File: NodeFile } = __require("node:buffer");
    var File6 = globalThis.File ?? NodeFile;
    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 i3 = 0; i3 < chars.length; ++i3) {
        if ((chars.charCodeAt(i3) & ~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 i3 = 0; i3 < length; ++i3) {
        const cp3 = boundary.charCodeAt(i3);
        if (!(cp3 >= 48 && cp3 <= 57 || cp3 >= 65 && cp3 <= 90 || cp3 >= 97 && cp3 <= 122 || cp3 === 39 || cp3 === 45 || cp3 === 95)) {
          return false;
        }
      }
      return true;
    }
    __name(validateBoundary, "validateBoundary");
    function multipartFormDataParser(input, mimeType) {
      assert4(mimeType !== "failure" && mimeType.essence === "multipart/form-data");
      const boundaryString = mimeType.parameters.get("boundary");
      if (boundaryString === void 0) {
        return "failure";
      }
      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 {
          return "failure";
        }
        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) {
          return "failure";
        }
        position.position += 2;
        const result = parseMultipartFormDataHeaders(input, position);
        if (result === "failure") {
          return "failure";
        }
        let { name: name3, filename, contentType, encoding } = result;
        position.position += 2;
        let body;
        {
          const boundaryIndex = input.indexOf(boundary.subarray(2), position.position);
          if (boundaryIndex === -1) {
            return "failure";
          }
          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) {
          return "failure";
        } else {
          position.position += 2;
        }
        let value;
        if (filename !== null) {
          contentType ??= "text/plain";
          if (!isAsciiString(contentType)) {
            contentType = "";
          }
          value = new File6([body], filename, { type: contentType });
        } else {
          value = utf8DecodeBytes(Buffer.from(body));
        }
        assert4(isUSVString(name3));
        assert4(typeof value === "string" && isUSVString(value) || isFileLike4(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) {
            return "failure";
          }
          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())) {
          return "failure";
        }
        if (input[position.position] !== 58) {
          return "failure";
        }
        position.position++;
        collectASequenceOfBytes(
          (char) => char === 32 || char === 9,
          input,
          position
        );
        switch (bufferToLowerCasedHeaderName(headerName)) {
          case "content-disposition": {
            name3 = filename = null;
            if (!bufferStartsWith(input, formDataNameBuffer, position)) {
              return "failure";
            }
            position.position += 17;
            name3 = parseMultipartFormDataName(input, position);
            if (name3 === null) {
              return "failure";
            }
            if (bufferStartsWith(input, filenameBuffer, position)) {
              let check2 = position.position + filenameBuffer.length;
              if (input[check2] === 42) {
                position.position += 1;
                check2 += 1;
              }
              if (input[check2] !== 61 || input[check2 + 1] !== 34) {
                return "failure";
              }
              position.position += 12;
              filename = parseMultipartFormDataName(input, position);
              if (filename === null) {
                return "failure";
              }
            }
            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) {
          return "failure";
        } else {
          position.position += 2;
        }
      }
    }
    __name(parseMultipartFormDataHeaders, "parseMultipartFormDataHeaders");
    function parseMultipartFormDataName(input, position) {
      assert4(input[position.position - 1] === 34);
      let name3 = collectASequenceOfBytes(
        (char) => char !== 10 && char !== 13 && char !== 34,
        input,
        position
      );
      if (input[position.position] !== 34) {
        return null;
      } 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 i3 = 0; i3 < start.length; i3++) {
        if (start[i3] !== buffer[position.position + i3]) {
          return false;
        }
      }
      return true;
    }
    __name(bufferStartsWith, "bufferStartsWith");
    module2.exports = {
      multipartFormDataParser,
      validateBoundary
    };
  }
});

// packages/cli/node_modules/undici/lib/web/fetch/body.js
var require_body2 = __commonJS({
  "packages/cli/node_modules/undici/lib/web/fetch/body.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var util3 = require_util22();
    var {
      ReadableStreamFrom: ReadableStreamFrom2,
      isBlobLike: isBlobLike3,
      isReadableStreamLike,
      readableStreamClose,
      createDeferredPromise,
      fullyReadBody,
      extractMimeType,
      utf8DecodeBytes
    } = require_util23();
    var { FormData: FormData6 } = require_formdata2();
    var { kState } = require_symbols7();
    var { webidl } = require_webidl2();
    var { Blob: Blob6 } = __require("node:buffer");
    var assert4 = __require("node:assert");
    var { isErrored, isDisturbed } = __require("node:stream");
    var { isArrayBuffer } = __require("node:util/types");
    var { serializeAMimeType } = require_data_url2();
    var { multipartFormDataParser } = require_formdata_parser2();
    var random2;
    try {
      const crypto14 = __require("node:crypto");
      random2 = /* @__PURE__ */ __name((max) => crypto14.randomInt(0, max), "random");
    } catch {
      random2 = /* @__PURE__ */ __name((max) => Math.floor(Math.random(max)), "random");
    }
    var textEncoder = new TextEncoder();
    function noop8() {
    }
    __name(noop8, "noop");
    var hasFinalizationRegistry = globalThis.FinalizationRegistry && process.version.indexOf("v18") !== 0;
    var streamRegistry;
    if (hasFinalizationRegistry) {
      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(noop8);
        }
      });
    }
    function extractBody(object3, keepalive = false) {
      let stream2 = null;
      if (object3 instanceof ReadableStream) {
        stream2 = object3;
      } else if (isBlobLike3(object3)) {
        stream2 = object3.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"
        });
      }
      assert4(isReadableStreamLike(stream2));
      let action = null;
      let source2 = null;
      let length = null;
      let type = null;
      if (typeof object3 === "string") {
        source2 = object3;
        type = "text/plain;charset=UTF-8";
      } else if (object3 instanceof URLSearchParams) {
        source2 = object3.toString();
        type = "application/x-www-form-urlencoded;charset=UTF-8";
      } else if (isArrayBuffer(object3)) {
        source2 = new Uint8Array(object3.slice());
      } else if (ArrayBuffer.isView(object3)) {
        source2 = new Uint8Array(object3.buffer.slice(object3.byteOffset, object3.byteOffset + object3.byteLength));
      } else if (util3.isFormDataLike(object3)) {
        const boundary = `----formdata-undici-0${`${random2(1e11)}`.padStart(11, "0")}`;
        const prefix = `--${boundary}\r
Content-Disposition: form-data`;
        const escape7 = /* @__PURE__ */ __name((str2) => str2.replace(/\n/g, "%0A").replace(/\r/g, "%0D").replace(/"/g, "%22"), "escape");
        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 object3) {
          if (typeof value === "string") {
            const chunk2 = textEncoder.encode(prefix + `; name="${escape7(normalizeLinefeeds(name3))}"\r
\r
${normalizeLinefeeds(value)}\r
`);
            blobParts.push(chunk2);
            length += chunk2.byteLength;
          } else {
            const chunk2 = textEncoder.encode(`${prefix}; name="${escape7(normalizeLinefeeds(name3))}"` + (value.name ? `; filename="${escape7(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 = object3;
        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 (isBlobLike3(object3)) {
        source2 = object3;
        length = object3.size;
        if (object3.type) {
          type = object3.type;
        }
      } else if (typeof object3[Symbol.asyncIterator] === "function") {
        if (keepalive) {
          throw new TypeError("keepalive");
        }
        if (util3.isDisturbed(object3) || object3.locked) {
          throw new TypeError(
            "Response body object should not be disturbed or locked"
          );
        }
        stream2 = object3 instanceof ReadableStream ? object3 : ReadableStreamFrom2(object3);
      }
      if (typeof source2 === "string" || util3.isBuffer(source2)) {
        length = Buffer.byteLength(source2);
      }
      if (action != null) {
        let iterator;
        stream2 = new ReadableStream({
          async start() {
            iterator = action(object3)[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(object3, keepalive = false) {
      if (object3 instanceof ReadableStream) {
        assert4(!util3.isDisturbed(object3), "The body has already been consumed.");
        assert4(!object3.locked, "The stream is locked.");
      }
      return extractBody(object3, keepalive);
    }
    __name(safelyExtractBody, "safelyExtractBody");
    function cloneBody(instance, body) {
      const [out1, 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) {
      const methods = {
        blob() {
          return consumeBody3(this, (bytes) => {
            let mimeType = bodyMimeType(this);
            if (mimeType === null) {
              mimeType = "";
            } else if (mimeType) {
              mimeType = serializeAMimeType(mimeType);
            }
            return new Blob6([bytes], { type: mimeType });
          }, instance);
        },
        arrayBuffer() {
          return consumeBody3(this, (bytes) => {
            return new Uint8Array(bytes).buffer;
          }, instance);
        },
        text() {
          return consumeBody3(this, utf8DecodeBytes, instance);
        },
        json() {
          return consumeBody3(this, parseJSONFromBytes, instance);
        },
        formData() {
          return consumeBody3(this, (value) => {
            const mimeType = bodyMimeType(this);
            if (mimeType !== null) {
              switch (mimeType.essence) {
                case "multipart/form-data": {
                  const parsed = multipartFormDataParser(value, mimeType);
                  if (parsed === "failure") {
                    throw new TypeError("Failed to parse body as FormData.");
                  }
                  const fd = new FormData6();
                  fd[kState] = parsed;
                  return fd;
                }
                case "application/x-www-form-urlencoded": {
                  const entries = new URLSearchParams(value.toString());
                  const fd = new FormData6();
                  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);
        },
        bytes() {
          return consumeBody3(this, (bytes) => {
            return new Uint8Array(bytes);
          }, instance);
        }
      };
      return methods;
    }
    __name(bodyMixinMethods, "bodyMixinMethods");
    function mixinBody(prototype) {
      Object.assign(prototype.prototype, bodyMixinMethods(prototype));
    }
    __name(mixinBody, "mixinBody");
    async function consumeBody3(object3, convertBytesToJSValue, instance) {
      webidl.brandCheck(object3, instance);
      if (bodyUnusable(object3)) {
        throw new TypeError("Body is unusable: Body has already been read");
      }
      throwIfAborted(object3[kState]);
      const promise = createDeferredPromise();
      const errorSteps = /* @__PURE__ */ __name((error2) => promise.reject(error2), "errorSteps");
      const successSteps = /* @__PURE__ */ __name((data) => {
        try {
          promise.resolve(convertBytesToJSValue(data));
        } catch (e4) {
          errorSteps(e4);
        }
      }, "successSteps");
      if (object3[kState].body == null) {
        successSteps(Buffer.allocUnsafe(0));
        return promise.promise;
      }
      await fullyReadBody(object3[kState].body, successSteps, errorSteps);
      return promise.promise;
    }
    __name(consumeBody3, "consumeBody");
    function bodyUnusable(object3) {
      const body = object3[kState].body;
      return body != null && (body.stream.locked || util3.isDisturbed(body.stream));
    }
    __name(bodyUnusable, "bodyUnusable");
    function parseJSONFromBytes(bytes) {
      return JSON.parse(utf8DecodeBytes(bytes));
    }
    __name(parseJSONFromBytes, "parseJSONFromBytes");
    function bodyMimeType(requestOrResponse) {
      const headers = requestOrResponse[kState].headersList;
      const mimeType = extractMimeType(headers);
      if (mimeType === "failure") {
        return null;
      }
      return mimeType;
    }
    __name(bodyMimeType, "bodyMimeType");
    module2.exports = {
      extractBody,
      safelyExtractBody,
      cloneBody,
      mixinBody,
      streamRegistry,
      hasFinalizationRegistry,
      bodyUnusable
    };
  }
});

// packages/cli/node_modules/undici/lib/dispatcher/client-h1.js
var require_client_h12 = __commonJS({
  "packages/cli/node_modules/undici/lib/dispatcher/client-h1.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var assert4 = __require("node:assert");
    var util3 = require_util22();
    var { channels } = require_diagnostics2();
    var timers = require_timers2();
    var {
      RequestContentLengthMismatchError,
      ResponseContentLengthMismatchError,
      RequestAbortedError,
      HeadersTimeoutError,
      HeadersOverflowError,
      SocketError,
      InformationalError,
      BodyTimeoutError,
      HTTPParserError,
      ResponseExceededMaxSizeError
    } = require_errors5();
    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
    } = require_symbols6();
    var constants4 = require_constants15();
    var EMPTY_BUF = Buffer.alloc(0);
    var FastBuffer = Buffer[Symbol.species];
    var addListener = util3.addListener;
    var removeAllListeners = util3.removeAllListeners;
    var extractBody;
    async function lazyllhttp() {
      const llhttpWasmData = process.env.JEST_WORKER_ID ? require_llhttp_wasm2() : void 0;
      let mod2;
      try {
        mod2 = await WebAssembly.compile(require_llhttp_simd_wasm2());
      } catch (e4) {
        mod2 = await WebAssembly.compile(llhttpWasmData || require_llhttp_wasm2());
      }
      return await WebAssembly.instantiate(mod2, {
        env: {
          /* eslint-disable camelcase */
          wasm_on_url: /* @__PURE__ */ __name((p2, at2, len) => {
            return 0;
          }, "wasm_on_url"),
          wasm_on_status: /* @__PURE__ */ __name((p2, at2, len) => {
            assert4(currentParser.ptr === p2);
            const start = at2 - currentBufferPtr + currentBufferRef.byteOffset;
            return currentParser.onStatus(new FastBuffer(currentBufferRef.buffer, start, len)) || 0;
          }, "wasm_on_status"),
          wasm_on_message_begin: /* @__PURE__ */ __name((p2) => {
            assert4(currentParser.ptr === p2);
            return currentParser.onMessageBegin() || 0;
          }, "wasm_on_message_begin"),
          wasm_on_header_field: /* @__PURE__ */ __name((p2, at2, len) => {
            assert4(currentParser.ptr === p2);
            const start = at2 - currentBufferPtr + currentBufferRef.byteOffset;
            return currentParser.onHeaderField(new FastBuffer(currentBufferRef.buffer, start, len)) || 0;
          }, "wasm_on_header_field"),
          wasm_on_header_value: /* @__PURE__ */ __name((p2, at2, len) => {
            assert4(currentParser.ptr === p2);
            const start = at2 - currentBufferPtr + currentBufferRef.byteOffset;
            return currentParser.onHeaderValue(new FastBuffer(currentBufferRef.buffer, start, len)) || 0;
          }, "wasm_on_header_value"),
          wasm_on_headers_complete: /* @__PURE__ */ __name((p2, statusCode, upgrade, shouldKeepAlive) => {
            assert4(currentParser.ptr === p2);
            return currentParser.onHeadersComplete(statusCode, Boolean(upgrade), Boolean(shouldKeepAlive)) || 0;
          }, "wasm_on_headers_complete"),
          wasm_on_body: /* @__PURE__ */ __name((p2, at2, len) => {
            assert4(currentParser.ptr === p2);
            const start = at2 - currentBufferPtr + currentBufferRef.byteOffset;
            return currentParser.onBody(new FastBuffer(currentBufferRef.buffer, start, len)) || 0;
          }, "wasm_on_body"),
          wasm_on_message_complete: /* @__PURE__ */ __name((p2) => {
            assert4(currentParser.ptr === p2);
            return currentParser.onMessageComplete() || 0;
          }, "wasm_on_message_complete")
          /* eslint-enable camelcase */
        }
      });
    }
    __name(lazyllhttp, "lazyllhttp");
    var llhttpInstance = null;
    var llhttpPromise = lazyllhttp();
    llhttpPromise.catch();
    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");
      }
      constructor(client, socket, { exports: exports3 }) {
        assert4(Number.isFinite(client[kMaxHeadersSize]) && client[kMaxHeadersSize] > 0);
        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 = null;
        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;
        }
        assert4(this.ptr != null);
        assert4(currentParser == null);
        this.llhttp.llhttp_resume(this.ptr);
        assert4(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);
        }
      }
      execute(data) {
        assert4(this.ptr != null);
        assert4(currentParser == null);
        assert4(!this.paused);
        const { socket, llhttp } = this;
        if (data.length > currentBufferSize) {
          if (currentBufferPtr) {
            llhttp.free(currentBufferPtr);
          }
          currentBufferSize = Math.ceil(data.length / 4096) * 4096;
          currentBufferPtr = llhttp.malloc(currentBufferSize);
        }
        new Uint8Array(llhttp.memory.buffer, currentBufferPtr, currentBufferSize).set(data);
        try {
          let ret;
          try {
            currentBufferRef = data;
            currentParser = this;
            ret = llhttp.llhttp_execute(this.ptr, currentBufferPtr, data.length);
          } catch (err) {
            throw err;
          } finally {
            currentParser = null;
            currentBufferRef = null;
          }
          const offset = llhttp.llhttp_get_error_pos(this.ptr) - currentBufferPtr;
          if (ret === constants4.ERROR.PAUSED_UPGRADE) {
            this.onUpgrade(data.slice(offset));
          } else if (ret === constants4.ERROR.PAUSED) {
            this.paused = true;
            socket.unshift(data.slice(offset));
          } else if (ret !== constants4.ERROR.OK) {
            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.slice(offset));
          }
        } catch (err) {
          util3.destroy(socket, err);
        }
      }
      destroy() {
        assert4(this.ptr != null);
        assert4(currentParser == 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;
      }
      onStatus(buf) {
        this.statusText = buf.toString();
      }
      onMessageBegin() {
        const { socket, client } = this;
        if (socket.destroyed) {
          return -1;
        }
        const request4 = client[kQueue][client[kRunningIdx]];
        if (!request4) {
          return -1;
        }
        request4.onResponseStarted();
      }
      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);
      }
      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 = util3.bufferToLowerCasedHeaderName(key);
          if (headerName === "keep-alive") {
            this.keepAlive += buf.toString();
          } else if (headerName === "connection") {
            this.connection += buf.toString();
          }
        } else if (key.length === 14 && util3.bufferToLowerCasedHeaderName(key) === "content-length") {
          this.contentLength += buf.toString();
        }
        this.trackHeader(buf.length);
      }
      trackHeader(len) {
        this.headersSize += len;
        if (this.headersSize >= this.headersMaxSize) {
          util3.destroy(this.socket, new HeadersOverflowError());
        }
      }
      onUpgrade(head) {
        const { upgrade, client, socket, headers, statusCode } = this;
        assert4(upgrade);
        assert4(client[kSocket] === socket);
        assert4(!socket.destroyed);
        assert4(!this.paused);
        assert4((headers.length & 1) === 0);
        const request4 = client[kQueue][client[kRunningIdx]];
        assert4(request4);
        assert4(request4.upgrade || request4.method === "CONNECT");
        this.statusCode = null;
        this.statusText = "";
        this.shouldKeepAlive = null;
        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) {
          util3.destroy(socket, err);
        }
        client[kResume]();
      }
      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;
        }
        assert4(!this.upgrade);
        assert4(this.statusCode < 200);
        if (statusCode === 100) {
          util3.destroy(socket, new SocketError("bad response", util3.getSocketInfo(socket)));
          return -1;
        }
        if (upgrade && !request4.upgrade) {
          util3.destroy(socket, new SocketError("bad upgrade", util3.getSocketInfo(socket)));
          return -1;
        }
        assert4(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") {
          assert4(client[kRunning] === 1);
          this.upgrade = true;
          return 2;
        }
        if (upgrade) {
          assert4(client[kRunning] === 1);
          this.upgrade = true;
          return 2;
        }
        assert4((this.headers.length & 1) === 0);
        this.headers = [];
        this.headersSize = 0;
        if (this.shouldKeepAlive && client[kPipelining]) {
          const keepAliveTimeout = this.keepAlive ? util3.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;
      }
      onBody(buf) {
        const { client, socket, statusCode, maxResponseSize } = this;
        if (socket.destroyed) {
          return -1;
        }
        const request4 = client[kQueue][client[kRunningIdx]];
        assert4(request4);
        assert4(this.timeoutType === TIMEOUT_BODY);
        if (this.timeout) {
          if (this.timeout.refresh) {
            this.timeout.refresh();
          }
        }
        assert4(statusCode >= 200);
        if (maxResponseSize > -1 && this.bytesRead + buf.length > maxResponseSize) {
          util3.destroy(socket, new ResponseExceededMaxSizeError());
          return -1;
        }
        this.bytesRead += buf.length;
        if (request4.onData(buf) === false) {
          return constants4.ERROR.PAUSED;
        }
      }
      onMessageComplete() {
        const { client, socket, statusCode, upgrade, headers, contentLength, bytesRead, shouldKeepAlive } = this;
        if (socket.destroyed && (!statusCode || shouldKeepAlive)) {
          return -1;
        }
        if (upgrade) {
          return;
        }
        assert4(statusCode >= 100);
        assert4((this.headers.length & 1) === 0);
        const request4 = client[kQueue][client[kRunningIdx]];
        assert4(request4);
        this.statusCode = null;
        this.statusText = "";
        this.bytesRead = 0;
        this.contentLength = "";
        this.keepAlive = "";
        this.connection = "";
        this.headers = [];
        this.headersSize = 0;
        if (statusCode < 200) {
          return;
        }
        if (request4.method !== "HEAD" && contentLength && bytesRead !== parseInt(contentLength, 10)) {
          util3.destroy(socket, new ResponseContentLengthMismatchError());
          return -1;
        }
        request4.onComplete(headers);
        client[kQueue][client[kRunningIdx]++] = null;
        if (socket[kWriting]) {
          assert4(client[kRunning] === 0);
          util3.destroy(socket, new InformationalError("reset"));
          return constants4.ERROR.PAUSED;
        } else if (!shouldKeepAlive) {
          util3.destroy(socket, new InformationalError("reset"));
          return constants4.ERROR.PAUSED;
        } else if (socket[kReset2] && client[kRunning] === 0) {
          util3.destroy(socket, new InformationalError("reset"));
          return constants4.ERROR.PAUSED;
        } else if (client[kPipelining] == null || client[kPipelining] === 1) {
          setImmediate(() => client[kResume]());
        } else {
          client[kResume]();
        }
      }
    };
    function onParserTimeout(parser6) {
      const { socket, timeoutType, client, paused } = parser6.deref();
      if (timeoutType === TIMEOUT_HEADERS) {
        if (!socket[kWriting] || socket.writableNeedDrain || client[kRunning] > 1) {
          assert4(!paused, "cannot be paused while waiting for headers");
          util3.destroy(socket, new HeadersTimeoutError());
        }
      } else if (timeoutType === TIMEOUT_BODY) {
        if (!paused) {
          util3.destroy(socket, new BodyTimeoutError());
        }
      } else if (timeoutType === TIMEOUT_KEEP_ALIVE) {
        assert4(client[kRunning] === 0 && client[kKeepAliveTimeoutValue]);
        util3.destroy(socket, new InformationalError("socket idle timeout"));
      }
    }
    __name(onParserTimeout, "onParserTimeout");
    async function connectH1(client, socket) {
      client[kSocket] = socket;
      if (!llhttpInstance) {
        llhttpInstance = await llhttpPromise;
        llhttpPromise = null;
      }
      socket[kNoRef] = false;
      socket[kWriting] = false;
      socket[kReset2] = false;
      socket[kBlocking] = false;
      socket[kParser] = new Parser4(client, socket, llhttpInstance);
      addListener(socket, "error", function(err) {
        assert4(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);
      });
      addListener(socket, "readable", function() {
        const parser6 = this[kParser];
        if (parser6) {
          parser6.readMore();
        }
      });
      addListener(socket, "end", function() {
        const parser6 = this[kParser];
        if (parser6.statusCode && !parser6.shouldKeepAlive) {
          parser6.onMessageComplete();
          return;
        }
        util3.destroy(this, new SocketError("other side closed", util3.getSocketInfo(this)));
      });
      addListener(socket, "close", function() {
        const client2 = this[kClient];
        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", util3.getSocketInfo(this));
        client2[kSocket] = null;
        client2[kHTTPContext] = null;
        if (client2.destroyed) {
          assert4(client2[kPending] === 0);
          const requests = client2[kQueue].splice(client2[kRunningIdx]);
          for (let i3 = 0; i3 < requests.length; i3++) {
            const request4 = requests[i3];
            util3.errorRequest(client2, request4, err);
          }
        } else if (client2[kRunning] > 0 && err.code !== "UND_ERR_INFO") {
          const request4 = client2[kQueue][client2[kRunningIdx]];
          client2[kQueue][client2[kRunningIdx]++] = null;
          util3.errorRequest(client2, request4, err);
        }
        client2[kPendingIdx] = client2[kRunningIdx];
        assert4(client2[kRunning] === 0);
        client2.emit("disconnect", client2[kUrl], [client2], err);
        client2[kResume]();
      });
      let closed = false;
      socket.on("close", () => {
        closed = true;
      });
      return {
        version: "h1",
        defaultPipelining: 1,
        write(...args) {
          return writeH1(client, ...args);
        },
        resume() {
          resumeH1(client);
        },
        destroy(err, callback) {
          if (closed) {
            queueMicrotask(callback);
          } else {
            socket.destroy(err).on("close", callback);
          }
        },
        get destroyed() {
          return socket.destroyed;
        },
        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 && util3.bodyLength(request4.body) !== 0 && (util3.isStream(request4.body) || util3.isAsyncIterable(request4.body) || util3.isFormDataLike(request4.body))) {
              return true;
            }
          }
          return false;
        }
      };
    }
    __name(connectH1, "connectH1");
    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: path125, 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 (util3.isFormDataLike(body)) {
        if (!extractBody) {
          extractBody = require_body2().extractBody;
        }
        const [bodyStream, contentType] = extractBody(body);
        if (request4.contentType == null) {
          headers.push("content-type", contentType);
        }
        body = bodyStream.stream;
        contentLength = bodyStream.length;
      } else if (util3.isBlobLike(body) && request4.contentType == null && body.type) {
        headers.push("content-type", body.type);
      }
      if (body && typeof body.read === "function") {
        body.read(0);
      }
      const bodyLength = util3.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]) {
          util3.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;
        }
        util3.errorRequest(client, request4, err || new RequestAbortedError());
        util3.destroy(body);
        util3.destroy(socket, new InformationalError("aborted"));
      }, "abort");
      try {
        request4.onConnect(abort);
      } catch (err) {
        util3.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} ${path125} 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 n3 = 0; n3 < headers.length; n3 += 2) {
          const key = headers[n3 + 0];
          const val = headers[n3 + 1];
          if (Array.isArray(val)) {
            for (let i3 = 0; i3 < val.length; i3++) {
              header += `${key}: ${val[i3]}\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 (util3.isBuffer(body)) {
        writeBuffer(abort, body, client, request4, socket, contentLength, header, expectsPayload);
      } else if (util3.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 (util3.isStream(body)) {
        writeStream(abort, body, client, request4, socket, contentLength, header, expectsPayload);
      } else if (util3.isIterable(body)) {
        writeIterable(abort, body, client, request4, socket, contentLength, header, expectsPayload);
      } else {
        assert4(false);
      }
      return true;
    }
    __name(writeH1, "writeH1");
    function writeStream(abort, body, client, request4, socket, contentLength, header, expectsPayload) {
      assert4(contentLength !== 0 || client[kRunning] === 0, "stream body cannot be pipelined");
      let finished2 = false;
      const writer = new AsyncWriter({ abort, socket, request: request4, contentLength, client, expectsPayload, header });
      const onData = /* @__PURE__ */ __name(function(chunk) {
        if (finished2) {
          return;
        }
        try {
          if (!writer.write(chunk) && this.pause) {
            this.pause();
          }
        } catch (err) {
          util3.destroy(this, err);
        }
      }, "onData");
      const onDrain = /* @__PURE__ */ __name(function() {
        if (finished2) {
          return;
        }
        if (body.resume) {
          body.resume();
        }
      }, "onDrain");
      const onClose = /* @__PURE__ */ __name(function() {
        queueMicrotask(() => {
          body.removeListener("error", onFinished);
        });
        if (!finished2) {
          const err = new RequestAbortedError();
          queueMicrotask(() => onFinished(err));
        }
      }, "onClose");
      const onFinished = /* @__PURE__ */ __name(function(err) {
        if (finished2) {
          return;
        }
        finished2 = true;
        assert4(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 (er2) {
            err = er2;
          }
        }
        writer.destroy(err);
        if (err && (err.code !== "UND_ERR_INFO" || err.message !== "reset")) {
          util3.destroy(body, err);
        } else {
          util3.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 {
            assert4(contentLength === null, "no body must not have content length");
            socket.write(`${header}\r
`, "latin1");
          }
        } else if (util3.isBuffer(body)) {
          assert4(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) {
      assert4(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) {
      assert4(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((resolve30, reject) => {
        assert4(callback === null);
        if (socket[kError]) {
          reject(socket[kError]);
        } else {
          callback = resolve30;
        }
      }), "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");
      }
      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;
      }
      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;
      }
      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]();
      }
      destroy(err) {
        const { socket, client, abort } = this;
        socket[kWriting] = false;
        if (err) {
          assert4(client[kRunning] <= 1, "pipeline should only contain this request");
          abort(err);
        }
      }
    };
    module2.exports = connectH1;
  }
});

// packages/cli/node_modules/undici/lib/dispatcher/client-h2.js
var require_client_h22 = __commonJS({
  "packages/cli/node_modules/undici/lib/dispatcher/client-h2.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var assert4 = __require("node:assert");
    var { pipeline: pipeline3 } = __require("node:stream");
    var util3 = require_util22();
    var {
      RequestContentLengthMismatchError,
      RequestAbortedError,
      SocketError,
      InformationalError
    } = require_errors5();
    var {
      kUrl,
      kReset: kReset2,
      kClient,
      kRunning,
      kPending,
      kQueue,
      kPendingIdx,
      kRunningIdx,
      kError,
      kSocket,
      kStrictContentLength,
      kOnError,
      kMaxConcurrentStreams,
      kHTTP2Session,
      kResume,
      kSize,
      kHTTPContext
    } = require_symbols6();
    var kOpenStreams = Symbol("open streams");
    var extractBody;
    var h2ExperimentalWarned = false;
    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;
      if (!h2ExperimentalWarned) {
        h2ExperimentalWarned = true;
        process.emitWarning("H2 support is experimental, expect them to change at any time.", {
          code: "UNDICI-H2"
        });
      }
      const session = http22.connect(client[kUrl], {
        createConnection: /* @__PURE__ */ __name(() => socket, "createConnection"),
        peerMaxConcurrentStreams: client[kMaxConcurrentStreams]
      });
      session[kOpenStreams] = 0;
      session[kClient] = client;
      session[kSocket] = socket;
      util3.addListener(session, "error", onHttp2SessionError);
      util3.addListener(session, "frameError", onHttp2FrameError);
      util3.addListener(session, "end", onHttp2SessionEnd);
      util3.addListener(session, "goaway", onHTTP2GoAway);
      util3.addListener(session, "close", function() {
        const { [kClient]: client2 } = this;
        const { [kSocket]: socket2 } = client2;
        const err = this[kSocket][kError] || this[kError] || new SocketError("closed", util3.getSocketInfo(socket2));
        client2[kHTTP2Session] = null;
        if (client2.destroyed) {
          assert4(client2[kPending] === 0);
          const requests = client2[kQueue].splice(client2[kRunningIdx]);
          for (let i3 = 0; i3 < requests.length; i3++) {
            const request4 = requests[i3];
            util3.errorRequest(client2, request4, err);
          }
        }
      });
      session.unref();
      client[kHTTP2Session] = session;
      socket[kHTTP2Session] = session;
      util3.addListener(socket, "error", function(err) {
        assert4(err.code !== "ERR_TLS_CERT_ALTNAME_INVALID");
        this[kError] = err;
        this[kClient][kOnError](err);
      });
      util3.addListener(socket, "end", function() {
        util3.destroy(this, new SocketError("other side closed", util3.getSocketInfo(this)));
      });
      util3.addListener(socket, "close", function() {
        const err = this[kError] || new SocketError("closed", util3.getSocketInfo(this));
        client[kSocket] = null;
        if (this[kHTTP2Session] != null) {
          this[kHTTP2Session].destroy(err);
        }
        client[kPendingIdx] = client[kRunningIdx];
        assert4(client[kRunning] === 0);
        client.emit("disconnect", client[kUrl], [client], err);
        client[kResume]();
      });
      let closed = false;
      socket.on("close", () => {
        closed = true;
      });
      return {
        version: "h2",
        defaultPipelining: Infinity,
        write(...args) {
          return writeH2(client, ...args);
        },
        resume() {
          resumeH2(client);
        },
        destroy(err, callback) {
          if (closed) {
            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) {
      assert4(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", util3.getSocketInfo(this[kSocket]));
      this.destroy(err);
      util3.destroy(this[kSocket], err);
    }
    __name(onHttp2SessionEnd, "onHttp2SessionEnd");
    function onHTTP2GoAway(code2) {
      const err = this[kError] || new SocketError(`HTTP/2: "GOAWAY" frame received with code ${code2}`, util3.getSocketInfo(this));
      const client = this[kClient];
      client[kSocket] = null;
      client[kHTTPContext] = null;
      if (this[kHTTP2Session] != null) {
        this[kHTTP2Session].destroy(err);
        this[kHTTP2Session] = null;
      }
      util3.destroy(this[kSocket], err);
      if (client[kRunningIdx] < client[kQueue].length) {
        const request4 = client[kQueue][client[kRunningIdx]];
        client[kQueue][client[kRunningIdx]++] = null;
        util3.errorRequest(client, request4, err);
        client[kPendingIdx] = client[kRunningIdx];
      }
      assert4(client[kRunning] === 0);
      client.emit("disconnect", client[kUrl], [client], err);
      client[kResume]();
    }
    __name(onHTTP2GoAway, "onHTTP2GoAway");
    function shouldSendContentLength(method) {
      return method !== "GET" && method !== "HEAD" && method !== "OPTIONS" && method !== "TRACE" && method !== "CONNECT";
    }
    __name(shouldSendContentLength, "shouldSendContentLength");
    function writeH2(client, request4) {
      const session = client[kHTTP2Session];
      const { method, path: path125, host, upgrade, expectContinue, signal, headers: reqHeaders } = request4;
      let { body } = request4;
      if (upgrade) {
        util3.errorRequest(client, request4, new Error("Upgrade not supported for H2"));
        return false;
      }
      const headers = {};
      for (let n3 = 0; n3 < reqHeaders.length; n3 += 2) {
        const key = reqHeaders[n3 + 0];
        const val = reqHeaders[n3 + 1];
        if (Array.isArray(val)) {
          for (let i3 = 0; i3 < val.length; i3++) {
            if (headers[key]) {
              headers[key] += `,${val[i3]}`;
            } else {
              headers[key] = val[i3];
            }
          }
        } else {
          headers[key] = val;
        }
      }
      let stream2;
      const { hostname: hostname4, port } = client[kUrl];
      headers[HTTP2_HEADER_AUTHORITY] = host || `${hostname4}${port ? `:${port}` : ""}`;
      headers[HTTP2_HEADER_METHOD] = method;
      const abort = /* @__PURE__ */ __name((err) => {
        if (request4.aborted || request4.completed) {
          return;
        }
        err = err || new RequestAbortedError();
        util3.errorRequest(client, request4, err);
        if (stream2 != null) {
          util3.destroy(stream2, err);
        }
        util3.destroy(body, err);
        client[kQueue][client[kRunningIdx]++] = null;
        client[kResume]();
      }, "abort");
      try {
        request4.onConnect(abort);
      } catch (err) {
        util3.errorRequest(client, request4, err);
      }
      if (request4.aborted) {
        return false;
      }
      if (method === "CONNECT") {
        session.ref();
        stream2 = session.request(headers, { endStream: false, signal });
        if (stream2.id && !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();
        });
        return true;
      }
      headers[HTTP2_HEADER_PATH] = path125;
      headers[HTTP2_HEADER_SCHEME] = "https";
      const expectsPayload = method === "PUT" || method === "POST" || method === "PATCH";
      if (body && typeof body.read === "function") {
        body.read(0);
      }
      let contentLength = util3.bodyLength(body);
      if (util3.isFormDataLike(body)) {
        extractBody ??= require_body2().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]) {
          util3.errorRequest(client, request4, new RequestContentLengthMismatchError());
          return false;
        }
        process.emitWarning(new RequestContentLengthMismatchError());
      }
      if (contentLength != null) {
        assert4(body, "no body must not have content length");
        headers[HTTP2_HEADER_CONTENT_LENGTH] = `${contentLength}`;
      }
      session.ref();
      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.once("response", (headers2) => {
        const { [HTTP2_HEADER_STATUS]: statusCode, ...realHeaders } = headers2;
        request4.onResponseStarted();
        if (request4.aborted) {
          const err = new RequestAbortedError();
          util3.errorRequest(client, request4, err);
          util3.destroy(stream2, err);
          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", () => {
        if (stream2.state?.state == null || stream2.state.state < 6) {
          request4.onComplete([]);
        }
        if (session[kOpenStreams] === 0) {
          session.unref();
        }
        abort(new InformationalError("HTTP/2: stream half-closed (remote)"));
        client[kQueue][client[kRunningIdx]++] = null;
        client[kPendingIdx] = client[kRunningIdx];
        client[kResume]();
      });
      stream2.once("close", () => {
        session[kOpenStreams] -= 1;
        if (session[kOpenStreams] === 0) {
          session.unref();
        }
      });
      stream2.once("error", function(err) {
        abort(err);
      });
      stream2.once("frameError", (type, code2) => {
        abort(new InformationalError(`HTTP/2: "frameError" received - type ${type}, code ${code2}`));
      });
      return true;
      function writeBodyH2() {
        if (!body || contentLength === 0) {
          writeBuffer(
            abort,
            stream2,
            null,
            client,
            request4,
            client[kSocket],
            contentLength,
            expectsPayload
          );
        } else if (util3.isBuffer(body)) {
          writeBuffer(
            abort,
            stream2,
            body,
            client,
            request4,
            client[kSocket],
            contentLength,
            expectsPayload
          );
        } else if (util3.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 (util3.isStream(body)) {
          writeStream(
            abort,
            client[kSocket],
            expectsPayload,
            stream2,
            body,
            client,
            request4,
            contentLength
          );
        } else if (util3.isIterable(body)) {
          writeIterable(
            abort,
            stream2,
            body,
            client,
            request4,
            client[kSocket],
            contentLength,
            expectsPayload
          );
        } else {
          assert4(false);
        }
      }
      __name(writeBodyH2, "writeBodyH2");
    }
    __name(writeH2, "writeH2");
    function writeBuffer(abort, h2stream, body, client, request4, socket, contentLength, expectsPayload) {
      try {
        if (body != null && util3.isBuffer(body)) {
          assert4(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 (error2) {
        abort(error2);
      }
    }
    __name(writeBuffer, "writeBuffer");
    function writeStream(abort, socket, expectsPayload, h2stream, body, client, request4, contentLength) {
      assert4(contentLength !== 0 || client[kRunning] === 0, "stream body cannot be pipelined");
      const pipe2 = pipeline3(
        body,
        h2stream,
        (err) => {
          if (err) {
            util3.destroy(pipe2, err);
            abort(err);
          } else {
            util3.removeAllListeners(pipe2);
            request4.onRequestSent();
            if (!expectsPayload) {
              socket[kReset2] = true;
            }
            client[kResume]();
          }
        }
      );
      util3.addListener(pipe2, "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) {
      assert4(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) {
      assert4(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((resolve30, reject) => {
        assert4(callback === null);
        if (socket[kError]) {
          reject(socket[kError]);
        } else {
          callback = resolve30;
        }
      }), "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;
  }
});

// packages/cli/node_modules/undici/lib/handler/redirect-handler.js
var require_redirect_handler2 = __commonJS({
  "packages/cli/node_modules/undici/lib/handler/redirect-handler.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var util3 = require_util22();
    var { kBodyUsed } = require_symbols6();
    var assert4 = __require("node:assert");
    var { InvalidArgumentError } = require_errors5();
    var EE3 = __require("node:events");
    var redirectableStatusCodes = [300, 301, 302, 303, 307, 308];
    var kBody = Symbol("body");
    var BodyAsyncIterable = class {
      static {
        __name(this, "BodyAsyncIterable");
      }
      constructor(body) {
        this[kBody] = body;
        this[kBodyUsed] = false;
      }
      async *[Symbol.asyncIterator]() {
        assert4(!this[kBodyUsed], "disturbed");
        this[kBodyUsed] = true;
        yield* this[kBody];
      }
    };
    var RedirectHandler = class {
      static {
        __name(this, "RedirectHandler");
      }
      constructor(dispatch, maxRedirections, opts, handler) {
        if (maxRedirections != null && (!Number.isInteger(maxRedirections) || maxRedirections < 0)) {
          throw new InvalidArgumentError("maxRedirections must be a positive number");
        }
        util3.validateHandler(handler, opts.method, opts.upgrade);
        this.dispatch = dispatch;
        this.location = null;
        this.abort = null;
        this.opts = { ...opts, maxRedirections: 0 };
        this.maxRedirections = maxRedirections;
        this.handler = handler;
        this.history = [];
        this.redirectionLimitReached = false;
        if (util3.isStream(this.opts.body)) {
          if (util3.bodyLength(this.opts.body) === 0) {
            this.opts.body.on("data", function() {
              assert4(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) && util3.isIterable(this.opts.body)) {
          this.opts.body = new BodyAsyncIterable(this.opts.body);
        }
      }
      onConnect(abort) {
        this.abort = abort;
        this.handler.onConnect(abort, { history: this.history });
      }
      onUpgrade(statusCode, headers, socket) {
        this.handler.onUpgrade(statusCode, headers, socket);
      }
      onError(error2) {
        this.handler.onError(error2);
      }
      onHeaders(statusCode, headers, resume, statusText) {
        this.location = this.history.length >= this.maxRedirections || util3.isDisturbed(this.opts.body) ? null : parseLocation(statusCode, headers);
        if (this.opts.throwOnMaxRedirect && this.history.length >= this.maxRedirections) {
          if (this.request) {
            this.request.abort(new Error("max redirects"));
          }
          this.redirectionLimitReached = true;
          this.abort(new Error("max redirects"));
          return;
        }
        if (this.opts.origin) {
          this.history.push(new URL(this.opts.path, this.opts.origin));
        }
        if (!this.location) {
          return this.handler.onHeaders(statusCode, headers, resume, statusText);
        }
        const { origin, pathname, search } = util3.parseURL(new URL(this.location, this.opts.origin && new URL(this.opts.path, this.opts.origin)));
        const path125 = search ? `${pathname}${search}` : pathname;
        this.opts.headers = cleanRequestHeaders(this.opts.headers, statusCode === 303, this.opts.origin !== origin);
        this.opts.path = path125;
        this.opts.origin = origin;
        this.opts.maxRedirections = 0;
        this.opts.query = null;
        if (statusCode === 303 && this.opts.method !== "HEAD") {
          this.opts.method = "GET";
          this.opts.body = null;
        }
      }
      onData(chunk) {
        if (this.location) {
        } else {
          return this.handler.onData(chunk);
        }
      }
      onComplete(trailers) {
        if (this.location) {
          this.location = null;
          this.abort = null;
          this.dispatch(this.opts, this);
        } else {
          this.handler.onComplete(trailers);
        }
      }
      onBodySent(chunk) {
        if (this.handler.onBodySent) {
          this.handler.onBodySent(chunk);
        }
      }
    };
    function parseLocation(statusCode, headers) {
      if (redirectableStatusCodes.indexOf(statusCode) === -1) {
        return null;
      }
      for (let i3 = 0; i3 < headers.length; i3 += 2) {
        if (headers[i3].length === 8 && util3.headerNameToString(headers[i3]) === "location") {
          return headers[i3 + 1];
        }
      }
    }
    __name(parseLocation, "parseLocation");
    function shouldRemoveHeader(header, removeContent, unknownOrigin) {
      if (header.length === 4) {
        return util3.headerNameToString(header) === "host";
      }
      if (removeContent && util3.headerNameToString(header).startsWith("content-")) {
        return true;
      }
      if (unknownOrigin && (header.length === 13 || header.length === 6 || header.length === 19)) {
        const name3 = util3.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 i3 = 0; i3 < headers.length; i3 += 2) {
          if (!shouldRemoveHeader(headers[i3], removeContent, unknownOrigin)) {
            ret.push(headers[i3], headers[i3 + 1]);
          }
        }
      } else if (headers && typeof headers === "object") {
        for (const key of Object.keys(headers)) {
          if (!shouldRemoveHeader(key, removeContent, unknownOrigin)) {
            ret.push(key, headers[key]);
          }
        }
      } else {
        assert4(headers == null, "headers must be an object or an array");
      }
      return ret;
    }
    __name(cleanRequestHeaders, "cleanRequestHeaders");
    module2.exports = RedirectHandler;
  }
});

// packages/cli/node_modules/undici/lib/interceptor/redirect-interceptor.js
var require_redirect_interceptor2 = __commonJS({
  "packages/cli/node_modules/undici/lib/interceptor/redirect-interceptor.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var RedirectHandler = require_redirect_handler2();
    function createRedirectInterceptor({ maxRedirections: defaultMaxRedirections }) {
      return (dispatch) => {
        return /* @__PURE__ */ __name(function Intercept(opts, handler) {
          const { maxRedirections = defaultMaxRedirections } = opts;
          if (!maxRedirections) {
            return dispatch(opts, handler);
          }
          const redirectHandler = new RedirectHandler(dispatch, maxRedirections, opts, handler);
          opts = { ...opts, maxRedirections: 0 };
          return dispatch(opts, redirectHandler);
        }, "Intercept");
      };
    }
    __name(createRedirectInterceptor, "createRedirectInterceptor");
    module2.exports = createRedirectInterceptor;
  }
});

// packages/cli/node_modules/undici/lib/dispatcher/client.js
var require_client3 = __commonJS({
  "packages/cli/node_modules/undici/lib/dispatcher/client.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var assert4 = __require("node:assert");
    var net2 = __require("node:net");
    var http7 = __require("node:http");
    var util3 = require_util22();
    var { channels } = require_diagnostics2();
    var Request6 = require_request3();
    var DispatcherBase = require_dispatcher_base2();
    var {
      InvalidArgumentError,
      InformationalError,
      ClientDestroyedError
    } = require_errors5();
    var buildConnector = require_connect2();
    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,
      kMaxRedirections,
      kMaxRequests,
      kCounter,
      kClose,
      kDestroy,
      kDispatch,
      kInterceptors,
      kLocalAddress,
      kMaxResponseSize,
      kOnError,
      kHTTPContext,
      kMaxConcurrentStreams,
      kResume
    } = require_symbols6();
    var connectH1 = require_client_h12();
    var connectH2 = require_client_h22();
    var deprecatedInterceptorWarned = false;
    var kClosedResolve = Symbol("kClosedResolve");
    var noop8 = /* @__PURE__ */ __name(() => {
    }, "noop");
    function getPipelining(client) {
      return client[kPipelining] ?? client[kHTTPContext]?.defaultPipelining ?? 1;
    }
    __name(getPipelining, "getPipelining");
    var Client3 = class extends DispatcherBase {
      static {
        __name(this, "Client");
      }
      /**
       *
       * @param {string|URL} url
       * @param {import('../../types/client.js').Client.Options} options
       */
      constructor(url2, {
        interceptors,
        maxHeaderSize,
        headersTimeout,
        socketTimeout,
        requestTimeout,
        connectTimeout,
        bodyTimeout,
        idleTimeout,
        keepAlive,
        keepAliveTimeout,
        maxKeepAliveTimeout,
        keepAliveMaxTimeout,
        keepAliveTimeoutThreshold,
        socketPath,
        pipelining,
        tls,
        strictContentLength,
        maxCachedSessions,
        maxRedirections,
        connect: connect2,
        maxRequestsPerClient,
        localAddress,
        maxResponseSize,
        autoSelectFamily,
        autoSelectFamilyAttemptTimeout,
        // h2
        maxConcurrentStreams,
        allowH2
      } = {}) {
        super();
        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 && !Number.isFinite(maxHeaderSize)) {
          throw new InvalidArgumentError("invalid maxHeaderSize");
        }
        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 (maxRedirections != null && (!Number.isInteger(maxRedirections) || maxRedirections < 0)) {
          throw new InvalidArgumentError("maxRedirections must be a positive number");
        }
        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");
        }
        if (typeof connect2 !== "function") {
          connect2 = buildConnector({
            ...tls,
            maxCachedSessions,
            allowH2,
            socketPath,
            timeout: connectTimeout,
            ...autoSelectFamily ? { autoSelectFamily, autoSelectFamilyAttemptTimeout } : void 0,
            ...connect2
          });
        }
        if (interceptors?.Client && Array.isArray(interceptors.Client)) {
          this[kInterceptors] = interceptors.Client;
          if (!deprecatedInterceptorWarned) {
            deprecatedInterceptorWarned = true;
            process.emitWarning("Client.Options#interceptor is deprecated. Use Dispatcher#compose instead.", {
              code: "UNDICI-CLIENT-INTERCEPTOR-DEPRECATED"
            });
          }
        } else {
          this[kInterceptors] = [createRedirectInterceptor({ maxRedirections })];
        }
        this[kUrl] = util3.parseOrigin(url2);
        this[kConnector] = connect2;
        this[kPipelining] = pipelining != null ? pipelining : 1;
        this[kMaxHeadersSize] = maxHeaderSize || http7.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[kMaxRedirections] = maxRedirections;
        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 [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 Request6(origin, opts, handler);
        this[kQueue].push(request4);
        if (this[kResuming]) {
        } else if (util3.bodyLength(request4.body) == null && util3.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((resolve30) => {
          if (this[kSize]) {
            this[kClosedResolve] = resolve30;
          } else {
            resolve30(null);
          }
        });
      }
      async [kDestroy](err) {
        return new Promise((resolve30) => {
          const requests = this[kQueue].splice(this[kPendingIdx]);
          for (let i3 = 0; i3 < requests.length; i3++) {
            const request4 = requests[i3];
            util3.errorRequest(this, request4, err);
          }
          const callback = /* @__PURE__ */ __name(() => {
            if (this[kClosedResolve]) {
              this[kClosedResolve]();
              this[kClosedResolve] = null;
            }
            resolve30(null);
          }, "callback");
          if (this[kHTTPContext]) {
            this[kHTTPContext].destroy(err, callback);
            this[kHTTPContext] = null;
          } else {
            queueMicrotask(callback);
          }
          this[kResume]();
        });
      }
    };
    var createRedirectInterceptor = require_redirect_interceptor2();
    function onError2(client, err) {
      if (client[kRunning] === 0 && err.code !== "UND_ERR_INFO" && err.code !== "UND_ERR_SOCKET") {
        assert4(client[kPendingIdx] === client[kRunningIdx]);
        const requests = client[kQueue].splice(client[kRunningIdx]);
        for (let i3 = 0; i3 < requests.length; i3++) {
          const request4 = requests[i3];
          util3.errorRequest(client, request4, err);
        }
        assert4(client[kSize] === 0);
      }
    }
    __name(onError2, "onError");
    async function connect(client) {
      assert4(!client[kConnecting]);
      assert4(!client[kHTTPContext]);
      let { host, hostname: hostname4, protocol, port } = client[kUrl];
      if (hostname4[0] === "[") {
        const idx = hostname4.indexOf("]");
        assert4(idx !== -1);
        const ip = hostname4.substring(1, idx);
        assert4(net2.isIP(ip));
        hostname4 = ip;
      }
      client[kConnecting] = true;
      if (channels.beforeConnect.hasSubscribers) {
        channels.beforeConnect.publish({
          connectParams: {
            host,
            hostname: hostname4,
            protocol,
            port,
            version: client[kHTTPContext]?.version,
            servername: client[kServerName],
            localAddress: client[kLocalAddress]
          },
          connector: client[kConnector]
        });
      }
      try {
        const socket = await new Promise((resolve30, reject) => {
          client[kConnector]({
            host,
            hostname: hostname4,
            protocol,
            port,
            servername: client[kServerName],
            localAddress: client[kLocalAddress]
          }, (err, socket2) => {
            if (err) {
              reject(err);
            } else {
              resolve30(socket2);
            }
          });
        });
        if (client.destroyed) {
          util3.destroy(socket.on("error", noop8), new ClientDestroyedError());
          return;
        }
        assert4(socket);
        try {
          client[kHTTPContext] = socket.alpnProtocol === "h2" ? await connectH2(client, socket) : await connectH1(client, socket);
        } catch (err) {
          socket.destroy().on("error", noop8);
          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: hostname4,
              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: hostname4,
              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") {
          assert4(client[kRunning] === 0);
          while (client[kPending] > 0 && client[kQueue][client[kPendingIdx]].servername === client[kServerName]) {
            const request4 = client[kQueue][client[kPendingIdx]++];
            util3.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) {
          assert4(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 = Client3;
  }
});

// packages/cli/node_modules/undici/lib/dispatcher/fixed-queue.js
var require_fixed_queue2 = __commonJS({
  "packages/cli/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);
        this.next = null;
      }
      isEmpty() {
        return this.top === this.bottom;
      }
      isFull() {
        return (this.top + 1 & kMask) === this.bottom;
      }
      push(data) {
        this.list[this.top] = data;
        this.top = this.top + 1 & kMask;
      }
      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();
      }
      isEmpty() {
        return this.head.isEmpty();
      }
      push(data) {
        if (this.head.isFull()) {
          this.head = this.head.next = new FixedCircularBuffer();
        }
        this.head.push(data);
      }
      shift() {
        const tail = this.tail;
        const next = tail.shift();
        if (tail.isEmpty() && tail.next !== null) {
          this.tail = tail.next;
        }
        return next;
      }
    };
  }
});

// packages/cli/node_modules/undici/lib/dispatcher/pool-stats.js
var require_pool_stats2 = __commonJS({
  "packages/cli/node_modules/undici/lib/dispatcher/pool-stats.js"(exports2, module2) {
    init_esbuild_shims();
    var { kFree, kConnected, kPending, kQueued, kRunning, kSize } = require_symbols6();
    var kPool = Symbol("pool");
    var PoolStats = class {
      static {
        __name(this, "PoolStats");
      }
      constructor(pool) {
        this[kPool] = pool;
      }
      get connected() {
        return this[kPool][kConnected];
      }
      get free() {
        return this[kPool][kFree];
      }
      get pending() {
        return this[kPool][kPending];
      }
      get queued() {
        return this[kPool][kQueued];
      }
      get running() {
        return this[kPool][kRunning];
      }
      get size() {
        return this[kPool][kSize];
      }
    };
    module2.exports = PoolStats;
  }
});

// packages/cli/node_modules/undici/lib/dispatcher/pool-base.js
var require_pool_base2 = __commonJS({
  "packages/cli/node_modules/undici/lib/dispatcher/pool-base.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var DispatcherBase = require_dispatcher_base2();
    var FixedQueue = require_fixed_queue2();
    var { kConnected, kSize, kRunning, kPending, kQueued, kBusy, kFree, kUrl, kClose, kDestroy, kDispatch } = require_symbols6();
    var PoolStats = require_pool_stats2();
    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 kStats = Symbol("stats");
    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((c4) => c4.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);
        };
        this[kStats] = new PoolStats(this);
      }
      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 this[kStats];
      }
      async [kClose]() {
        if (this[kQueue].isEmpty()) {
          await Promise.all(this[kClients].map((c4) => c4.close()));
        } else {
          await new Promise((resolve30) => {
            this[kClosedResolve] = resolve30;
          });
        }
      }
      async [kDestroy](err) {
        while (true) {
          const item = this[kQueue].shift();
          if (!item) {
            break;
          }
          item.handler.onError(err);
        }
        await Promise.all(this[kClients].map((c4) => c4.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
    };
  }
});

// packages/cli/node_modules/undici/lib/dispatcher/pool.js
var require_pool3 = __commonJS({
  "packages/cli/node_modules/undici/lib/dispatcher/pool.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var {
      PoolBase,
      kClients,
      kNeedDrain,
      kAddClient,
      kGetDispatcher
    } = require_pool_base2();
    var Client3 = require_client3();
    var {
      InvalidArgumentError
    } = require_errors5();
    var util3 = require_util22();
    var { kUrl, kInterceptors } = require_symbols6();
    var buildConnector = require_connect2();
    var kOptions = Symbol("options");
    var kConnections = Symbol("connections");
    var kFactory = Symbol("factory");
    function defaultFactory(origin, opts) {
      return new Client3(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,
        ...options2
      } = {}) {
        super();
        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");
        }
        if (typeof connect !== "function") {
          connect = buildConnector({
            ...tls,
            maxCachedSessions,
            allowH2,
            socketPath,
            timeout: connectTimeout,
            ...autoSelectFamily ? { autoSelectFamily, autoSelectFamilyAttemptTimeout } : void 0,
            ...connect
          });
        }
        this[kInterceptors] = options2.interceptors?.Pool && Array.isArray(options2.interceptors.Pool) ? options2.interceptors.Pool : [];
        this[kConnections] = connections || null;
        this[kUrl] = util3.parseOrigin(origin);
        this[kOptions] = { ...util3.deepClone(options2), connect, allowH2 };
        this[kOptions].interceptors = options2.interceptors ? { ...options2.interceptors } : void 0;
        this[kFactory] = factory;
        this.on("connectionError", (origin2, targets, error2) => {
          for (const target of targets) {
            const idx = this[kClients].indexOf(target);
            if (idx !== -1) {
              this[kClients].splice(idx, 1);
            }
          }
        });
      }
      [kGetDispatcher]() {
        for (const client of this[kClients]) {
          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;
  }
});

// packages/cli/node_modules/undici/lib/dispatcher/balanced-pool.js
var require_balanced_pool2 = __commonJS({
  "packages/cli/node_modules/undici/lib/dispatcher/balanced-pool.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var {
      BalancedPoolMissingUpstreamError,
      InvalidArgumentError
    } = require_errors5();
    var {
      PoolBase,
      kClients,
      kNeedDrain,
      kAddClient,
      kRemoveClient,
      kGetDispatcher
    } = require_pool_base2();
    var Pool = require_pool3();
    var { kUrl, kInterceptors } = require_symbols6();
    var { parseOrigin } = require_util22();
    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(a2, b2) {
      if (a2 === 0) return b2;
      while (b2 !== 0) {
        const t5 = b2;
        b2 = a2 % b2;
        a2 = t5;
      }
      return a2;
    }
    __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 } = {}) {
        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];
        }
        if (typeof factory !== "function") {
          throw new InvalidArgumentError("factory must be a function.");
        }
        this[kInterceptors] = opts.interceptors?.BalancedPool && Array.isArray(opts.interceptors.BalancedPool) ? opts.interceptors.BalancedPool : [];
        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 i3 = 0; i3 < this[kClients].length; i3++) {
          result = getGreatestCommonDivisor(this[kClients][i3][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((p2) => p2[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((a2, b2) => a2 && b2, 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;
  }
});

// packages/cli/node_modules/undici/lib/dispatcher/agent.js
var require_agent3 = __commonJS({
  "packages/cli/node_modules/undici/lib/dispatcher/agent.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var { InvalidArgumentError } = require_errors5();
    var { kClients, kRunning, kClose, kDestroy, kDispatch, kInterceptors } = require_symbols6();
    var DispatcherBase = require_dispatcher_base2();
    var Pool = require_pool3();
    var Client3 = require_client3();
    var util3 = require_util22();
    var createRedirectInterceptor = require_redirect_interceptor2();
    var kOnConnect = Symbol("onConnect");
    var kOnDisconnect = Symbol("onDisconnect");
    var kOnConnectionError = Symbol("onConnectionError");
    var kMaxRedirections = Symbol("maxRedirections");
    var kOnDrain = Symbol("onDrain");
    var kFactory = Symbol("factory");
    var kOptions = Symbol("options");
    function defaultFactory(origin, opts) {
      return opts && opts.connections === 1 ? new Client3(origin, opts) : new Pool(origin, opts);
    }
    __name(defaultFactory, "defaultFactory");
    var Agent4 = class extends DispatcherBase {
      static {
        __name(this, "Agent");
      }
      constructor({ factory = defaultFactory, maxRedirections = 0, connect, ...options2 } = {}) {
        super();
        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");
        }
        if (!Number.isInteger(maxRedirections) || maxRedirections < 0) {
          throw new InvalidArgumentError("maxRedirections must be a positive number");
        }
        if (connect && typeof connect !== "function") {
          connect = { ...connect };
        }
        this[kInterceptors] = options2.interceptors?.Agent && Array.isArray(options2.interceptors.Agent) ? options2.interceptors.Agent : [createRedirectInterceptor({ maxRedirections })];
        this[kOptions] = { ...util3.deepClone(options2), connect };
        this[kOptions].interceptors = options2.interceptors ? { ...options2.interceptors } : void 0;
        this[kMaxRedirections] = maxRedirections;
        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 client of this[kClients].values()) {
          ret += client[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.");
        }
        let dispatcher = this[kClients].get(key);
        if (!dispatcher) {
          dispatcher = this[kFactory](opts.origin, this[kOptions]).on("drain", this[kOnDrain]).on("connect", this[kOnConnect]).on("disconnect", this[kOnDisconnect]).on("connectionError", this[kOnConnectionError]);
          this[kClients].set(key, dispatcher);
        }
        return dispatcher.dispatch(opts, handler);
      }
      async [kClose]() {
        const closePromises = [];
        for (const client of this[kClients].values()) {
          closePromises.push(client.close());
        }
        this[kClients].clear();
        await Promise.all(closePromises);
      }
      async [kDestroy](err) {
        const destroyPromises = [];
        for (const client of this[kClients].values()) {
          destroyPromises.push(client.destroy(err));
        }
        this[kClients].clear();
        await Promise.all(destroyPromises);
      }
    };
    module2.exports = Agent4;
  }
});

// packages/cli/node_modules/undici/lib/dispatcher/proxy-agent.js
var require_proxy_agent2 = __commonJS({
  "packages/cli/node_modules/undici/lib/dispatcher/proxy-agent.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var { kProxy, kClose, kDestroy, kDispatch, kInterceptors } = require_symbols6();
    var { URL: URL5 } = __require("node:url");
    var Agent4 = require_agent3();
    var Pool = require_pool3();
    var DispatcherBase = require_dispatcher_base2();
    var { InvalidArgumentError, RequestAbortedError, SecureProxyConnectionError } = require_errors5();
    var buildConnector = require_connect2();
    var Client3 = require_client3();
    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 noop8 = /* @__PURE__ */ __name(() => {
    }, "noop");
    function defaultAgentFactory(origin, opts) {
      if (opts.connections === 1) {
        return new Client3(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 Client3(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: path125 = "/",
          headers = {}
        } = opts;
        opts.path = origin + path125;
        if (!("host" in headers) && !("Host" in headers)) {
          const { host } = new URL5(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 ProxyAgent6 = class extends DispatcherBase {
      static {
        __name(this, "ProxyAgent");
      }
      constructor(opts) {
        super();
        if (!opts || typeof opts === "object" && !(opts instanceof URL5) && !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;
        const url2 = this.#getUrl(opts);
        const { href, origin, port, protocol, username, password, hostname: proxyHostname } = url2;
        this[kProxy] = { uri: href, protocol };
        this[kInterceptors] = opts.interceptors?.ProxyAgent && Array.isArray(opts.interceptors.ProxyAgent) ? opts.interceptors.ProxyAgent : [];
        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 URL5(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 Agent4({
          ...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
                },
                servername: this[kProxyTls]?.servername || proxyHostname
              });
              if (statusCode !== 200) {
                socket.on("error", noop8).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 URL5(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 URL5(opts);
        } else if (opts instanceof URL5) {
          return opts;
        } else {
          return new URL5(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 i3 = 0; i3 < headers.length; i3 += 2) {
          headersPair[headers[i3]] = headers[i3 + 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 = ProxyAgent6;
  }
});

// packages/cli/node_modules/undici/lib/dispatcher/env-http-proxy-agent.js
var require_env_http_proxy_agent2 = __commonJS({
  "packages/cli/node_modules/undici/lib/dispatcher/env-http-proxy-agent.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var DispatcherBase = require_dispatcher_base2();
    var { kClose, kDestroy, kClosed, kDestroyed, kDispatch, kNoProxyAgent, kHttpProxyAgent, kHttpsProxyAgent } = require_symbols6();
    var ProxyAgent6 = require_proxy_agent2();
    var Agent4 = require_agent3();
    var DEFAULT_PORTS = {
      "http:": 80,
      "https:": 443
    };
    var experimentalWarned = false;
    var EnvHttpProxyAgent2 = class extends DispatcherBase {
      static {
        __name(this, "EnvHttpProxyAgent");
      }
      #noProxyValue = null;
      #noProxyEntries = null;
      #opts = null;
      constructor(opts = {}) {
        super();
        this.#opts = opts;
        if (!experimentalWarned) {
          experimentalWarned = true;
          process.emitWarning("EnvHttpProxyAgent is experimental, expect them to change at any time.", {
            code: "UNDICI-EHPA"
          });
        }
        const { httpProxy, httpsProxy, noProxy, ...agentOpts } = opts;
        this[kNoProxyAgent] = new Agent4(agentOpts);
        const HTTP_PROXY = httpProxy ?? process.env.http_proxy ?? process.env.HTTP_PROXY;
        if (HTTP_PROXY) {
          this[kHttpProxyAgent] = new ProxyAgent6({ ...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 ProxyAgent6({ ...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: hostname4, port } = url2;
        hostname4 = hostname4.replace(/:\d*$/, "").toLowerCase();
        port = Number.parseInt(port, 10) || DEFAULT_PORTS[protocol] || 0;
        if (!this.#shouldProxy(hostname4, port)) {
          return this[kNoProxyAgent];
        }
        if (protocol === "https:") {
          return this[kHttpsProxyAgent];
        }
        return this[kHttpProxyAgent];
      }
      #shouldProxy(hostname4, port) {
        if (this.#noProxyChanged) {
          this.#parseNoProxy();
        }
        if (this.#noProxyEntries.length === 0) {
          return true;
        }
        if (this.#noProxyValue === "*") {
          return false;
        }
        for (let i3 = 0; i3 < this.#noProxyEntries.length; i3++) {
          const entry = this.#noProxyEntries[i3];
          if (entry.port && entry.port !== port) {
            continue;
          }
          if (!/^[.*]/.test(entry.hostname)) {
            if (hostname4 === entry.hostname) {
              return false;
            }
          } else {
            if (hostname4.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 i3 = 0; i3 < noProxySplit.length; i3++) {
          const entry = noProxySplit[i3];
          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;
  }
});

// packages/cli/node_modules/undici/lib/handler/retry-handler.js
var require_retry_handler2 = __commonJS({
  "packages/cli/node_modules/undici/lib/handler/retry-handler.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var assert4 = __require("node:assert");
    var { kRetryHandlerDefaultRetry } = require_symbols6();
    var { RequestRetryError } = require_errors5();
    var {
      isDisturbed,
      parseHeaders,
      parseRangeHeader,
      wrapRequestBody
    } = require_util22();
    function calculateRetryAfterHeader(retryAfter) {
      const current = Date.now();
      return new Date(retryAfter).getTime() - current;
    }
    __name(calculateRetryAfterHeader, "calculateRetryAfterHeader");
    var RetryHandler = class _RetryHandler {
      static {
        __name(this, "RetryHandler");
      }
      constructor(opts, handlers) {
        const { retryOptions, ...dispatchOpts } = opts;
        const {
          // Retry scoped
          retry: retryFn,
          maxRetries,
          maxTimeout,
          minTimeout,
          timeoutFactor,
          // Response scoped
          methods,
          errorCodes,
          retryAfter,
          statusCodes
        } = retryOptions ?? {};
        this.dispatch = handlers.dispatch;
        this.handler = handlers.handler;
        this.opts = { ...dispatchOpts, body: wrapRequestBody(opts.body) };
        this.abort = null;
        this.aborted = false;
        this.retryOpts = {
          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.start = 0;
        this.end = null;
        this.etag = null;
        this.resume = null;
        this.handler.onConnect((reason) => {
          this.aborted = true;
          if (this.abort) {
            this.abort(reason);
          } else {
            this.reason = reason;
          }
        });
      }
      onRequestSent() {
        if (this.handler.onRequestSent) {
          this.handler.onRequestSent();
        }
      }
      onUpgrade(statusCode, headers, socket) {
        if (this.handler.onUpgrade) {
          this.handler.onUpgrade(statusCode, headers, socket);
        }
      }
      onConnect(abort) {
        if (this.aborted) {
          abort(this.reason);
        } else {
          this.abort = abort;
        }
      }
      onBodySent(chunk) {
        if (this.handler.onBodySent) return this.handler.onBodySent(chunk);
      }
      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(retryAfterHeader) : retryAfterHeader * 1e3;
        }
        const retryTimeout = retryAfterHeader > 0 ? Math.min(retryAfterHeader, maxTimeout) : Math.min(minTimeout * timeoutFactor ** (counter - 1), maxTimeout);
        setTimeout(() => cb(null), retryTimeout);
      }
      onHeaders(statusCode, rawHeaders, resume, statusMessage) {
        const headers = parseHeaders(rawHeaders);
        this.retryCount += 1;
        if (statusCode >= 300) {
          if (this.retryOpts.statusCodes.includes(statusCode) === false) {
            return this.handler.onHeaders(
              statusCode,
              rawHeaders,
              resume,
              statusMessage
            );
          } else {
            this.abort(
              new RequestRetryError("Request failed", statusCode, {
                headers,
                data: {
                  count: this.retryCount
                }
              })
            );
            return false;
          }
        }
        if (this.resume != null) {
          this.resume = null;
          if (statusCode !== 206 && (this.start > 0 || statusCode !== 200)) {
            this.abort(
              new RequestRetryError("server does not support the range header and the payload was partially consumed", statusCode, {
                headers,
                data: { count: this.retryCount }
              })
            );
            return false;
          }
          const contentRange = parseRangeHeader(headers["content-range"]);
          if (!contentRange) {
            this.abort(
              new RequestRetryError("Content-Range mismatch", statusCode, {
                headers,
                data: { count: this.retryCount }
              })
            );
            return false;
          }
          if (this.etag != null && this.etag !== headers.etag) {
            this.abort(
              new RequestRetryError("ETag mismatch", statusCode, {
                headers,
                data: { count: this.retryCount }
              })
            );
            return false;
          }
          const { start, size, end = size - 1 } = contentRange;
          assert4(this.start === start, "content-range mismatch");
          assert4(this.end == null || this.end === end, "content-range mismatch");
          this.resume = resume;
          return true;
        }
        if (this.end == null) {
          if (statusCode === 206) {
            const range = parseRangeHeader(headers["content-range"]);
            if (range == null) {
              return this.handler.onHeaders(
                statusCode,
                rawHeaders,
                resume,
                statusMessage
              );
            }
            const { start, size, end = size - 1 } = range;
            assert4(
              start != null && Number.isFinite(start),
              "content-range mismatch"
            );
            assert4(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;
          }
          assert4(Number.isFinite(this.start));
          assert4(
            this.end == null || Number.isFinite(this.end),
            "invalid content-length"
          );
          this.resume = resume;
          this.etag = headers.etag != null ? headers.etag : null;
          if (this.etag != null && this.etag.startsWith("W/")) {
            this.etag = null;
          }
          return this.handler.onHeaders(
            statusCode,
            rawHeaders,
            resume,
            statusMessage
          );
        }
        const err = new RequestRetryError("Request failed", statusCode, {
          headers,
          data: { count: this.retryCount }
        });
        this.abort(err);
        return false;
      }
      onData(chunk) {
        this.start += chunk.length;
        return this.handler.onData(chunk);
      }
      onComplete(rawTrailers) {
        this.retryCount = 0;
        return this.handler.onComplete(rawTrailers);
      }
      onError(err) {
        if (this.aborted || isDisturbed(this.opts.body)) {
          return this.handler.onError(err);
        }
        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 }
          },
          onRetry.bind(this)
        );
        function onRetry(err2) {
          if (err2 != null || this.aborted || isDisturbed(this.opts.body)) {
            return this.handler.onError(err2);
          }
          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 (err3) {
            this.handler.onError(err3);
          }
        }
        __name(onRetry, "onRetry");
      }
    };
    module2.exports = RetryHandler;
  }
});

// packages/cli/node_modules/undici/lib/dispatcher/retry-agent.js
var require_retry_agent2 = __commonJS({
  "packages/cli/node_modules/undici/lib/dispatcher/retry-agent.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var Dispatcher = require_dispatcher2();
    var RetryHandler = require_retry_handler2();
    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;
  }
});

// packages/cli/node_modules/undici/lib/api/readable.js
var require_readable2 = __commonJS({
  "packages/cli/node_modules/undici/lib/api/readable.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var assert4 = __require("node:assert");
    var { Readable: Readable6 } = __require("node:stream");
    var { RequestAbortedError, NotSupportedError, InvalidArgumentError, AbortError: AbortError4 } = require_errors5();
    var util3 = require_util22();
    var { ReadableStreamFrom: ReadableStreamFrom2 } = require_util22();
    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 noop8 = /* @__PURE__ */ __name(() => {
    }, "noop");
    var BodyReadable = class extends Readable6 {
      static {
        __name(this, "BodyReadable");
      }
      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[kBody] = null;
        this[kContentType] = contentType;
        this[kContentLength] = contentLength;
        this[kReading] = false;
      }
      destroy(err) {
        if (!err && !this._readableState.endEmitted) {
          err = new RequestAbortedError();
        }
        if (err) {
          this[kAbort]();
        }
        return super.destroy(err);
      }
      _destroy(err, callback) {
        if (!this[kReading]) {
          setImmediate(() => {
            callback(err);
          });
        } else {
          callback(err);
        }
      }
      on(ev, ...args) {
        if (ev === "data" || ev === "readable") {
          this[kReading] = true;
        }
        return super.on(ev, ...args);
      }
      addListener(ev, ...args) {
        return this.on(ev, ...args);
      }
      off(ev, ...args) {
        const ret = super.off(ev, ...args);
        if (ev === "data" || ev === "readable") {
          this[kReading] = this.listenerCount("data") > 0 || this.listenerCount("readable") > 0;
        }
        return ret;
      }
      removeListener(ev, ...args) {
        return this.off(ev, ...args);
      }
      push(chunk) {
        if (this[kConsume] && chunk !== null) {
          consumePush(this[kConsume], chunk);
          return this[kReading] ? super.push(chunk) : true;
        }
        return super.push(chunk);
      }
      // https://fetch.spec.whatwg.org/#dom-body-text
      async text() {
        return consume(this, "text");
      }
      // https://fetch.spec.whatwg.org/#dom-body-json
      async json() {
        return consume(this, "json");
      }
      // https://fetch.spec.whatwg.org/#dom-body-blob
      async blob() {
        return consume(this, "blob");
      }
      // https://fetch.spec.whatwg.org/#dom-body-bytes
      async bytes() {
        return consume(this, "bytes");
      }
      // https://fetch.spec.whatwg.org/#dom-body-arraybuffer
      async arrayBuffer() {
        return consume(this, "arrayBuffer");
      }
      // https://fetch.spec.whatwg.org/#dom-body-formdata
      async formData() {
        throw new NotSupportedError();
      }
      // https://fetch.spec.whatwg.org/#dom-body-bodyused
      get bodyUsed() {
        return util3.isDisturbed(this);
      }
      // https://fetch.spec.whatwg.org/#dom-body-body
      get body() {
        if (!this[kBody]) {
          this[kBody] = ReadableStreamFrom2(this);
          if (this[kConsume]) {
            this[kBody].getReader();
            assert4(this[kBody].locked);
          }
        }
        return this[kBody];
      }
      async dump(opts) {
        let limit2 = Number.isFinite(opts?.limit) ? opts.limit : 128 * 1024;
        const signal = opts?.signal;
        if (signal != null && (typeof signal !== "object" || !("aborted" in signal))) {
          throw new InvalidArgumentError("signal must be an AbortSignal");
        }
        signal?.throwIfAborted();
        if (this._readableState.closeEmitted) {
          return null;
        }
        return await new Promise((resolve30, reject) => {
          if (this[kContentLength] > limit2) {
            this.destroy(new AbortError4());
          }
          const onAbort = /* @__PURE__ */ __name(() => {
            this.destroy(signal.reason ?? new AbortError4());
          }, "onAbort");
          signal?.addEventListener("abort", onAbort);
          this.on("close", function() {
            signal?.removeEventListener("abort", onAbort);
            if (signal?.aborted) {
              reject(signal.reason ?? new AbortError4());
            } else {
              resolve30(null);
            }
          }).on("error", noop8).on("data", function(chunk) {
            limit2 -= chunk.length;
            if (limit2 <= 0) {
              this.destroy();
            }
          }).resume();
        });
      }
    };
    function isLocked(self2) {
      return self2[kBody] && self2[kBody].locked === true || self2[kConsume];
    }
    __name(isLocked, "isLocked");
    function isUnusable(self2) {
      return util3.isDisturbed(self2) || isLocked(self2);
    }
    __name(isUnusable, "isUnusable");
    async function consume(stream2, type) {
      assert4(!stream2[kConsume]);
      return new Promise((resolve30, reject) => {
        if (isUnusable(stream2)) {
          const rState = stream2._readableState;
          if (rState.destroyed && rState.closeEmitted === false) {
            stream2.on("error", (err) => {
              reject(err);
            }).on("close", () => {
              reject(new TypeError("unusable"));
            });
          } else {
            reject(rState.errored ?? new TypeError("unusable"));
          }
        } else {
          queueMicrotask(() => {
            stream2[kConsume] = {
              type,
              stream: stream2,
              resolve: resolve30,
              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 n3 = start; n3 < end; n3++) {
          consumePush(consume2, state.buffer[n3]);
        }
      } else {
        for (const chunk of state.buffer) {
          consumePush(consume2, chunk);
        }
      }
      if (state.endEmitted) {
        consumeEnd(this[kConsume]);
      } else {
        consume2.stream.on("end", function() {
          consumeEnd(this[kConsume]);
        });
      }
      consume2.stream.resume();
      while (consume2.stream.read() != null) {
      }
    }
    __name(consumeStart, "consumeStart");
    function chunksDecode(chunks, length) {
      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;
      return buffer.utf8Slice(start, bufferLength);
    }
    __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 i3 = 0; i3 < chunks.length; ++i3) {
        const chunk = chunks[i3];
        buffer.set(chunk, offset);
        offset += chunk.length;
      }
      return buffer;
    }
    __name(chunksConcat, "chunksConcat");
    function consumeEnd(consume2) {
      const { type, body, resolve: resolve30, stream: stream2, length } = consume2;
      try {
        if (type === "text") {
          resolve30(chunksDecode(body, length));
        } else if (type === "json") {
          resolve30(JSON.parse(chunksDecode(body, length)));
        } else if (type === "arrayBuffer") {
          resolve30(chunksConcat(body, length).buffer);
        } else if (type === "blob") {
          resolve30(new Blob(body, { type: stream2[kContentType] }));
        } else if (type === "bytes") {
          resolve30(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 };
  }
});

// packages/cli/node_modules/undici/lib/api/util.js
var require_util24 = __commonJS({
  "packages/cli/node_modules/undici/lib/api/util.js"(exports2, module2) {
    init_esbuild_shims();
    var assert4 = __require("node:assert");
    var {
      ResponseStatusCodeError
    } = require_errors5();
    var { chunksDecode } = require_readable2();
    var CHUNK_LIMIT = 128 * 1024;
    async function getResolveErrorBodyCallback({ callback, body, contentType, statusCode, statusMessage, headers }) {
      assert4(body);
      let chunks = [];
      let length = 0;
      try {
        for await (const chunk of body) {
          chunks.push(chunk);
          length += chunk.length;
          if (length > CHUNK_LIMIT) {
            chunks = [];
            length = 0;
            break;
          }
        }
      } catch {
        chunks = [];
        length = 0;
      }
      const message = `Response status code ${statusCode}${statusMessage ? `: ${statusMessage}` : ""}`;
      if (statusCode === 204 || !contentType || !length) {
        queueMicrotask(() => callback(new ResponseStatusCodeError(message, statusCode, headers)));
        return;
      }
      const stackTraceLimit = Error.stackTraceLimit;
      Error.stackTraceLimit = 0;
      let payload;
      try {
        if (isContentTypeApplicationJson(contentType)) {
          payload = JSON.parse(chunksDecode(chunks, length));
        } else if (isContentTypeText(contentType)) {
          payload = chunksDecode(chunks, length);
        }
      } catch {
      } finally {
        Error.stackTraceLimit = stackTraceLimit;
      }
      queueMicrotask(() => callback(new ResponseStatusCodeError(message, statusCode, headers, payload)));
    }
    __name(getResolveErrorBodyCallback, "getResolveErrorBodyCallback");
    var isContentTypeApplicationJson = /* @__PURE__ */ __name((contentType) => {
      return contentType.length > 15 && contentType[11] === "/" && contentType[0] === "a" && contentType[1] === "p" && contentType[2] === "p" && contentType[3] === "l" && contentType[4] === "i" && contentType[5] === "c" && contentType[6] === "a" && contentType[7] === "t" && contentType[8] === "i" && contentType[9] === "o" && contentType[10] === "n" && contentType[12] === "j" && contentType[13] === "s" && contentType[14] === "o" && contentType[15] === "n";
    }, "isContentTypeApplicationJson");
    var isContentTypeText = /* @__PURE__ */ __name((contentType) => {
      return contentType.length > 4 && contentType[4] === "/" && contentType[0] === "t" && contentType[1] === "e" && contentType[2] === "x" && contentType[3] === "t";
    }, "isContentTypeText");
    module2.exports = {
      getResolveErrorBodyCallback,
      isContentTypeApplicationJson,
      isContentTypeText
    };
  }
});

// packages/cli/node_modules/undici/lib/api/api-request.js
var require_api_request2 = __commonJS({
  "packages/cli/node_modules/undici/lib/api/api-request.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var assert4 = __require("node:assert");
    var { Readable: Readable6 } = require_readable2();
    var { InvalidArgumentError, RequestAbortedError } = require_errors5();
    var util3 = require_util22();
    var { getResolveErrorBodyCallback } = require_util24();
    var { AsyncResource } = __require("node:async_hooks");
    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, throwOnError, 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 (util3.isStream(body)) {
            util3.destroy(body.on("error", util3.nop), 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.throwOnError = throwOnError;
        this.highWaterMark = highWaterMark;
        this.signal = signal;
        this.reason = null;
        this.removeAbortListener = null;
        if (util3.isStream(body)) {
          body.on("error", (err) => {
            this.onError(err);
          });
        }
        if (this.signal) {
          if (this.signal.aborted) {
            this.reason = this.signal.reason ?? new RequestAbortedError();
          } else {
            this.removeAbortListener = util3.addAbortListener(this.signal, () => {
              this.reason = this.signal.reason ?? new RequestAbortedError();
              if (this.res) {
                util3.destroy(this.res.on("error", util3.nop), this.reason);
              } else if (this.abort) {
                this.abort(this.reason);
              }
              if (this.removeAbortListener) {
                this.res?.off("close", this.removeAbortListener);
                this.removeAbortListener();
                this.removeAbortListener = null;
              }
            });
          }
        }
      }
      onConnect(abort, context2) {
        if (this.reason) {
          abort(this.reason);
          return;
        }
        assert4(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" ? util3.parseRawHeaders(rawHeaders) : util3.parseHeaders(rawHeaders);
        if (statusCode < 200) {
          if (this.onInfo) {
            this.onInfo({ statusCode, headers });
          }
          return;
        }
        const parsedHeaders = responseHeaders === "raw" ? util3.parseHeaders(rawHeaders) : headers;
        const contentType = parsedHeaders["content-type"];
        const contentLength = parsedHeaders["content-length"];
        const res = new Readable6({
          resume,
          abort,
          contentType,
          contentLength: this.method !== "HEAD" && contentLength ? Number(contentLength) : null,
          highWaterMark
        });
        if (this.removeAbortListener) {
          res.on("close", this.removeAbortListener);
        }
        this.callback = null;
        this.res = res;
        if (callback !== null) {
          if (this.throwOnError && statusCode >= 400) {
            this.runInAsyncScope(
              getResolveErrorBodyCallback,
              null,
              { callback, body: res, contentType, statusCode, statusMessage, headers }
            );
          } else {
            this.runInAsyncScope(callback, null, null, {
              statusCode,
              headers,
              trailers: this.trailers,
              opaque,
              body: res,
              context: context2
            });
          }
        }
      }
      onData(chunk) {
        return this.res.push(chunk);
      }
      onComplete(trailers) {
        util3.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(() => {
            util3.destroy(res, err);
          });
        }
        if (body) {
          this.body = null;
          util3.destroy(body, err);
        }
        if (this.removeAbortListener) {
          res?.off("close", this.removeAbortListener);
          this.removeAbortListener();
          this.removeAbortListener = null;
        }
      }
    };
    function request4(opts, callback) {
      if (callback === void 0) {
        return new Promise((resolve30, reject) => {
          request4.call(this, opts, (err, data) => {
            return err ? reject(err) : resolve30(data);
          });
        });
      }
      try {
        this.dispatch(opts, new RequestHandler(opts, callback));
      } 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;
  }
});

// packages/cli/node_modules/undici/lib/api/abort-signal.js
var require_abort_signal2 = __commonJS({
  "packages/cli/node_modules/undici/lib/api/abort-signal.js"(exports2, module2) {
    init_esbuild_shims();
    var { addAbortListener } = require_util22();
    var { RequestAbortedError } = require_errors5();
    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
    };
  }
});

// packages/cli/node_modules/undici/lib/api/api-stream.js
var require_api_stream2 = __commonJS({
  "packages/cli/node_modules/undici/lib/api/api-stream.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var assert4 = __require("node:assert");
    var { finished: finished2, PassThrough: PassThrough8 } = __require("node:stream");
    var { InvalidArgumentError, InvalidReturnValueError } = require_errors5();
    var util3 = require_util22();
    var { getResolveErrorBodyCallback } = require_util24();
    var { AsyncResource } = __require("node:async_hooks");
    var { addSignal, removeSignal } = require_abort_signal2();
    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, throwOnError } = 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 (util3.isStream(body)) {
            util3.destroy(body.on("error", util3.nop), 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;
        this.throwOnError = throwOnError || false;
        if (util3.isStream(body)) {
          body.on("error", (err) => {
            this.onError(err);
          });
        }
        addSignal(this, signal);
      }
      onConnect(abort, context2) {
        if (this.reason) {
          abort(this.reason);
          return;
        }
        assert4(this.callback);
        this.abort = abort;
        this.context = context2;
      }
      onHeaders(statusCode, rawHeaders, resume, statusMessage) {
        const { factory, opaque, context: context2, callback, responseHeaders } = this;
        const headers = responseHeaders === "raw" ? util3.parseRawHeaders(rawHeaders) : util3.parseHeaders(rawHeaders);
        if (statusCode < 200) {
          if (this.onInfo) {
            this.onInfo({ statusCode, headers });
          }
          return;
        }
        this.factory = null;
        let res;
        if (this.throwOnError && statusCode >= 400) {
          const parsedHeaders = responseHeaders === "raw" ? util3.parseHeaders(rawHeaders) : headers;
          const contentType = parsedHeaders["content-type"];
          res = new PassThrough8();
          this.callback = null;
          this.runInAsyncScope(
            getResolveErrorBodyCallback,
            null,
            { callback, body: res, contentType, statusCode, statusMessage, headers }
          );
        } else {
          if (factory === null) {
            return;
          }
          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");
          }
          finished2(res, { readable: false }, (err) => {
            const { callback: callback2, res: res2, opaque: opaque2, trailers, abort } = this;
            this.res = null;
            if (err || !res2.readable) {
              util3.destroy(res2, err);
            }
            this.callback = null;
            this.runInAsyncScope(callback2, 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 = util3.parseHeaders(trailers);
        res.end();
      }
      onError(err) {
        const { res, callback, opaque, body } = this;
        removeSignal(this);
        this.factory = null;
        if (res) {
          this.res = null;
          util3.destroy(res, err);
        } else if (callback) {
          this.callback = null;
          queueMicrotask(() => {
            this.runInAsyncScope(callback, null, err, { opaque });
          });
        }
        if (body) {
          this.body = null;
          util3.destroy(body, err);
        }
      }
    };
    function stream2(opts, factory, callback) {
      if (callback === void 0) {
        return new Promise((resolve30, reject) => {
          stream2.call(this, opts, factory, (err, data) => {
            return err ? reject(err) : resolve30(data);
          });
        });
      }
      try {
        this.dispatch(opts, new StreamHandler(opts, factory, callback));
      } catch (err) {
        if (typeof callback !== "function") {
          throw err;
        }
        const opaque = opts?.opaque;
        queueMicrotask(() => callback(err, { opaque }));
      }
    }
    __name(stream2, "stream");
    module2.exports = stream2;
  }
});

// packages/cli/node_modules/undici/lib/api/api-pipeline.js
var require_api_pipeline2 = __commonJS({
  "packages/cli/node_modules/undici/lib/api/api-pipeline.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var {
      Readable: Readable6,
      Duplex,
      PassThrough: PassThrough8
    } = __require("node:stream");
    var {
      InvalidArgumentError,
      InvalidReturnValueError,
      RequestAbortedError
    } = require_errors5();
    var util3 = require_util22();
    var { AsyncResource } = __require("node:async_hooks");
    var { addSignal, removeSignal } = require_abort_signal2();
    var assert4 = __require("node:assert");
    var kResume = Symbol("resume");
    var PipelineRequest = class extends Readable6 {
      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 Readable6 {
      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", util3.nop);
        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();
            }
            util3.destroy(body, err);
            util3.destroy(req, err);
            util3.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 { ret, res } = this;
        if (this.reason) {
          abort(this.reason);
          return;
        }
        assert4(!res, "pipeline cannot be retried");
        assert4(!ret.destroyed);
        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" ? util3.parseRawHeaders(rawHeaders) : util3.parseHeaders(rawHeaders);
            this.onInfo({ statusCode, headers });
          }
          return;
        }
        this.res = new PipelineResponse(resume);
        let body;
        try {
          this.handler = null;
          const headers = this.responseHeaders === "raw" ? util3.parseRawHeaders(rawHeaders) : util3.parseHeaders(rawHeaders);
          body = this.runInAsyncScope(handler, null, {
            statusCode,
            headers,
            opaque,
            body: this.res,
            context: context2
          });
        } catch (err) {
          this.res.on("error", util3.nop);
          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;
          util3.destroy(ret, err);
        }).on("end", () => {
          const { ret } = this;
          ret.push(null);
        }).on("close", () => {
          const { ret } = this;
          if (!ret._readableState.ended) {
            util3.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;
        util3.destroy(ret, err);
      }
    };
    function pipeline3(opts, handler) {
      try {
        const pipelineHandler = new PipelineHandler(opts, handler);
        this.dispatch({ ...opts, body: pipelineHandler.req }, pipelineHandler);
        return pipelineHandler.ret;
      } catch (err) {
        return new PassThrough8().destroy(err);
      }
    }
    __name(pipeline3, "pipeline");
    module2.exports = pipeline3;
  }
});

// packages/cli/node_modules/undici/lib/api/api-upgrade.js
var require_api_upgrade2 = __commonJS({
  "packages/cli/node_modules/undici/lib/api/api-upgrade.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var { InvalidArgumentError, SocketError } = require_errors5();
    var { AsyncResource } = __require("node:async_hooks");
    var util3 = require_util22();
    var { addSignal, removeSignal } = require_abort_signal2();
    var assert4 = __require("node:assert");
    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;
        }
        assert4(this.callback);
        this.abort = abort;
        this.context = null;
      }
      onHeaders() {
        throw new SocketError("bad upgrade", null);
      }
      onUpgrade(statusCode, rawHeaders, socket) {
        assert4(statusCode === 101);
        const { callback, opaque, context: context2 } = this;
        removeSignal(this);
        this.callback = null;
        const headers = this.responseHeaders === "raw" ? util3.parseRawHeaders(rawHeaders) : util3.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((resolve30, reject) => {
          upgrade.call(this, opts, (err, data) => {
            return err ? reject(err) : resolve30(data);
          });
        });
      }
      try {
        const upgradeHandler = new UpgradeHandler(opts, callback);
        this.dispatch({
          ...opts,
          method: opts.method || "GET",
          upgrade: opts.protocol || "Websocket"
        }, upgradeHandler);
      } catch (err) {
        if (typeof callback !== "function") {
          throw err;
        }
        const opaque = opts?.opaque;
        queueMicrotask(() => callback(err, { opaque }));
      }
    }
    __name(upgrade, "upgrade");
    module2.exports = upgrade;
  }
});

// packages/cli/node_modules/undici/lib/api/api-connect.js
var require_api_connect2 = __commonJS({
  "packages/cli/node_modules/undici/lib/api/api-connect.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var assert4 = __require("node:assert");
    var { AsyncResource } = __require("node:async_hooks");
    var { InvalidArgumentError, SocketError } = require_errors5();
    var util3 = require_util22();
    var { addSignal, removeSignal } = require_abort_signal2();
    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;
        }
        assert4(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" ? util3.parseRawHeaders(rawHeaders) : util3.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((resolve30, reject) => {
          connect.call(this, opts, (err, data) => {
            return err ? reject(err) : resolve30(data);
          });
        });
      }
      try {
        const connectHandler = new ConnectHandler(opts, callback);
        this.dispatch({ ...opts, method: "CONNECT" }, connectHandler);
      } catch (err) {
        if (typeof callback !== "function") {
          throw err;
        }
        const opaque = opts?.opaque;
        queueMicrotask(() => callback(err, { opaque }));
      }
    }
    __name(connect, "connect");
    module2.exports = connect;
  }
});

// packages/cli/node_modules/undici/lib/api/index.js
var require_api3 = __commonJS({
  "packages/cli/node_modules/undici/lib/api/index.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    module2.exports.request = require_api_request2();
    module2.exports.stream = require_api_stream2();
    module2.exports.pipeline = require_api_pipeline2();
    module2.exports.upgrade = require_api_upgrade2();
    module2.exports.connect = require_api_connect2();
  }
});

// packages/cli/node_modules/undici/lib/mock/mock-errors.js
var require_mock_errors2 = __commonJS({
  "packages/cli/node_modules/undici/lib/mock/mock-errors.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var { UndiciError } = require_errors5();
    var kMockNotMatchedError = Symbol.for("undici.error.UND_MOCK_ERR_MOCK_NOT_MATCHED");
    var MockNotMatchedError = class _MockNotMatchedError extends UndiciError {
      static {
        __name(this, "MockNotMatchedError");
      }
      constructor(message) {
        super(message);
        Error.captureStackTrace(this, _MockNotMatchedError);
        this.name = "MockNotMatchedError";
        this.message = message || "The request does not match any registered mock dispatches";
        this.code = "UND_MOCK_ERR_MOCK_NOT_MATCHED";
      }
      static [Symbol.hasInstance](instance) {
        return instance && instance[kMockNotMatchedError] === true;
      }
      [kMockNotMatchedError] = true;
    };
    module2.exports = {
      MockNotMatchedError
    };
  }
});

// packages/cli/node_modules/undici/lib/mock/mock-symbols.js
var require_mock_symbols2 = __commonJS({
  "packages/cli/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"),
      kOrigin: Symbol("origin"),
      kIsMockActive: Symbol("is mock active"),
      kNetConnect: Symbol("net connect"),
      kGetNetConnect: Symbol("get net connect"),
      kConnected: Symbol("connected")
    };
  }
});

// packages/cli/node_modules/undici/lib/mock/mock-utils.js
var require_mock_utils2 = __commonJS({
  "packages/cli/node_modules/undici/lib/mock/mock-utils.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var { MockNotMatchedError } = require_mock_errors2();
    var {
      kDispatches,
      kMockAgent,
      kOriginalDispatch,
      kOrigin,
      kGetNetConnect
    } = require_mock_symbols2();
    var { buildURL } = require_util22();
    var { STATUS_CODES } = __require("node:http");
    var {
      types: {
        isPromise: isPromise2
      }
    } = __require("node:util");
    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 i3 = 0; i3 < headers.length; i3 += 2) {
          if (headers[i3].toLocaleLowerCase() === key.toLocaleLowerCase()) {
            return headers[i3 + 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 clone4 = headers.slice();
      const entries = [];
      for (let index = 0; index < clone4.length; index += 2) {
        entries.push([clone4[index], clone4[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 safeUrl(path125) {
      if (typeof path125 !== "string") {
        return path125;
      }
      const pathSegments = path125.split("?");
      if (pathSegments.length !== 2) {
        return path125;
      }
      const qp = new URLSearchParams(pathSegments.pop());
      qp.sort();
      return [...pathSegments, qp.toString()].join("?");
    }
    __name(safeUrl, "safeUrl");
    function matchKey(mockDispatch2, { path: path125, method, body, headers }) {
      const pathMatch = matchValue(mockDispatch2.path, path125);
      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 {
        return data.toString();
      }
    }
    __name(getResponseData, "getResponseData");
    function getMockDispatch(mockDispatches, key) {
      const basePath = key.query ? buildURL(key.path, key.query) : key.path;
      const resolvedPath = typeof basePath === "string" ? safeUrl(basePath) : basePath;
      let matchedMockDispatches = mockDispatches.filter(({ consumed }) => !consumed).filter(({ path: path125 }) => matchValue(safeUrl(path125), 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) {
      const baseData = { timesInvoked: 0, times: 1, persist: false, consumed: false };
      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 buildKey(opts) {
      const { path: path125, method, body, headers, query } = opts;
      return {
        path: path125,
        method,
        body,
        headers,
        query
      };
    }
    __name(buildKey, "buildKey");
    function generateKeyValues(data) {
      const keys = Object.keys(data);
      const result = [];
      for (let i3 = 0; i3 < keys.length; ++i3) {
        const key = keys[i3];
        const value = data[key];
        const name3 = Buffer.from(`${key}`);
        if (Array.isArray(value)) {
          for (let j2 = 0; j2 < value.length; ++j2) {
            result.push(name3, Buffer.from(`${value[j2]}`));
          }
        } 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: error2 }, delay: delay4, persist } = mockDispatch2;
      const { timesInvoked, times } = mockDispatch2;
      mockDispatch2.consumed = !persist && timesInvoked >= times;
      mockDispatch2.pending = timesInvoked < times;
      if (error2 !== null) {
        deleteMockDispatch(this[kDispatches], key);
        handler.onError(error2);
        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 (error2) {
            if (error2 instanceof MockNotMatchedError) {
              const netConnect = agent[kGetNetConnect]();
              if (netConnect === false) {
                throw new MockNotMatchedError(`${error2.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(`${error2.message}: subsequent request to origin ${origin} was not allowed (net.connect is not enabled for this origin)`);
              }
            } else {
              throw error2;
            }
          }
        } 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 buildMockOptions(opts) {
      if (opts) {
        const { agent, ...mockOptions } = opts;
        return mockOptions;
      }
    }
    __name(buildMockOptions, "buildMockOptions");
    module2.exports = {
      getResponseData,
      getMockDispatch,
      addMockDispatch,
      deleteMockDispatch,
      buildKey,
      generateKeyValues,
      matchValue,
      getResponse,
      getStatusText: getStatusText2,
      mockDispatch,
      buildMockDispatch,
      checkNetConnect,
      buildMockOptions,
      getHeaderByName,
      buildHeadersFromArray
    };
  }
});

// packages/cli/node_modules/undici/lib/mock/mock-interceptor.js
var require_mock_interceptor2 = __commonJS({
  "packages/cli/node_modules/undici/lib/mock/mock-interceptor.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var { getResponseData, buildKey, addMockDispatch } = require_mock_utils2();
    var {
      kDispatches,
      kDispatchKey,
      kDefaultHeaders,
      kDefaultTrailers,
      kContentLength,
      kMockDispatch
    } = require_mock_symbols2();
    var { InvalidArgumentError } = require_errors5();
    var { buildURL } = require_util22();
    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 = buildURL(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[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);
          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);
        return new MockScope(newMockDispatch);
      }
      /**
       * Mock an undici request with a defined error.
       */
      replyWithError(error2) {
        if (typeof error2 === "undefined") {
          throw new InvalidArgumentError("error must be defined");
        }
        const newMockDispatch = addMockDispatch(this[kDispatches], this[kDispatchKey], { error: error2 });
        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;
  }
});

// packages/cli/node_modules/undici/lib/mock/mock-client.js
var require_mock_client2 = __commonJS({
  "packages/cli/node_modules/undici/lib/mock/mock-client.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var { promisify: promisify13 } = __require("node:util");
    var Client3 = require_client3();
    var { buildMockDispatch } = require_mock_utils2();
    var {
      kDispatches,
      kMockAgent,
      kClose,
      kOriginalClose,
      kOrigin,
      kOriginalDispatch,
      kConnected
    } = require_mock_symbols2();
    var { MockInterceptor } = require_mock_interceptor2();
    var Symbols = require_symbols6();
    var { InvalidArgumentError } = require_errors5();
    var MockClient = class extends Client3 {
      static {
        __name(this, "MockClient");
      }
      constructor(origin, opts) {
        super(origin, opts);
        if (!opts || !opts.agent || typeof opts.agent.dispatch !== "function") {
          throw new InvalidArgumentError("Argument opts.agent must implement Agent");
        }
        this[kMockAgent] = opts.agent;
        this[kOrigin] = origin;
        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, this[kDispatches]);
      }
      async [kClose]() {
        await promisify13(this[kOriginalClose])();
        this[kConnected] = 0;
        this[kMockAgent][Symbols.kClients].delete(this[kOrigin]);
      }
    };
    module2.exports = MockClient;
  }
});

// packages/cli/node_modules/undici/lib/mock/mock-pool.js
var require_mock_pool2 = __commonJS({
  "packages/cli/node_modules/undici/lib/mock/mock-pool.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var { promisify: promisify13 } = __require("node:util");
    var Pool = require_pool3();
    var { buildMockDispatch } = require_mock_utils2();
    var {
      kDispatches,
      kMockAgent,
      kClose,
      kOriginalClose,
      kOrigin,
      kOriginalDispatch,
      kConnected
    } = require_mock_symbols2();
    var { MockInterceptor } = require_mock_interceptor2();
    var Symbols = require_symbols6();
    var { InvalidArgumentError } = require_errors5();
    var MockPool = class extends Pool {
      static {
        __name(this, "MockPool");
      }
      constructor(origin, opts) {
        super(origin, opts);
        if (!opts || !opts.agent || typeof opts.agent.dispatch !== "function") {
          throw new InvalidArgumentError("Argument opts.agent must implement Agent");
        }
        this[kMockAgent] = opts.agent;
        this[kOrigin] = origin;
        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, this[kDispatches]);
      }
      async [kClose]() {
        await promisify13(this[kOriginalClose])();
        this[kConnected] = 0;
        this[kMockAgent][Symbols.kClients].delete(this[kOrigin]);
      }
    };
    module2.exports = MockPool;
  }
});

// packages/cli/node_modules/undici/lib/mock/pluralizer.js
var require_pluralizer2 = __commonJS({
  "packages/cli/node_modules/undici/lib/mock/pluralizer.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var singulars = {
      pronoun: "it",
      is: "is",
      was: "was",
      this: "this"
    };
    var plurals = {
      pronoun: "they",
      is: "are",
      was: "were",
      this: "these"
    };
    module2.exports = class Pluralizer {
      static {
        __name(this, "Pluralizer");
      }
      constructor(singular, plural) {
        this.singular = singular;
        this.plural = plural;
      }
      pluralize(count) {
        const one = count === 1;
        const keys = one ? singulars : plurals;
        const noun = one ? this.singular : this.plural;
        return { ...keys, count, noun };
      }
    };
  }
});

// packages/cli/node_modules/undici/lib/mock/pending-interceptors-formatter.js
var require_pending_interceptors_formatter2 = __commonJS({
  "packages/cli/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: path125, data: { statusCode }, persist, times, timesInvoked, origin }) => ({
            Method: method,
            Origin: origin,
            Path: path125,
            "Status code": statusCode,
            Persistent: persist ? PERSISTENT : NOT_PERSISTENT,
            Invocations: timesInvoked,
            Remaining: persist ? Infinity : times - timesInvoked
          })
        );
        this.logger.table(withPrettyHeaders);
        return this.transform.read().toString();
      }
    };
  }
});

// packages/cli/node_modules/undici/lib/mock/mock-agent.js
var require_mock_agent2 = __commonJS({
  "packages/cli/node_modules/undici/lib/mock/mock-agent.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var { kClients } = require_symbols6();
    var Agent4 = require_agent3();
    var {
      kAgent,
      kMockAgentSet,
      kMockAgentGet,
      kDispatches,
      kIsMockActive,
      kNetConnect,
      kGetNetConnect,
      kOptions,
      kFactory
    } = require_mock_symbols2();
    var MockClient = require_mock_client2();
    var MockPool = require_mock_pool2();
    var { matchValue, buildMockOptions } = require_mock_utils2();
    var { InvalidArgumentError, UndiciError } = require_errors5();
    var Dispatcher = require_dispatcher2();
    var Pluralizer = require_pluralizer2();
    var PendingInterceptorsFormatter = require_pending_interceptors_formatter2();
    var MockAgent = class extends Dispatcher {
      static {
        __name(this, "MockAgent");
      }
      constructor(opts) {
        super(opts);
        this[kNetConnect] = true;
        this[kIsMockActive] = true;
        if (opts?.agent && typeof opts.agent.dispatch !== "function") {
          throw new InvalidArgumentError("Argument opts.agent must implement Agent");
        }
        const agent = opts?.agent ? opts.agent : new Agent4(opts);
        this[kAgent] = agent;
        this[kClients] = agent[kClients];
        this[kOptions] = buildMockOptions(opts);
      }
      get(origin) {
        let dispatcher = this[kMockAgentGet](origin);
        if (!dispatcher) {
          dispatcher = this[kFactory](origin);
          this[kMockAgentSet](origin, dispatcher);
        }
        return dispatcher;
      }
      dispatch(opts, handler) {
        this.get(opts.origin);
        return this[kAgent].dispatch(opts, handler);
      }
      async close() {
        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;
      }
      // This is required to bypass issues caused by using global symbols - see:
      // https://github.com/nodejs/undici/issues/1447
      get isMockActive() {
        return this[kIsMockActive];
      }
      [kMockAgentSet](origin, dispatcher) {
        this[kClients].set(origin, 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 client = this[kClients].get(origin);
        if (client) {
          return client;
        }
        if (typeof origin !== "string") {
          const dispatcher = this[kFactory]("http://localhost:9999");
          this[kMockAgentSet](origin, dispatcher);
          return dispatcher;
        }
        for (const [keyMatcher, nonExplicitDispatcher] of Array.from(this[kClients])) {
          if (nonExplicitDispatcher && typeof keyMatcher !== "string" && matchValue(keyMatcher, origin)) {
            const dispatcher = this[kFactory](origin);
            this[kMockAgentSet](origin, dispatcher);
            dispatcher[kDispatches] = nonExplicitDispatcher[kDispatches];
            return dispatcher;
          }
        }
      }
      [kGetNetConnect]() {
        return this[kNetConnect];
      }
      pendingInterceptors() {
        const mockAgentClients = this[kClients];
        return Array.from(mockAgentClients.entries()).flatMap(([origin, scope]) => scope[kDispatches].map((dispatch) => ({ ...dispatch, origin }))).filter(({ pending }) => pending);
      }
      assertNoPendingInterceptors({ pendingInterceptorsFormatter = new PendingInterceptorsFormatter() } = {}) {
        const pending = this.pendingInterceptors();
        if (pending.length === 0) {
          return;
        }
        const pluralizer = new Pluralizer("interceptor", "interceptors").pluralize(pending.length);
        throw new UndiciError(`
${pluralizer.count} ${pluralizer.noun} ${pluralizer.is} pending:

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

// packages/cli/node_modules/undici/lib/global.js
var require_global4 = __commonJS({
  "packages/cli/node_modules/undici/lib/global.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var globalDispatcher = Symbol.for("undici.globalDispatcher.1");
    var { InvalidArgumentError } = require_errors5();
    var Agent4 = require_agent3();
    if (getGlobalDispatcher() === void 0) {
      setGlobalDispatcher3(new Agent4());
    }
    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
    };
  }
});

// packages/cli/node_modules/undici/lib/handler/decorator-handler.js
var require_decorator_handler2 = __commonJS({
  "packages/cli/node_modules/undici/lib/handler/decorator-handler.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    module2.exports = class DecoratorHandler {
      static {
        __name(this, "DecoratorHandler");
      }
      #handler;
      constructor(handler) {
        if (typeof handler !== "object" || handler === null) {
          throw new TypeError("handler must be an object");
        }
        this.#handler = handler;
      }
      onConnect(...args) {
        return this.#handler.onConnect?.(...args);
      }
      onError(...args) {
        return this.#handler.onError?.(...args);
      }
      onUpgrade(...args) {
        return this.#handler.onUpgrade?.(...args);
      }
      onResponseStarted(...args) {
        return this.#handler.onResponseStarted?.(...args);
      }
      onHeaders(...args) {
        return this.#handler.onHeaders?.(...args);
      }
      onData(...args) {
        return this.#handler.onData?.(...args);
      }
      onComplete(...args) {
        return this.#handler.onComplete?.(...args);
      }
      onBodySent(...args) {
        return this.#handler.onBodySent?.(...args);
      }
    };
  }
});

// packages/cli/node_modules/undici/lib/interceptor/redirect.js
var require_redirect2 = __commonJS({
  "packages/cli/node_modules/undici/lib/interceptor/redirect.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var RedirectHandler = require_redirect_handler2();
    module2.exports = (opts) => {
      const globalMaxRedirections = opts?.maxRedirections;
      return (dispatch) => {
        return /* @__PURE__ */ __name(function redirectInterceptor(opts2, handler) {
          const { maxRedirections = globalMaxRedirections, ...baseOpts } = opts2;
          if (!maxRedirections) {
            return dispatch(opts2, handler);
          }
          const redirectHandler = new RedirectHandler(
            dispatch,
            maxRedirections,
            opts2,
            handler
          );
          return dispatch(baseOpts, redirectHandler);
        }, "redirectInterceptor");
      };
    };
  }
});

// packages/cli/node_modules/undici/lib/interceptor/retry.js
var require_retry3 = __commonJS({
  "packages/cli/node_modules/undici/lib/interceptor/retry.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var RetryHandler = require_retry_handler2();
    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");
      };
    };
  }
});

// packages/cli/node_modules/undici/lib/interceptor/dump.js
var require_dump2 = __commonJS({
  "packages/cli/node_modules/undici/lib/interceptor/dump.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var util3 = require_util22();
    var { InvalidArgumentError, RequestAbortedError } = require_errors5();
    var DecoratorHandler = require_decorator_handler2();
    var DumpHandler = class extends DecoratorHandler {
      static {
        __name(this, "DumpHandler");
      }
      #maxSize = 1024 * 1024;
      #abort = null;
      #dumped = false;
      #aborted = false;
      #size = 0;
      #reason = null;
      #handler = null;
      constructor({ maxSize }, handler) {
        super(handler);
        if (maxSize != null && (!Number.isFinite(maxSize) || maxSize < 1)) {
          throw new InvalidArgumentError("maxSize must be a number greater than 0");
        }
        this.#maxSize = maxSize ?? this.#maxSize;
        this.#handler = handler;
      }
      onConnect(abort) {
        this.#abort = abort;
        this.#handler.onConnect(this.#customAbort.bind(this));
      }
      #customAbort(reason) {
        this.#aborted = true;
        this.#reason = reason;
      }
      // TODO: will require adjustment after new hooks are out
      onHeaders(statusCode, rawHeaders, resume, statusMessage) {
        const headers = util3.parseHeaders(rawHeaders);
        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) {
          return true;
        }
        return this.#handler.onHeaders(
          statusCode,
          rawHeaders,
          resume,
          statusMessage
        );
      }
      onError(err) {
        if (this.#dumped) {
          return;
        }
        err = this.#reason ?? err;
        this.#handler.onError(err);
      }
      onData(chunk) {
        this.#size = this.#size + chunk.length;
        if (this.#size >= this.#maxSize) {
          this.#dumped = true;
          if (this.#aborted) {
            this.#handler.onError(this.#reason);
          } else {
            this.#handler.onComplete([]);
          }
        }
        return true;
      }
      onComplete(trailers) {
        if (this.#dumped) {
          return;
        }
        if (this.#aborted) {
          this.#handler.onError(this.reason);
          return;
        }
        this.#handler.onComplete(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 },
            handler
          );
          return dispatch(opts, dumpHandler);
        }, "Intercept");
      };
    }
    __name(createDumpInterceptor, "createDumpInterceptor");
    module2.exports = createDumpInterceptor;
  }
});

// packages/cli/node_modules/undici/lib/interceptor/dns.js
var require_dns2 = __commonJS({
  "packages/cli/node_modules/undici/lib/interceptor/dns.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var { isIP: isIP3 } = __require("node:net");
    var { lookup } = __require("node:dns");
    var DecoratorHandler = require_decorator_handler2();
    var { InvalidArgumentError, InformationalError } = require_errors5();
    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.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,
              `${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,
            `${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;
      }
      setRecords(origin, addresses) {
        const timestamp = Date.now();
        const records = { records: { 4: null, 6: null } };
        for (const record2 of addresses) {
          record2.timestamp = timestamp;
          if (typeof record2.ttl === "number") {
            record2.ttl = Math.min(record2.ttl, this.#maxTTL);
          } else {
            record2.ttl = this.#maxTTL;
          }
          const familyRecords = records.records[record2.family] ?? { ips: [] };
          familyRecords.ips.push(record2);
          records.records[record2.family] = familyRecords;
        }
        this.#records.set(origin.hostname, records);
      }
      getHandler(meta, opts) {
        return new DNSDispatchHandler(this, meta, opts);
      }
    };
    var DNSDispatchHandler = class extends DecoratorHandler {
      static {
        __name(this, "DNSDispatchHandler");
      }
      #state = null;
      #opts = null;
      #dispatch = null;
      #handler = null;
      #origin = null;
      constructor(state, { origin, handler, dispatch }, opts) {
        super(handler);
        this.#origin = origin;
        this.#handler = handler;
        this.#opts = { ...opts };
        this.#state = state;
        this.#dispatch = dispatch;
      }
      onError(err) {
        switch (err.code) {
          case "ETIMEDOUT":
          case "ECONNREFUSED": {
            if (this.#state.dualStack) {
              this.#state.runLookup(this.#origin, this.#opts, (err2, newOrigin) => {
                if (err2) {
                  return this.#handler.onError(err2);
                }
                const dispatchOpts = {
                  ...this.#opts,
                  origin: newOrigin
                };
                this.#dispatch(dispatchOpts, this);
              });
              return;
            }
            this.#handler.onError(err);
            return;
          }
          case "ENOTFOUND":
            this.#state.deleteRecord(this.#origin);
          // eslint-disable-next-line no-fallthrough
          default:
            this.#handler.onError(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 (isIP3(origin.hostname) !== 0) {
            return dispatch(origDispatchOpts, handler);
          }
          instance.runLookup(origin, origDispatchOpts, (err, newOrigin) => {
            if (err) {
              return handler.onError(err);
            }
            let dispatchOpts = null;
            dispatchOpts = {
              ...origDispatchOpts,
              servername: origin.hostname,
              // For SNI on TLS
              origin: newOrigin,
              headers: {
                host: origin.hostname,
                ...origDispatchOpts.headers
              }
            };
            dispatch(
              dispatchOpts,
              instance.getHandler({ origin, dispatch, handler }, origDispatchOpts)
            );
          });
          return true;
        }, "dnsInterceptor");
      };
    };
  }
});

// packages/cli/node_modules/undici/lib/web/fetch/headers.js
var require_headers2 = __commonJS({
  "packages/cli/node_modules/undici/lib/web/fetch/headers.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var { kConstruct } = require_symbols6();
    var { kEnumerableProperty } = require_util22();
    var {
      iteratorMixin,
      isValidHeaderName,
      isValidHeaderValue
    } = require_util23();
    var { webidl } = require_webidl2();
    var assert4 = __require("node:assert");
    var util3 = __require("node:util");
    var kHeadersMap = Symbol("headers map");
    var kHeadersSortedMap = Symbol("headers map sorted");
    function isHTTPWhiteSpaceCharCode(code2) {
      return code2 === 10 || code2 === 13 || code2 === 9 || code2 === 32;
    }
    __name(isHTTPWhiteSpaceCharCode, "isHTTPWhiteSpaceCharCode");
    function headerValueNormalize(potentialValue) {
      let i3 = 0;
      let j2 = potentialValue.length;
      while (j2 > i3 && isHTTPWhiteSpaceCharCode(potentialValue.charCodeAt(j2 - 1))) --j2;
      while (j2 > i3 && isHTTPWhiteSpaceCharCode(potentialValue.charCodeAt(i3))) ++i3;
      return i3 === 0 && j2 === potentialValue.length ? potentialValue : potentialValue.substring(i3, j2);
    }
    __name(headerValueNormalize, "headerValueNormalize");
    function fill(headers, object3) {
      if (Array.isArray(object3)) {
        for (let i3 = 0; i3 < object3.length; ++i3) {
          const header = object3[i3];
          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 object3 === "object" && object3 !== null) {
        const keys = Object.keys(object3);
        for (let i3 = 0; i3 < keys.length; ++i3) {
          appendHeader(headers, keys[i3], object3[keys[i3]]);
        }
      } 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 compareHeaderName(a2, b2) {
      return a2[0] < b2[0] ? -1 : 1;
    }
    __name(compareHeaderName, "compareHeaderName");
    var HeadersList = class _HeadersList {
      static {
        __name(this, "HeadersList");
      }
      /** @type {[string, string][]|null} */
      cookies = null;
      constructor(init) {
        if (init instanceof _HeadersList) {
          this[kHeadersMap] = new Map(init[kHeadersMap]);
          this[kHeadersSortedMap] = init[kHeadersSortedMap];
          this.cookies = init.cookies === null ? null : [...init.cookies];
        } else {
          this[kHeadersMap] = new Map(init);
          this[kHeadersSortedMap] = null;
        }
      }
      /**
       * @see https://fetch.spec.whatwg.org/#header-list-contains
       * @param {string} name
       * @param {boolean} isLowerCase
       */
      contains(name3, isLowerCase) {
        return this[kHeadersMap].has(isLowerCase ? name3 : name3.toLowerCase());
      }
      clear() {
        this[kHeadersMap].clear();
        this[kHeadersSortedMap] = 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[kHeadersSortedMap] = null;
        const lowercaseName = isLowerCase ? name3 : name3.toLowerCase();
        const exists2 = this[kHeadersMap].get(lowercaseName);
        if (exists2) {
          const delimiter2 = lowercaseName === "cookie" ? "; " : ", ";
          this[kHeadersMap].set(lowercaseName, {
            name: exists2.name,
            value: `${exists2.value}${delimiter2}${value}`
          });
        } else {
          this[kHeadersMap].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[kHeadersSortedMap] = null;
        const lowercaseName = isLowerCase ? name3 : name3.toLowerCase();
        if (lowercaseName === "set-cookie") {
          this.cookies = [value];
        }
        this[kHeadersMap].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[kHeadersSortedMap] = null;
        if (!isLowerCase) name3 = name3.toLowerCase();
        if (name3 === "set-cookie") {
          this.cookies = null;
        }
        this[kHeadersMap].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[kHeadersMap].get(isLowerCase ? name3 : name3.toLowerCase())?.value ?? null;
      }
      *[Symbol.iterator]() {
        for (const { 0: name3, 1: { value } } of this[kHeadersMap]) {
          yield [name3, value];
        }
      }
      get entries() {
        const headers = {};
        if (this[kHeadersMap].size !== 0) {
          for (const { name: name3, value } of this[kHeadersMap].values()) {
            headers[name3] = value;
          }
        }
        return headers;
      }
      rawValues() {
        return this[kHeadersMap].values();
      }
      get entriesList() {
        const headers = [];
        if (this[kHeadersMap].size !== 0) {
          for (const { 0: lowerName, 1: { name: name3, value } } of this[kHeadersMap]) {
            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[kHeadersMap].size;
        const array2 = new Array(size);
        if (size <= 32) {
          if (size === 0) {
            return array2;
          }
          const iterator = this[kHeadersMap][Symbol.iterator]();
          const firstValue = iterator.next().value;
          array2[0] = [firstValue[0], firstValue[1].value];
          assert4(firstValue[1].value !== null);
          for (let i3 = 1, j2 = 0, right3 = 0, left3 = 0, pivot = 0, x3, value; i3 < size; ++i3) {
            value = iterator.next().value;
            x3 = array2[i3] = [value[0], value[1].value];
            assert4(x3[1] !== null);
            left3 = 0;
            right3 = i3;
            while (left3 < right3) {
              pivot = left3 + (right3 - left3 >> 1);
              if (array2[pivot][0] <= x3[0]) {
                left3 = pivot + 1;
              } else {
                right3 = pivot;
              }
            }
            if (i3 !== pivot) {
              j2 = i3;
              while (j2 > left3) {
                array2[j2] = array2[--j2];
              }
              array2[left3] = x3;
            }
          }
          if (!iterator.next().done) {
            throw new TypeError("Unreachable");
          }
          return array2;
        } else {
          let i3 = 0;
          for (const { 0: name3, 1: { value } } of this[kHeadersMap]) {
            array2[i3++] = [name3, value];
            assert4(value !== null);
          }
          return array2.sort(compareHeaderName);
        }
      }
    };
    var Headers6 = class _Headers {
      static {
        __name(this, "Headers");
      }
      #guard;
      #headersList;
      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 contructor", "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 [];
      }
      // https://fetch.spec.whatwg.org/#concept-header-list-sort-and-combine
      get [kHeadersSortedMap]() {
        if (this.#headersList[kHeadersSortedMap]) {
          return this.#headersList[kHeadersSortedMap];
        }
        const headers = [];
        const names = this.#headersList.toSortedArray();
        const cookies = this.#headersList.cookies;
        if (cookies === null || cookies.length === 1) {
          return this.#headersList[kHeadersSortedMap] = names;
        }
        for (let i3 = 0; i3 < names.length; ++i3) {
          const { 0: name3, 1: value } = names[i3];
          if (name3 === "set-cookie") {
            for (let j2 = 0; j2 < cookies.length; ++j2) {
              headers.push([name3, cookies[j2]]);
            }
          } else {
            headers.push([name3, value]);
          }
        }
        return this.#headersList[kHeadersSortedMap] = headers;
      }
      [util3.inspect.custom](depth, options2) {
        options2.depth ??= depth;
        return `Headers ${util3.formatWithOptions(options2, this.#headersList.entries)}`;
      }
      static getHeadersGuard(o3) {
        return o3.#guard;
      }
      static setHeadersGuard(o3, guard) {
        o3.#guard = guard;
      }
      static getHeadersList(o3) {
        return o3.#headersList;
      }
      static setHeadersList(o3, list3) {
        o3.#headersList = list3;
      }
    };
    var { getHeadersGuard, setHeadersGuard, getHeadersList, setHeadersList } = Headers6;
    Reflect.deleteProperty(Headers6, "getHeadersGuard");
    Reflect.deleteProperty(Headers6, "setHeadersGuard");
    Reflect.deleteProperty(Headers6, "getHeadersList");
    Reflect.deleteProperty(Headers6, "setHeadersList");
    iteratorMixin("Headers", Headers6, kHeadersSortedMap, 0, 1);
    Object.defineProperties(Headers6.prototype, {
      append: kEnumerableProperty,
      delete: kEnumerableProperty,
      get: kEnumerableProperty,
      has: kEnumerableProperty,
      set: kEnumerableProperty,
      getSetCookie: kEnumerableProperty,
      [Symbol.toStringTag]: {
        value: "Headers",
        configurable: true
      },
      [util3.inspect.custom]: {
        enumerable: false
      }
    });
    webidl.converters.HeadersInit = function(V3, prefix, argument) {
      if (webidl.util.Type(V3) === "Object") {
        const iterator = Reflect.get(V3, Symbol.iterator);
        if (!util3.types.isProxy(V3) && iterator === Headers6.prototype.entries) {
          try {
            return getHeadersList(V3).entriesList;
          } catch {
          }
        }
        if (typeof iterator === "function") {
          return webidl.converters["sequence<sequence<ByteString>>"](V3, prefix, argument, iterator.bind(V3));
        }
        return webidl.converters["record<ByteString, ByteString>"](V3, 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: Headers6,
      HeadersList,
      getHeadersGuard,
      setHeadersGuard,
      setHeadersList,
      getHeadersList
    };
  }
});

// packages/cli/node_modules/undici/lib/web/fetch/response.js
var require_response2 = __commonJS({
  "packages/cli/node_modules/undici/lib/web/fetch/response.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var { Headers: Headers6, HeadersList, fill, getHeadersGuard, setHeadersGuard, setHeadersList } = require_headers2();
    var { extractBody, cloneBody, mixinBody, hasFinalizationRegistry, streamRegistry, bodyUnusable } = require_body2();
    var util3 = require_util22();
    var nodeUtil = __require("node:util");
    var { kEnumerableProperty } = util3;
    var {
      isValidReasonPhrase,
      isCancelled,
      isAborted: isAborted2,
      isBlobLike: isBlobLike3,
      serializeJavascriptValueToJSONString,
      isErrorLike,
      isomorphicEncode,
      environmentSettingsObject: relevantRealm
    } = require_util23();
    var {
      redirectStatusSet,
      nullBodyStatus
    } = require_constants16();
    var { kState, kHeaders } = require_symbols7();
    var { webidl } = require_webidl2();
    var { FormData: FormData6 } = require_formdata2();
    var { URLSerializer } = require_data_url2();
    var { kConstruct } = require_symbols6();
    var assert4 = __require("node:assert");
    var { types: types7 } = __require("node:util");
    var textEncoder = new TextEncoder("utf-8");
    var Response6 = class _Response {
      static {
        __name(this, "Response");
      }
      // 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 = {}) {
        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[kState].status = status;
        const value = isomorphicEncode(URLSerializer(parsedURL));
        responseObject[kState].headersList.append("location", value, true);
        return responseObject;
      }
      // https://fetch.spec.whatwg.org/#dom-response
      constructor(body = null, init = {}) {
        webidl.util.markAsUncloneable(this);
        if (body === kConstruct) {
          return;
        }
        if (body !== null) {
          body = webidl.converters.BodyInit(body);
        }
        init = webidl.converters.ResponseInit(init);
        this[kState] = makeResponse({});
        this[kHeaders] = new Headers6(kConstruct);
        setHeadersGuard(this[kHeaders], "response");
        setHeadersList(this[kHeaders], this[kState].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[kState].type;
      }
      // Returns response’s URL, if it has one; otherwise the empty string.
      get url() {
        webidl.brandCheck(this, _Response);
        const urlList = this[kState].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[kState].urlList.length > 1;
      }
      // Returns response’s status.
      get status() {
        webidl.brandCheck(this, _Response);
        return this[kState].status;
      }
      // Returns whether response’s status is an ok status.
      get ok() {
        webidl.brandCheck(this, _Response);
        return this[kState].status >= 200 && this[kState].status <= 299;
      }
      // Returns response’s status message.
      get statusText() {
        webidl.brandCheck(this, _Response);
        return this[kState].statusText;
      }
      // Returns response’s headers as Headers.
      get headers() {
        webidl.brandCheck(this, _Response);
        return this[kHeaders];
      }
      get body() {
        webidl.brandCheck(this, _Response);
        return this[kState].body ? this[kState].body.stream : null;
      }
      get bodyUsed() {
        webidl.brandCheck(this, _Response);
        return !!this[kState].body && util3.isDisturbed(this[kState].body.stream);
      }
      // Returns a clone of response.
      clone() {
        webidl.brandCheck(this, _Response);
        if (bodyUnusable(this)) {
          throw webidl.errors.exception({
            header: "Response.clone",
            message: "Body has already been consumed."
          });
        }
        const clonedResponse = cloneResponse(this[kState]);
        if (hasFinalizationRegistry && this[kState].body?.stream) {
          streamRegistry.register(this, new WeakRef(this[kState].body.stream));
        }
        return fromInnerResponse(clonedResponse, getHeadersGuard(this[kHeaders]));
      }
      [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)}`;
      }
    };
    mixinBody(Response6);
    Object.defineProperties(Response6.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(Response6, {
      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(newResponse, 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, p2) {
          return p2 in state ? state[p2] : target[p2];
        },
        set(target, p2, value) {
          assert4(!(p2 in state));
          target[p2] = 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 {
        assert4(false);
      }
    }
    __name(filterResponse, "filterResponse");
    function makeAppropriateNetworkError(fetchParams, err = null) {
      assert4(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) {
        response[kState].status = init.status;
      }
      if ("statusText" in init && init.statusText != null) {
        response[kState].statusText = init.statusText;
      }
      if ("headers" in init && init.headers != null) {
        fill(response[kHeaders], init.headers);
      }
      if (body) {
        if (nullBodyStatus.includes(response.status)) {
          throw webidl.errors.exception({
            header: "Response constructor",
            message: `Invalid response status code ${response.status}`
          });
        }
        response[kState].body = body.body;
        if (body.type != null && !response[kState].headersList.contains("content-type", true)) {
          response[kState].headersList.append("content-type", body.type, true);
        }
      }
    }
    __name(initializeResponse, "initializeResponse");
    function fromInnerResponse(innerResponse, guard) {
      const response = new Response6(kConstruct);
      response[kState] = innerResponse;
      response[kHeaders] = new Headers6(kConstruct);
      setHeadersList(response[kHeaders], innerResponse.headersList);
      setHeadersGuard(response[kHeaders], guard);
      if (hasFinalizationRegistry && innerResponse.body?.stream) {
        streamRegistry.register(response, new WeakRef(innerResponse.body.stream));
      }
      return response;
    }
    __name(fromInnerResponse, "fromInnerResponse");
    webidl.converters.ReadableStream = webidl.interfaceConverter(
      ReadableStream
    );
    webidl.converters.FormData = webidl.interfaceConverter(
      FormData6
    );
    webidl.converters.URLSearchParams = webidl.interfaceConverter(
      URLSearchParams
    );
    webidl.converters.XMLHttpRequestBodyInit = function(V3, prefix, name3) {
      if (typeof V3 === "string") {
        return webidl.converters.USVString(V3, prefix, name3);
      }
      if (isBlobLike3(V3)) {
        return webidl.converters.Blob(V3, prefix, name3, { strict: false });
      }
      if (ArrayBuffer.isView(V3) || types7.isArrayBuffer(V3)) {
        return webidl.converters.BufferSource(V3, prefix, name3);
      }
      if (util3.isFormDataLike(V3)) {
        return webidl.converters.FormData(V3, prefix, name3, { strict: false });
      }
      if (V3 instanceof URLSearchParams) {
        return webidl.converters.URLSearchParams(V3, prefix, name3);
      }
      return webidl.converters.DOMString(V3, prefix, name3);
    };
    webidl.converters.BodyInit = function(V3, prefix, argument) {
      if (V3 instanceof ReadableStream) {
        return webidl.converters.ReadableStream(V3, prefix, argument);
      }
      if (V3?.[Symbol.asyncIterator]) {
        return V3;
      }
      return webidl.converters.XMLHttpRequestBodyInit(V3, 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
      }
    ]);
    module2.exports = {
      isNetworkError,
      makeNetworkError,
      makeResponse,
      makeAppropriateNetworkError,
      filterResponse,
      Response: Response6,
      cloneResponse,
      fromInnerResponse
    };
  }
});

// packages/cli/node_modules/undici/lib/web/fetch/dispatcher-weakref.js
var require_dispatcher_weakref2 = __commonJS({
  "packages/cli/node_modules/undici/lib/web/fetch/dispatcher-weakref.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var { kConnected, kSize } = require_symbols6();
    var CompatWeakRef = class {
      static {
        __name(this, "CompatWeakRef");
      }
      constructor(value) {
        this.value = value;
      }
      deref() {
        return this.value[kConnected] === 0 && this.value[kSize] === 0 ? void 0 : this.value;
      }
    };
    var CompatFinalizer = class {
      static {
        __name(this, "CompatFinalizer");
      }
      constructor(finalizer) {
        this.finalizer = finalizer;
      }
      register(dispatcher, key) {
        if (dispatcher.on) {
          dispatcher.on("disconnect", () => {
            if (dispatcher[kConnected] === 0 && dispatcher[kSize] === 0) {
              this.finalizer(key);
            }
          });
        }
      }
      unregister(key) {
      }
    };
    module2.exports = function() {
      if (process.env.NODE_V8_COVERAGE && process.version.startsWith("v18")) {
        process._rawDebug("Using compatibility WeakRef and FinalizationRegistry");
        return {
          WeakRef: CompatWeakRef,
          FinalizationRegistry: CompatFinalizer
        };
      }
      return { WeakRef, FinalizationRegistry };
    };
  }
});

// packages/cli/node_modules/undici/lib/web/fetch/request.js
var require_request4 = __commonJS({
  "packages/cli/node_modules/undici/lib/web/fetch/request.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var { extractBody, mixinBody, cloneBody, bodyUnusable } = require_body2();
    var { Headers: Headers6, fill: fillHeaders, HeadersList, setHeadersGuard, getHeadersGuard, setHeadersList, getHeadersList } = require_headers2();
    var { FinalizationRegistry: FinalizationRegistry2 } = require_dispatcher_weakref2()();
    var util3 = require_util22();
    var nodeUtil = __require("node:util");
    var {
      isValidHTTPToken,
      sameOrigin,
      environmentSettingsObject
    } = require_util23();
    var {
      forbiddenMethodsSet,
      corsSafeListedMethodsSet,
      referrerPolicy,
      requestRedirect,
      requestMode,
      requestCredentials,
      requestCache,
      requestDuplex
    } = require_constants16();
    var { kEnumerableProperty, normalizedMethodRecordsBase, normalizedMethodRecords } = util3;
    var { kHeaders, kSignal, kState, kDispatcher } = require_symbols7();
    var { webidl } = require_webidl2();
    var { URLSerializer } = require_data_url2();
    var { kConstruct } = require_symbols6();
    var assert4 = __require("node:assert");
    var { getMaxListeners, setMaxListeners, getEventListeners, defaultMaxListeners } = __require("node:events");
    var kAbortController = Symbol("abortController");
    var requestFinalizer = new FinalizationRegistry2(({ signal, abort }) => {
      signal.removeEventListener("abort", abort);
    });
    var dependentControllerMap = /* @__PURE__ */ new WeakMap();
    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 Request6 = class _Request {
      static {
        __name(this, "Request");
      }
      // https://fetch.spec.whatwg.org/#dom-request
      constructor(input, init = {}) {
        webidl.util.markAsUncloneable(this);
        if (input === kConstruct) {
          return;
        }
        const prefix = "Request constructor";
        webidl.argumentLengthCheck(arguments, 1, prefix);
        input = webidl.converters.RequestInfo(input, prefix, "input");
        init = webidl.converters.RequestInit(init, prefix, "init");
        let request4 = null;
        let fallbackMode = null;
        const baseUrl = environmentSettingsObject.settingsObject.baseUrl;
        let signal = null;
        if (typeof input === "string") {
          this[kDispatcher] = 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 {
          this[kDispatcher] = init.dispatcher || input[kDispatcher];
          assert4(input instanceof _Request);
          request4 = input[kState];
          signal = input[kSignal];
        }
        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[kState] = request4;
        const ac = new AbortController();
        this[kSignal] = ac.signal;
        if (signal != null) {
          if (!signal || typeof signal.aborted !== "boolean" || typeof signal.addEventListener !== "function") {
            throw new TypeError(
              "Failed to construct 'Request': member signal is not of type AbortSignal."
            );
          }
          if (signal.aborted) {
            ac.abort(signal.reason);
          } else {
            this[kAbortController] = ac;
            const acRef = new WeakRef(ac);
            const abort = buildAbort(acRef);
            try {
              if (typeof getMaxListeners === "function" && getMaxListeners(signal) === defaultMaxListeners) {
                setMaxListeners(1500, signal);
              } else if (getEventListeners(signal, "abort").length >= defaultMaxListeners) {
                setMaxListeners(1500, signal);
              }
            } catch {
            }
            util3.addAbortListener(signal, abort);
            requestFinalizer.register(ac, { signal, abort }, abort);
          }
        }
        this[kHeaders] = new Headers6(kConstruct);
        setHeadersList(this[kHeaders], request4.headersList);
        setHeadersGuard(this[kHeaders], "request");
        if (mode === "no-cors") {
          if (!corsSafeListedMethodsSet.has(request4.method)) {
            throw new TypeError(
              `'${request4.method} is unsupported in no-cors mode.`
            );
          }
          setHeadersGuard(this[kHeaders], "request-no-cors");
        }
        if (initHasKey) {
          const headersList = getHeadersList(this[kHeaders]);
          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[kHeaders], headers);
          }
        }
        const inputBody = input instanceof _Request ? input[kState].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[kHeaders]).contains("content-type", true)) {
            this[kHeaders].append("content-type", contentType);
          }
        }
        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)) {
            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[kState].body = finalBody;
      }
      // Returns request’s HTTP method, which is "GET" by default.
      get method() {
        webidl.brandCheck(this, _Request);
        return this[kState].method;
      }
      // Returns the URL of request as a string.
      get url() {
        webidl.brandCheck(this, _Request);
        return URLSerializer(this[kState].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[kHeaders];
      }
      // Returns the kind of resource requested by request, e.g., "document"
      // or "script".
      get destination() {
        webidl.brandCheck(this, _Request);
        return this[kState].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[kState].referrer === "no-referrer") {
          return "";
        }
        if (this[kState].referrer === "client") {
          return "about:client";
        }
        return this[kState].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[kState].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[kState].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() {
        return this[kState].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[kState].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[kState].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[kState].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[kState].keepalive;
      }
      // Returns a boolean indicating whether or not request is for a reload
      // navigation.
      get isReloadNavigation() {
        webidl.brandCheck(this, _Request);
        return this[kState].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[kState].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[kSignal];
      }
      get body() {
        webidl.brandCheck(this, _Request);
        return this[kState].body ? this[kState].body.stream : null;
      }
      get bodyUsed() {
        webidl.brandCheck(this, _Request);
        return !!this[kState].body && util3.isDisturbed(this[kState].body.stream);
      }
      get duplex() {
        webidl.brandCheck(this, _Request);
        return "half";
      }
      // Returns a clone of request.
      clone() {
        webidl.brandCheck(this, _Request);
        if (bodyUnusable(this)) {
          throw new TypeError("unusable");
        }
        const clonedRequest = cloneRequest(this[kState]);
        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);
          util3.addAbortListener(
            ac.signal,
            buildAbort(acRef)
          );
        }
        return fromInnerRequest(clonedRequest, ac.signal, getHeadersGuard(this[kHeaders]));
      }
      [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)}`;
      }
    };
    mixinBody(Request6);
    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(newRequest, request4.body);
      }
      return newRequest;
    }
    __name(cloneRequest, "cloneRequest");
    function fromInnerRequest(innerRequest, signal, guard) {
      const request4 = new Request6(kConstruct);
      request4[kState] = innerRequest;
      request4[kSignal] = signal;
      request4[kHeaders] = new Headers6(kConstruct);
      setHeadersList(request4[kHeaders], innerRequest.headersList);
      setHeadersGuard(request4[kHeaders], guard);
      return request4;
    }
    __name(fromInnerRequest, "fromInnerRequest");
    Object.defineProperties(Request6.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.converters.Request = webidl.interfaceConverter(
      Request6
    );
    webidl.converters.RequestInfo = function(V3, prefix, argument) {
      if (typeof V3 === "string") {
        return webidl.converters.USVString(V3, prefix, argument);
      }
      if (V3 instanceof Request6) {
        return webidl.converters.Request(V3, prefix, argument);
      }
      return webidl.converters.USVString(V3, prefix, argument);
    };
    webidl.converters.AbortSignal = webidl.interfaceConverter(
      AbortSignal
    );
    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",
            { strict: false }
          )
        )
      },
      {
        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: Request6, makeRequest, fromInnerRequest, cloneRequest };
  }
});

// packages/cli/node_modules/undici/lib/web/fetch/index.js
var require_fetch3 = __commonJS({
  "packages/cli/node_modules/undici/lib/web/fetch/index.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var {
      makeNetworkError,
      makeAppropriateNetworkError,
      filterResponse,
      makeResponse,
      fromInnerResponse
    } = require_response2();
    var { HeadersList } = require_headers2();
    var { Request: Request6, cloneRequest } = require_request4();
    var zlib4 = __require("node:zlib");
    var {
      bytesMatch,
      makePolicyContainer,
      clonePolicyContainer,
      requestBadPort,
      TAOCheck,
      appendRequestOriginHeader,
      responseLocationURL,
      requestCurrentURL,
      setRequestReferrerPolicyOnRedirect,
      tryUpgradeRequestToAPotentiallyTrustworthyURL,
      createOpaqueTimingInfo,
      appendFetchMetadata,
      corsCheck,
      crossOriginResourcePolicyCheck,
      determineRequestsReferrer: determineRequestsReferrer3,
      coarsenedSharedCurrentTime,
      createDeferredPromise,
      isBlobLike: isBlobLike3,
      sameOrigin,
      isCancelled,
      isAborted: isAborted2,
      isErrorLike,
      fullyReadBody,
      readableStreamClose,
      isomorphicEncode,
      urlIsLocal,
      urlIsHttpHttpsScheme,
      urlHasHttpsScheme,
      clampAndCoarsenConnectionTimingInfo,
      simpleRangeHeaderValue,
      buildContentRange,
      createInflate,
      extractMimeType
    } = require_util23();
    var { kState, kDispatcher } = require_symbols7();
    var assert4 = __require("node:assert");
    var { safelyExtractBody, extractBody } = require_body2();
    var {
      redirectStatusSet,
      nullBodyStatus,
      safeMethodsSet,
      requestBodyHeader,
      subresourceSet
    } = require_constants16();
    var EE3 = __require("node:events");
    var { Readable: Readable6, pipeline: pipeline3, finished: finished2 } = __require("node:stream");
    var { addAbortListener, isErrored, isReadable: isReadable2, bufferToLowerCasedHeaderName } = require_util22();
    var { dataURLProcessor, serializeAMimeType, minimizeSupportedMimeType } = require_data_url2();
    var { getGlobalDispatcher } = require_global4();
    var { webidl } = require_webidl2();
    var { STATUS_CODES } = __require("node:http");
    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(error2) {
        if (this.state !== "ongoing") {
          return;
        }
        this.state = "aborted";
        if (!error2) {
          error2 = new DOMException("The operation was aborted.", "AbortError");
        }
        this.serializedAbortReason = error2;
        this.connection?.destroy(error2);
        this.emit("terminated", error2);
      }
    };
    function handleFetchDone(response) {
      finalizeAndReportTiming(response, "fetch");
    }
    __name(handleFetchDone, "handleFetchDone");
    function fetch5(input, init = void 0) {
      webidl.argumentLengthCheck(arguments, 1, "globalThis.fetch");
      let p2 = createDeferredPromise();
      let requestObject;
      try {
        requestObject = new Request6(input, init);
      } catch (e4) {
        p2.reject(e4);
        return p2.promise;
      }
      const request4 = requestObject[kState];
      if (requestObject.signal.aborted) {
        abortFetch(p2, request4, null, requestObject.signal.reason);
        return p2.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;
          assert4(controller != null);
          controller.abort(requestObject.signal.reason);
          const realResponse = responseObject?.deref();
          abortFetch(p2, request4, realResponse, requestObject.signal.reason);
        }
      );
      const processResponse = /* @__PURE__ */ __name((response) => {
        if (locallyAborted) {
          return;
        }
        if (response.aborted) {
          abortFetch(p2, request4, responseObject, controller.serializedAbortReason);
          return;
        }
        if (response.type === "error") {
          p2.reject(new TypeError("fetch failed", { cause: response.error }));
          return;
        }
        responseObject = new WeakRef(fromInnerResponse(response, "immutable"));
        p2.resolve(responseObject.deref());
        p2 = null;
      }, "processResponse");
      controller = fetching({
        request: request4,
        processResponseEndOfBody: handleFetchDone,
        processResponse,
        dispatcher: requestObject[kDispatcher]
        // undici
      });
      return p2.promise;
    }
    __name(fetch5, "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
      );
    }
    __name(finalizeAndReportTiming, "finalizeAndReportTiming");
    var markResourceTiming = performance.markResourceTiming;
    function abortFetch(p2, request4, responseObject, error2) {
      if (p2) {
        p2.reject(error2);
      }
      if (request4.body != null && isReadable2(request4.body?.stream)) {
        request4.body.stream.cancel(error2).catch((err) => {
          if (err.code === "ERR_INVALID_STATE") {
            return;
          }
          throw err;
        });
      }
      if (responseObject == null) {
        return;
      }
      const response = responseObject[kState];
      if (response.body != null && isReadable2(response.body?.stream)) {
        response.body.stream.cancel(error2).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
    }) {
      assert4(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
      };
      assert4(!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).catch((err) => {
        fetchParams.controller.terminate(err);
      });
      return fetchParams.controller;
    }
    __name(fetching, "fetching");
    async function mainFetch(fetchParams, recursive = false) {
      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 = determineRequestsReferrer3(request4);
      }
      if (response === null) {
        response = await (async () => {
          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";
            return await schemeFetch(fetchParams);
          }
          if (request4.mode === "same-origin") {
            return makeNetworkError('request mode cannot be "same-origin"');
          }
          if (request4.mode === "no-cors") {
            if (request4.redirect !== "follow") {
              return makeNetworkError(
                'redirect mode cannot be "follow" for "no-cors" request'
              );
            }
            request4.responseTainting = "opaque";
            return await schemeFetch(fetchParams);
          }
          if (!urlIsHttpHttpsScheme(requestCurrentURL(request4))) {
            return makeNetworkError("URL scheme must be a HTTP(S) scheme");
          }
          request4.responseTainting = "cors";
          return 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 {
          assert4(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");
        await fullyReadBody(response.body, processBody, processBodyError);
      } else {
        fetchFinale(fetchParams, response);
      }
    }
    __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" || !isBlobLike3(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 (fetchParams.request.url.protocol !== "https:") {
            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 {
        finished2(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 {
          assert4(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) {
        assert4(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 (httpRequest.referrer instanceof URL) {
        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);
      }
      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) {
      assert4(!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((e4) => {
          if (isCancelled(fetchParams)) {
            return;
          }
          if (e4.name === "AbortError") {
            fetchParams.controller.abort();
          } else {
            fetchParams.controller.terminate(e4);
          }
        }, "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(async () => {
        await fetchParams.controller.resume();
      }, "pullAlgorithm");
      const cancelAlgorithm = /* @__PURE__ */ __name((reason) => {
        if (!isCancelled(fetchParams)) {
          fetchParams.controller.abort(reason);
        }
      }, "cancelAlgorithm");
      const stream2 = new ReadableStream(
        {
          async start(controller) {
            fetchParams.controller.controller = controller;
          },
          async pull(controller) {
            await pullAlgorithm(controller);
          },
          async cancel(reason) {
            await cancelAlgorithm(reason);
          },
          type: "bytes"
        }
      );
      response.body = { stream: stream2, source: null, length: null };
      fetchParams.controller.onAborted = onAborted;
      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((resolve30, 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;
              }
              let codings = [];
              let location = "";
              const headersList = new HeadersList();
              for (let i3 = 0; i3 < rawHeaders.length; i3 += 2) {
                headersList.append(bufferToLowerCasedHeaderName(rawHeaders[i3]), rawHeaders[i3 + 1].toString("latin1"), true);
              }
              const contentEncoding = headersList.get("content-encoding", true);
              if (contentEncoding) {
                codings = contentEncoding.toLowerCase().split(",").map((x3) => x3.trim());
              }
              location = headersList.get("location", true);
              this.body = new Readable6({ 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 i3 = codings.length - 1; i3 >= 0; --i3) {
                  const coding = codings[i3];
                  if (coding === "x-gzip" || coding === "gzip") {
                    decoders.push(zlib4.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: zlib4.constants.Z_SYNC_FLUSH,
                      finishFlush: zlib4.constants.Z_SYNC_FLUSH
                    }));
                  } else if (coding === "deflate") {
                    decoders.push(createInflate({
                      flush: zlib4.constants.Z_SYNC_FLUSH,
                      finishFlush: zlib4.constants.Z_SYNC_FLUSH
                    }));
                  } else if (coding === "br") {
                    decoders.push(zlib4.createBrotliDecompress({
                      flush: zlib4.constants.BROTLI_OPERATION_FLUSH,
                      finishFlush: zlib4.constants.BROTLI_OPERATION_FLUSH
                    }));
                  } else {
                    decoders.length = 0;
                    break;
                  }
                }
              }
              const onError2 = this.onError.bind(this);
              resolve30({
                status,
                statusText,
                headersList,
                body: decoders.length ? pipeline3(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);
              }
              if (fetchParams.controller.onAborted) {
                fetchParams.controller.off("terminated", fetchParams.controller.onAborted);
              }
              fetchParams.controller.ended = true;
              this.body.push(null);
            },
            onError(error2) {
              if (this.abort) {
                fetchParams.controller.off("terminated", this.abort);
              }
              this.body?.destroy(error2);
              fetchParams.controller.terminate(error2);
              reject(error2);
            },
            onUpgrade(status, rawHeaders, socket) {
              if (status !== 101) {
                return;
              }
              const headersList = new HeadersList();
              for (let i3 = 0; i3 < rawHeaders.length; i3 += 2) {
                headersList.append(bufferToLowerCasedHeaderName(rawHeaders[i3]), rawHeaders[i3 + 1].toString("latin1"), true);
              }
              resolve30({
                status,
                statusText: STATUS_CODES[status],
                headersList,
                socket
              });
              return true;
            }
          }
        ));
      }
      __name(dispatch, "dispatch");
    }
    __name(httpNetworkFetch, "httpNetworkFetch");
    module2.exports = {
      fetch: fetch5,
      Fetch,
      fetching,
      finalizeAndReportTiming
    };
  }
});

// packages/cli/node_modules/undici/lib/web/fileapi/symbols.js
var require_symbols8 = __commonJS({
  "packages/cli/node_modules/undici/lib/web/fileapi/symbols.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    module2.exports = {
      kState: Symbol("FileReader state"),
      kResult: Symbol("FileReader result"),
      kError: Symbol("FileReader error"),
      kLastProgressEventFired: Symbol("FileReader last progress event fired timestamp"),
      kEvents: Symbol("FileReader events"),
      kAborted: Symbol("FileReader aborted")
    };
  }
});

// packages/cli/node_modules/undici/lib/web/fileapi/progressevent.js
var require_progressevent2 = __commonJS({
  "packages/cli/node_modules/undici/lib/web/fileapi/progressevent.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var { webidl } = require_webidl2();
    var kState = Symbol("ProgressEvent state");
    var ProgressEvent = class _ProgressEvent extends Event {
      static {
        __name(this, "ProgressEvent");
      }
      constructor(type, eventInitDict = {}) {
        type = webidl.converters.DOMString(type, "ProgressEvent constructor", "type");
        eventInitDict = webidl.converters.ProgressEventInit(eventInitDict ?? {});
        super(type, eventInitDict);
        this[kState] = {
          lengthComputable: eventInitDict.lengthComputable,
          loaded: eventInitDict.loaded,
          total: eventInitDict.total
        };
      }
      get lengthComputable() {
        webidl.brandCheck(this, _ProgressEvent);
        return this[kState].lengthComputable;
      }
      get loaded() {
        webidl.brandCheck(this, _ProgressEvent);
        return this[kState].loaded;
      }
      get total() {
        webidl.brandCheck(this, _ProgressEvent);
        return this[kState].total;
      }
    };
    webidl.converters.ProgressEventInit = webidl.dictionaryConverter([
      {
        key: "lengthComputable",
        converter: webidl.converters.boolean,
        defaultValue: /* @__PURE__ */ __name(() => false, "defaultValue")
      },
      {
        key: "loaded",
        converter: webidl.converters["unsigned long long"],
        defaultValue: /* @__PURE__ */ __name(() => 0, "defaultValue")
      },
      {
        key: "total",
        converter: webidl.converters["unsigned long long"],
        defaultValue: /* @__PURE__ */ __name(() => 0, "defaultValue")
      },
      {
        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")
      }
    ]);
    module2.exports = {
      ProgressEvent
    };
  }
});

// packages/cli/node_modules/undici/lib/web/fileapi/encoding.js
var require_encoding2 = __commonJS({
  "packages/cli/node_modules/undici/lib/web/fileapi/encoding.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    function getEncoding(label) {
      if (!label) {
        return "failure";
      }
      switch (label.trim().toLowerCase()) {
        case "unicode-1-1-utf-8":
        case "unicode11utf8":
        case "unicode20utf8":
        case "utf-8":
        case "utf8":
        case "x-unicode20utf8":
          return "UTF-8";
        case "866":
        case "cp866":
        case "csibm866":
        case "ibm866":
          return "IBM866";
        case "csisolatin2":
        case "iso-8859-2":
        case "iso-ir-101":
        case "iso8859-2":
        case "iso88592":
        case "iso_8859-2":
        case "iso_8859-2:1987":
        case "l2":
        case "latin2":
          return "ISO-8859-2";
        case "csisolatin3":
        case "iso-8859-3":
        case "iso-ir-109":
        case "iso8859-3":
        case "iso88593":
        case "iso_8859-3":
        case "iso_8859-3:1988":
        case "l3":
        case "latin3":
          return "ISO-8859-3";
        case "csisolatin4":
        case "iso-8859-4":
        case "iso-ir-110":
        case "iso8859-4":
        case "iso88594":
        case "iso_8859-4":
        case "iso_8859-4:1988":
        case "l4":
        case "latin4":
          return "ISO-8859-4";
        case "csisolatincyrillic":
        case "cyrillic":
        case "iso-8859-5":
        case "iso-ir-144":
        case "iso8859-5":
        case "iso88595":
        case "iso_8859-5":
        case "iso_8859-5:1988":
          return "ISO-8859-5";
        case "arabic":
        case "asmo-708":
        case "csiso88596e":
        case "csiso88596i":
        case "csisolatinarabic":
        case "ecma-114":
        case "iso-8859-6":
        case "iso-8859-6-e":
        case "iso-8859-6-i":
        case "iso-ir-127":
        case "iso8859-6":
        case "iso88596":
        case "iso_8859-6":
        case "iso_8859-6:1987":
          return "ISO-8859-6";
        case "csisolatingreek":
        case "ecma-118":
        case "elot_928":
        case "greek":
        case "greek8":
        case "iso-8859-7":
        case "iso-ir-126":
        case "iso8859-7":
        case "iso88597":
        case "iso_8859-7":
        case "iso_8859-7:1987":
        case "sun_eu_greek":
          return "ISO-8859-7";
        case "csiso88598e":
        case "csisolatinhebrew":
        case "hebrew":
        case "iso-8859-8":
        case "iso-8859-8-e":
        case "iso-ir-138":
        case "iso8859-8":
        case "iso88598":
        case "iso_8859-8":
        case "iso_8859-8:1988":
        case "visual":
          return "ISO-8859-8";
        case "csiso88598i":
        case "iso-8859-8-i":
        case "logical":
          return "ISO-8859-8-I";
        case "csisolatin6":
        case "iso-8859-10":
        case "iso-ir-157":
        case "iso8859-10":
        case "iso885910":
        case "l6":
        case "latin6":
          return "ISO-8859-10";
        case "iso-8859-13":
        case "iso8859-13":
        case "iso885913":
          return "ISO-8859-13";
        case "iso-8859-14":
        case "iso8859-14":
        case "iso885914":
          return "ISO-8859-14";
        case "csisolatin9":
        case "iso-8859-15":
        case "iso8859-15":
        case "iso885915":
        case "iso_8859-15":
        case "l9":
          return "ISO-8859-15";
        case "iso-8859-16":
          return "ISO-8859-16";
        case "cskoi8r":
        case "koi":
        case "koi8":
        case "koi8-r":
        case "koi8_r":
          return "KOI8-R";
        case "koi8-ru":
        case "koi8-u":
          return "KOI8-U";
        case "csmacintosh":
        case "mac":
        case "macintosh":
        case "x-mac-roman":
          return "macintosh";
        case "iso-8859-11":
        case "iso8859-11":
        case "iso885911":
        case "tis-620":
        case "windows-874":
          return "windows-874";
        case "cp1250":
        case "windows-1250":
        case "x-cp1250":
          return "windows-1250";
        case "cp1251":
        case "windows-1251":
        case "x-cp1251":
          return "windows-1251";
        case "ansi_x3.4-1968":
        case "ascii":
        case "cp1252":
        case "cp819":
        case "csisolatin1":
        case "ibm819":
        case "iso-8859-1":
        case "iso-ir-100":
        case "iso8859-1":
        case "iso88591":
        case "iso_8859-1":
        case "iso_8859-1:1987":
        case "l1":
        case "latin1":
        case "us-ascii":
        case "windows-1252":
        case "x-cp1252":
          return "windows-1252";
        case "cp1253":
        case "windows-1253":
        case "x-cp1253":
          return "windows-1253";
        case "cp1254":
        case "csisolatin5":
        case "iso-8859-9":
        case "iso-ir-148":
        case "iso8859-9":
        case "iso88599":
        case "iso_8859-9":
        case "iso_8859-9:1989":
        case "l5":
        case "latin5":
        case "windows-1254":
        case "x-cp1254":
          return "windows-1254";
        case "cp1255":
        case "windows-1255":
        case "x-cp1255":
          return "windows-1255";
        case "cp1256":
        case "windows-1256":
        case "x-cp1256":
          return "windows-1256";
        case "cp1257":
        case "windows-1257":
        case "x-cp1257":
          return "windows-1257";
        case "cp1258":
        case "windows-1258":
        case "x-cp1258":
          return "windows-1258";
        case "x-mac-cyrillic":
        case "x-mac-ukrainian":
          return "x-mac-cyrillic";
        case "chinese":
        case "csgb2312":
        case "csiso58gb231280":
        case "gb2312":
        case "gb_2312":
        case "gb_2312-80":
        case "gbk":
        case "iso-ir-58":
        case "x-gbk":
          return "GBK";
        case "gb18030":
          return "gb18030";
        case "big5":
        case "big5-hkscs":
        case "cn-big5":
        case "csbig5":
        case "x-x-big5":
          return "Big5";
        case "cseucpkdfmtjapanese":
        case "euc-jp":
        case "x-euc-jp":
          return "EUC-JP";
        case "csiso2022jp":
        case "iso-2022-jp":
          return "ISO-2022-JP";
        case "csshiftjis":
        case "ms932":
        case "ms_kanji":
        case "shift-jis":
        case "shift_jis":
        case "sjis":
        case "windows-31j":
        case "x-sjis":
          return "Shift_JIS";
        case "cseuckr":
        case "csksc56011987":
        case "euc-kr":
        case "iso-ir-149":
        case "korean":
        case "ks_c_5601-1987":
        case "ks_c_5601-1989":
        case "ksc5601":
        case "ksc_5601":
        case "windows-949":
          return "EUC-KR";
        case "csiso2022kr":
        case "hz-gb-2312":
        case "iso-2022-cn":
        case "iso-2022-cn-ext":
        case "iso-2022-kr":
        case "replacement":
          return "replacement";
        case "unicodefffe":
        case "utf-16be":
          return "UTF-16BE";
        case "csunicode":
        case "iso-10646-ucs-2":
        case "ucs-2":
        case "unicode":
        case "unicodefeff":
        case "utf-16":
        case "utf-16le":
          return "UTF-16LE";
        case "x-user-defined":
          return "x-user-defined";
        default:
          return "failure";
      }
    }
    __name(getEncoding, "getEncoding");
    module2.exports = {
      getEncoding
    };
  }
});

// packages/cli/node_modules/undici/lib/web/fileapi/util.js
var require_util25 = __commonJS({
  "packages/cli/node_modules/undici/lib/web/fileapi/util.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var {
      kState,
      kError,
      kResult,
      kAborted,
      kLastProgressEventFired
    } = require_symbols8();
    var { ProgressEvent } = require_progressevent2();
    var { getEncoding } = require_encoding2();
    var { serializeAMimeType, parseMIMEType } = require_data_url2();
    var { types: types7 } = __require("node:util");
    var { StringDecoder: StringDecoder3 } = __require("string_decoder");
    var { btoa: btoa2 } = __require("node:buffer");
    var staticPropertyDescriptors = {
      enumerable: true,
      writable: false,
      configurable: false
    };
    function readOperation(fr2, blob, type, encodingName) {
      if (fr2[kState] === "loading") {
        throw new DOMException("Invalid state", "InvalidStateError");
      }
      fr2[kState] = "loading";
      fr2[kResult] = null;
      fr2[kError] = null;
      const stream2 = blob.stream();
      const reader = stream2.getReader();
      const bytes = [];
      let chunkPromise = reader.read();
      let isFirstChunk = true;
      (async () => {
        while (!fr2[kAborted]) {
          try {
            const { done, value } = await chunkPromise;
            if (isFirstChunk && !fr2[kAborted]) {
              queueMicrotask(() => {
                fireAProgressEvent("loadstart", fr2);
              });
            }
            isFirstChunk = false;
            if (!done && types7.isUint8Array(value)) {
              bytes.push(value);
              if ((fr2[kLastProgressEventFired] === void 0 || Date.now() - fr2[kLastProgressEventFired] >= 50) && !fr2[kAborted]) {
                fr2[kLastProgressEventFired] = Date.now();
                queueMicrotask(() => {
                  fireAProgressEvent("progress", fr2);
                });
              }
              chunkPromise = reader.read();
            } else if (done) {
              queueMicrotask(() => {
                fr2[kState] = "done";
                try {
                  const result = packageData(bytes, type, blob.type, encodingName);
                  if (fr2[kAborted]) {
                    return;
                  }
                  fr2[kResult] = result;
                  fireAProgressEvent("load", fr2);
                } catch (error2) {
                  fr2[kError] = error2;
                  fireAProgressEvent("error", fr2);
                }
                if (fr2[kState] !== "loading") {
                  fireAProgressEvent("loadend", fr2);
                }
              });
              break;
            }
          } catch (error2) {
            if (fr2[kAborted]) {
              return;
            }
            queueMicrotask(() => {
              fr2[kState] = "done";
              fr2[kError] = error2;
              fireAProgressEvent("error", fr2);
              if (fr2[kState] !== "loading") {
                fireAProgressEvent("loadend", fr2);
              }
            });
            break;
          }
        }
      })();
    }
    __name(readOperation, "readOperation");
    function fireAProgressEvent(e4, reader) {
      const event = new ProgressEvent(e4, {
        bubbles: false,
        cancelable: false
      });
      reader.dispatchEvent(event);
    }
    __name(fireAProgressEvent, "fireAProgressEvent");
    function packageData(bytes, type, mimeType, encodingName) {
      switch (type) {
        case "DataURL": {
          let dataURL = "data:";
          const parsed = parseMIMEType(mimeType || "application/octet-stream");
          if (parsed !== "failure") {
            dataURL += serializeAMimeType(parsed);
          }
          dataURL += ";base64,";
          const decoder = new StringDecoder3("latin1");
          for (const chunk of bytes) {
            dataURL += btoa2(decoder.write(chunk));
          }
          dataURL += btoa2(decoder.end());
          return dataURL;
        }
        case "Text": {
          let encoding = "failure";
          if (encodingName) {
            encoding = getEncoding(encodingName);
          }
          if (encoding === "failure" && mimeType) {
            const type2 = parseMIMEType(mimeType);
            if (type2 !== "failure") {
              encoding = getEncoding(type2.parameters.get("charset"));
            }
          }
          if (encoding === "failure") {
            encoding = "UTF-8";
          }
          return decode2(bytes, encoding);
        }
        case "ArrayBuffer": {
          const sequence = combineByteSequences(bytes);
          return sequence.buffer;
        }
        case "BinaryString": {
          let binaryString = "";
          const decoder = new StringDecoder3("latin1");
          for (const chunk of bytes) {
            binaryString += decoder.write(chunk);
          }
          binaryString += decoder.end();
          return binaryString;
        }
      }
    }
    __name(packageData, "packageData");
    function decode2(ioQueue, encoding) {
      const bytes = combineByteSequences(ioQueue);
      const BOMEncoding = BOMSniffing(bytes);
      let slice = 0;
      if (BOMEncoding !== null) {
        encoding = BOMEncoding;
        slice = BOMEncoding === "UTF-8" ? 3 : 2;
      }
      const sliced = bytes.slice(slice);
      return new TextDecoder(encoding).decode(sliced);
    }
    __name(decode2, "decode");
    function BOMSniffing(ioQueue) {
      const [a2, b2, c4] = ioQueue;
      if (a2 === 239 && b2 === 187 && c4 === 191) {
        return "UTF-8";
      } else if (a2 === 254 && b2 === 255) {
        return "UTF-16BE";
      } else if (a2 === 255 && b2 === 254) {
        return "UTF-16LE";
      }
      return null;
    }
    __name(BOMSniffing, "BOMSniffing");
    function combineByteSequences(sequences) {
      const size = sequences.reduce((a2, b2) => {
        return a2 + b2.byteLength;
      }, 0);
      let offset = 0;
      return sequences.reduce((a2, b2) => {
        a2.set(b2, offset);
        offset += b2.byteLength;
        return a2;
      }, new Uint8Array(size));
    }
    __name(combineByteSequences, "combineByteSequences");
    module2.exports = {
      staticPropertyDescriptors,
      readOperation,
      fireAProgressEvent
    };
  }
});

// packages/cli/node_modules/undici/lib/web/fileapi/filereader.js
var require_filereader2 = __commonJS({
  "packages/cli/node_modules/undici/lib/web/fileapi/filereader.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var {
      staticPropertyDescriptors,
      readOperation,
      fireAProgressEvent
    } = require_util25();
    var {
      kState,
      kError,
      kResult,
      kEvents,
      kAborted
    } = require_symbols8();
    var { webidl } = require_webidl2();
    var { kEnumerableProperty } = require_util22();
    var FileReader = class _FileReader extends EventTarget {
      static {
        __name(this, "FileReader");
      }
      constructor() {
        super();
        this[kState] = "empty";
        this[kResult] = null;
        this[kError] = null;
        this[kEvents] = {
          loadend: null,
          error: null,
          abort: null,
          load: null,
          progress: null,
          loadstart: null
        };
      }
      /**
       * @see https://w3c.github.io/FileAPI/#dfn-readAsArrayBuffer
       * @param {import('buffer').Blob} blob
       */
      readAsArrayBuffer(blob) {
        webidl.brandCheck(this, _FileReader);
        webidl.argumentLengthCheck(arguments, 1, "FileReader.readAsArrayBuffer");
        blob = webidl.converters.Blob(blob, { strict: false });
        readOperation(this, blob, "ArrayBuffer");
      }
      /**
       * @see https://w3c.github.io/FileAPI/#readAsBinaryString
       * @param {import('buffer').Blob} blob
       */
      readAsBinaryString(blob) {
        webidl.brandCheck(this, _FileReader);
        webidl.argumentLengthCheck(arguments, 1, "FileReader.readAsBinaryString");
        blob = webidl.converters.Blob(blob, { strict: false });
        readOperation(this, blob, "BinaryString");
      }
      /**
       * @see https://w3c.github.io/FileAPI/#readAsDataText
       * @param {import('buffer').Blob} blob
       * @param {string?} encoding
       */
      readAsText(blob, encoding = void 0) {
        webidl.brandCheck(this, _FileReader);
        webidl.argumentLengthCheck(arguments, 1, "FileReader.readAsText");
        blob = webidl.converters.Blob(blob, { strict: false });
        if (encoding !== void 0) {
          encoding = webidl.converters.DOMString(encoding, "FileReader.readAsText", "encoding");
        }
        readOperation(this, blob, "Text", encoding);
      }
      /**
       * @see https://w3c.github.io/FileAPI/#dfn-readAsDataURL
       * @param {import('buffer').Blob} blob
       */
      readAsDataURL(blob) {
        webidl.brandCheck(this, _FileReader);
        webidl.argumentLengthCheck(arguments, 1, "FileReader.readAsDataURL");
        blob = webidl.converters.Blob(blob, { strict: false });
        readOperation(this, blob, "DataURL");
      }
      /**
       * @see https://w3c.github.io/FileAPI/#dfn-abort
       */
      abort() {
        if (this[kState] === "empty" || this[kState] === "done") {
          this[kResult] = null;
          return;
        }
        if (this[kState] === "loading") {
          this[kState] = "done";
          this[kResult] = null;
        }
        this[kAborted] = true;
        fireAProgressEvent("abort", this);
        if (this[kState] !== "loading") {
          fireAProgressEvent("loadend", this);
        }
      }
      /**
       * @see https://w3c.github.io/FileAPI/#dom-filereader-readystate
       */
      get readyState() {
        webidl.brandCheck(this, _FileReader);
        switch (this[kState]) {
          case "empty":
            return this.EMPTY;
          case "loading":
            return this.LOADING;
          case "done":
            return this.DONE;
        }
      }
      /**
       * @see https://w3c.github.io/FileAPI/#dom-filereader-result
       */
      get result() {
        webidl.brandCheck(this, _FileReader);
        return this[kResult];
      }
      /**
       * @see https://w3c.github.io/FileAPI/#dom-filereader-error
       */
      get error() {
        webidl.brandCheck(this, _FileReader);
        return this[kError];
      }
      get onloadend() {
        webidl.brandCheck(this, _FileReader);
        return this[kEvents].loadend;
      }
      set onloadend(fn) {
        webidl.brandCheck(this, _FileReader);
        if (this[kEvents].loadend) {
          this.removeEventListener("loadend", this[kEvents].loadend);
        }
        if (typeof fn === "function") {
          this[kEvents].loadend = fn;
          this.addEventListener("loadend", fn);
        } else {
          this[kEvents].loadend = null;
        }
      }
      get onerror() {
        webidl.brandCheck(this, _FileReader);
        return this[kEvents].error;
      }
      set onerror(fn) {
        webidl.brandCheck(this, _FileReader);
        if (this[kEvents].error) {
          this.removeEventListener("error", this[kEvents].error);
        }
        if (typeof fn === "function") {
          this[kEvents].error = fn;
          this.addEventListener("error", fn);
        } else {
          this[kEvents].error = null;
        }
      }
      get onloadstart() {
        webidl.brandCheck(this, _FileReader);
        return this[kEvents].loadstart;
      }
      set onloadstart(fn) {
        webidl.brandCheck(this, _FileReader);
        if (this[kEvents].loadstart) {
          this.removeEventListener("loadstart", this[kEvents].loadstart);
        }
        if (typeof fn === "function") {
          this[kEvents].loadstart = fn;
          this.addEventListener("loadstart", fn);
        } else {
          this[kEvents].loadstart = null;
        }
      }
      get onprogress() {
        webidl.brandCheck(this, _FileReader);
        return this[kEvents].progress;
      }
      set onprogress(fn) {
        webidl.brandCheck(this, _FileReader);
        if (this[kEvents].progress) {
          this.removeEventListener("progress", this[kEvents].progress);
        }
        if (typeof fn === "function") {
          this[kEvents].progress = fn;
          this.addEventListener("progress", fn);
        } else {
          this[kEvents].progress = null;
        }
      }
      get onload() {
        webidl.brandCheck(this, _FileReader);
        return this[kEvents].load;
      }
      set onload(fn) {
        webidl.brandCheck(this, _FileReader);
        if (this[kEvents].load) {
          this.removeEventListener("load", this[kEvents].load);
        }
        if (typeof fn === "function") {
          this[kEvents].load = fn;
          this.addEventListener("load", fn);
        } else {
          this[kEvents].load = null;
        }
      }
      get onabort() {
        webidl.brandCheck(this, _FileReader);
        return this[kEvents].abort;
      }
      set onabort(fn) {
        webidl.brandCheck(this, _FileReader);
        if (this[kEvents].abort) {
          this.removeEventListener("abort", this[kEvents].abort);
        }
        if (typeof fn === "function") {
          this[kEvents].abort = fn;
          this.addEventListener("abort", fn);
        } else {
          this[kEvents].abort = null;
        }
      }
    };
    FileReader.EMPTY = FileReader.prototype.EMPTY = 0;
    FileReader.LOADING = FileReader.prototype.LOADING = 1;
    FileReader.DONE = FileReader.prototype.DONE = 2;
    Object.defineProperties(FileReader.prototype, {
      EMPTY: staticPropertyDescriptors,
      LOADING: staticPropertyDescriptors,
      DONE: staticPropertyDescriptors,
      readAsArrayBuffer: kEnumerableProperty,
      readAsBinaryString: kEnumerableProperty,
      readAsText: kEnumerableProperty,
      readAsDataURL: kEnumerableProperty,
      abort: kEnumerableProperty,
      readyState: kEnumerableProperty,
      result: kEnumerableProperty,
      error: kEnumerableProperty,
      onloadstart: kEnumerableProperty,
      onprogress: kEnumerableProperty,
      onload: kEnumerableProperty,
      onabort: kEnumerableProperty,
      onerror: kEnumerableProperty,
      onloadend: kEnumerableProperty,
      [Symbol.toStringTag]: {
        value: "FileReader",
        writable: false,
        enumerable: false,
        configurable: true
      }
    });
    Object.defineProperties(FileReader, {
      EMPTY: staticPropertyDescriptors,
      LOADING: staticPropertyDescriptors,
      DONE: staticPropertyDescriptors
    });
    module2.exports = {
      FileReader
    };
  }
});

// packages/cli/node_modules/undici/lib/web/cache/symbols.js
var require_symbols9 = __commonJS({
  "packages/cli/node_modules/undici/lib/web/cache/symbols.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    module2.exports = {
      kConstruct: require_symbols6().kConstruct
    };
  }
});

// packages/cli/node_modules/undici/lib/web/cache/util.js
var require_util26 = __commonJS({
  "packages/cli/node_modules/undici/lib/web/cache/util.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var assert4 = __require("node:assert");
    var { URLSerializer } = require_data_url2();
    var { isValidHeaderName } = require_util23();
    function urlEquals(A4, B2, excludeFragment = false) {
      const serializedA = URLSerializer(A4, excludeFragment);
      const serializedB = URLSerializer(B2, excludeFragment);
      return serializedA === serializedB;
    }
    __name(urlEquals, "urlEquals");
    function getFieldValues(header) {
      assert4(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
    };
  }
});

// packages/cli/node_modules/undici/lib/web/cache/cache.js
var require_cache2 = __commonJS({
  "packages/cli/node_modules/undici/lib/web/cache/cache.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var { kConstruct } = require_symbols9();
    var { urlEquals, getFieldValues } = require_util26();
    var { kEnumerableProperty, isDisturbed } = require_util22();
    var { webidl } = require_webidl2();
    var { Response: Response6, cloneResponse, fromInnerResponse } = require_response2();
    var { Request: Request6, fromInnerRequest } = require_request4();
    var { kState } = require_symbols7();
    var { fetching } = require_fetch3();
    var { urlIsHttpHttpsScheme, createDeferredPromise, readAllBytes } = require_util23();
    var assert4 = __require("node:assert");
    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, prefix, "request");
        options2 = webidl.converters.CacheQueryOptions(options2, prefix, "options");
        const p2 = this.#internalMatchAll(request4, options2, 1);
        if (p2.length === 0) {
          return;
        }
        return p2[0];
      }
      async matchAll(request4 = void 0, options2 = {}) {
        webidl.brandCheck(this, _Cache);
        const prefix = "Cache.matchAll";
        if (request4 !== void 0) request4 = webidl.converters.RequestInfo(request4, prefix, "request");
        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, prefix, "request");
        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 r5 = request4[kState];
          if (!urlIsHttpHttpsScheme(r5.url) || r5.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 r5 = new Request6(request4)[kState];
          if (!urlIsHttpHttpsScheme(r5.url)) {
            throw webidl.errors.exception({
              header: prefix,
              message: "Expected http/s scheme."
            });
          }
          r5.initiator = "fetch";
          r5.destination = "subresource";
          requestList.push(r5);
          const responsePromise = createDeferredPromise();
          fetchControllers.push(fetching({
            request: r5,
            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 p2 = Promise.all(responsePromises);
        const responses = await p2;
        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 (e4) {
          errorData = e4;
        }
        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, prefix, "request");
        response = webidl.converters.Response(response, prefix, "response");
        let innerRequest = null;
        if (request4 instanceof Request6) {
          innerRequest = request4[kState];
        } else {
          innerRequest = new Request6(request4)[kState];
        }
        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 = response[kState];
        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).then(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 (e4) {
          errorData = e4;
        }
        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, prefix, "request");
        options2 = webidl.converters.CacheQueryOptions(options2, prefix, "options");
        let r5 = null;
        if (request4 instanceof Request6) {
          r5 = request4[kState];
          if (r5.method !== "GET" && !options2.ignoreMethod) {
            return false;
          }
        } else {
          assert4(typeof request4 === "string");
          r5 = new Request6(request4)[kState];
        }
        const operations = [];
        const operation = {
          type: "delete",
          request: r5,
          options: options2
        };
        operations.push(operation);
        const cacheJobPromise = createDeferredPromise();
        let errorData = null;
        let requestResponses;
        try {
          requestResponses = this.#batchCacheOperations(operations);
        } catch (e4) {
          errorData = e4;
        }
        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, prefix, "request");
        options2 = webidl.converters.CacheQueryOptions(options2, prefix, "options");
        let r5 = null;
        if (request4 !== void 0) {
          if (request4 instanceof Request6) {
            r5 = request4[kState];
            if (r5.method !== "GET" && !options2.ignoreMethod) {
              return [];
            }
          } else if (typeof request4 === "string") {
            r5 = new Request6(request4)[kState];
          }
        }
        const promise = createDeferredPromise();
        const requests = [];
        if (request4 === void 0) {
          for (const requestResponse of this.#relevantRequestResponseList) {
            requests.push(requestResponse[0]);
          }
        } else {
          const requestResponses = this.#queryCache(r5, options2);
          for (const requestResponse of requestResponses) {
            requests.push(requestResponse[0]);
          }
        }
        queueMicrotask(() => {
          const requestList = [];
          for (const request5 of requests) {
            const requestObject = fromInnerRequest(
              request5,
              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);
                assert4(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 r5 = operation.request;
              if (!urlIsHttpHttpsScheme(r5.url)) {
                throw webidl.errors.exception({
                  header: "Cache.#batchCacheOperations",
                  message: "expected http or https scheme"
                });
              }
              if (r5.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);
                assert4(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 (e4) {
          this.#relevantRequestResponseList.length = 0;
          this.#relevantRequestResponseList = backupCache;
          throw e4;
        }
      }
      /**
       * @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 r5 = null;
        if (request4 !== void 0) {
          if (request4 instanceof Request6) {
            r5 = request4[kState];
            if (r5.method !== "GET" && !options2.ignoreMethod) {
              return [];
            }
          } else if (typeof request4 === "string") {
            r5 = new Request6(request4)[kState];
          }
        }
        const responses = [];
        if (request4 === void 0) {
          for (const requestResponse of this.#relevantRequestResponseList) {
            responses.push(requestResponse[1]);
          }
        } else {
          const requestResponses = this.#queryCache(r5, 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(Response6);
    webidl.converters["sequence<RequestInfo>"] = webidl.sequenceConverter(
      webidl.converters.RequestInfo
    );
    module2.exports = {
      Cache
    };
  }
});

// packages/cli/node_modules/undici/lib/web/cache/cachestorage.js
var require_cachestorage2 = __commonJS({
  "packages/cli/node_modules/undici/lib/web/cache/cachestorage.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var { kConstruct } = require_symbols9();
    var { Cache } = require_cache2();
    var { webidl } = require_webidl2();
    var { kEnumerableProperty } = require_util22();
    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
    };
  }
});

// packages/cli/node_modules/undici/lib/web/cookies/constants.js
var require_constants17 = __commonJS({
  "packages/cli/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
    };
  }
});

// packages/cli/node_modules/undici/lib/web/cookies/util.js
var require_util27 = __commonJS({
  "packages/cli/node_modules/undici/lib/web/cookies/util.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    function isCTLExcludingHtab(value) {
      for (let i3 = 0; i3 < value.length; ++i3) {
        const code2 = value.charCodeAt(i3);
        if (code2 >= 0 && code2 <= 8 || code2 >= 10 && code2 <= 31 || code2 === 127) {
          return true;
        }
      }
      return false;
    }
    __name(isCTLExcludingHtab, "isCTLExcludingHtab");
    function validateCookieName(name3) {
      for (let i3 = 0; i3 < name3.length; ++i3) {
        const code2 = name3.charCodeAt(i3);
        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 i3 = 0;
      if (value[0] === '"') {
        if (len === 1 || value[len - 1] !== '"') {
          throw new Error("Invalid cookie value");
        }
        --len;
        ++i3;
      }
      while (i3 < len) {
        const code2 = value.charCodeAt(i3++);
        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(path125) {
      for (let i3 = 0; i3 < path125.length; ++i3) {
        const code2 = path125.charCodeAt(i3);
        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((_2, i3) => i3.toString().padStart(2, "0"));
    function toIMFDate(date4) {
      if (typeof date4 === "number") {
        date4 = new Date(date4);
      }
      return `${IMFDays[date4.getUTCDay()]}, ${IMFPaddedNumbers[date4.getUTCDate()]} ${IMFMonths[date4.getUTCMonth()]} ${date4.getUTCFullYear()} ${IMFPaddedNumbers[date4.getUTCHours()]}:${IMFPaddedNumbers[date4.getUTCMinutes()]}:${IMFPaddedNumbers[date4.getUTCSeconds()]} GMT`;
    }
    __name(toIMFDate, "toIMFDate");
    function validateCookieMaxAge(maxAge) {
      if (maxAge < 0) {
        throw new Error("Invalid cookie max-age");
      }
    }
    __name(validateCookieMaxAge, "validateCookieMaxAge");
    function stringify4(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(stringify4, "stringify");
    module2.exports = {
      isCTLExcludingHtab,
      validateCookieName,
      validateCookiePath,
      validateCookieValue,
      toIMFDate,
      stringify: stringify4
    };
  }
});

// packages/cli/node_modules/undici/lib/web/cookies/parse.js
var require_parse11 = __commonJS({
  "packages/cli/node_modules/undici/lib/web/cookies/parse.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var { maxNameValuePairSize, maxAttributeValueSize } = require_constants17();
    var { isCTLExcludingHtab } = require_util27();
    var { collectASequenceOfCodePointsFast } = require_data_url2();
    var assert4 = __require("node:assert");
    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,
        ...parseUnparsedAttributes(unparsedAttributes)
      };
    }
    __name(parseSetCookie, "parseSetCookie");
    function parseUnparsedAttributes(unparsedAttributes, cookieAttributeList = {}) {
      if (unparsedAttributes.length === 0) {
        return cookieAttributeList;
      }
      assert4(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
    };
  }
});

// packages/cli/node_modules/undici/lib/web/cookies/index.js
var require_cookies2 = __commonJS({
  "packages/cli/node_modules/undici/lib/web/cookies/index.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var { parseSetCookie } = require_parse11();
    var { stringify: stringify4 } = require_util27();
    var { webidl } = require_webidl2();
    var { Headers: Headers6 } = require_headers2();
    function getCookies(headers) {
      webidl.argumentLengthCheck(arguments, 1, "getCookies");
      webidl.brandCheck(headers, Headers6, { strict: false });
      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) {
      webidl.brandCheck(headers, Headers6, { strict: false });
      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");
      webidl.brandCheck(headers, Headers6, { strict: false });
      const cookies = headers.getSetCookie();
      if (!cookies) {
        return [];
      }
      return cookies.map((pair) => parseSetCookie(pair));
    }
    __name(getSetCookies, "getSetCookies");
    function setCookie(headers, cookie) {
      webidl.argumentLengthCheck(arguments, 2, "setCookie");
      webidl.brandCheck(headers, Headers6, { strict: false });
      cookie = webidl.converters.Cookie(cookie);
      const str2 = stringify4(cookie);
      if (str2) {
        headers.append("Set-Cookie", str2);
      }
    }
    __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
    };
  }
});

// packages/cli/node_modules/undici/lib/web/websocket/events.js
var require_events2 = __commonJS({
  "packages/cli/node_modules/undici/lib/web/websocket/events.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var { webidl } = require_webidl2();
    var { kEnumerableProperty } = require_util22();
    var { kConstruct } = require_symbols6();
    var { MessagePort } = __require("node:worker_threads");
    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(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
    };
  }
});

// packages/cli/node_modules/undici/lib/web/websocket/constants.js
var require_constants18 = __commonJS({
  "packages/cli/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 = {
      NOT_SENT: 0,
      PROCESSING: 1,
      SENT: 2
    };
    var opcodes = {
      CONTINUATION: 0,
      TEXT: 1,
      BINARY: 2,
      CLOSE: 8,
      PING: 9,
      PONG: 10
    };
    var maxUnsigned16Bit = 2 ** 16 - 1;
    var parserStates = {
      INFO: 0,
      PAYLOADLENGTH_16: 2,
      PAYLOADLENGTH_64: 3,
      READ_DATA: 4
    };
    var emptyBuffer = Buffer.allocUnsafe(0);
    var sendHints = {
      string: 1,
      typedArray: 2,
      arrayBuffer: 3,
      blob: 4
    };
    module2.exports = {
      uid,
      sentCloseFrameState,
      staticPropertyDescriptors,
      states,
      opcodes,
      maxUnsigned16Bit,
      parserStates,
      emptyBuffer,
      sendHints
    };
  }
});

// packages/cli/node_modules/undici/lib/web/websocket/symbols.js
var require_symbols10 = __commonJS({
  "packages/cli/node_modules/undici/lib/web/websocket/symbols.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    module2.exports = {
      kWebSocketURL: Symbol("url"),
      kReadyState: Symbol("ready state"),
      kController: Symbol("controller"),
      kResponse: Symbol("response"),
      kBinaryType: Symbol("binary type"),
      kSentClose: Symbol("sent close"),
      kReceivedClose: Symbol("received close"),
      kByteParser: Symbol("byte parser")
    };
  }
});

// packages/cli/node_modules/undici/lib/web/websocket/util.js
var require_util28 = __commonJS({
  "packages/cli/node_modules/undici/lib/web/websocket/util.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var { kReadyState, kController, kResponse, kBinaryType, kWebSocketURL } = require_symbols10();
    var { states, opcodes } = require_constants18();
    var { ErrorEvent: ErrorEvent2, createFastMessageEvent } = require_events2();
    var { isUtf8 } = __require("node:buffer");
    var { collectASequenceOfCodePointsFast, removeHTTPWhitespace } = require_data_url2();
    function isConnecting(ws2) {
      return ws2[kReadyState] === states.CONNECTING;
    }
    __name(isConnecting, "isConnecting");
    function isEstablished(ws2) {
      return ws2[kReadyState] === states.OPEN;
    }
    __name(isEstablished, "isEstablished");
    function isClosing(ws2) {
      return ws2[kReadyState] === states.CLOSING;
    }
    __name(isClosing, "isClosing");
    function isClosed(ws2) {
      return ws2[kReadyState] === states.CLOSED;
    }
    __name(isClosed, "isClosed");
    function fireEvent(e4, target, eventFactory = (type, init) => new Event(type, init), eventInitDict = {}) {
      const event = eventFactory(e4, eventInitDict);
      target.dispatchEvent(event);
    }
    __name(fireEvent, "fireEvent");
    function websocketMessageReceived(ws2, type, data) {
      if (ws2[kReadyState] !== states.OPEN) {
        return;
      }
      let dataForEvent;
      if (type === opcodes.TEXT) {
        try {
          dataForEvent = utf8Decode(data);
        } catch {
          failWebsocketConnection(ws2, "Received invalid UTF-8 in text frame.");
          return;
        }
      } else if (type === opcodes.BINARY) {
        if (ws2[kBinaryType] === "blob") {
          dataForEvent = new Blob([data]);
        } else {
          dataForEvent = toArrayBuffer(data);
        }
      }
      fireEvent("message", ws2, createFastMessageEvent, {
        origin: ws2[kWebSocketURL].origin,
        data: dataForEvent
      });
    }
    __name(websocketMessageReceived, "websocketMessageReceived");
    function toArrayBuffer(buffer) {
      if (buffer.byteLength === buffer.buffer.byteLength) {
        return buffer.buffer;
      }
      return buffer.buffer.slice(buffer.byteOffset, buffer.byteOffset + buffer.byteLength);
    }
    __name(toArrayBuffer, "toArrayBuffer");
    function isValidSubprotocol(protocol) {
      if (protocol.length === 0) {
        return false;
      }
      for (let i3 = 0; i3 < protocol.length; ++i3) {
        const code2 = protocol.charCodeAt(i3);
        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 failWebsocketConnection(ws2, reason) {
      const { [kController]: controller, [kResponse]: response } = ws2;
      controller.abort();
      if (response?.socket && !response.socket.destroyed) {
        response.socket.destroy();
      }
      if (reason) {
        fireEvent("error", ws2, (type, init) => new ErrorEvent2(type, init), {
          error: new Error(reason),
          message: reason
        });
      }
    }
    __name(failWebsocketConnection, "failWebsocketConnection");
    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("=");
        extensionList.set(
          removeHTTPWhitespace(name3, true, false),
          removeHTTPWhitespace(value, false, true)
        );
        position.position++;
      }
      return extensionList;
    }
    __name(parseExtensions, "parseExtensions");
    function isValidClientWindowBits(value) {
      for (let i3 = 0; i3 < value.length; i3++) {
        const byte = value.charCodeAt(i3);
        if (byte < 48 || byte > 57) {
          return false;
        }
      }
      return true;
    }
    __name(isValidClientWindowBits, "isValidClientWindowBits");
    var hasIntl = typeof process.versions.icu === "string";
    var fatalDecoder = hasIntl ? new TextDecoder("utf-8", { fatal: true }) : void 0;
    var utf8Decode = hasIntl ? fatalDecoder.decode.bind(fatalDecoder) : 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,
      failWebsocketConnection,
      websocketMessageReceived,
      utf8Decode,
      isControlFrame,
      isContinuationFrame,
      isTextBinaryFrame,
      isValidOpcode,
      parseExtensions,
      isValidClientWindowBits
    };
  }
});

// packages/cli/node_modules/undici/lib/web/websocket/frame.js
var require_frame2 = __commonJS({
  "packages/cli/node_modules/undici/lib/web/websocket/frame.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var { maxUnsigned16Bit } = require_constants18();
    var BUFFER_SIZE = 16386;
    var crypto14;
    var buffer = null;
    var bufIdx = BUFFER_SIZE;
    try {
      crypto14 = __require("node:crypto");
    } catch {
      crypto14 = {
        // not full compatibility, but minimum.
        randomFillSync: /* @__PURE__ */ __name(function randomFillSync(buffer2, _offset, _size3) {
          for (let i3 = 0; i3 < buffer2.length; ++i3) {
            buffer2[i3] = Math.random() * 255 | 0;
          }
          return buffer2;
        }, "randomFillSync")
      };
    }
    function generateMask() {
      if (bufIdx === BUFFER_SIZE) {
        bufIdx = 0;
        crypto14.randomFillSync(buffer ??= Buffer.allocUnsafe(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 i3 = 0; i3 < bodyLength; ++i3) {
          buffer2[offset + i3] = frameData[i3] ^ maskKey[i3 & 3];
        }
        return buffer2;
      }
    };
    module2.exports = {
      WebsocketFrameSend
    };
  }
});

// packages/cli/node_modules/undici/lib/web/websocket/connection.js
var require_connection2 = __commonJS({
  "packages/cli/node_modules/undici/lib/web/websocket/connection.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var { uid, states, sentCloseFrameState, emptyBuffer, opcodes } = require_constants18();
    var {
      kReadyState,
      kSentClose,
      kByteParser,
      kReceivedClose,
      kResponse
    } = require_symbols10();
    var { fireEvent, failWebsocketConnection, isClosing, isClosed, isEstablished, parseExtensions } = require_util28();
    var { channels } = require_diagnostics2();
    var { CloseEvent } = require_events2();
    var { makeRequest } = require_request4();
    var { fetching } = require_fetch3();
    var { Headers: Headers6, getHeadersList } = require_headers2();
    var { getDecodeSplit } = require_util23();
    var { WebsocketFrameSend } = require_frame2();
    var crypto14;
    try {
      crypto14 = __require("node:crypto");
    } catch {
    }
    function establishWebSocketConnection(url2, protocols, client, ws2, onEstablish, 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 Headers6(options2.headers));
        request4.headersList = headersList;
      }
      const keyValue = crypto14.randomBytes(16).toString("base64");
      request4.headersList.append("sec-websocket-key", keyValue);
      request4.headersList.append("sec-websocket-version", "13");
      for (const protocol of protocols) {
        request4.headersList.append("sec-websocket-protocol", protocol);
      }
      const permessageDeflate = "permessage-deflate; client_max_window_bits";
      request4.headersList.append("sec-websocket-extensions", permessageDeflate);
      const controller = fetching({
        request: request4,
        useParallelQueue: true,
        dispatcher: options2.dispatcher,
        processResponse(response) {
          if (response.type === "error" || response.status !== 101) {
            failWebsocketConnection(ws2, "Received network error or non-101 status code.");
            return;
          }
          if (protocols.length !== 0 && !response.headersList.get("Sec-WebSocket-Protocol")) {
            failWebsocketConnection(ws2, "Server did not respond with sent protocols.");
            return;
          }
          if (response.headersList.get("Upgrade")?.toLowerCase() !== "websocket") {
            failWebsocketConnection(ws2, 'Server did not set Upgrade header to "websocket".');
            return;
          }
          if (response.headersList.get("Connection")?.toLowerCase() !== "upgrade") {
            failWebsocketConnection(ws2, 'Server did not set Connection header to "upgrade".');
            return;
          }
          const secWSAccept = response.headersList.get("Sec-WebSocket-Accept");
          const digest = crypto14.createHash("sha1").update(keyValue + uid).digest("base64");
          if (secWSAccept !== digest) {
            failWebsocketConnection(ws2, "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(ws2, "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(ws2, "Protocol was not set in the opening handshake.");
              return;
            }
          }
          response.socket.on("data", onSocketData);
          response.socket.on("close", onSocketClose);
          response.socket.on("error", onSocketError);
          if (channels.open.hasSubscribers) {
            channels.open.publish({
              address: response.socket.address(),
              protocol: secProtocol,
              extensions: secExtension
            });
          }
          onEstablish(response, extensions);
        }
      });
      return controller;
    }
    __name(establishWebSocketConnection, "establishWebSocketConnection");
    function closeWebSocketConnection(ws2, code2, reason, reasonByteLength) {
      if (isClosing(ws2) || isClosed(ws2)) {
      } else if (!isEstablished(ws2)) {
        failWebsocketConnection(ws2, "Connection was closed before it was established.");
        ws2[kReadyState] = states.CLOSING;
      } else if (ws2[kSentClose] === sentCloseFrameState.NOT_SENT) {
        ws2[kSentClose] = sentCloseFrameState.PROCESSING;
        const frame = new WebsocketFrameSend();
        if (code2 !== void 0 && reason === void 0) {
          frame.frameData = Buffer.allocUnsafe(2);
          frame.frameData.writeUInt16BE(code2, 0);
        } else if (code2 !== void 0 && reason !== void 0) {
          frame.frameData = Buffer.allocUnsafe(2 + reasonByteLength);
          frame.frameData.writeUInt16BE(code2, 0);
          frame.frameData.write(reason, 2, "utf-8");
        } else {
          frame.frameData = emptyBuffer;
        }
        const socket = ws2[kResponse].socket;
        socket.write(frame.createFrame(opcodes.CLOSE));
        ws2[kSentClose] = sentCloseFrameState.SENT;
        ws2[kReadyState] = states.CLOSING;
      } else {
        ws2[kReadyState] = states.CLOSING;
      }
    }
    __name(closeWebSocketConnection, "closeWebSocketConnection");
    function onSocketData(chunk) {
      if (!this.ws[kByteParser].write(chunk)) {
        this.pause();
      }
    }
    __name(onSocketData, "onSocketData");
    function onSocketClose() {
      const { ws: ws2 } = this;
      const { [kResponse]: response } = ws2;
      response.socket.off("data", onSocketData);
      response.socket.off("close", onSocketClose);
      response.socket.off("error", onSocketError);
      const wasClean = ws2[kSentClose] === sentCloseFrameState.SENT && ws2[kReceivedClose];
      let code2 = 1005;
      let reason = "";
      const result = ws2[kByteParser].closingInfo;
      if (result && !result.error) {
        code2 = result.code ?? 1005;
        reason = result.reason;
      } else if (!ws2[kReceivedClose]) {
        code2 = 1006;
      }
      ws2[kReadyState] = states.CLOSED;
      fireEvent("close", ws2, (type, init) => new CloseEvent(type, init), {
        wasClean,
        code: code2,
        reason
      });
      if (channels.close.hasSubscribers) {
        channels.close.publish({
          websocket: ws2,
          code: code2,
          reason
        });
      }
    }
    __name(onSocketClose, "onSocketClose");
    function onSocketError(error2) {
      const { ws: ws2 } = this;
      ws2[kReadyState] = states.CLOSING;
      if (channels.socketError.hasSubscribers) {
        channels.socketError.publish(error2);
      }
      this.destroy();
    }
    __name(onSocketError, "onSocketError");
    module2.exports = {
      establishWebSocketConnection,
      closeWebSocketConnection
    };
  }
});

// packages/cli/node_modules/undici/lib/web/websocket/permessage-deflate.js
var require_permessage_deflate3 = __commonJS({
  "packages/cli/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_util28();
    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 };
  }
});

// packages/cli/node_modules/undici/lib/web/websocket/receiver.js
var require_receiver3 = __commonJS({
  "packages/cli/node_modules/undici/lib/web/websocket/receiver.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var { Writable: Writable3 } = __require("node:stream");
    var assert4 = __require("node:assert");
    var { parserStates, opcodes, states, emptyBuffer, sentCloseFrameState } = require_constants18();
    var { kReadyState, kSentClose, kResponse, kReceivedClose } = require_symbols10();
    var { channels } = require_diagnostics2();
    var {
      isValidStatusCode,
      isValidOpcode,
      failWebsocketConnection,
      websocketMessageReceived,
      utf8Decode,
      isControlFrame,
      isTextBinaryFrame,
      isContinuationFrame
    } = require_util28();
    var { WebsocketFrameSend } = require_frame2();
    var { closeWebSocketConnection } = require_connection2();
    var { PerMessageDeflate } = require_permessage_deflate3();
    var ByteParser = class extends Writable3 {
      static {
        __name(this, "ByteParser");
      }
      #buffers = [];
      #byteOffset = 0;
      #loop = false;
      #state = parserStates.INFO;
      #info = {};
      #fragments = [];
      /** @type {Map<string, PerMessageDeflate>} */
      #extensions;
      constructor(ws2, extensions) {
        super();
        this.ws = ws2;
        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, _2, 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.ws, "Invalid opcode received");
              return callback();
            }
            if (masked) {
              failWebsocketConnection(this.ws, "Frame cannot be masked");
              return callback();
            }
            if (rsv1 !== 0 && !this.#extensions.has("permessage-deflate")) {
              failWebsocketConnection(this.ws, "Expected RSV1 to be clear.");
              return;
            }
            if (rsv2 !== 0 || rsv3 !== 0) {
              failWebsocketConnection(this.ws, "RSV1, RSV2, RSV3 must be clear");
              return;
            }
            if (fragmented && !isTextBinaryFrame(opcode)) {
              failWebsocketConnection(this.ws, "Invalid frame type was fragmented.");
              return;
            }
            if (isTextBinaryFrame(opcode) && this.#fragments.length > 0) {
              failWebsocketConnection(this.ws, "Expected continuation frame");
              return;
            }
            if (this.#info.fragmented && fragmented) {
              failWebsocketConnection(this.ws, "Fragmented frame exceeded 125 bytes.");
              return;
            }
            if ((payloadLength > 125 || fragmented) && isControlFrame(opcode)) {
              failWebsocketConnection(this.ws, "Control frame either too large or fragmented");
              return;
            }
            if (isContinuationFrame(opcode) && this.#fragments.length === 0 && !this.#info.compressed) {
              failWebsocketConnection(this.ws, "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.ws, "Received payload length > 2^31 bytes.");
              return;
            }
            const lower3 = buffer.readUInt32BE(4);
            this.#info.payloadLength = (upper << 8) + lower3;
            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.#fragments.push(body);
                if (!this.#info.fragmented && this.#info.fin) {
                  const fullMessage = Buffer.concat(this.#fragments);
                  websocketMessageReceived(this.ws, this.#info.binaryType, fullMessage);
                  this.#fragments.length = 0;
                }
                this.#state = parserStates.INFO;
              } else {
                this.#extensions.get("permessage-deflate").decompress(body, this.#info.fin, (error2, data) => {
                  if (error2) {
                    closeWebSocketConnection(this.ws, 1007, error2.message, error2.message.length);
                    return;
                  }
                  this.#fragments.push(data);
                  if (!this.#info.fin) {
                    this.#state = parserStates.INFO;
                    this.#loop = true;
                    this.run(callback);
                    return;
                  }
                  websocketMessageReceived(this.ws, this.#info.binaryType, Buffer.concat(this.#fragments));
                  this.#loop = true;
                  this.#state = parserStates.INFO;
                  this.#fragments.length = 0;
                  this.run(callback);
                });
                this.#loop = false;
                break;
              }
            }
          }
        }
      }
      /**
       * Take n bytes from the buffered Buffers
       * @param {number} n
       * @returns {Buffer}
       */
      consume(n3) {
        if (n3 > this.#byteOffset) {
          throw new Error("Called consume() before buffers satiated.");
        } else if (n3 === 0) {
          return emptyBuffer;
        }
        if (this.#buffers[0].length === n3) {
          this.#byteOffset -= this.#buffers[0].length;
          return this.#buffers.shift();
        }
        const buffer = Buffer.allocUnsafe(n3);
        let offset = 0;
        while (offset !== n3) {
          const next = this.#buffers[0];
          const { length } = next;
          if (length + offset === n3) {
            buffer.set(this.#buffers.shift(), offset);
            break;
          } else if (length + offset > n3) {
            buffer.set(next.subarray(0, n3 - offset), offset);
            this.#buffers[0] = next.subarray(n3 - offset);
            break;
          } else {
            buffer.set(this.#buffers.shift(), offset);
            offset += next.length;
          }
        }
        this.#byteOffset -= n3;
        return buffer;
      }
      parseCloseBody(data) {
        assert4(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.ws, "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;
            closeWebSocketConnection(this.ws, code2, reason, reason.length);
            failWebsocketConnection(this.ws, reason);
            return false;
          }
          if (this.ws[kSentClose] !== sentCloseFrameState.SENT) {
            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.ws[kResponse].socket.write(
              closeFrame.createFrame(opcodes.CLOSE),
              (err) => {
                if (!err) {
                  this.ws[kSentClose] = sentCloseFrameState.SENT;
                }
              }
            );
          }
          this.ws[kReadyState] = states.CLOSING;
          this.ws[kReceivedClose] = true;
          return false;
        } else if (opcode === opcodes.PING) {
          if (!this.ws[kReceivedClose]) {
            const frame = new WebsocketFrameSend(body);
            this.ws[kResponse].socket.write(frame.createFrame(opcodes.PONG));
            if (channels.ping.hasSubscribers) {
              channels.ping.publish({
                payload: body
              });
            }
          }
        } else if (opcode === opcodes.PONG) {
          if (channels.pong.hasSubscribers) {
            channels.pong.publish({
              payload: body
            });
          }
        }
        return true;
      }
      get closingInfo() {
        return this.#info.closeInfo;
      }
    };
    module2.exports = {
      ByteParser
    };
  }
});

// packages/cli/node_modules/undici/lib/web/websocket/sender.js
var require_sender3 = __commonJS({
  "packages/cli/node_modules/undici/lib/web/websocket/sender.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var { WebsocketFrameSend } = require_frame2();
    var { opcodes, sendHints } = require_constants18();
    var FixedQueue = require_fixed_queue2();
    var FastBuffer = Buffer[Symbol.species];
    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) {
          const frame = createFrame(item, hint);
          if (!this.#running) {
            this.#socket.write(frame, cb);
          } else {
            const node2 = {
              promise: null,
              callback: cb,
              frame
            };
            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.string ? opcodes.TEXT : opcodes.BINARY);
    }
    __name(createFrame, "createFrame");
    function toBuffer(data, hint) {
      switch (hint) {
        case sendHints.string:
          return Buffer.from(data);
        case sendHints.arrayBuffer:
        case sendHints.blob:
          return new FastBuffer(data);
        case sendHints.typedArray:
          return new FastBuffer(data.buffer, data.byteOffset, data.byteLength);
      }
    }
    __name(toBuffer, "toBuffer");
    module2.exports = { SendQueue };
  }
});

// packages/cli/node_modules/undici/lib/web/websocket/websocket.js
var require_websocket3 = __commonJS({
  "packages/cli/node_modules/undici/lib/web/websocket/websocket.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var { webidl } = require_webidl2();
    var { URLSerializer } = require_data_url2();
    var { environmentSettingsObject } = require_util23();
    var { staticPropertyDescriptors, states, sentCloseFrameState, sendHints } = require_constants18();
    var {
      kWebSocketURL,
      kReadyState,
      kController,
      kBinaryType,
      kResponse,
      kSentClose,
      kByteParser
    } = require_symbols10();
    var {
      isConnecting,
      isEstablished,
      isClosing,
      isValidSubprotocol,
      fireEvent
    } = require_util28();
    var { establishWebSocketConnection, closeWebSocketConnection } = require_connection2();
    var { ByteParser } = require_receiver3();
    var { kEnumerableProperty, isBlobLike: isBlobLike3 } = require_util22();
    var { getGlobalDispatcher } = require_global4();
    var { types: types7 } = __require("node:util");
    var { ErrorEvent: ErrorEvent2, CloseEvent } = require_events2();
    var { SendQueue } = require_sender3();
    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;
      /**
       * @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, prefix, "url");
        protocols = options2.protocols;
        const baseURL = environmentSettingsObject.settingsObject.baseUrl;
        let urlRecord;
        try {
          urlRecord = new URL(url2, baseURL);
        } catch (e4) {
          throw new DOMException(e4, "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: protocol, got ${urlRecord.protocol}`,
            "SyntaxError"
          );
        }
        if (urlRecord.hash || urlRecord.href.endsWith("#")) {
          throw new DOMException("Got fragment", "SyntaxError");
        }
        if (typeof protocols === "string") {
          protocols = [protocols];
        }
        if (protocols.length !== new Set(protocols.map((p2) => p2.toLowerCase())).size) {
          throw new DOMException("Invalid Sec-WebSocket-Protocol value", "SyntaxError");
        }
        if (protocols.length > 0 && !protocols.every((p2) => isValidSubprotocol(p2))) {
          throw new DOMException("Invalid Sec-WebSocket-Protocol value", "SyntaxError");
        }
        this[kWebSocketURL] = new URL(urlRecord.href);
        const client = environmentSettingsObject.settingsObject;
        this[kController] = establishWebSocketConnection(
          urlRecord,
          protocols,
          client,
          this,
          (response, extensions) => this.#onConnectionEstablished(response, extensions),
          options2
        );
        this[kReadyState] = _WebSocket.CONNECTING;
        this[kSentClose] = sentCloseFrameState.NOT_SENT;
        this[kBinaryType] = "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, prefix, "reason");
        }
        if (code2 !== void 0) {
          if (code2 !== 1e3 && (code2 < 3e3 || code2 > 4999)) {
            throw new DOMException("invalid code", "InvalidAccessError");
          }
        }
        let reasonByteLength = 0;
        if (reason !== void 0) {
          reasonByteLength = Buffer.byteLength(reason);
          if (reasonByteLength > 123) {
            throw new DOMException(
              `Reason must be less than 123 bytes; received ${reasonByteLength}`,
              "SyntaxError"
            );
          }
        }
        closeWebSocketConnection(this, code2, reason, reasonByteLength);
      }
      /**
       * @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)) {
          throw new DOMException("Sent before connected.", "InvalidStateError");
        }
        if (!isEstablished(this) || isClosing(this)) {
          return;
        }
        if (typeof data === "string") {
          const length = Buffer.byteLength(data);
          this.#bufferedAmount += length;
          this.#sendQueue.add(data, () => {
            this.#bufferedAmount -= length;
          }, sendHints.string);
        } else if (types7.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 (isBlobLike3(data)) {
          this.#bufferedAmount += data.size;
          this.#sendQueue.add(data, () => {
            this.#bufferedAmount -= data.size;
          }, sendHints.blob);
        }
      }
      get readyState() {
        webidl.brandCheck(this, _WebSocket);
        return this[kReadyState];
      }
      get bufferedAmount() {
        webidl.brandCheck(this, _WebSocket);
        return this.#bufferedAmount;
      }
      get url() {
        webidl.brandCheck(this, _WebSocket);
        return URLSerializer(this[kWebSocketURL]);
      }
      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[kBinaryType];
      }
      set binaryType(type) {
        webidl.brandCheck(this, _WebSocket);
        if (type !== "blob" && type !== "arraybuffer") {
          this[kBinaryType] = "blob";
        } else {
          this[kBinaryType] = type;
        }
      }
      /**
       * @see https://websockets.spec.whatwg.org/#feedback-from-the-protocol
       */
      #onConnectionEstablished(response, parsedExtensions) {
        this[kResponse] = response;
        const parser6 = new ByteParser(this, parsedExtensions);
        parser6.on("drain", onParserDrain);
        parser6.on("error", onParserError.bind(this));
        response.socket.ws = this;
        this[kByteParser] = parser6;
        this.#sendQueue = new SendQueue(response.socket);
        this[kReadyState] = 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);
      }
    };
    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(V3, prefix, argument) {
      if (webidl.util.Type(V3) === "Object" && Symbol.iterator in V3) {
        return webidl.converters["sequence<DOMString>"](V3);
      }
      return webidl.converters.DOMString(V3, 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(V3) {
      if (webidl.util.Type(V3) === "Object" && !(Symbol.iterator in V3)) {
        return webidl.converters.WebSocketInit(V3);
      }
      return { protocols: webidl.converters["DOMString or sequence<DOMString>"](V3) };
    };
    webidl.converters.WebSocketSendData = function(V3) {
      if (webidl.util.Type(V3) === "Object") {
        if (isBlobLike3(V3)) {
          return webidl.converters.Blob(V3, { strict: false });
        }
        if (ArrayBuffer.isView(V3) || types7.isArrayBuffer(V3)) {
          return webidl.converters.BufferSource(V3);
        }
      }
      return webidl.converters.USVString(V3);
    };
    function onParserDrain() {
      this.ws[kResponse].socket.resume();
    }
    __name(onParserDrain, "onParserDrain");
    function onParserError(err) {
      let message;
      let code2;
      if (err instanceof CloseEvent) {
        message = err.reason;
        code2 = err.code;
      } else {
        message = err.message;
      }
      fireEvent("error", this, () => new ErrorEvent2("error", { error: err, message }));
      closeWebSocketConnection(this, code2);
    }
    __name(onParserError, "onParserError");
    module2.exports = {
      WebSocket: WebSocket2
    };
  }
});

// packages/cli/node_modules/undici/lib/web/eventsource/util.js
var require_util29 = __commonJS({
  "packages/cli/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 i3 = 0; i3 < value.length; i3++) {
        if (value.charCodeAt(i3) < 48 || value.charCodeAt(i3) > 57) return false;
      }
      return true;
    }
    __name(isASCIINumber, "isASCIINumber");
    function delay4(ms) {
      return new Promise((resolve30) => {
        setTimeout(resolve30, ms).unref();
      });
    }
    __name(delay4, "delay");
    module2.exports = {
      isValidLastEventId,
      isASCIINumber,
      delay: delay4
    };
  }
});

// packages/cli/node_modules/undici/lib/web/eventsource/eventsource-stream.js
var require_eventsource_stream2 = __commonJS({
  "packages/cli/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_util29();
    var BOM = [239, 187, 191];
    var LF3 = 10;
    var CR3 = 13;
    var COLON3 = 58;
    var SPACE3 = 32;
    var EventSourceStream = class extends Transform2 {
      static {
        __name(this, "EventSourceStream");
      }
      /**
       * @type {eventSourceSettings}
       */
      state = null;
      /**
       * Leading byte-order-mark check.
       * @type {boolean}
       */
      checkBOM = true;
      /**
       * @type {boolean}
       */
      crlfCheck = false;
      /**
       * @type {boolean}
       */
      eventEndCheck = false;
      /**
       * @type {Buffer}
       */
      buffer = null;
      pos = 0;
      event = {
        data: void 0,
        event: void 0,
        id: void 0,
        retry: void 0
      };
      /**
       * @param {object} options
       * @param {eventSourceSettings} options.eventSourceSettings
       * @param {Function} [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] === LF3) {
                this.buffer = this.buffer.subarray(this.pos + 1);
                this.pos = 0;
                this.crlfCheck = false;
                continue;
              }
              this.crlfCheck = false;
            }
            if (this.buffer[this.pos] === LF3 || this.buffer[this.pos] === CR3) {
              if (this.buffer[this.pos] === CR3) {
                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] === LF3 || this.buffer[this.pos] === CR3) {
            if (this.buffer[this.pos] === CR3) {
              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 {EventStreamEvent} event
       */
      parseLine(line, event) {
        if (line.length === 0) {
          return;
        }
        const colonPosition = line.indexOf(COLON3);
        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] === SPACE3) {
            ++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
    };
  }
});

// packages/cli/node_modules/undici/lib/web/eventsource/eventsource.js
var require_eventsource2 = __commonJS({
  "packages/cli/node_modules/undici/lib/web/eventsource/eventsource.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var { pipeline: pipeline3 } = __require("node:stream");
    var { fetching } = require_fetch3();
    var { makeRequest } = require_request4();
    var { webidl } = require_webidl2();
    var { EventSourceStream } = require_eventsource_stream2();
    var { parseMIMEType } = require_data_url2();
    var { createFastMessageEvent } = require_events2();
    var { isNetworkError } = require_response2();
    var { delay: delay4 } = require_util29();
    var { kEnumerableProperty } = require_util22();
    var { environmentSettingsObject } = require_util23();
    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 = null;
      #withCredentials = false;
      #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, prefix, "url");
        eventSourceInitDict = webidl.converters.EventSourceInitDict(eventSourceInitDict, prefix, "eventSourceInitDict");
        this.#dispatcher = eventSourceInitDict.dispatcher;
        this.#state = {
          lastEventId: "",
          reconnectionTime: defaultReconnectionTime
        };
        const settings = environmentSettingsObject;
        let urlRecord;
        try {
          urlRecord = new URL(url2, settings.settingsObject.baseUrl);
          this.#state.origin = urlRecord.origin;
        } catch (e4) {
          throw new DOMException(e4, "SyntaxError");
        }
        this.#url = urlRecord.href;
        let corsAttributeState = ANONYMOUS;
        if (eventSourceInitDict.withCredentials) {
          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 {0|1|2}
       * @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)) {
            this.dispatchEvent(new Event("error"));
            this.close();
          }
          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")
          });
          pipeline3(
            response.body.stream,
            eventSourceStream,
            (error2) => {
              if (error2?.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
      }
    ]);
    module2.exports = {
      EventSource: EventSource2,
      defaultReconnectionTime
    };
  }
});

// packages/cli/node_modules/undici/index.js
var require_undici2 = __commonJS({
  "packages/cli/node_modules/undici/index.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var Client3 = require_client3();
    var Dispatcher = require_dispatcher2();
    var Pool = require_pool3();
    var BalancedPool = require_balanced_pool2();
    var Agent4 = require_agent3();
    var ProxyAgent6 = require_proxy_agent2();
    var EnvHttpProxyAgent2 = require_env_http_proxy_agent2();
    var RetryAgent = require_retry_agent2();
    var errors = require_errors5();
    var util3 = require_util22();
    var { InvalidArgumentError } = errors;
    var api = require_api3();
    var buildConnector = require_connect2();
    var MockClient = require_mock_client2();
    var MockAgent = require_mock_agent2();
    var MockPool = require_mock_pool2();
    var mockErrors = require_mock_errors2();
    var RetryHandler = require_retry_handler2();
    var { getGlobalDispatcher, setGlobalDispatcher: setGlobalDispatcher3 } = require_global4();
    var DecoratorHandler = require_decorator_handler2();
    var RedirectHandler = require_redirect_handler2();
    var createRedirectInterceptor = require_redirect_interceptor2();
    Object.assign(Dispatcher.prototype, api);
    module2.exports.Dispatcher = Dispatcher;
    module2.exports.Client = Client3;
    module2.exports.Pool = Pool;
    module2.exports.BalancedPool = BalancedPool;
    module2.exports.Agent = Agent4;
    module2.exports.ProxyAgent = ProxyAgent6;
    module2.exports.EnvHttpProxyAgent = EnvHttpProxyAgent2;
    module2.exports.RetryAgent = RetryAgent;
    module2.exports.RetryHandler = RetryHandler;
    module2.exports.DecoratorHandler = DecoratorHandler;
    module2.exports.RedirectHandler = RedirectHandler;
    module2.exports.createRedirectInterceptor = createRedirectInterceptor;
    module2.exports.interceptors = {
      redirect: require_redirect2(),
      retry: require_retry3(),
      dump: require_dump2(),
      dns: require_dns2()
    };
    module2.exports.buildConnector = buildConnector;
    module2.exports.errors = errors;
    module2.exports.util = {
      parseHeaders: util3.parseHeaders,
      headerNameToString: util3.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 path125 = opts.path;
          if (!opts.path.startsWith("/")) {
            path125 = `/${path125}`;
          }
          url2 = new URL(util3.parseOrigin(url2).origin + path125);
        } else {
          if (!opts) {
            opts = typeof url2 === "object" ? url2 : {};
          }
          url2 = util3.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_fetch3().fetch;
    module2.exports.fetch = /* @__PURE__ */ __name(async function fetch5(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_headers2().Headers;
    module2.exports.Response = require_response2().Response;
    module2.exports.Request = require_request4().Request;
    module2.exports.FormData = require_formdata2().FormData;
    module2.exports.File = globalThis.File ?? __require("node:buffer").File;
    module2.exports.FileReader = require_filereader2().FileReader;
    var { setGlobalOrigin, getGlobalOrigin } = require_global3();
    module2.exports.setGlobalOrigin = setGlobalOrigin;
    module2.exports.getGlobalOrigin = getGlobalOrigin;
    var { CacheStorage } = require_cachestorage2();
    var { kConstruct } = require_symbols9();
    module2.exports.caches = new CacheStorage(kConstruct);
    var { deleteCookie, getCookies, getSetCookies, setCookie } = require_cookies2();
    module2.exports.deleteCookie = deleteCookie;
    module2.exports.getCookies = getCookies;
    module2.exports.getSetCookies = getSetCookies;
    module2.exports.setCookie = setCookie;
    var { parseMIMEType, serializeAMimeType } = require_data_url2();
    module2.exports.parseMIMEType = parseMIMEType;
    module2.exports.serializeAMimeType = serializeAMimeType;
    var { CloseEvent, ErrorEvent: ErrorEvent2, MessageEvent: MessageEvent2 } = require_events2();
    module2.exports.WebSocket = require_websocket3().WebSocket;
    module2.exports.CloseEvent = CloseEvent;
    module2.exports.ErrorEvent = ErrorEvent2;
    module2.exports.MessageEvent = MessageEvent2;
    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.MockPool = MockPool;
    module2.exports.MockAgent = MockAgent;
    module2.exports.mockErrors = mockErrors;
    var { EventSource: EventSource2 } = require_eventsource2();
    module2.exports.EventSource = EventSource2;
  }
});

// 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, config2, maybeKey) {
      var key = null;
      void 0 !== maybeKey && (key = "" + maybeKey);
      void 0 !== config2.key && (key = "" + config2.key);
      if ("key" in config2) {
        maybeKey = {};
        for (var propName in config2)
          "key" !== propName && (maybeKey[propName] = config2[propName]);
      } else maybeKey = config2;
      config2 = maybeKey.ref;
      return {
        $$typeof: REACT_ELEMENT_TYPE,
        type,
        key,
        ref: void 0 !== config2 ? config2 : 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";
            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 (x3) {
              }
          }
        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 (e4) {
          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 (x3) {
          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(config2) {
        if (hasOwnProperty2.call(config2, "key")) {
          var getter = Object.getOwnPropertyDescriptor(config2, "key").get;
          if (getter && getter.isReactWarning) return false;
        }
        return void 0 !== config2.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, props, owner, debugStack, debugTask) {
        var refProp = props.ref;
        type = {
          $$typeof: REACT_ELEMENT_TYPE,
          type,
          key,
          props,
          _owner: owner
        };
        null !== (void 0 !== refProp ? refProp : 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, config2, maybeKey, isStaticChildren, debugStack, debugTask) {
        var children = config2.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(config2, "key")) {
          children = getComponentNameFromType(type);
          var keys = Object.keys(config2).filter(function(k2) {
            return "key" !== k2;
          });
          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(config2) && (checkKeyStringCoercion(config2.key), children = "" + config2.key);
        if ("key" in config2) {
          maybeKey = {};
          for (var propName in config2)
            "key" !== propName && (maybeKey[propName] = config2[propName]);
        } else maybeKey = config2;
        children && defineKeyPropWarningGetter(
          maybeKey,
          "function" === typeof type ? type.displayName || type.name || "Unknown" : type
        );
        return ReactElement(
          type,
          children,
          maybeKey,
          getOwner(),
          debugStack,
          debugTask
        );
      }
      __name(jsxDEVImpl, "jsxDEVImpl");
      function validateChildKeys(node) {
        isValidElement(node) ? node._store && (node._store.validated = 1) : "object" === typeof node && null !== node && node.$$typeof === REACT_LAZY_TYPE && ("fulfilled" === node._payload.status ? isValidElement(node._payload.value) && node._payload.value._store && (node._payload.value._store.validated = 1) : node._store && (node._store.validated = 1));
      }
      __name(validateChildKeys, "validateChildKeys");
      function isValidElement(object3) {
        return "object" === typeof object3 && null !== object3 && object3.$$typeof === REACT_ELEMENT_TYPE;
      }
      __name(isValidElement, "isValidElement");
      var React27 = 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"), 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 = React27.__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;
      };
      React27 = {
        react_stack_bottom_frame: /* @__PURE__ */ __name(function(callStackForError) {
          return callStackForError();
        }, "react_stack_bottom_frame")
      };
      var specialPropKeyWarningShown;
      var didWarnAboutElementRef = {};
      var unknownOwnerDebugStack = React27.react_stack_bottom_frame.bind(
        React27,
        UnknownOwner
      )();
      var unknownOwnerDebugTask = createTask(getTaskName(UnknownOwner));
      var didWarnAboutKeySpread = {};
      exports2.Fragment = REACT_FRAGMENT_TYPE;
      exports2.jsx = function(type, config2, maybeKey) {
        var trackActualOwner = 1e4 > ReactSharedInternals.recentlyCreatedOwnerStacks++;
        return jsxDEVImpl(
          type,
          config2,
          maybeKey,
          false,
          trackActualOwner ? Error("react-stack-top-frame") : unknownOwnerDebugStack,
          trackActualOwner ? createTask(getTaskName(type)) : unknownOwnerDebugTask
        );
      };
      exports2.jsxs = function(type, config2, maybeKey) {
        var trackActualOwner = 1e4 > ReactSharedInternals.recentlyCreatedOwnerStacks++;
        return jsxDEVImpl(
          type,
          config2,
          maybeKey,
          true,
          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_core11 = __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 Response6 = 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((x3, i3) => `${x3}${"_".repeat(i3 + 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(re3) {
      if (!re3) return null;
      if (typeof re3 === "string") return re3;
      return re3.source;
    }
    __name(source2, "source");
    function lookahead2(re3) {
      return concat2("(?=", re3, ")");
    }
    __name(lookahead2, "lookahead");
    function anyNumberOfTimes(re3) {
      return concat2("(?:", re3, ")*");
    }
    __name(anyNumberOfTimes, "anyNumberOfTimes");
    function optional2(re3) {
      return concat2("(?:", re3, ")?");
    }
    __name(optional2, "optional");
    function concat2(...args) {
      const joined = args.map((x3) => source2(x3)).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((x3) => source2(x3)).join("|") + ")";
      return joined;
    }
    __name(either2, "either");
    function countMatchGroups(re3) {
      return new RegExp(re3.toString() + "|").exec("").length - 1;
    }
    __name(countMatchGroups, "countMatchGroups");
    function startsWith(re3, lexeme) {
      const match2 = re3 && re3.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 re3 = source2(regex3);
        let out = "";
        while (re3.length > 0) {
          const match2 = BACKREF_RE.exec(re3);
          if (!match2) {
            out += re3;
            break;
          }
          out += re3.substring(0, match2.index);
          re3 = re3.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((re3) => `(${re3})`).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((m3, resp) => {
          if (m3.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((m3, resp) => {
            resp.data._beginMatch = m3[1];
          }, "on:begin"),
          /** @type {ModeCallback} */
          "on:end": /* @__PURE__ */ __name((m3, resp) => {
            if (resp.data._beginMatch !== m3[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((x3) => x3.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 error2 = /* @__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 i3 = 1; i3 <= regexes.length; i3++) {
        positions[i3 + offset] = scopeNames[i3];
        emit[i3 + offset] = true;
        offset += countMatchGroups(regexes[i3 - 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) {
        error2("skip, excludeBegin, returnBegin not compatible with beginScope: {}");
        throw MultiClassError;
      }
      if (typeof mode.beginScope !== "object" || mode.beginScope === null) {
        error2("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) {
        error2("skip, excludeEnd, returnEnd not compatible with endScope: {}");
        throw MultiClassError;
      }
      if (typeof mode.endScope !== "object" || mode.endScope === null) {
        error2("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(re3, opts) {
          opts.position = this.position++;
          this.matchIndexes[this.matchAt] = opts;
          this.regexes.push([opts, re3]);
          this.matchAt += countMatchGroups(re3) + 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(s5) {
          this.matcherRe.lastIndex = this.lastIndex;
          const match2 = this.matcherRe.exec(s5);
          if (!match2) {
            return null;
          }
          const i3 = match2.findIndex((el, i4) => i4 > 0 && el !== void 0);
          const matchData = this.matchIndexes[i3];
          match2.splice(0, i3);
          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(([re3, opts]) => matcher.addRule(re3, opts));
          matcher.compile();
          this.multiRegexes[index] = matcher;
          return matcher;
        }
        resumingScanAtSamePosition() {
          return this.regexIndex !== 0;
        }
        considerAll() {
          this.regexIndex = 0;
        }
        // @ts-ignore
        addRule(re3, opts) {
          this.rules.push([re3, opts]);
          if (opts.type === "begin") this.count++;
        }
        /** @param {string} s */
        exec(s5) {
          const m3 = this.getMatcher(this.regexIndex);
          m3.lastIndex = this.lastIndex;
          let result = m3.exec(s5);
          if (this.resumingScanAtSamePosition()) {
            if (result && result.index === this.lastIndex) ;
            else {
              const m22 = this.getMatcher(0);
              m22.lastIndex = this.lastIndex + 1;
              result = m22.exec(s5);
            }
          }
          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(c4) {
          return expandOrCloneMode(c4 === "self" ? mode : c4);
        }));
        mode.contains.forEach(function(c4) {
          compileMode(
            /** @type Mode */
            c4,
            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 [kind2, keywordRelevance] = data;
              emitter.addText(buf);
              buf = "";
              keywordHits[word] = (keywordHits[word] || 0) + 1;
              if (keywordHits[word] <= MAX_KEYWORD_HITS) relevance += keywordRelevance;
              if (kind2.startsWith("_")) {
                buf += match2[0];
              } else {
                const cssClass = language.classNameAliases[kind2] || kind2;
                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 i3 = 1;
          const max = match2.length - 1;
          while (i3 <= max) {
            if (!scope._emit[i3]) {
              i3++;
              continue;
            }
            const klass = language.classNameAliases[scope[i3]] || scope[i3];
            const text = match2[i3];
            if (klass) {
              emitKeyword(text, klass);
            } else {
              modeBuffer = text;
              processKeywords();
              modeBuffer = "";
            }
            i3++;
          }
        }
        __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 Response6(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 Response6(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) {
          error2(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((a2, b2) => {
          if (a2.relevance !== b2.relevance) return b2.relevance - a2.relevance;
          if (a2.language && b2.language) {
            if (getLanguage(a2.language).supersetOf === b2.language) {
              return 1;
            } else if (getLanguage(b2.language).supersetOf === a2.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) {
          error2("Language definition for '{}' could not be registered.".replace("{}", languageName));
          if (!SAFE_MODE) {
            throw error$1;
          } else {
            error2(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: optional2,
        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/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 b2 = "function" === typeof Symbol && Symbol.for;
    var c4 = b2 ? Symbol.for("react.element") : 60103;
    var d2 = b2 ? Symbol.for("react.portal") : 60106;
    var e4 = b2 ? Symbol.for("react.fragment") : 60107;
    var f5 = b2 ? Symbol.for("react.strict_mode") : 60108;
    var g2 = b2 ? Symbol.for("react.profiler") : 60114;
    var h3 = b2 ? Symbol.for("react.provider") : 60109;
    var k2 = b2 ? Symbol.for("react.context") : 60110;
    var l3 = b2 ? Symbol.for("react.async_mode") : 60111;
    var m3 = b2 ? Symbol.for("react.concurrent_mode") : 60111;
    var n3 = b2 ? Symbol.for("react.forward_ref") : 60112;
    var p2 = b2 ? Symbol.for("react.suspense") : 60113;
    var q2 = b2 ? Symbol.for("react.suspense_list") : 60120;
    var r5 = b2 ? Symbol.for("react.memo") : 60115;
    var t5 = b2 ? Symbol.for("react.lazy") : 60116;
    var v2 = b2 ? Symbol.for("react.block") : 60121;
    var w2 = b2 ? Symbol.for("react.fundamental") : 60117;
    var x3 = b2 ? Symbol.for("react.responder") : 60118;
    var y2 = b2 ? Symbol.for("react.scope") : 60119;
    function z2(a2) {
      if ("object" === typeof a2 && null !== a2) {
        var u2 = a2.$$typeof;
        switch (u2) {
          case c4:
            switch (a2 = a2.type, a2) {
              case l3:
              case m3:
              case e4:
              case g2:
              case f5:
              case p2:
                return a2;
              default:
                switch (a2 = a2 && a2.$$typeof, a2) {
                  case k2:
                  case n3:
                  case t5:
                  case r5:
                  case h3:
                    return a2;
                  default:
                    return u2;
                }
            }
          case d2:
            return u2;
        }
      }
    }
    __name(z2, "z");
    function A4(a2) {
      return z2(a2) === m3;
    }
    __name(A4, "A");
    exports2.AsyncMode = l3;
    exports2.ConcurrentMode = m3;
    exports2.ContextConsumer = k2;
    exports2.ContextProvider = h3;
    exports2.Element = c4;
    exports2.ForwardRef = n3;
    exports2.Fragment = e4;
    exports2.Lazy = t5;
    exports2.Memo = r5;
    exports2.Portal = d2;
    exports2.Profiler = g2;
    exports2.StrictMode = f5;
    exports2.Suspense = p2;
    exports2.isAsyncMode = function(a2) {
      return A4(a2) || z2(a2) === l3;
    };
    exports2.isConcurrentMode = A4;
    exports2.isContextConsumer = function(a2) {
      return z2(a2) === k2;
    };
    exports2.isContextProvider = function(a2) {
      return z2(a2) === h3;
    };
    exports2.isElement = function(a2) {
      return "object" === typeof a2 && null !== a2 && a2.$$typeof === c4;
    };
    exports2.isForwardRef = function(a2) {
      return z2(a2) === n3;
    };
    exports2.isFragment = function(a2) {
      return z2(a2) === e4;
    };
    exports2.isLazy = function(a2) {
      return z2(a2) === t5;
    };
    exports2.isMemo = function(a2) {
      return z2(a2) === r5;
    };
    exports2.isPortal = function(a2) {
      return z2(a2) === d2;
    };
    exports2.isProfiler = function(a2) {
      return z2(a2) === g2;
    };
    exports2.isStrictMode = function(a2) {
      return z2(a2) === f5;
    };
    exports2.isSuspense = function(a2) {
      return z2(a2) === p2;
    };
    exports2.isValidElementType = function(a2) {
      return "string" === typeof a2 || "function" === typeof a2 || a2 === e4 || a2 === m3 || a2 === g2 || a2 === f5 || a2 === p2 || a2 === q2 || "object" === typeof a2 && null !== a2 && (a2.$$typeof === t5 || a2.$$typeof === r5 || a2.$$typeof === h3 || a2.$$typeof === k2 || a2.$$typeof === n3 || a2.$$typeof === w2 || a2.$$typeof === x3 || a2.$$typeof === y2 || a2.$$typeof === v2);
    };
    exports2.typeOf = z2;
  }
});

// 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(object3) {
          if (typeof object3 === "object" && object3 !== null) {
            var $$typeof = object3.$$typeof;
            switch ($$typeof) {
              case REACT_ELEMENT_TYPE:
                var type = object3.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 Fragment16 = 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(object3) {
          {
            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(object3) || typeOf(object3) === REACT_ASYNC_MODE_TYPE;
        }
        __name(isAsyncMode, "isAsyncMode");
        function isConcurrentMode(object3) {
          return typeOf(object3) === REACT_CONCURRENT_MODE_TYPE;
        }
        __name(isConcurrentMode, "isConcurrentMode");
        function isContextConsumer(object3) {
          return typeOf(object3) === REACT_CONTEXT_TYPE;
        }
        __name(isContextConsumer, "isContextConsumer");
        function isContextProvider(object3) {
          return typeOf(object3) === REACT_PROVIDER_TYPE;
        }
        __name(isContextProvider, "isContextProvider");
        function isElement(object3) {
          return typeof object3 === "object" && object3 !== null && object3.$$typeof === REACT_ELEMENT_TYPE;
        }
        __name(isElement, "isElement");
        function isForwardRef(object3) {
          return typeOf(object3) === REACT_FORWARD_REF_TYPE;
        }
        __name(isForwardRef, "isForwardRef");
        function isFragment(object3) {
          return typeOf(object3) === REACT_FRAGMENT_TYPE;
        }
        __name(isFragment, "isFragment");
        function isLazy(object3) {
          return typeOf(object3) === REACT_LAZY_TYPE;
        }
        __name(isLazy, "isLazy");
        function isMemo(object3) {
          return typeOf(object3) === REACT_MEMO_TYPE;
        }
        __name(isMemo, "isMemo");
        function isPortal(object3) {
          return typeOf(object3) === REACT_PORTAL_TYPE;
        }
        __name(isPortal, "isPortal");
        function isProfiler(object3) {
          return typeOf(object3) === REACT_PROFILER_TYPE;
        }
        __name(isProfiler, "isProfiler");
        function isStrictMode(object3) {
          return typeOf(object3) === REACT_STRICT_MODE_TYPE;
        }
        __name(isStrictMode, "isStrictMode");
        function isSuspense(object3) {
          return typeOf(object3) === 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 = Fragment16;
        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 i3 = 0; i3 < 10; i3++) {
          test2["_" + String.fromCharCode(i3)] = i3;
        }
        var order2 = Object.getOwnPropertyNames(test2).map(function(n3) {
          return test2[n3];
        });
        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 s5 = 1; s5 < arguments.length; s5++) {
        from = Object(arguments[s5]);
        for (var key in from) {
          if (hasOwnProperty2.call(from, key)) {
            to[key] = from[key];
          }
        }
        if (getOwnPropertySymbols) {
          symbols = getOwnPropertySymbols(from);
          for (var i3 = 0; i3 < symbols.length; i3++) {
            if (propIsEnumerable.call(from, symbols[i3])) {
              to[symbols[i3]] = from[symbols[i3]];
            }
          }
        }
      }
      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 (x3) {
        }
      }, "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 error2;
            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;
              }
              error2 = typeSpecs[typeSpecName](values, typeSpecName, componentName, location, null, ReactPropTypesSecret);
            } catch (ex) {
              error2 = ex;
            }
            if (error2 && !(error2 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 error2 + ". 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 (error2 instanceof Error && !(error2.message in loggedTypeFailures)) {
              loggedTypeFailures[error2.message] = true;
              var stack = getStack ? getStack() : "";
              printWarning(
                "Failed " + location + " type: " + error2.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 (x3) {
        }
      }, "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(x3, y2) {
        if (x3 === y2) {
          return x3 !== 0 || 1 / x3 === 1 / y2;
        } else {
          return x3 !== x3 && y2 !== y2;
        }
      }
      __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(validate3) {
        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 validate3(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 validate3(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(validate3, "validate");
        return createChainableTypeChecker(validate3);
      }
      __name(createPrimitiveTypeChecker, "createPrimitiveTypeChecker");
      function createAnyTypeChecker() {
        return createChainableTypeChecker(emptyFunctionThatReturnsNull);
      }
      __name(createAnyTypeChecker, "createAnyTypeChecker");
      function createArrayOfTypeChecker(typeChecker) {
        function validate3(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 i3 = 0; i3 < propValue.length; i3++) {
            var error2 = typeChecker(propValue, i3, componentName, location, propFullName + "[" + i3 + "]", ReactPropTypesSecret);
            if (error2 instanceof Error) {
              return error2;
            }
          }
          return null;
        }
        __name(validate3, "validate");
        return createChainableTypeChecker(validate3);
      }
      __name(createArrayOfTypeChecker, "createArrayOfTypeChecker");
      function createElementTypeChecker() {
        function validate3(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(validate3, "validate");
        return createChainableTypeChecker(validate3);
      }
      __name(createElementTypeChecker, "createElementTypeChecker");
      function createElementTypeTypeChecker() {
        function validate3(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(validate3, "validate");
        return createChainableTypeChecker(validate3);
      }
      __name(createElementTypeTypeChecker, "createElementTypeTypeChecker");
      function createInstanceTypeChecker(expectedClass) {
        function validate3(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(validate3, "validate");
        return createChainableTypeChecker(validate3);
      }
      __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 validate3(props, propName, componentName, location, propFullName) {
          var propValue = props[propName];
          for (var i3 = 0; i3 < expectedValues.length; i3++) {
            if (is(propValue, expectedValues[i3])) {
              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(validate3, "validate");
        return createChainableTypeChecker(validate3);
      }
      __name(createEnumTypeChecker, "createEnumTypeChecker");
      function createObjectOfTypeChecker(typeChecker) {
        function validate3(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 error2 = typeChecker(propValue, key, componentName, location, propFullName + "." + key, ReactPropTypesSecret);
              if (error2 instanceof Error) {
                return error2;
              }
            }
          }
          return null;
        }
        __name(validate3, "validate");
        return createChainableTypeChecker(validate3);
      }
      __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 i3 = 0; i3 < arrayOfTypeCheckers.length; i3++) {
          var checker = arrayOfTypeCheckers[i3];
          if (typeof checker !== "function") {
            printWarning(
              "Invalid argument supplied to oneOfType. Expected an array of check functions, but received " + getPostfixForTypeWarning(checker) + " at index " + i3 + "."
            );
            return emptyFunctionThatReturnsNull;
          }
        }
        function validate3(props, propName, componentName, location, propFullName) {
          var expectedTypes = [];
          for (var i4 = 0; i4 < arrayOfTypeCheckers.length; i4++) {
            var checker2 = arrayOfTypeCheckers[i4];
            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(validate3, "validate");
        return createChainableTypeChecker(validate3);
      }
      __name(createUnionTypeChecker, "createUnionTypeChecker");
      function createNodeChecker() {
        function validate3(props, propName, componentName, location, propFullName) {
          if (!isNode3(props[propName])) {
            return new PropTypeError("Invalid " + location + " `" + propFullName + "` supplied to " + ("`" + componentName + "`, expected a ReactNode."));
          }
          return null;
        }
        __name(validate3, "validate");
        return createChainableTypeChecker(validate3);
      }
      __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 validate3(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 error2 = checker(propValue, key, componentName, location, propFullName + "." + key, ReactPropTypesSecret);
            if (error2) {
              return error2;
            }
          }
          return null;
        }
        __name(validate3, "validate");
        return createChainableTypeChecker(validate3);
      }
      __name(createShapeTypeChecker, "createShapeTypeChecker");
      function createStrictShapeTypeChecker(shapeTypes) {
        function validate3(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 error2 = checker(propValue, key, componentName, location, propFullName + "." + key, ReactPropTypesSecret);
            if (error2) {
              return error2;
            }
          }
          return null;
        }
        __name(validate3, "validate");
        return createChainableTypeChecker(validate3);
      }
      __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, R2, G2, B2;
          RsRGB = rgb.r / 255;
          GsRGB = rgb.g / 255;
          BsRGB = rgb.b / 255;
          if (RsRGB <= 0.03928) R2 = RsRGB / 12.92;
          else R2 = Math.pow((RsRGB + 0.055) / 1.055, 2.4);
          if (GsRGB <= 0.03928) G2 = GsRGB / 12.92;
          else G2 = Math.pow((GsRGB + 0.055) / 1.055, 2.4);
          if (BsRGB <= 0.03928) B2 = BsRGB / 12.92;
          else B2 = Math.pow((BsRGB + 0.055) / 1.055, 2.4);
          return 0.2126 * R2 + 0.7152 * G2 + 0.0722 * B2;
        }, "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 h3 = Math.round(hsv.h * 360), s5 = Math.round(hsv.s * 100), v2 = Math.round(hsv.v * 100);
          return this._a == 1 ? "hsv(" + h3 + ", " + s5 + "%, " + v2 + "%)" : "hsva(" + h3 + ", " + s5 + "%, " + v2 + "%, " + 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 h3 = Math.round(hsl.h * 360), s5 = Math.round(hsl.s * 100), l3 = Math.round(hsl.l * 100);
          return this._a == 1 ? "hsl(" + h3 + ", " + s5 + "%, " + l3 + "%)" : "hsla(" + h3 + ", " + s5 + "%, " + l3 + "%, " + 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 s5 = tinycolor(secondColor);
            secondHex8String = "#" + rgbaToArgbHex(s5._r, s5._g, s5._b, s5._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 clone4() {
          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 i3 in color) {
            if (color.hasOwnProperty(i3)) {
              if (i3 === "a") {
                newColor[i3] = color[i3];
              } else {
                newColor[i3] = convertToPercentage(color[i3]);
              }
            }
          }
          color = newColor;
        }
        return tinycolor(color, opts);
      };
      function inputToRGB(color) {
        var rgb = {
          r: 0,
          g: 0,
          b: 0
        };
        var a2 = 1;
        var s5 = null;
        var v2 = null;
        var l3 = 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)) {
            s5 = convertToPercentage(color.s);
            v2 = convertToPercentage(color.v);
            rgb = hsvToRgb(color.h, s5, v2);
            ok2 = true;
            format4 = "hsv";
          } else if (isValidCSSUnit(color.h) && isValidCSSUnit(color.s) && isValidCSSUnit(color.l)) {
            s5 = convertToPercentage(color.s);
            l3 = convertToPercentage(color.l);
            rgb = hslToRgb(color.h, s5, l3);
            ok2 = true;
            format4 = "hsl";
          }
          if (color.hasOwnProperty("a")) {
            a2 = color.a;
          }
        }
        a2 = boundAlpha(a2);
        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: a2
        };
      }
      __name(inputToRGB, "inputToRGB");
      function rgbToRgb(r5, g2, b2) {
        return {
          r: bound01(r5, 255) * 255,
          g: bound01(g2, 255) * 255,
          b: bound01(b2, 255) * 255
        };
      }
      __name(rgbToRgb, "rgbToRgb");
      function rgbToHsl(r5, g2, b2) {
        r5 = bound01(r5, 255);
        g2 = bound01(g2, 255);
        b2 = bound01(b2, 255);
        var max = Math.max(r5, g2, b2), min = Math.min(r5, g2, b2);
        var h3, s5, l3 = (max + min) / 2;
        if (max == min) {
          h3 = s5 = 0;
        } else {
          var d2 = max - min;
          s5 = l3 > 0.5 ? d2 / (2 - max - min) : d2 / (max + min);
          switch (max) {
            case r5:
              h3 = (g2 - b2) / d2 + (g2 < b2 ? 6 : 0);
              break;
            case g2:
              h3 = (b2 - r5) / d2 + 2;
              break;
            case b2:
              h3 = (r5 - g2) / d2 + 4;
              break;
          }
          h3 /= 6;
        }
        return {
          h: h3,
          s: s5,
          l: l3
        };
      }
      __name(rgbToHsl, "rgbToHsl");
      function hslToRgb(h3, s5, l3) {
        var r5, g2, b2;
        h3 = bound01(h3, 360);
        s5 = bound01(s5, 100);
        l3 = bound01(l3, 100);
        function hue2rgb(p3, q3, t5) {
          if (t5 < 0) t5 += 1;
          if (t5 > 1) t5 -= 1;
          if (t5 < 1 / 6) return p3 + (q3 - p3) * 6 * t5;
          if (t5 < 1 / 2) return q3;
          if (t5 < 2 / 3) return p3 + (q3 - p3) * (2 / 3 - t5) * 6;
          return p3;
        }
        __name(hue2rgb, "hue2rgb");
        if (s5 === 0) {
          r5 = g2 = b2 = l3;
        } else {
          var q2 = l3 < 0.5 ? l3 * (1 + s5) : l3 + s5 - l3 * s5;
          var p2 = 2 * l3 - q2;
          r5 = hue2rgb(p2, q2, h3 + 1 / 3);
          g2 = hue2rgb(p2, q2, h3);
          b2 = hue2rgb(p2, q2, h3 - 1 / 3);
        }
        return {
          r: r5 * 255,
          g: g2 * 255,
          b: b2 * 255
        };
      }
      __name(hslToRgb, "hslToRgb");
      function rgbToHsv(r5, g2, b2) {
        r5 = bound01(r5, 255);
        g2 = bound01(g2, 255);
        b2 = bound01(b2, 255);
        var max = Math.max(r5, g2, b2), min = Math.min(r5, g2, b2);
        var h3, s5, v2 = max;
        var d2 = max - min;
        s5 = max === 0 ? 0 : d2 / max;
        if (max == min) {
          h3 = 0;
        } else {
          switch (max) {
            case r5:
              h3 = (g2 - b2) / d2 + (g2 < b2 ? 6 : 0);
              break;
            case g2:
              h3 = (b2 - r5) / d2 + 2;
              break;
            case b2:
              h3 = (r5 - g2) / d2 + 4;
              break;
          }
          h3 /= 6;
        }
        return {
          h: h3,
          s: s5,
          v: v2
        };
      }
      __name(rgbToHsv, "rgbToHsv");
      function hsvToRgb(h3, s5, v2) {
        h3 = bound01(h3, 360) * 6;
        s5 = bound01(s5, 100);
        v2 = bound01(v2, 100);
        var i3 = Math.floor(h3), f5 = h3 - i3, p2 = v2 * (1 - s5), q2 = v2 * (1 - f5 * s5), t5 = v2 * (1 - (1 - f5) * s5), mod2 = i3 % 6, r5 = [v2, q2, p2, p2, t5, v2][mod2], g2 = [t5, v2, v2, q2, p2, p2][mod2], b2 = [p2, p2, t5, v2, v2, q2][mod2];
        return {
          r: r5 * 255,
          g: g2 * 255,
          b: b2 * 255
        };
      }
      __name(hsvToRgb, "hsvToRgb");
      function rgbToHex(r5, g2, b2, allow3Char) {
        var hex = [pad2(Math.round(r5).toString(16)), pad2(Math.round(g2).toString(16)), pad2(Math.round(b2).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(r5, g2, b2, a2, allow4Char) {
        var hex = [pad2(Math.round(r5).toString(16)), pad2(Math.round(g2).toString(16)), pad2(Math.round(b2).toString(16)), pad2(convertDecimalToHex(a2))];
        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(r5, g2, b2, a2) {
        var hex = [pad2(convertDecimalToHex(a2)), pad2(Math.round(r5).toString(16)), pad2(Math.round(g2).toString(16)), pad2(Math.round(b2).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, number4) {
        if (isNaN(number4) || number4 <= 0) {
          throw new Error("Argument to polyad must be a positive number");
        }
        var hsl = tinycolor(color).toHsl();
        var result = [tinycolor(color)];
        var step = 360 / number4;
        for (var i3 = 1; i3 < number4; i3++) {
          result.push(tinycolor({
            h: (hsl.h + i3 * step) % 360,
            s: hsl.s,
            l: hsl.l
          }));
        }
        return result;
      }
      __name(polyad, "polyad");
      function _splitcomplement(color) {
        var hsl = tinycolor(color).toHsl();
        var h3 = hsl.h;
        return [tinycolor(color), tinycolor({
          h: (h3 + 72) % 360,
          s: hsl.s,
          l: hsl.l
        }), tinycolor({
          h: (h3 + 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 h3 = hsv.h, s5 = hsv.s, v2 = hsv.v;
        var ret = [];
        var modification = 1 / results;
        while (results--) {
          ret.push(tinycolor({
            h: h3,
            s: s5,
            v: v2
          }));
          v2 = (v2 + 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 p2 = amount / 100;
        var rgba = {
          r: (rgb2.r - rgb1.r) * p2 + rgb1.r,
          g: (rgb2.g - rgb1.g) * p2 + rgb1.g,
          b: (rgb2.b - rgb1.b) * p2 + rgb1.b,
          a: (rgb2.a - rgb1.a) * p2 + 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 i3 = 0; i3 < colorList.length; i3++) {
          readability = tinycolor.readability(baseColor, colorList[i3]);
          if (readability > bestScore) {
            bestScore = readability;
            bestColor = tinycolor(colorList[i3]);
          }
        }
        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(o3) {
        var flipped = {};
        for (var i3 in o3) {
          if (o3.hasOwnProperty(i3)) {
            flipped[o3[i3]] = i3;
          }
        }
        return flipped;
      }
      __name(flip, "flip");
      function boundAlpha(a2) {
        a2 = parseFloat(a2);
        if (isNaN(a2) || a2 < 0 || a2 > 1) {
          a2 = 1;
        }
        return a2;
      }
      __name(boundAlpha, "boundAlpha");
      function bound01(n3, max) {
        if (isOnePointZero(n3)) n3 = "100%";
        var processPercent = isPercentage(n3);
        n3 = Math.min(max, Math.max(0, parseFloat(n3)));
        if (processPercent) {
          n3 = parseInt(n3 * max, 10) / 100;
        }
        if (Math.abs(n3 - max) < 1e-6) {
          return 1;
        }
        return n3 % 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(n3) {
        return typeof n3 == "string" && n3.indexOf(".") != -1 && parseFloat(n3) === 1;
      }
      __name(isOnePointZero, "isOnePointZero");
      function isPercentage(n3) {
        return typeof n3 === "string" && n3.indexOf("%") != -1;
      }
      __name(isPercentage, "isPercentage");
      function pad2(c4) {
        return c4.length == 1 ? "0" + c4 : "" + c4;
      }
      __name(pad2, "pad2");
      function convertToPercentage(n3) {
        if (n3 <= 1) {
          n3 = n3 * 100 + "%";
        }
        return n3;
      }
      __name(convertToPercentage, "convertToPercentage");
      function convertDecimalToHex(d2) {
        return Math.round(parseFloat(d2) * 255).toString(16);
      }
      __name(convertDecimalToHex, "convertDecimalToHex");
      function convertHexToDecimal(h3) {
        return parseIntFromHex(h3) / 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 k2 in start) {
        if (start.hasOwnProperty(k2)) {
          step[k2] = steps === 0 ? 0 : (end[k2] - start[k2]) / steps;
        }
      }
      return step;
    }
    __name(stepize, "stepize");
    function interpolate2(step, start, i3, max) {
      let color = {};
      for (let k2 in start) {
        if (start.hasOwnProperty(k2)) {
          color[k2] = step[k2] * i3 + start[k2];
          color[k2] = color[k2] < 0 ? color[k2] + max[k2] : max[k2] !== 1 ? color[k2] % max[k2] : color[k2];
        }
      }
      return color;
    }
    __name(interpolate2, "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 i3 = 1; i3 < steps; i3++) {
        const color = interpolate2(step, start, i3, 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 i3 = 1; i3 < steps; i3++) {
        const color = interpolate2(step, start, i3, HSVA_MAX);
        gradient.push(tinycolor(color));
      }
      return gradient;
    }
    __name(interpolateHsv, "interpolateHsv");
    function computeSubsteps(stops, steps) {
      const l3 = stops.length;
      steps = parseInt(steps, 10);
      if (isNaN(steps) || steps < 2) {
        throw new Error("Invalid number of steps (< 2)");
      }
      if (steps < l3) {
        throw new Error("Number of steps cannot be inferior to number of stops");
      }
      let substeps = [];
      for (let i3 = 1; i3 < l3; i3++) {
        const step = (steps - 1) * (stops[i3].pos - stops[i3 - 1].pos);
        substeps.push(Math.max(1, Math.round(step)));
      }
      let totalSubsteps = 1;
      for (let n3 = l3 - 1; n3--; ) totalSubsteps += substeps[n3];
      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 i3 = 0, l3 = stops.length; i3 < l3 - 1; i3++) {
        if (pos2 >= stops[i3].pos && pos2 < stops[i3 + 1].pos) {
          start = stops[i3];
          end = stops[i3 + 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 = interpolate2(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 l3 = stops.length;
        let p2 = -1;
        let lastColorLess = false;
        this.stops = stops.map((stop2, i3) => {
          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 || i3 === 0 || i3 === l3 - 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 < p2) {
              throw new Error("Color stops positions are not ordered");
            }
            p2 = stop2.pos;
          } else {
            stop2 = {
              color: tinycolor(stop2.color !== void 0 ? stop2.color : stop2),
              pos: i3 / (l3 - 1)
            };
          }
          return stop2;
        });
        if (this.stops[0].pos !== 0) {
          this.stops.unshift({
            color: this.stops[0].color,
            pos: 0
          });
          l3++;
        }
        if (this.stops[l3 - 1].pos !== 1) {
          this.stops.push({
            color: this.stops[l3 - 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, i3) => {
          if (stop2.colorLess) {
            stop2.color = interpolateRgb(this.stops[i3 - 1], this.stops[i3 + 1], 2)[1];
          }
        });
        for (let i3 = 0, l3 = this.stops.length; i3 < l3 - 1; i3++) {
          const rgb = interpolateRgb(this.stops[i3], this.stops[i3 + 1], substeps[i3]);
          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, i3) => {
          if (stop2.colorLess) {
            stop2.color = interpolateHsv(this.stops[i3 - 1], this.stops[i3 + 1], 2, mode)[1];
          }
        });
        for (let i3 = 0, l3 = this.stops.length; i3 < l3 - 1; i3++) {
          const hsv = interpolateHsv(this.stops[i3], this.stops[i3 + 1], substeps[i3], 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 chalk9 = 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 s5 of str2) {
        result += s5.match(forbiddenChars) ? s5 : chalk9.hex(colors.shift().toHex())(s5);
      }
      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((l3) => l3.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 l3 of line) {
          lineResult += chalk9.hex(lineColors.shift().toHex())(l3);
        }
        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 a2 in aliases) {
      module2.exports[a2] = (str2) => new InitGradient(aliases[a2].colors)(str2, aliases[a2].options);
      module2.exports[a2].multiline = (str2) => new InitGradient(aliases[a2].colors).multiline(str2, aliases[a2].options);
    }
  }
});

// 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 os47 = __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 = os47.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 m3 = /(\d{1,2})(\d{2})/.exec(versionString);
        return {
          major: 0,
          minor: parseInt(m3[1], 10),
          patch: parseInt(m3[2], 10)
        };
      }
      const versions = (versionString || "").split(".").map((n3) => parseInt(n3, 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 i3 = 0; i3 < this.data.length; i3++) {
          buffer.put(this.data.charCodeAt(i3), 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(n3) {
        if (n3 < 1) {
          throw new Error("glog(" + n3 + ")");
        }
        return QRMath.LOG_TABLE[n3];
      }, "glog"),
      gexp: /* @__PURE__ */ __name(function(n3) {
        while (n3 < 0) {
          n3 += 255;
        }
        while (n3 >= 256) {
          n3 -= 255;
        }
        return QRMath.EXP_TABLE[n3];
      }, "gexp"),
      EXP_TABLE: new Array(256),
      LOG_TABLE: new Array(256)
    };
    for (i3 = 0; i3 < 8; i3++) {
      QRMath.EXP_TABLE[i3] = 1 << i3;
    }
    var i3;
    for (i3 = 8; i3 < 256; i3++) {
      QRMath.EXP_TABLE[i3] = QRMath.EXP_TABLE[i3 - 4] ^ QRMath.EXP_TABLE[i3 - 5] ^ QRMath.EXP_TABLE[i3 - 6] ^ QRMath.EXP_TABLE[i3 - 8];
    }
    var i3;
    for (i3 = 0; i3 < 255; i3++) {
      QRMath.LOG_TABLE[QRMath.EXP_TABLE[i3]] = i3;
    }
    var i3;
    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 i3 = 0; i3 < num.length - offset; i3++) {
        this.num[i3] = num[i3 + 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(e4) {
        var num = new Array(this.getLength() + e4.getLength() - 1);
        for (var i3 = 0; i3 < this.getLength(); i3++) {
          for (var j2 = 0; j2 < e4.getLength(); j2++) {
            num[i3 + j2] ^= QRMath.gexp(QRMath.glog(this.get(i3)) + QRMath.glog(e4.get(j2)));
          }
        }
        return new QRPolynomial(num, 0);
      }, "multiply"),
      mod: /* @__PURE__ */ __name(function(e4) {
        if (this.getLength() - e4.getLength() < 0) {
          return this;
        }
        var ratio = QRMath.glog(this.get(0)) - QRMath.glog(e4.get(0));
        var num = new Array(this.getLength());
        for (var i3 = 0; i3 < this.getLength(); i3++) {
          num[i3] = this.get(i3);
        }
        for (var x3 = 0; x3 < e4.getLength(); x3++) {
          num[x3] ^= QRMath.gexp(QRMath.glog(e4.get(x3)) + ratio);
        }
        return new QRPolynomial(num, 0).mod(e4);
      }, "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 d2 = data << 10;
        while (QRUtil.getBCHDigit(d2) - QRUtil.getBCHDigit(QRUtil.G15) >= 0) {
          d2 ^= QRUtil.G15 << QRUtil.getBCHDigit(d2) - QRUtil.getBCHDigit(QRUtil.G15);
        }
        return (data << 10 | d2) ^ QRUtil.G15_MASK;
      }, "getBCHTypeInfo"),
      getBCHTypeNumber: /* @__PURE__ */ __name(function(data) {
        var d2 = data << 12;
        while (QRUtil.getBCHDigit(d2) - QRUtil.getBCHDigit(QRUtil.G18) >= 0) {
          d2 ^= QRUtil.G18 << QRUtil.getBCHDigit(d2) - QRUtil.getBCHDigit(QRUtil.G18);
        }
        return data << 12 | d2;
      }, "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, i3, j2) {
        switch (maskPattern) {
          case QRMaskPattern.PATTERN000:
            return (i3 + j2) % 2 === 0;
          case QRMaskPattern.PATTERN001:
            return i3 % 2 === 0;
          case QRMaskPattern.PATTERN010:
            return j2 % 3 === 0;
          case QRMaskPattern.PATTERN011:
            return (i3 + j2) % 3 === 0;
          case QRMaskPattern.PATTERN100:
            return (Math.floor(i3 / 2) + Math.floor(j2 / 3)) % 2 === 0;
          case QRMaskPattern.PATTERN101:
            return i3 * j2 % 2 + i3 * j2 % 3 === 0;
          case QRMaskPattern.PATTERN110:
            return (i3 * j2 % 2 + i3 * j2 % 3) % 2 === 0;
          case QRMaskPattern.PATTERN111:
            return (i3 * j2 % 3 + (i3 + j2) % 2) % 2 === 0;
          default:
            throw new Error("bad maskPattern:" + maskPattern);
        }
      }, "getMask"),
      getErrorCorrectPolynomial: /* @__PURE__ */ __name(function(errorCorrectLength) {
        var a2 = new QRPolynomial([1], 0);
        for (var i3 = 0; i3 < errorCorrectLength; i3++) {
          a2 = a2.multiply(new QRPolynomial([1, QRMath.gexp(i3)], 0));
        }
        return a2;
      }, "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 r5 = -1; r5 <= 1; r5++) {
              if (row + r5 < 0 || moduleCount <= row + r5) {
                continue;
              }
              for (var c4 = -1; c4 <= 1; c4++) {
                if (col + c4 < 0 || moduleCount <= col + c4) {
                  continue;
                }
                if (r5 === 0 && c4 === 0) {
                  continue;
                }
                if (dark === qrCode.isDark(row + r5, col + c4)) {
                  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 i3 = 0; i3 < length; i3++) {
        var count = rsBlock[i3 * 3 + 0];
        var totalCount = rsBlock[i3 * 3 + 1];
        var dataCount = rsBlock[i3 * 3 + 2];
        for (var j2 = 0; j2 < count; j2++) {
          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 i3 = 0; i3 < length; i3++) {
          this.putBit((num >>> length - i3 - 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 i3 = 0; i3 < rsBlocks.length; i3++) {
              totalDataCount += rsBlocks[i3].dataCount;
            }
            for (var x3 = 0; x3 < this.dataList.length; x3++) {
              var data = this.dataList[x3];
              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 r5 = -1; r5 <= 7; r5++) {
          if (row + r5 <= -1 || this.moduleCount <= row + r5) continue;
          for (var c4 = -1; c4 <= 7; c4++) {
            if (col + c4 <= -1 || this.moduleCount <= col + c4) continue;
            if (0 <= r5 && r5 <= 6 && (c4 === 0 || c4 === 6) || 0 <= c4 && c4 <= 6 && (r5 === 0 || r5 === 6) || 2 <= r5 && r5 <= 4 && 2 <= c4 && c4 <= 4) {
              this.modules[row + r5][col + c4] = true;
            } else {
              this.modules[row + r5][col + c4] = false;
            }
          }
        }
      }, "setupPositionProbePattern"),
      getBestMaskPattern: /* @__PURE__ */ __name(function() {
        var minLostPoint = 0;
        var pattern = 0;
        for (var i3 = 0; i3 < 8; i3++) {
          this.makeImpl(true, i3);
          var lostPoint = QRUtil.getLostPoint(this);
          if (i3 === 0 || minLostPoint > lostPoint) {
            minLostPoint = lostPoint;
            pattern = i3;
          }
        }
        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 y2 = row * cs;
          for (var col = 0; col < this.modules[row].length; col++) {
            var x3 = col * cs;
            var dark = this.modules[row][col];
            if (dark) {
              qr_mc.beginFill(0, 100);
              qr_mc.moveTo(x3, y2);
              qr_mc.lineTo(x3 + cs, y2);
              qr_mc.lineTo(x3 + cs, y2 + cs);
              qr_mc.lineTo(x3, y2 + cs);
              qr_mc.endFill();
            }
          }
        }
        return qr_mc;
      }, "createMovieClip"),
      setupTimingPattern: /* @__PURE__ */ __name(function() {
        for (var r5 = 8; r5 < this.moduleCount - 8; r5++) {
          if (this.modules[r5][6] !== null) {
            continue;
          }
          this.modules[r5][6] = r5 % 2 === 0;
        }
        for (var c4 = 8; c4 < this.moduleCount - 8; c4++) {
          if (this.modules[6][c4] !== null) {
            continue;
          }
          this.modules[6][c4] = c4 % 2 === 0;
        }
      }, "setupTimingPattern"),
      setupPositionAdjustPattern: /* @__PURE__ */ __name(function() {
        var pos2 = QRUtil.getPatternPosition(this.typeNumber);
        for (var i3 = 0; i3 < pos2.length; i3++) {
          for (var j2 = 0; j2 < pos2.length; j2++) {
            var row = pos2[i3];
            var col = pos2[j2];
            if (this.modules[row][col] !== null) {
              continue;
            }
            for (var r5 = -2; r5 <= 2; r5++) {
              for (var c4 = -2; c4 <= 2; c4++) {
                if (Math.abs(r5) === 2 || Math.abs(c4) === 2 || r5 === 0 && c4 === 0) {
                  this.modules[row + r5][col + c4] = true;
                } else {
                  this.modules[row + r5][col + c4] = false;
                }
              }
            }
          }
        }
      }, "setupPositionAdjustPattern"),
      setupTypeNumber: /* @__PURE__ */ __name(function(test) {
        var bits = QRUtil.getBCHTypeNumber(this.typeNumber);
        var mod2;
        for (var i3 = 0; i3 < 18; i3++) {
          mod2 = !test && (bits >> i3 & 1) === 1;
          this.modules[Math.floor(i3 / 3)][i3 % 3 + this.moduleCount - 8 - 3] = mod2;
        }
        for (var x3 = 0; x3 < 18; x3++) {
          mod2 = !test && (bits >> x3 & 1) === 1;
          this.modules[x3 % 3 + this.moduleCount - 8 - 3][Math.floor(x3 / 3)] = mod2;
        }
      }, "setupTypeNumber"),
      setupTypeInfo: /* @__PURE__ */ __name(function(test, maskPattern) {
        var data = this.errorCorrectLevel << 3 | maskPattern;
        var bits = QRUtil.getBCHTypeInfo(data);
        var mod2;
        for (var v2 = 0; v2 < 15; v2++) {
          mod2 = !test && (bits >> v2 & 1) === 1;
          if (v2 < 6) {
            this.modules[v2][8] = mod2;
          } else if (v2 < 8) {
            this.modules[v2 + 1][8] = mod2;
          } else {
            this.modules[this.moduleCount - 15 + v2][8] = mod2;
          }
        }
        for (var h3 = 0; h3 < 15; h3++) {
          mod2 = !test && (bits >> h3 & 1) === 1;
          if (h3 < 8) {
            this.modules[8][this.moduleCount - h3 - 1] = mod2;
          } else if (h3 < 9) {
            this.modules[8][15 - h3 - 1 + 1] = mod2;
          } else {
            this.modules[8][15 - h3 - 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 c4 = 0; c4 < 2; c4++) {
              if (this.modules[row][col - c4] === null) {
                var dark = false;
                if (byteIndex < data.length) {
                  dark = (data[byteIndex] >>> bitIndex & 1) === 1;
                }
                var mask = QRUtil.getMask(maskPattern, row, col - c4);
                if (mask) {
                  dark = !dark;
                }
                this.modules[row][col - c4] = 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 i3 = 0; i3 < dataList.length; i3++) {
        var data = dataList[i3];
        buffer.put(data.mode, 4);
        buffer.put(data.getLength(), QRUtil.getLengthInBits(data.mode, typeNumber));
        data.write(buffer);
      }
      var totalDataCount = 0;
      for (var x3 = 0; x3 < rsBlocks.length; x3++) {
        totalDataCount += rsBlocks[x3].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 r5 = 0; r5 < rsBlocks.length; r5++) {
        var dcCount = rsBlocks[r5].dataCount;
        var ecCount = rsBlocks[r5].totalCount - dcCount;
        maxDcCount = Math.max(maxDcCount, dcCount);
        maxEcCount = Math.max(maxEcCount, ecCount);
        dcdata[r5] = new Array(dcCount);
        for (var i3 = 0; i3 < dcdata[r5].length; i3++) {
          dcdata[r5][i3] = 255 & buffer.buffer[i3 + offset];
        }
        offset += dcCount;
        var rsPoly = QRUtil.getErrorCorrectPolynomial(ecCount);
        var rawPoly = new QRPolynomial(dcdata[r5], rsPoly.getLength() - 1);
        var modPoly = rawPoly.mod(rsPoly);
        ecdata[r5] = new Array(rsPoly.getLength() - 1);
        for (var x3 = 0; x3 < ecdata[r5].length; x3++) {
          var modIndex = x3 + modPoly.getLength() - ecdata[r5].length;
          ecdata[r5][x3] = modIndex >= 0 ? modPoly.get(modIndex) : 0;
        }
      }
      var totalCodeCount = 0;
      for (var y2 = 0; y2 < rsBlocks.length; y2++) {
        totalCodeCount += rsBlocks[y2].totalCount;
      }
      var data = new Array(totalCodeCount);
      var index = 0;
      for (var z2 = 0; z2 < maxDcCount; z2++) {
        for (var s5 = 0; s5 < rsBlocks.length; s5++) {
          if (z2 < dcdata[s5].length) {
            data[index++] = dcdata[s5][z2];
          }
        }
      }
      for (var xx = 0; xx < maxEcCount; xx++) {
        for (var t5 = 0; t5 < rsBlocks.length; t5++) {
          if (xx < ecdata[t5].length) {
            data[index++] = ecdata[t5][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 i3 = 0; i3 < length; i3++) {
        arr[i3] = 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(error2) {
        this.error = QRErrorCorrectLevel[error2] || this.error;
      }, "setErrorLevel")
    };
  }
});

// packages/cli/node_modules/gaxios/package.json
var require_package6 = __commonJS({
  "packages/cli/node_modules/gaxios/package.json"(exports2, module2) {
    module2.exports = {
      name: "gaxios",
      version: "7.1.3",
      description: "A simple common HTTP client specifically for Google APIs and services.",
      main: "build/cjs/src/index.js",
      types: "build/cjs/src/index.d.ts",
      files: [
        "build/"
      ],
      exports: {
        ".": {
          import: {
            types: "./build/esm/src/index.d.ts",
            default: "./build/esm/src/index.js"
          },
          require: {
            types: "./build/cjs/src/index.d.ts",
            default: "./build/cjs/src/index.js"
          }
        }
      },
      scripts: {
        lint: "gts check --no-inline-config",
        test: "c8 mocha build/esm/test",
        "presystem-test": "npm run compile",
        "system-test": "mocha build/esm/system-test --timeout 80000",
        compile: "tsc -b ./tsconfig.json ./tsconfig.cjs.json && node utils/enable-esm.mjs",
        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: "jsdoc -c .jsdoc.js",
        "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"
      },
      repository: {
        type: "git",
        directory: "packages/gaxios",
        url: "https://github.com/googleapis/google-cloud-node-core.git"
      },
      keywords: [
        "google"
      ],
      engines: {
        node: ">=18"
      },
      author: "Google, LLC",
      license: "Apache-2.0",
      devDependencies: {
        "@babel/plugin-proposal-private-methods": "^7.18.6",
        "@types/cors": "^2.8.6",
        "@types/express": "^5.0.0",
        "@types/extend": "^3.0.1",
        "@types/mocha": "^10.0.10",
        "@types/multiparty": "4.2.1",
        "@types/mv": "^2.1.0",
        "@types/ncp": "^2.0.1",
        "@types/node": "^22.0.0",
        "@types/sinon": "^17.0.0",
        "@types/tmp": "0.2.6",
        assert: "^2.0.0",
        browserify: "^17.0.0",
        c8: "^10.0.0",
        cors: "^2.8.5",
        express: "^5.0.0",
        gts: "^6.0.0",
        "is-docker": "^3.0.0",
        jsdoc: "^4.0.0",
        "jsdoc-fresh": "^5.0.0",
        "jsdoc-region-tag": "^4.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.1",
        linkinator: "^6.1.2",
        mocha: "^11.1.0",
        multiparty: "^4.2.1",
        mv: "^2.1.1",
        ncp: "^2.0.0",
        nock: "^14.0.0-beta.13",
        "null-loader": "^4.0.0",
        "pack-n-play": "^4.0.0",
        puppeteer: "^24.0.0",
        sinon: "^21.0.0",
        "stream-browserify": "^3.0.0",
        tmp: "0.2.5",
        "ts-loader": "^9.5.2",
        typescript: "^5.8.3",
        webpack: "^5.35.0",
        "webpack-cli": "^6.0.1"
      },
      dependencies: {
        extend: "^3.0.2",
        "https-proxy-agent": "^7.0.1",
        "node-fetch": "^3.3.2",
        rimraf: "^5.0.1"
      },
      homepage: "https://github.com/googleapis/google-cloud-node-core/tree/main/packages/gaxios"
    };
  }
});

// packages/cli/node_modules/gaxios/build/cjs/src/util.cjs
var require_util30 = __commonJS({
  "packages/cli/node_modules/gaxios/build/cjs/src/util.cjs"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var pkg2 = require_package6();
    module2.exports = { pkg: pkg2 };
  }
});

// packages/cli/node_modules/gaxios/build/cjs/src/common.js
var require_common6 = __commonJS({
  "packages/cli/node_modules/gaxios/build/cjs/src/common.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.GaxiosError = exports2.GAXIOS_ERROR_SYMBOL = void 0;
    exports2.defaultErrorRedactor = defaultErrorRedactor;
    var extend_1 = __importDefault(require_extend());
    var util_cjs_1 = __importDefault(require_util30());
    var pkg2 = util_cjs_1.default.pkg;
    exports2.GAXIOS_ERROR_SYMBOL = Symbol.for(`${pkg2.name}-gaxios-error`);
    var GaxiosError = class _GaxiosError extends Error {
      static {
        __name(this, "GaxiosError");
      }
      config;
      response;
      /**
       * An error code.
       * Can be a system error code, DOMException error name, or any error's 'code' property where it is a `string`.
       *
       * It is only a `number` when the cause is sourced from an API-level error (AIP-193).
       *
       * @see {@link https://nodejs.org/api/errors.html#errorcode error.code}
       * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/DOMException#error_names DOMException#error_names}
       * @see {@link https://google.aip.dev/193#http11json-representation AIP-193}
       *
       * @example
       * 'ECONNRESET'
       *
       * @example
       * 'TimeoutError'
       *
       * @example
       * 500
       */
      code;
      /**
       * An HTTP Status code.
       * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/Response/status Response#status}
       *
       * @example
       * 500
       */
      status;
      /**
       * @deprecated use {@link GaxiosError.cause} instead.
       *
       * @see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error/cause Error#cause}
       *
       * @privateRemarks
       *
       * We will want to remove this property later as the modern `cause` property is better suited
       * for displaying and relaying nested errors. Keeping this here makes the resulting
       * error log larger than it needs to be.
       *
       */
      error;
      /**
       * Support `instanceof` operator for `GaxiosError` across builds/duplicated files.
       *
       * @see {@link GAXIOS_ERROR_SYMBOL}
       * @see {@link GaxiosError[Symbol.hasInstance]}
       * @see {@link https://github.com/microsoft/TypeScript/issues/13965#issuecomment-278570200}
       * @see {@link https://stackoverflow.com/questions/46618852/require-and-instanceof}
       * @see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/@@hasInstance#reverting_to_default_instanceof_behavior}
       */
      [exports2.GAXIOS_ERROR_SYMBOL] = pkg2.version;
      /**
       * Support `instanceof` operator for `GaxiosError` across builds/duplicated files.
       *
       * @see {@link GAXIOS_ERROR_SYMBOL}
       * @see {@link GaxiosError[GAXIOS_ERROR_SYMBOL]}
       */
      static [Symbol.hasInstance](instance) {
        if (instance && typeof instance === "object" && exports2.GAXIOS_ERROR_SYMBOL in instance && instance[exports2.GAXIOS_ERROR_SYMBOL] === pkg2.version) {
          return true;
        }
        return Function.prototype[Symbol.hasInstance].call(_GaxiosError, instance);
      }
      constructor(message, config2, response, cause) {
        super(message, { cause });
        this.config = config2;
        this.response = response;
        this.error = cause instanceof Error ? cause : void 0;
        this.config = (0, extend_1.default)(true, {}, config2);
        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,
              // workaround for `node-fetch`'s `.data` deprecation...
              this.response?.bodyUsed ? this.response?.data : void 0
            );
          } catch {
          }
          this.status = this.response.status;
        }
        if (cause instanceof DOMException) {
          this.code = cause.name;
        } else if (cause && typeof cause === "object" && "code" in cause && (typeof cause.code === "string" || typeof cause.code === "number")) {
          this.code = cause.code;
        }
      }
      /**
       * An AIP-193 conforming error extractor.
       *
       * @see {@link https://google.aip.dev/193#http11json-representation AIP-193}
       *
       * @internal
       * @expiremental
       *
       * @param res the response object
       * @returns the extracted error information
       */
      static extractAPIErrorFromResponse(res, defaultErrorMessage = "The request failed") {
        let message = defaultErrorMessage;
        if (typeof res.data === "string") {
          message = res.data;
        }
        if (res.data && typeof res.data === "object" && "error" in res.data && res.data.error && !res.ok) {
          if (typeof res.data.error === "string") {
            return {
              message: res.data.error,
              code: res.status,
              status: res.statusText
            };
          }
          if (typeof res.data.error === "object") {
            message = "message" in res.data.error && typeof res.data.error.message === "string" ? res.data.error.message : message;
            const status = "status" in res.data.error && typeof res.data.error.status === "string" ? res.data.error.status : res.statusText;
            const code2 = "code" in res.data.error && typeof res.data.error.code === "number" ? res.data.error.code : res.status;
            if ("errors" in res.data.error && Array.isArray(res.data.error.errors)) {
              const errorMessages = [];
              for (const e4 of res.data.error.errors) {
                if (typeof e4 === "object" && "message" in e4 && typeof e4.message === "string") {
                  errorMessages.push(e4.message);
                }
              }
              return Object.assign({
                message: errorMessages.join("\n") || message,
                code: code2,
                status
              }, res.data.error);
            }
            return Object.assign({
              message,
              code: code2,
              status
            }, res.data.error);
          }
        }
        return {
          message,
          code: res.status,
          status: res.statusText
        };
      }
    };
    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;
        headers.forEach((_2, key) => {
          if (/^authentication$/i.test(key) || /^authorization$/i.test(key) || /secret/i.test(key))
            headers.set(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 (!obj || typeof obj !== "object") {
          return;
        } else if (obj instanceof FormData || obj instanceof URLSearchParams || // support `node-fetch` FormData/URLSearchParams
        "forEach" in obj && "set" in obj) {
          obj.forEach((_2, key) => {
            if (["grant_type", "assertion"].includes(key) || /secret/.test(key)) {
              obj.set(key, REDACT);
            }
          });
        } else {
          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);
        if (data.config.url.searchParams.has("token")) {
          data.config.url.searchParams.set("token", REDACT);
        }
        if (data.config.url.searchParams.has("client_secret")) {
          data.config.url.searchParams.set("client_secret", REDACT);
        }
      }
      if (data.response) {
        defaultErrorRedactor({ config: data.response.config });
        redactHeaders(data.response.headers);
        if (data.response.bodyUsed) {
          redactString(data.response, "data");
          redactObject(data.response.data);
        }
      }
      return data;
    }
    __name(defaultErrorRedactor, "defaultErrorRedactor");
  }
});

// packages/cli/node_modules/gaxios/build/cjs/src/retry.js
var require_retry4 = __commonJS({
  "packages/cli/node_modules/gaxios/build/cjs/src/retry.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.getRetryConfig = getRetryConfig;
    async function getRetryConfig(err) {
      let config2 = getConfig(err);
      if (!err || !err.config || !config2 && !err.config.retry) {
        return { shouldRetry: false };
      }
      config2 = config2 || {};
      config2.currentRetryAttempt = config2.currentRetryAttempt || 0;
      config2.retry = config2.retry === void 0 || config2.retry === null ? 3 : config2.retry;
      config2.httpMethodsToRetry = config2.httpMethodsToRetry || [
        "GET",
        "HEAD",
        "PUT",
        "OPTIONS",
        "DELETE"
      ];
      config2.noResponseRetries = config2.noResponseRetries === void 0 || config2.noResponseRetries === null ? 2 : config2.noResponseRetries;
      config2.retryDelayMultiplier = config2.retryDelayMultiplier ? config2.retryDelayMultiplier : 2;
      config2.timeOfFirstRequest = config2.timeOfFirstRequest ? config2.timeOfFirstRequest : Date.now();
      config2.totalTimeout = config2.totalTimeout ? config2.totalTimeout : Number.MAX_SAFE_INTEGER;
      config2.maxRetryDelay = config2.maxRetryDelay ? config2.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]
      ];
      config2.statusCodesToRetry = config2.statusCodesToRetry || retryRanges;
      err.config.retryConfig = config2;
      const shouldRetryFn = config2.shouldRetry || shouldRetryRequest;
      if (!await shouldRetryFn(err)) {
        return { shouldRetry: false, config: err.config };
      }
      const delay4 = getNextRetryDelay(config2);
      err.config.retryConfig.currentRetryAttempt += 1;
      const backoff = config2.retryBackoff ? config2.retryBackoff(err, delay4) : new Promise((resolve30) => {
        setTimeout(resolve30, delay4);
      });
      if (config2.onRetryAttempt) {
        await config2.onRetryAttempt(err);
      }
      await backoff;
      return { shouldRetry: true, config: err.config };
    }
    __name(getRetryConfig, "getRetryConfig");
    function shouldRetryRequest(err) {
      const config2 = getConfig(err);
      if (err.config.signal?.aborted && err.code !== "TimeoutError" || err.code === "AbortError") {
        return false;
      }
      if (!config2 || config2.retry === 0) {
        return false;
      }
      if (!err.response && (config2.currentRetryAttempt || 0) >= config2.noResponseRetries) {
        return false;
      }
      if (!config2.httpMethodsToRetry || !config2.httpMethodsToRetry.includes(err.config.method?.toUpperCase() || "GET")) {
        return false;
      }
      if (err.response && err.response.status) {
        let isInRange = false;
        for (const [min, max] of config2.statusCodesToRetry) {
          const status = err.response.status;
          if (status >= min && status <= max) {
            isInRange = true;
            break;
          }
        }
        if (!isInRange) {
          return false;
        }
      }
      config2.currentRetryAttempt = config2.currentRetryAttempt || 0;
      if (config2.currentRetryAttempt >= config2.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(config2) {
      const retryDelay = config2.currentRetryAttempt ? 0 : config2.retryDelay ?? 100;
      const calculatedDelay = retryDelay + (Math.pow(config2.retryDelayMultiplier, config2.currentRetryAttempt) - 1) / 2 * 1e3;
      const maxAllowableDelay = config2.totalTimeout - (Date.now() - config2.timeOfFirstRequest);
      return Math.min(calculatedDelay, maxAllowableDelay, config2.maxRetryDelay);
    }
    __name(getNextRetryDelay, "getNextRetryDelay");
  }
});

// packages/cli/node_modules/gaxios/build/cjs/src/interceptor.js
var require_interceptor2 = __commonJS({
  "packages/cli/node_modules/gaxios/build/cjs/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;
  }
});

// packages/cli/node_modules/node-fetch/src/errors/base.js
var FetchBaseError2;
var init_base2 = __esm({
  "packages/cli/node_modules/node-fetch/src/errors/base.js"() {
    init_esbuild_shims();
    FetchBaseError2 = class extends Error {
      static {
        __name(this, "FetchBaseError");
      }
      constructor(message, type) {
        super(message);
        Error.captureStackTrace(this, this.constructor);
        this.type = type;
      }
      get name() {
        return this.constructor.name;
      }
      get [Symbol.toStringTag]() {
        return this.constructor.name;
      }
    };
  }
});

// packages/cli/node_modules/node-fetch/src/errors/fetch-error.js
var FetchError3;
var init_fetch_error2 = __esm({
  "packages/cli/node_modules/node-fetch/src/errors/fetch-error.js"() {
    init_esbuild_shims();
    init_base2();
    FetchError3 = class extends FetchBaseError2 {
      static {
        __name(this, "FetchError");
      }
      /**
       * @param  {string} message -      Error message for human
       * @param  {string} [type] -        Error type for machine
       * @param  {SystemError} [systemError] - For Node.js system error
       */
      constructor(message, type, systemError) {
        super(message, type);
        if (systemError) {
          this.code = this.errno = systemError.code;
          this.erroredSysCall = systemError.syscall;
        }
      }
    };
  }
});

// packages/cli/node_modules/node-fetch/src/utils/is.js
var NAME2, isURLSearchParameters2, isBlob3, isAbortSignal2, isDomainOrSubdomain2, isSameProtocol2;
var init_is2 = __esm({
  "packages/cli/node_modules/node-fetch/src/utils/is.js"() {
    init_esbuild_shims();
    NAME2 = Symbol.toStringTag;
    isURLSearchParameters2 = /* @__PURE__ */ __name((object3) => {
      return typeof object3 === "object" && typeof object3.append === "function" && typeof object3.delete === "function" && typeof object3.get === "function" && typeof object3.getAll === "function" && typeof object3.has === "function" && typeof object3.set === "function" && typeof object3.sort === "function" && object3[NAME2] === "URLSearchParams";
    }, "isURLSearchParameters");
    isBlob3 = /* @__PURE__ */ __name((object3) => {
      return object3 && typeof object3 === "object" && typeof object3.arrayBuffer === "function" && typeof object3.type === "string" && typeof object3.stream === "function" && typeof object3.constructor === "function" && /^(Blob|File)$/.test(object3[NAME2]);
    }, "isBlob");
    isAbortSignal2 = /* @__PURE__ */ __name((object3) => {
      return typeof object3 === "object" && (object3[NAME2] === "AbortSignal" || object3[NAME2] === "EventTarget");
    }, "isAbortSignal");
    isDomainOrSubdomain2 = /* @__PURE__ */ __name((destination, original) => {
      const orig = new URL(original).hostname;
      const dest = new URL(destination).hostname;
      return orig === dest || orig.endsWith(`.${dest}`);
    }, "isDomainOrSubdomain");
    isSameProtocol2 = /* @__PURE__ */ __name((destination, original) => {
      const orig = new URL(original).protocol;
      const dest = new URL(destination).protocol;
      return orig === dest;
    }, "isSameProtocol");
  }
});

// packages/cli/node_modules/node-fetch/src/utils/multipart-parser.js
var multipart_parser_exports2 = {};
__export(multipart_parser_exports2, {
  toFormData: () => toFormData2
});
function _fileName2(headerValue) {
  const m3 = headerValue.match(/\bfilename=("(.*?)"|([^()<>@,;:\\"/[\]?={}\s\t]+))($|;\s)/i);
  if (!m3) {
    return;
  }
  const match2 = m3[2] || m3[3] || "";
  let filename = match2.slice(match2.lastIndexOf("\\") + 1);
  filename = filename.replace(/%22/g, '"');
  filename = filename.replace(/&#(\d{4});/g, (m4, code2) => {
    return String.fromCharCode(code2);
  });
  return filename;
}
async function toFormData2(Body3, ct2) {
  if (!/multipart/i.test(ct2)) {
    throw new TypeError("Failed to fetch");
  }
  const m3 = ct2.match(/boundary=(?:"([^"]+)"|([^;]+))/i);
  if (!m3) {
    throw new TypeError("no or bad content-type header, no multipart boundary");
  }
  const parser6 = new MultipartParser2(m3[1] || m3[2]);
  let headerField;
  let headerValue;
  let entryValue;
  let entryName;
  let contentType;
  let filename;
  const entryChunks = [];
  const formData = new FormData2();
  const onPartData = /* @__PURE__ */ __name((ui8a) => {
    entryValue += decoder.decode(ui8a, { stream: true });
  }, "onPartData");
  const appendToFile = /* @__PURE__ */ __name((ui8a) => {
    entryChunks.push(ui8a);
  }, "appendToFile");
  const appendFileToFormData = /* @__PURE__ */ __name(() => {
    const file = new file_default(entryChunks, filename, { type: contentType });
    formData.append(entryName, file);
  }, "appendFileToFormData");
  const appendEntryToFormData = /* @__PURE__ */ __name(() => {
    formData.append(entryName, entryValue);
  }, "appendEntryToFormData");
  const decoder = new TextDecoder("utf-8");
  decoder.decode();
  parser6.onPartBegin = function() {
    parser6.onPartData = onPartData;
    parser6.onPartEnd = appendEntryToFormData;
    headerField = "";
    headerValue = "";
    entryValue = "";
    entryName = "";
    contentType = "";
    filename = null;
    entryChunks.length = 0;
  };
  parser6.onHeaderField = function(ui8a) {
    headerField += decoder.decode(ui8a, { stream: true });
  };
  parser6.onHeaderValue = function(ui8a) {
    headerValue += decoder.decode(ui8a, { stream: true });
  };
  parser6.onHeaderEnd = function() {
    headerValue += decoder.decode();
    headerField = headerField.toLowerCase();
    if (headerField === "content-disposition") {
      const m4 = headerValue.match(/\bname=("([^"]*)"|([^()<>@,;:\\"/[\]?={}\s\t]+))/i);
      if (m4) {
        entryName = m4[2] || m4[3] || "";
      }
      filename = _fileName2(headerValue);
      if (filename) {
        parser6.onPartData = appendToFile;
        parser6.onPartEnd = appendFileToFormData;
      }
    } else if (headerField === "content-type") {
      contentType = headerValue;
    }
    headerValue = "";
    headerField = "";
  };
  for await (const chunk of Body3) {
    parser6.write(chunk);
  }
  parser6.end();
  return formData;
}
var s4, S3, f4, F3, LF2, CR2, SPACE2, HYPHEN2, COLON2, A3, Z3, lower2, noop7, MultipartParser2;
var init_multipart_parser2 = __esm({
  "packages/cli/node_modules/node-fetch/src/utils/multipart-parser.js"() {
    init_esbuild_shims();
    init_from();
    init_esm_min();
    s4 = 0;
    S3 = {
      START_BOUNDARY: s4++,
      HEADER_FIELD_START: s4++,
      HEADER_FIELD: s4++,
      HEADER_VALUE_START: s4++,
      HEADER_VALUE: s4++,
      HEADER_VALUE_ALMOST_DONE: s4++,
      HEADERS_ALMOST_DONE: s4++,
      PART_DATA_START: s4++,
      PART_DATA: s4++,
      END: s4++
    };
    f4 = 1;
    F3 = {
      PART_BOUNDARY: f4,
      LAST_BOUNDARY: f4 *= 2
    };
    LF2 = 10;
    CR2 = 13;
    SPACE2 = 32;
    HYPHEN2 = 45;
    COLON2 = 58;
    A3 = 97;
    Z3 = 122;
    lower2 = /* @__PURE__ */ __name((c4) => c4 | 32, "lower");
    noop7 = /* @__PURE__ */ __name(() => {
    }, "noop");
    MultipartParser2 = class {
      static {
        __name(this, "MultipartParser");
      }
      /**
       * @param {string} boundary
       */
      constructor(boundary) {
        this.index = 0;
        this.flags = 0;
        this.onHeaderEnd = noop7;
        this.onHeaderField = noop7;
        this.onHeadersEnd = noop7;
        this.onHeaderValue = noop7;
        this.onPartBegin = noop7;
        this.onPartData = noop7;
        this.onPartEnd = noop7;
        this.boundaryChars = {};
        boundary = "\r\n--" + boundary;
        const ui8a = new Uint8Array(boundary.length);
        for (let i3 = 0; i3 < boundary.length; i3++) {
          ui8a[i3] = boundary.charCodeAt(i3);
          this.boundaryChars[ui8a[i3]] = true;
        }
        this.boundary = ui8a;
        this.lookbehind = new Uint8Array(this.boundary.length + 8);
        this.state = S3.START_BOUNDARY;
      }
      /**
       * @param {Uint8Array} data
       */
      write(data) {
        let i3 = 0;
        const length_ = data.length;
        let previousIndex = this.index;
        let { lookbehind, boundary, boundaryChars, index, state, flags } = this;
        const boundaryLength = this.boundary.length;
        const boundaryEnd = boundaryLength - 1;
        const bufferLength = data.length;
        let c4;
        let cl;
        const mark = /* @__PURE__ */ __name((name3) => {
          this[name3 + "Mark"] = i3;
        }, "mark");
        const clear = /* @__PURE__ */ __name((name3) => {
          delete this[name3 + "Mark"];
        }, "clear");
        const callback = /* @__PURE__ */ __name((callbackSymbol, start, end, ui8a) => {
          if (start === void 0 || start !== end) {
            this[callbackSymbol](ui8a && ui8a.subarray(start, end));
          }
        }, "callback");
        const dataCallback = /* @__PURE__ */ __name((name3, clear2) => {
          const markSymbol = name3 + "Mark";
          if (!(markSymbol in this)) {
            return;
          }
          if (clear2) {
            callback(name3, this[markSymbol], i3, data);
            delete this[markSymbol];
          } else {
            callback(name3, this[markSymbol], data.length, data);
            this[markSymbol] = 0;
          }
        }, "dataCallback");
        for (i3 = 0; i3 < length_; i3++) {
          c4 = data[i3];
          switch (state) {
            case S3.START_BOUNDARY:
              if (index === boundary.length - 2) {
                if (c4 === HYPHEN2) {
                  flags |= F3.LAST_BOUNDARY;
                } else if (c4 !== CR2) {
                  return;
                }
                index++;
                break;
              } else if (index - 1 === boundary.length - 2) {
                if (flags & F3.LAST_BOUNDARY && c4 === HYPHEN2) {
                  state = S3.END;
                  flags = 0;
                } else if (!(flags & F3.LAST_BOUNDARY) && c4 === LF2) {
                  index = 0;
                  callback("onPartBegin");
                  state = S3.HEADER_FIELD_START;
                } else {
                  return;
                }
                break;
              }
              if (c4 !== boundary[index + 2]) {
                index = -2;
              }
              if (c4 === boundary[index + 2]) {
                index++;
              }
              break;
            case S3.HEADER_FIELD_START:
              state = S3.HEADER_FIELD;
              mark("onHeaderField");
              index = 0;
            // falls through
            case S3.HEADER_FIELD:
              if (c4 === CR2) {
                clear("onHeaderField");
                state = S3.HEADERS_ALMOST_DONE;
                break;
              }
              index++;
              if (c4 === HYPHEN2) {
                break;
              }
              if (c4 === COLON2) {
                if (index === 1) {
                  return;
                }
                dataCallback("onHeaderField", true);
                state = S3.HEADER_VALUE_START;
                break;
              }
              cl = lower2(c4);
              if (cl < A3 || cl > Z3) {
                return;
              }
              break;
            case S3.HEADER_VALUE_START:
              if (c4 === SPACE2) {
                break;
              }
              mark("onHeaderValue");
              state = S3.HEADER_VALUE;
            // falls through
            case S3.HEADER_VALUE:
              if (c4 === CR2) {
                dataCallback("onHeaderValue", true);
                callback("onHeaderEnd");
                state = S3.HEADER_VALUE_ALMOST_DONE;
              }
              break;
            case S3.HEADER_VALUE_ALMOST_DONE:
              if (c4 !== LF2) {
                return;
              }
              state = S3.HEADER_FIELD_START;
              break;
            case S3.HEADERS_ALMOST_DONE:
              if (c4 !== LF2) {
                return;
              }
              callback("onHeadersEnd");
              state = S3.PART_DATA_START;
              break;
            case S3.PART_DATA_START:
              state = S3.PART_DATA;
              mark("onPartData");
            // falls through
            case S3.PART_DATA:
              previousIndex = index;
              if (index === 0) {
                i3 += boundaryEnd;
                while (i3 < bufferLength && !(data[i3] in boundaryChars)) {
                  i3 += boundaryLength;
                }
                i3 -= boundaryEnd;
                c4 = data[i3];
              }
              if (index < boundary.length) {
                if (boundary[index] === c4) {
                  if (index === 0) {
                    dataCallback("onPartData", true);
                  }
                  index++;
                } else {
                  index = 0;
                }
              } else if (index === boundary.length) {
                index++;
                if (c4 === CR2) {
                  flags |= F3.PART_BOUNDARY;
                } else if (c4 === HYPHEN2) {
                  flags |= F3.LAST_BOUNDARY;
                } else {
                  index = 0;
                }
              } else if (index - 1 === boundary.length) {
                if (flags & F3.PART_BOUNDARY) {
                  index = 0;
                  if (c4 === LF2) {
                    flags &= ~F3.PART_BOUNDARY;
                    callback("onPartEnd");
                    callback("onPartBegin");
                    state = S3.HEADER_FIELD_START;
                    break;
                  }
                } else if (flags & F3.LAST_BOUNDARY) {
                  if (c4 === HYPHEN2) {
                    callback("onPartEnd");
                    state = S3.END;
                    flags = 0;
                  } else {
                    index = 0;
                  }
                } else {
                  index = 0;
                }
              }
              if (index > 0) {
                lookbehind[index - 1] = c4;
              } else if (previousIndex > 0) {
                const _lookbehind = new Uint8Array(lookbehind.buffer, lookbehind.byteOffset, lookbehind.byteLength);
                callback("onPartData", 0, previousIndex, _lookbehind);
                previousIndex = 0;
                mark("onPartData");
                i3--;
              }
              break;
            case S3.END:
              break;
            default:
              throw new Error(`Unexpected state entered: ${state}`);
          }
        }
        dataCallback("onHeaderField");
        dataCallback("onHeaderValue");
        dataCallback("onPartData");
        this.index = index;
        this.state = state;
        this.flags = flags;
      }
      end() {
        if (this.state === S3.HEADER_FIELD_START && this.index === 0 || this.state === S3.PART_DATA && this.index === this.boundary.length) {
          this.onPartEnd();
        } else if (this.state !== S3.END) {
          throw new Error("MultipartParser.end(): stream ended unexpectedly");
        }
      }
    };
    __name(_fileName2, "_fileName");
    __name(toFormData2, "toFormData");
  }
});

// packages/cli/node_modules/node-fetch/src/body.js
import Stream7, { PassThrough as PassThrough6 } from "node:stream";
import { types as types5, deprecate as deprecate4, promisify as promisify10 } from "node:util";
import { Buffer as Buffer7 } from "node:buffer";
async function consumeBody2(data) {
  if (data[INTERNALS4].disturbed) {
    throw new TypeError(`body used already for: ${data.url}`);
  }
  data[INTERNALS4].disturbed = true;
  if (data[INTERNALS4].error) {
    throw data[INTERNALS4].error;
  }
  const { body } = data;
  if (body === null) {
    return Buffer7.alloc(0);
  }
  if (!(body instanceof Stream7)) {
    return Buffer7.alloc(0);
  }
  const accum = [];
  let accumBytes = 0;
  try {
    for await (const chunk of body) {
      if (data.size > 0 && accumBytes + chunk.length > data.size) {
        const error2 = new FetchError3(`content size at ${data.url} over limit: ${data.size}`, "max-size");
        body.destroy(error2);
        throw error2;
      }
      accumBytes += chunk.length;
      accum.push(chunk);
    }
  } catch (error2) {
    const error_ = error2 instanceof FetchBaseError2 ? error2 : new FetchError3(`Invalid response body while trying to fetch ${data.url}: ${error2.message}`, "system", error2);
    throw error_;
  }
  if (body.readableEnded === true || body._readableState.ended === true) {
    try {
      if (accum.every((c4) => typeof c4 === "string")) {
        return Buffer7.from(accum.join(""));
      }
      return Buffer7.concat(accum, accumBytes);
    } catch (error2) {
      throw new FetchError3(`Could not create Buffer from response body for ${data.url}: ${error2.message}`, "system", error2);
    }
  } else {
    throw new FetchError3(`Premature close of server response while trying to fetch ${data.url}`);
  }
}
var pipeline2, INTERNALS4, Body2, clone3, getNonSpecFormDataBoundary2, extractContentType2, getTotalBytes2, writeToStream2;
var init_body2 = __esm({
  "packages/cli/node_modules/node-fetch/src/body.js"() {
    init_esbuild_shims();
    init_fetch_blob();
    init_esm_min();
    init_fetch_error2();
    init_base2();
    init_is2();
    pipeline2 = promisify10(Stream7.pipeline);
    INTERNALS4 = Symbol("Body internals");
    Body2 = class {
      static {
        __name(this, "Body");
      }
      constructor(body, {
        size = 0
      } = {}) {
        let boundary = null;
        if (body === null) {
          body = null;
        } else if (isURLSearchParameters2(body)) {
          body = Buffer7.from(body.toString());
        } else if (isBlob3(body)) {
        } else if (Buffer7.isBuffer(body)) {
        } else if (types5.isAnyArrayBuffer(body)) {
          body = Buffer7.from(body);
        } else if (ArrayBuffer.isView(body)) {
          body = Buffer7.from(body.buffer, body.byteOffset, body.byteLength);
        } else if (body instanceof Stream7) {
        } else if (body instanceof FormData2) {
          body = formDataToBlob(body);
          boundary = body.type.split("=")[1];
        } else {
          body = Buffer7.from(String(body));
        }
        let stream2 = body;
        if (Buffer7.isBuffer(body)) {
          stream2 = Stream7.Readable.from(body);
        } else if (isBlob3(body)) {
          stream2 = Stream7.Readable.from(body.stream());
        }
        this[INTERNALS4] = {
          body,
          stream: stream2,
          boundary,
          disturbed: false,
          error: null
        };
        this.size = size;
        if (body instanceof Stream7) {
          body.on("error", (error_) => {
            const error2 = error_ instanceof FetchBaseError2 ? error_ : new FetchError3(`Invalid response body while trying to fetch ${this.url}: ${error_.message}`, "system", error_);
            this[INTERNALS4].error = error2;
          });
        }
      }
      get body() {
        return this[INTERNALS4].stream;
      }
      get bodyUsed() {
        return this[INTERNALS4].disturbed;
      }
      /**
       * Decode response as ArrayBuffer
       *
       * @return  Promise
       */
      async arrayBuffer() {
        const { buffer, byteOffset, byteLength } = await consumeBody2(this);
        return buffer.slice(byteOffset, byteOffset + byteLength);
      }
      async formData() {
        const ct2 = this.headers.get("content-type");
        if (ct2.startsWith("application/x-www-form-urlencoded")) {
          const formData = new FormData2();
          const parameters = new URLSearchParams(await this.text());
          for (const [name3, value] of parameters) {
            formData.append(name3, value);
          }
          return formData;
        }
        const { toFormData: toFormData3 } = await Promise.resolve().then(() => (init_multipart_parser2(), multipart_parser_exports2));
        return toFormData3(this.body, ct2);
      }
      /**
       * Return raw response as Blob
       *
       * @return Promise
       */
      async blob() {
        const ct2 = this.headers && this.headers.get("content-type") || this[INTERNALS4].body && this[INTERNALS4].body.type || "";
        const buf = await this.arrayBuffer();
        return new fetch_blob_default([buf], {
          type: ct2
        });
      }
      /**
       * Decode response as json
       *
       * @return  Promise
       */
      async json() {
        const text = await this.text();
        return JSON.parse(text);
      }
      /**
       * Decode response as text
       *
       * @return  Promise
       */
      async text() {
        const buffer = await consumeBody2(this);
        return new TextDecoder().decode(buffer);
      }
      /**
       * Decode response as buffer (non-spec api)
       *
       * @return  Promise
       */
      buffer() {
        return consumeBody2(this);
      }
    };
    Body2.prototype.buffer = deprecate4(Body2.prototype.buffer, "Please use 'response.arrayBuffer()' instead of 'response.buffer()'", "node-fetch#buffer");
    Object.defineProperties(Body2.prototype, {
      body: { enumerable: true },
      bodyUsed: { enumerable: true },
      arrayBuffer: { enumerable: true },
      blob: { enumerable: true },
      json: { enumerable: true },
      text: { enumerable: true },
      data: { get: deprecate4(
        () => {
        },
        "data doesn't exist, use json(), text(), arrayBuffer(), or body instead",
        "https://github.com/node-fetch/node-fetch/issues/1000 (response)"
      ) }
    });
    __name(consumeBody2, "consumeBody");
    clone3 = /* @__PURE__ */ __name((instance, highWaterMark) => {
      let p1;
      let p2;
      let { body } = instance[INTERNALS4];
      if (instance.bodyUsed) {
        throw new Error("cannot clone body after it is used");
      }
      if (body instanceof Stream7 && typeof body.getBoundary !== "function") {
        p1 = new PassThrough6({ highWaterMark });
        p2 = new PassThrough6({ highWaterMark });
        body.pipe(p1);
        body.pipe(p2);
        instance[INTERNALS4].stream = p1;
        body = p2;
      }
      return body;
    }, "clone");
    getNonSpecFormDataBoundary2 = deprecate4(
      (body) => body.getBoundary(),
      "form-data doesn't follow the spec and requires special treatment. Use alternative package",
      "https://github.com/node-fetch/node-fetch/issues/1167"
    );
    extractContentType2 = /* @__PURE__ */ __name((body, request4) => {
      if (body === null) {
        return null;
      }
      if (typeof body === "string") {
        return "text/plain;charset=UTF-8";
      }
      if (isURLSearchParameters2(body)) {
        return "application/x-www-form-urlencoded;charset=UTF-8";
      }
      if (isBlob3(body)) {
        return body.type || null;
      }
      if (Buffer7.isBuffer(body) || types5.isAnyArrayBuffer(body) || ArrayBuffer.isView(body)) {
        return null;
      }
      if (body instanceof FormData2) {
        return `multipart/form-data; boundary=${request4[INTERNALS4].boundary}`;
      }
      if (body && typeof body.getBoundary === "function") {
        return `multipart/form-data;boundary=${getNonSpecFormDataBoundary2(body)}`;
      }
      if (body instanceof Stream7) {
        return null;
      }
      return "text/plain;charset=UTF-8";
    }, "extractContentType");
    getTotalBytes2 = /* @__PURE__ */ __name((request4) => {
      const { body } = request4[INTERNALS4];
      if (body === null) {
        return 0;
      }
      if (isBlob3(body)) {
        return body.size;
      }
      if (Buffer7.isBuffer(body)) {
        return body.length;
      }
      if (body && typeof body.getLengthSync === "function") {
        return body.hasKnownLength && body.hasKnownLength() ? body.getLengthSync() : null;
      }
      return null;
    }, "getTotalBytes");
    writeToStream2 = /* @__PURE__ */ __name(async (dest, { body }) => {
      if (body === null) {
        dest.end();
      } else {
        await pipeline2(body, dest);
      }
    }, "writeToStream");
  }
});

// packages/cli/node_modules/node-fetch/src/headers.js
import { types as types6 } from "node:util";
import http5 from "node:http";
function fromRawHeaders2(headers = []) {
  return new Headers5(
    headers.reduce((result, value, index, array2) => {
      if (index % 2 === 0) {
        result.push(array2.slice(index, index + 2));
      }
      return result;
    }, []).filter(([name3, value]) => {
      try {
        validateHeaderName2(name3);
        validateHeaderValue2(name3, String(value));
        return true;
      } catch {
        return false;
      }
    })
  );
}
var validateHeaderName2, validateHeaderValue2, Headers5;
var init_headers3 = __esm({
  "packages/cli/node_modules/node-fetch/src/headers.js"() {
    init_esbuild_shims();
    validateHeaderName2 = typeof http5.validateHeaderName === "function" ? http5.validateHeaderName : (name3) => {
      if (!/^[\^`\-\w!#$%&'*+.|~]+$/.test(name3)) {
        const error2 = new TypeError(`Header name must be a valid HTTP token [${name3}]`);
        Object.defineProperty(error2, "code", { value: "ERR_INVALID_HTTP_TOKEN" });
        throw error2;
      }
    };
    validateHeaderValue2 = typeof http5.validateHeaderValue === "function" ? http5.validateHeaderValue : (name3, value) => {
      if (/[^\t\u0020-\u007E\u0080-\u00FF]/.test(value)) {
        const error2 = new TypeError(`Invalid character in header content ["${name3}"]`);
        Object.defineProperty(error2, "code", { value: "ERR_INVALID_CHAR" });
        throw error2;
      }
    };
    Headers5 = class _Headers extends URLSearchParams {
      static {
        __name(this, "Headers");
      }
      /**
       * Headers class
       *
       * @constructor
       * @param {HeadersInit} [init] - Response headers
       */
      constructor(init) {
        let result = [];
        if (init instanceof _Headers) {
          const raw2 = init.raw();
          for (const [name3, values] of Object.entries(raw2)) {
            result.push(...values.map((value) => [name3, value]));
          }
        } else if (init == null) {
        } else if (typeof init === "object" && !types6.isBoxedPrimitive(init)) {
          const method = init[Symbol.iterator];
          if (method == null) {
            result.push(...Object.entries(init));
          } else {
            if (typeof method !== "function") {
              throw new TypeError("Header pairs must be iterable");
            }
            result = [...init].map((pair) => {
              if (typeof pair !== "object" || types6.isBoxedPrimitive(pair)) {
                throw new TypeError("Each header pair must be an iterable object");
              }
              return [...pair];
            }).map((pair) => {
              if (pair.length !== 2) {
                throw new TypeError("Each header pair must be a name/value tuple");
              }
              return [...pair];
            });
          }
        } else {
          throw new TypeError("Failed to construct 'Headers': The provided value is not of type '(sequence<sequence<ByteString>> or record<ByteString, ByteString>)");
        }
        result = result.length > 0 ? result.map(([name3, value]) => {
          validateHeaderName2(name3);
          validateHeaderValue2(name3, String(value));
          return [String(name3).toLowerCase(), String(value)];
        }) : void 0;
        super(result);
        return new Proxy(this, {
          get(target, p2, receiver) {
            switch (p2) {
              case "append":
              case "set":
                return (name3, value) => {
                  validateHeaderName2(name3);
                  validateHeaderValue2(name3, String(value));
                  return URLSearchParams.prototype[p2].call(
                    target,
                    String(name3).toLowerCase(),
                    String(value)
                  );
                };
              case "delete":
              case "has":
              case "getAll":
                return (name3) => {
                  validateHeaderName2(name3);
                  return URLSearchParams.prototype[p2].call(
                    target,
                    String(name3).toLowerCase()
                  );
                };
              case "keys":
                return () => {
                  target.sort();
                  return new Set(URLSearchParams.prototype.keys.call(target)).keys();
                };
              default:
                return Reflect.get(target, p2, receiver);
            }
          }
        });
      }
      get [Symbol.toStringTag]() {
        return this.constructor.name;
      }
      toString() {
        return Object.prototype.toString.call(this);
      }
      get(name3) {
        const values = this.getAll(name3);
        if (values.length === 0) {
          return null;
        }
        let value = values.join(", ");
        if (/^content-encoding$/i.test(name3)) {
          value = value.toLowerCase();
        }
        return value;
      }
      forEach(callback, thisArg = void 0) {
        for (const name3 of this.keys()) {
          Reflect.apply(callback, thisArg, [this.get(name3), name3, this]);
        }
      }
      *values() {
        for (const name3 of this.keys()) {
          yield this.get(name3);
        }
      }
      /**
       * @type {() => IterableIterator<[string, string]>}
       */
      *entries() {
        for (const name3 of this.keys()) {
          yield [name3, this.get(name3)];
        }
      }
      [Symbol.iterator]() {
        return this.entries();
      }
      /**
       * Node-fetch non-spec method
       * returning all headers and their values as array
       * @returns {Record<string, string[]>}
       */
      raw() {
        return [...this.keys()].reduce((result, key) => {
          result[key] = this.getAll(key);
          return result;
        }, {});
      }
      /**
       * For better console.log(headers) and also to convert Headers into Node.js Request compatible format
       */
      [Symbol.for("nodejs.util.inspect.custom")]() {
        return [...this.keys()].reduce((result, key) => {
          const values = this.getAll(key);
          if (key === "host") {
            result[key] = values[0];
          } else {
            result[key] = values.length > 1 ? values : values[0];
          }
          return result;
        }, {});
      }
    };
    Object.defineProperties(
      Headers5.prototype,
      ["get", "entries", "forEach", "values"].reduce((result, property) => {
        result[property] = { enumerable: true };
        return result;
      }, {})
    );
    __name(fromRawHeaders2, "fromRawHeaders");
  }
});

// packages/cli/node_modules/node-fetch/src/utils/is-redirect.js
var redirectStatus2, isRedirect2;
var init_is_redirect2 = __esm({
  "packages/cli/node_modules/node-fetch/src/utils/is-redirect.js"() {
    init_esbuild_shims();
    redirectStatus2 = /* @__PURE__ */ new Set([301, 302, 303, 307, 308]);
    isRedirect2 = /* @__PURE__ */ __name((code2) => {
      return redirectStatus2.has(code2);
    }, "isRedirect");
  }
});

// packages/cli/node_modules/node-fetch/src/response.js
var INTERNALS5, Response5;
var init_response2 = __esm({
  "packages/cli/node_modules/node-fetch/src/response.js"() {
    init_esbuild_shims();
    init_headers3();
    init_body2();
    init_is_redirect2();
    INTERNALS5 = Symbol("Response internals");
    Response5 = class _Response extends Body2 {
      static {
        __name(this, "Response");
      }
      constructor(body = null, options2 = {}) {
        super(body, options2);
        const status = options2.status != null ? options2.status : 200;
        const headers = new Headers5(options2.headers);
        if (body !== null && !headers.has("Content-Type")) {
          const contentType = extractContentType2(body, this);
          if (contentType) {
            headers.append("Content-Type", contentType);
          }
        }
        this[INTERNALS5] = {
          type: "default",
          url: options2.url,
          status,
          statusText: options2.statusText || "",
          headers,
          counter: options2.counter,
          highWaterMark: options2.highWaterMark
        };
      }
      get type() {
        return this[INTERNALS5].type;
      }
      get url() {
        return this[INTERNALS5].url || "";
      }
      get status() {
        return this[INTERNALS5].status;
      }
      /**
       * Convenience property representing if the request ended normally
       */
      get ok() {
        return this[INTERNALS5].status >= 200 && this[INTERNALS5].status < 300;
      }
      get redirected() {
        return this[INTERNALS5].counter > 0;
      }
      get statusText() {
        return this[INTERNALS5].statusText;
      }
      get headers() {
        return this[INTERNALS5].headers;
      }
      get highWaterMark() {
        return this[INTERNALS5].highWaterMark;
      }
      /**
       * Clone this response
       *
       * @return  Response
       */
      clone() {
        return new _Response(clone3(this, this.highWaterMark), {
          type: this.type,
          url: this.url,
          status: this.status,
          statusText: this.statusText,
          headers: this.headers,
          ok: this.ok,
          redirected: this.redirected,
          size: this.size,
          highWaterMark: this.highWaterMark
        });
      }
      /**
       * @param {string} url    The URL that the new response is to originate from.
       * @param {number} status An optional status code for the response (e.g., 302.)
       * @returns {Response}    A Response object.
       */
      static redirect(url2, status = 302) {
        if (!isRedirect2(status)) {
          throw new RangeError('Failed to execute "redirect" on "response": Invalid status code');
        }
        return new _Response(null, {
          headers: {
            location: new URL(url2).toString()
          },
          status
        });
      }
      static error() {
        const response = new _Response(null, { status: 0, statusText: "" });
        response[INTERNALS5].type = "error";
        return response;
      }
      static json(data = void 0, init = {}) {
        const body = JSON.stringify(data);
        if (body === void 0) {
          throw new TypeError("data is not JSON serializable");
        }
        const headers = new Headers5(init && init.headers);
        if (!headers.has("content-type")) {
          headers.set("content-type", "application/json");
        }
        return new _Response(body, {
          ...init,
          headers
        });
      }
      get [Symbol.toStringTag]() {
        return "Response";
      }
    };
    Object.defineProperties(Response5.prototype, {
      type: { enumerable: true },
      url: { enumerable: true },
      status: { enumerable: true },
      ok: { enumerable: true },
      redirected: { enumerable: true },
      statusText: { enumerable: true },
      headers: { enumerable: true },
      clone: { enumerable: true }
    });
  }
});

// packages/cli/node_modules/node-fetch/src/utils/get-search.js
var getSearch2;
var init_get_search2 = __esm({
  "packages/cli/node_modules/node-fetch/src/utils/get-search.js"() {
    init_esbuild_shims();
    getSearch2 = /* @__PURE__ */ __name((parsedURL) => {
      if (parsedURL.search) {
        return parsedURL.search;
      }
      const lastOffset = parsedURL.href.length - 1;
      const hash = parsedURL.hash || (parsedURL.href[lastOffset] === "#" ? "#" : "");
      return parsedURL.href[lastOffset - hash.length] === "?" ? "?" : "";
    }, "getSearch");
  }
});

// packages/cli/node_modules/node-fetch/src/utils/referrer.js
import { isIP as isIP2 } from "node:net";
function stripURLForUseAsAReferrer2(url2, originOnly = false) {
  if (url2 == null) {
    return "no-referrer";
  }
  url2 = new URL(url2);
  if (/^(about|blob|data):$/.test(url2.protocol)) {
    return "no-referrer";
  }
  url2.username = "";
  url2.password = "";
  url2.hash = "";
  if (originOnly) {
    url2.pathname = "";
    url2.search = "";
  }
  return url2;
}
function validateReferrerPolicy2(referrerPolicy) {
  if (!ReferrerPolicy2.has(referrerPolicy)) {
    throw new TypeError(`Invalid referrerPolicy: ${referrerPolicy}`);
  }
  return referrerPolicy;
}
function isOriginPotentiallyTrustworthy2(url2) {
  if (/^(http|ws)s:$/.test(url2.protocol)) {
    return true;
  }
  const hostIp = url2.host.replace(/(^\[)|(]$)/g, "");
  const hostIPVersion = isIP2(hostIp);
  if (hostIPVersion === 4 && /^127\./.test(hostIp)) {
    return true;
  }
  if (hostIPVersion === 6 && /^(((0+:){7})|(::(0+:){0,6}))0*1$/.test(hostIp)) {
    return true;
  }
  if (url2.host === "localhost" || url2.host.endsWith(".localhost")) {
    return false;
  }
  if (url2.protocol === "file:") {
    return true;
  }
  return false;
}
function isUrlPotentiallyTrustworthy2(url2) {
  if (/^about:(blank|srcdoc)$/.test(url2)) {
    return true;
  }
  if (url2.protocol === "data:") {
    return true;
  }
  if (/^(blob|filesystem):$/.test(url2.protocol)) {
    return true;
  }
  return isOriginPotentiallyTrustworthy2(url2);
}
function determineRequestsReferrer2(request4, { referrerURLCallback, referrerOriginCallback } = {}) {
  if (request4.referrer === "no-referrer" || request4.referrerPolicy === "") {
    return null;
  }
  const policy = request4.referrerPolicy;
  if (request4.referrer === "about:client") {
    return "no-referrer";
  }
  const referrerSource = request4.referrer;
  let referrerURL = stripURLForUseAsAReferrer2(referrerSource);
  let referrerOrigin = stripURLForUseAsAReferrer2(referrerSource, true);
  if (referrerURL.toString().length > 4096) {
    referrerURL = referrerOrigin;
  }
  if (referrerURLCallback) {
    referrerURL = referrerURLCallback(referrerURL);
  }
  if (referrerOriginCallback) {
    referrerOrigin = referrerOriginCallback(referrerOrigin);
  }
  const currentURL = new URL(request4.url);
  switch (policy) {
    case "no-referrer":
      return "no-referrer";
    case "origin":
      return referrerOrigin;
    case "unsafe-url":
      return referrerURL;
    case "strict-origin":
      if (isUrlPotentiallyTrustworthy2(referrerURL) && !isUrlPotentiallyTrustworthy2(currentURL)) {
        return "no-referrer";
      }
      return referrerOrigin.toString();
    case "strict-origin-when-cross-origin":
      if (referrerURL.origin === currentURL.origin) {
        return referrerURL;
      }
      if (isUrlPotentiallyTrustworthy2(referrerURL) && !isUrlPotentiallyTrustworthy2(currentURL)) {
        return "no-referrer";
      }
      return referrerOrigin;
    case "same-origin":
      if (referrerURL.origin === currentURL.origin) {
        return referrerURL;
      }
      return "no-referrer";
    case "origin-when-cross-origin":
      if (referrerURL.origin === currentURL.origin) {
        return referrerURL;
      }
      return referrerOrigin;
    case "no-referrer-when-downgrade":
      if (isUrlPotentiallyTrustworthy2(referrerURL) && !isUrlPotentiallyTrustworthy2(currentURL)) {
        return "no-referrer";
      }
      return referrerURL;
    default:
      throw new TypeError(`Invalid referrerPolicy: ${policy}`);
  }
}
function parseReferrerPolicyFromHeader2(headers) {
  const policyTokens = (headers.get("referrer-policy") || "").split(/[,\s]+/);
  let policy = "";
  for (const token2 of policyTokens) {
    if (token2 && ReferrerPolicy2.has(token2)) {
      policy = token2;
    }
  }
  return policy;
}
var ReferrerPolicy2, DEFAULT_REFERRER_POLICY2;
var init_referrer2 = __esm({
  "packages/cli/node_modules/node-fetch/src/utils/referrer.js"() {
    init_esbuild_shims();
    __name(stripURLForUseAsAReferrer2, "stripURLForUseAsAReferrer");
    ReferrerPolicy2 = /* @__PURE__ */ new Set([
      "",
      "no-referrer",
      "no-referrer-when-downgrade",
      "same-origin",
      "origin",
      "strict-origin",
      "origin-when-cross-origin",
      "strict-origin-when-cross-origin",
      "unsafe-url"
    ]);
    DEFAULT_REFERRER_POLICY2 = "strict-origin-when-cross-origin";
    __name(validateReferrerPolicy2, "validateReferrerPolicy");
    __name(isOriginPotentiallyTrustworthy2, "isOriginPotentiallyTrustworthy");
    __name(isUrlPotentiallyTrustworthy2, "isUrlPotentiallyTrustworthy");
    __name(determineRequestsReferrer2, "determineRequestsReferrer");
    __name(parseReferrerPolicyFromHeader2, "parseReferrerPolicyFromHeader");
  }
});

// packages/cli/node_modules/node-fetch/src/request.js
import { format as formatUrl2 } from "node:url";
import { deprecate as deprecate5 } from "node:util";
var INTERNALS6, isRequest2, doBadDataWarn2, Request5, getNodeRequestOptions2;
var init_request2 = __esm({
  "packages/cli/node_modules/node-fetch/src/request.js"() {
    init_esbuild_shims();
    init_headers3();
    init_body2();
    init_is2();
    init_get_search2();
    init_referrer2();
    INTERNALS6 = Symbol("Request internals");
    isRequest2 = /* @__PURE__ */ __name((object3) => {
      return typeof object3 === "object" && typeof object3[INTERNALS6] === "object";
    }, "isRequest");
    doBadDataWarn2 = deprecate5(
      () => {
      },
      ".data is not a valid RequestInit property, use .body instead",
      "https://github.com/node-fetch/node-fetch/issues/1000 (request)"
    );
    Request5 = class _Request extends Body2 {
      static {
        __name(this, "Request");
      }
      constructor(input, init = {}) {
        let parsedURL;
        if (isRequest2(input)) {
          parsedURL = new URL(input.url);
        } else {
          parsedURL = new URL(input);
          input = {};
        }
        if (parsedURL.username !== "" || parsedURL.password !== "") {
          throw new TypeError(`${parsedURL} is an url with embedded credentials.`);
        }
        let method = init.method || input.method || "GET";
        if (/^(delete|get|head|options|post|put)$/i.test(method)) {
          method = method.toUpperCase();
        }
        if (!isRequest2(init) && "data" in init) {
          doBadDataWarn2();
        }
        if ((init.body != null || isRequest2(input) && input.body !== null) && (method === "GET" || method === "HEAD")) {
          throw new TypeError("Request with GET/HEAD method cannot have body");
        }
        const inputBody = init.body ? init.body : isRequest2(input) && input.body !== null ? clone3(input) : null;
        super(inputBody, {
          size: init.size || input.size || 0
        });
        const headers = new Headers5(init.headers || input.headers || {});
        if (inputBody !== null && !headers.has("Content-Type")) {
          const contentType = extractContentType2(inputBody, this);
          if (contentType) {
            headers.set("Content-Type", contentType);
          }
        }
        let signal = isRequest2(input) ? input.signal : null;
        if ("signal" in init) {
          signal = init.signal;
        }
        if (signal != null && !isAbortSignal2(signal)) {
          throw new TypeError("Expected signal to be an instanceof AbortSignal or EventTarget");
        }
        let referrer = init.referrer == null ? input.referrer : init.referrer;
        if (referrer === "") {
          referrer = "no-referrer";
        } else if (referrer) {
          const parsedReferrer = new URL(referrer);
          referrer = /^about:(\/\/)?client$/.test(parsedReferrer) ? "client" : parsedReferrer;
        } else {
          referrer = void 0;
        }
        this[INTERNALS6] = {
          method,
          redirect: init.redirect || input.redirect || "follow",
          headers,
          parsedURL,
          signal,
          referrer
        };
        this.follow = init.follow === void 0 ? input.follow === void 0 ? 20 : input.follow : init.follow;
        this.compress = init.compress === void 0 ? input.compress === void 0 ? true : input.compress : init.compress;
        this.counter = init.counter || input.counter || 0;
        this.agent = init.agent || input.agent;
        this.highWaterMark = init.highWaterMark || input.highWaterMark || 16384;
        this.insecureHTTPParser = init.insecureHTTPParser || input.insecureHTTPParser || false;
        this.referrerPolicy = init.referrerPolicy || input.referrerPolicy || "";
      }
      /** @returns {string} */
      get method() {
        return this[INTERNALS6].method;
      }
      /** @returns {string} */
      get url() {
        return formatUrl2(this[INTERNALS6].parsedURL);
      }
      /** @returns {Headers} */
      get headers() {
        return this[INTERNALS6].headers;
      }
      get redirect() {
        return this[INTERNALS6].redirect;
      }
      /** @returns {AbortSignal} */
      get signal() {
        return this[INTERNALS6].signal;
      }
      // https://fetch.spec.whatwg.org/#dom-request-referrer
      get referrer() {
        if (this[INTERNALS6].referrer === "no-referrer") {
          return "";
        }
        if (this[INTERNALS6].referrer === "client") {
          return "about:client";
        }
        if (this[INTERNALS6].referrer) {
          return this[INTERNALS6].referrer.toString();
        }
        return void 0;
      }
      get referrerPolicy() {
        return this[INTERNALS6].referrerPolicy;
      }
      set referrerPolicy(referrerPolicy) {
        this[INTERNALS6].referrerPolicy = validateReferrerPolicy2(referrerPolicy);
      }
      /**
       * Clone this request
       *
       * @return  Request
       */
      clone() {
        return new _Request(this);
      }
      get [Symbol.toStringTag]() {
        return "Request";
      }
    };
    Object.defineProperties(Request5.prototype, {
      method: { enumerable: true },
      url: { enumerable: true },
      headers: { enumerable: true },
      redirect: { enumerable: true },
      clone: { enumerable: true },
      signal: { enumerable: true },
      referrer: { enumerable: true },
      referrerPolicy: { enumerable: true }
    });
    getNodeRequestOptions2 = /* @__PURE__ */ __name((request4) => {
      const { parsedURL } = request4[INTERNALS6];
      const headers = new Headers5(request4[INTERNALS6].headers);
      if (!headers.has("Accept")) {
        headers.set("Accept", "*/*");
      }
      let contentLengthValue = null;
      if (request4.body === null && /^(post|put)$/i.test(request4.method)) {
        contentLengthValue = "0";
      }
      if (request4.body !== null) {
        const totalBytes = getTotalBytes2(request4);
        if (typeof totalBytes === "number" && !Number.isNaN(totalBytes)) {
          contentLengthValue = String(totalBytes);
        }
      }
      if (contentLengthValue) {
        headers.set("Content-Length", contentLengthValue);
      }
      if (request4.referrerPolicy === "") {
        request4.referrerPolicy = DEFAULT_REFERRER_POLICY2;
      }
      if (request4.referrer && request4.referrer !== "no-referrer") {
        request4[INTERNALS6].referrer = determineRequestsReferrer2(request4);
      } else {
        request4[INTERNALS6].referrer = "no-referrer";
      }
      if (request4[INTERNALS6].referrer instanceof URL) {
        headers.set("Referer", request4.referrer);
      }
      if (!headers.has("User-Agent")) {
        headers.set("User-Agent", "node-fetch");
      }
      if (request4.compress && !headers.has("Accept-Encoding")) {
        headers.set("Accept-Encoding", "gzip, deflate, br");
      }
      let { agent } = request4;
      if (typeof agent === "function") {
        agent = agent(parsedURL);
      }
      const search = getSearch2(parsedURL);
      const options2 = {
        // Overwrite search to retain trailing ? (issue #776)
        path: parsedURL.pathname + search,
        // The following options are not expressed in the URL
        method: request4.method,
        headers: headers[Symbol.for("nodejs.util.inspect.custom")](),
        insecureHTTPParser: request4.insecureHTTPParser,
        agent
      };
      return {
        /** @type {URL} */
        parsedURL,
        options: options2
      };
    }, "getNodeRequestOptions");
  }
});

// packages/cli/node_modules/node-fetch/src/errors/abort-error.js
var AbortError3;
var init_abort_error2 = __esm({
  "packages/cli/node_modules/node-fetch/src/errors/abort-error.js"() {
    init_esbuild_shims();
    init_base2();
    AbortError3 = class extends FetchBaseError2 {
      static {
        __name(this, "AbortError");
      }
      constructor(message, type = "aborted") {
        super(message, type);
      }
    };
  }
});

// packages/cli/node_modules/node-fetch/src/index.js
var src_exports2 = {};
__export(src_exports2, {
  AbortError: () => AbortError3,
  Blob: () => fetch_blob_default,
  FetchError: () => FetchError3,
  File: () => file_default,
  FormData: () => FormData2,
  Headers: () => Headers5,
  Request: () => Request5,
  Response: () => Response5,
  blobFrom: () => blobFrom,
  blobFromSync: () => blobFromSync,
  default: () => fetch4,
  fileFrom: () => fileFrom,
  fileFromSync: () => fileFromSync,
  isRedirect: () => isRedirect2
});
import http6 from "node:http";
import https6 from "node:https";
import zlib3 from "node:zlib";
import Stream8, { PassThrough as PassThrough7, pipeline as pump2 } from "node:stream";
import { Buffer as Buffer8 } from "node:buffer";
async function fetch4(url2, options_) {
  return new Promise((resolve30, reject) => {
    const request4 = new Request5(url2, options_);
    const { parsedURL, options: options2 } = getNodeRequestOptions2(request4);
    if (!supportedSchemas2.has(parsedURL.protocol)) {
      throw new TypeError(`node-fetch cannot load ${url2}. URL scheme "${parsedURL.protocol.replace(/:$/, "")}" is not supported.`);
    }
    if (parsedURL.protocol === "data:") {
      const data = dist_default(request4.url);
      const response2 = new Response5(data, { headers: { "Content-Type": data.typeFull } });
      resolve30(response2);
      return;
    }
    const send = (parsedURL.protocol === "https:" ? https6 : http6).request;
    const { signal } = request4;
    let response = null;
    const abort = /* @__PURE__ */ __name(() => {
      const error2 = new AbortError3("The operation was aborted.");
      reject(error2);
      if (request4.body && request4.body instanceof Stream8.Readable) {
        request4.body.destroy(error2);
      }
      if (!response || !response.body) {
        return;
      }
      response.body.emit("error", error2);
    }, "abort");
    if (signal && signal.aborted) {
      abort();
      return;
    }
    const abortAndFinalize = /* @__PURE__ */ __name(() => {
      abort();
      finalize();
    }, "abortAndFinalize");
    const request_ = send(parsedURL.toString(), options2);
    if (signal) {
      signal.addEventListener("abort", abortAndFinalize);
    }
    const finalize = /* @__PURE__ */ __name(() => {
      request_.abort();
      if (signal) {
        signal.removeEventListener("abort", abortAndFinalize);
      }
    }, "finalize");
    request_.on("error", (error2) => {
      reject(new FetchError3(`request to ${request4.url} failed, reason: ${error2.message}`, "system", error2));
      finalize();
    });
    fixResponseChunkedTransferBadEnding2(request_, (error2) => {
      if (response && response.body) {
        response.body.destroy(error2);
      }
    });
    if (process.version < "v14") {
      request_.on("socket", (s5) => {
        let endedWithEventsCount;
        s5.prependListener("end", () => {
          endedWithEventsCount = s5._eventsCount;
        });
        s5.prependListener("close", (hadError) => {
          if (response && endedWithEventsCount < s5._eventsCount && !hadError) {
            const error2 = new Error("Premature close");
            error2.code = "ERR_STREAM_PREMATURE_CLOSE";
            response.body.emit("error", error2);
          }
        });
      });
    }
    request_.on("response", (response_) => {
      request_.setTimeout(0);
      const headers = fromRawHeaders2(response_.rawHeaders);
      if (isRedirect2(response_.statusCode)) {
        const location = headers.get("Location");
        let locationURL = null;
        try {
          locationURL = location === null ? null : new URL(location, request4.url);
        } catch {
          if (request4.redirect !== "manual") {
            reject(new FetchError3(`uri requested responds with an invalid redirect URL: ${location}`, "invalid-redirect"));
            finalize();
            return;
          }
        }
        switch (request4.redirect) {
          case "error":
            reject(new FetchError3(`uri requested responds with a redirect, redirect mode is set to error: ${request4.url}`, "no-redirect"));
            finalize();
            return;
          case "manual":
            break;
          case "follow": {
            if (locationURL === null) {
              break;
            }
            if (request4.counter >= request4.follow) {
              reject(new FetchError3(`maximum redirect reached at: ${request4.url}`, "max-redirect"));
              finalize();
              return;
            }
            const requestOptions = {
              headers: new Headers5(request4.headers),
              follow: request4.follow,
              counter: request4.counter + 1,
              agent: request4.agent,
              compress: request4.compress,
              method: request4.method,
              body: clone3(request4),
              signal: request4.signal,
              size: request4.size,
              referrer: request4.referrer,
              referrerPolicy: request4.referrerPolicy
            };
            if (!isDomainOrSubdomain2(request4.url, locationURL) || !isSameProtocol2(request4.url, locationURL)) {
              for (const name3 of ["authorization", "www-authenticate", "cookie", "cookie2"]) {
                requestOptions.headers.delete(name3);
              }
            }
            if (response_.statusCode !== 303 && request4.body && options_.body instanceof Stream8.Readable) {
              reject(new FetchError3("Cannot follow redirect with body being a readable stream", "unsupported-redirect"));
              finalize();
              return;
            }
            if (response_.statusCode === 303 || (response_.statusCode === 301 || response_.statusCode === 302) && request4.method === "POST") {
              requestOptions.method = "GET";
              requestOptions.body = void 0;
              requestOptions.headers.delete("content-length");
            }
            const responseReferrerPolicy = parseReferrerPolicyFromHeader2(headers);
            if (responseReferrerPolicy) {
              requestOptions.referrerPolicy = responseReferrerPolicy;
            }
            resolve30(fetch4(new Request5(locationURL, requestOptions)));
            finalize();
            return;
          }
          default:
            return reject(new TypeError(`Redirect option '${request4.redirect}' is not a valid value of RequestRedirect`));
        }
      }
      if (signal) {
        response_.once("end", () => {
          signal.removeEventListener("abort", abortAndFinalize);
        });
      }
      let body = pump2(response_, new PassThrough7(), (error2) => {
        if (error2) {
          reject(error2);
        }
      });
      if (process.version < "v12.10") {
        response_.on("aborted", abortAndFinalize);
      }
      const responseOptions = {
        url: request4.url,
        status: response_.statusCode,
        statusText: response_.statusMessage,
        headers,
        size: request4.size,
        counter: request4.counter,
        highWaterMark: request4.highWaterMark
      };
      const codings = headers.get("Content-Encoding");
      if (!request4.compress || request4.method === "HEAD" || codings === null || response_.statusCode === 204 || response_.statusCode === 304) {
        response = new Response5(body, responseOptions);
        resolve30(response);
        return;
      }
      const zlibOptions = {
        flush: zlib3.Z_SYNC_FLUSH,
        finishFlush: zlib3.Z_SYNC_FLUSH
      };
      if (codings === "gzip" || codings === "x-gzip") {
        body = pump2(body, zlib3.createGunzip(zlibOptions), (error2) => {
          if (error2) {
            reject(error2);
          }
        });
        response = new Response5(body, responseOptions);
        resolve30(response);
        return;
      }
      if (codings === "deflate" || codings === "x-deflate") {
        const raw2 = pump2(response_, new PassThrough7(), (error2) => {
          if (error2) {
            reject(error2);
          }
        });
        raw2.once("data", (chunk) => {
          if ((chunk[0] & 15) === 8) {
            body = pump2(body, zlib3.createInflate(), (error2) => {
              if (error2) {
                reject(error2);
              }
            });
          } else {
            body = pump2(body, zlib3.createInflateRaw(), (error2) => {
              if (error2) {
                reject(error2);
              }
            });
          }
          response = new Response5(body, responseOptions);
          resolve30(response);
        });
        raw2.once("end", () => {
          if (!response) {
            response = new Response5(body, responseOptions);
            resolve30(response);
          }
        });
        return;
      }
      if (codings === "br") {
        body = pump2(body, zlib3.createBrotliDecompress(), (error2) => {
          if (error2) {
            reject(error2);
          }
        });
        response = new Response5(body, responseOptions);
        resolve30(response);
        return;
      }
      response = new Response5(body, responseOptions);
      resolve30(response);
    });
    writeToStream2(request_, request4).catch(reject);
  });
}
function fixResponseChunkedTransferBadEnding2(request4, errorCallback) {
  const LAST_CHUNK = Buffer8.from("0\r\n\r\n");
  let isChunkedTransfer = false;
  let properLastChunkReceived = false;
  let previousChunk;
  request4.on("response", (response) => {
    const { headers } = response;
    isChunkedTransfer = headers["transfer-encoding"] === "chunked" && !headers["content-length"];
  });
  request4.on("socket", (socket) => {
    const onSocketClose = /* @__PURE__ */ __name(() => {
      if (isChunkedTransfer && !properLastChunkReceived) {
        const error2 = new Error("Premature close");
        error2.code = "ERR_STREAM_PREMATURE_CLOSE";
        errorCallback(error2);
      }
    }, "onSocketClose");
    const onData = /* @__PURE__ */ __name((buf) => {
      properLastChunkReceived = Buffer8.compare(buf.slice(-5), LAST_CHUNK) === 0;
      if (!properLastChunkReceived && previousChunk) {
        properLastChunkReceived = Buffer8.compare(previousChunk.slice(-3), LAST_CHUNK.slice(0, 3)) === 0 && Buffer8.compare(buf.slice(-2), LAST_CHUNK.slice(3)) === 0;
      }
      previousChunk = buf;
    }, "onData");
    socket.prependListener("close", onSocketClose);
    socket.on("data", onData);
    request4.on("close", () => {
      socket.removeListener("close", onSocketClose);
      socket.removeListener("data", onData);
    });
  });
}
var supportedSchemas2;
var init_src3 = __esm({
  "packages/cli/node_modules/node-fetch/src/index.js"() {
    init_esbuild_shims();
    init_dist();
    init_body2();
    init_response2();
    init_headers3();
    init_request2();
    init_fetch_error2();
    init_abort_error2();
    init_is_redirect2();
    init_esm_min();
    init_is2();
    init_referrer2();
    init_from();
    supportedSchemas2 = /* @__PURE__ */ new Set(["data:", "http:", "https:"]);
    __name(fetch4, "fetch");
    __name(fixResponseChunkedTransferBadEnding2, "fixResponseChunkedTransferBadEnding");
  }
});

// packages/cli/node_modules/gaxios/build/cjs/src/gaxios.js
var require_gaxios2 = __commonJS({
  "packages/cli/node_modules/gaxios/build/cjs/src/gaxios.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    var __importDefault = exports2 && exports2.__importDefault || function(mod2) {
      return mod2 && mod2.__esModule ? mod2 : { "default": mod2 };
    };
    var _a7;
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.Gaxios = void 0;
    var extend_1 = __importDefault(require_extend());
    var https_1 = __require("https");
    var common_js_1 = require_common6();
    var retry_js_1 = require_retry4();
    var stream_1 = __require("stream");
    var interceptor_js_1 = require_interceptor2();
    var randomUUID10 = /* @__PURE__ */ __name(async () => globalThis.crypto?.randomUUID() || (await import("crypto")).randomUUID(), "randomUUID");
    var HTTP_STATUS_NO_CONTENT = 204;
    var Gaxios = class {
      static {
        __name(this, "Gaxios");
      }
      agentCache = /* @__PURE__ */ new Map();
      /**
       * Default HTTP options that will be used for every HTTP request.
       */
      defaults;
      /**
       * Interceptors
       */
      interceptors;
      /**
       * The Gaxios class is responsible for making HTTP requests.
       * @param defaults The default set of options to be used for this instance.
       */
      constructor(defaults3) {
        this.defaults = defaults3 || {};
        this.interceptors = {
          request: new interceptor_js_1.GaxiosInterceptorManager(),
          response: new interceptor_js_1.GaxiosInterceptorManager()
        };
      }
      /**
       * A {@link fetch `fetch`} compliant API for {@link Gaxios}.
       *
       * @remarks
       *
       * This is useful as a drop-in replacement for `fetch` API usage.
       *
       * @example
       *
       * ```ts
       * const gaxios = new Gaxios();
       * const myFetch: typeof fetch = (...args) => gaxios.fetch(...args);
       * await myFetch('https://example.com');
       * ```
       *
       * @param args `fetch` API or `Gaxios#request` parameters
       * @returns the {@link Response} with Gaxios-added properties
       */
      fetch(...args) {
        const input = args[0];
        const init = args[1];
        let url2 = void 0;
        const headers = new Headers();
        if (typeof input === "string") {
          url2 = new URL(input);
        } else if (input instanceof URL) {
          url2 = input;
        } else if (input && input.url) {
          url2 = new URL(input.url);
        }
        if (input && typeof input === "object" && "headers" in input) {
          _a7.mergeHeaders(headers, input.headers);
        }
        if (init) {
          _a7.mergeHeaders(headers, new Headers(init.headers));
        }
        if (typeof input === "object" && !(input instanceof URL)) {
          return this.request({ ...init, ...input, headers, url: url2 });
        } else {
          return this.request({ ...init, headers, url: url2 });
        }
      }
      /**
       * 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 = {}) {
        let prepared = await this.#prepareRequest(opts);
        prepared = await this.#applyRequestInterceptors(prepared);
        return this.#applyResponseInterceptors(this._request(prepared));
      }
      async _defaultAdapter(config2) {
        const fetchImpl = config2.fetchImplementation || this.defaults.fetchImplementation || await _a7.#getFetch();
        const preparedOpts = { ...config2 };
        delete preparedOpts.data;
        const res = await fetchImpl(config2.url, preparedOpts);
        const data = await this.getResponseData(config2, res);
        if (!Object.getOwnPropertyDescriptor(res, "data")?.configurable) {
          Object.defineProperties(res, {
            data: {
              configurable: true,
              writable: true,
              enumerable: true,
              value: data
            }
          });
        }
        return Object.assign(res, { config: config2, 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) {
        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") {
              const response = [];
              for await (const chunk of translatedResponse.data) {
                response.push(chunk);
              }
              translatedResponse.data = response.toString();
            }
            const errorInfo = common_js_1.GaxiosError.extractAPIErrorFromResponse(translatedResponse, `Request failed with status code ${translatedResponse.status}`);
            throw new common_js_1.GaxiosError(errorInfo?.message, opts, translatedResponse, errorInfo);
          }
          return translatedResponse;
        } catch (e4) {
          let err;
          if (e4 instanceof common_js_1.GaxiosError) {
            err = e4;
          } else if (e4 instanceof Error) {
            err = new common_js_1.GaxiosError(e4.message, opts, void 0, e4);
          } else {
            err = new common_js_1.GaxiosError("Unexpected Gaxios Error", opts, void 0, e4);
          }
          const { shouldRetry, config: config2 } = await (0, retry_js_1.getRetryConfig)(err);
          if (shouldRetry && config2) {
            err.config.retryConfig.currentRetryAttempt = config2.retryConfig.currentRetryAttempt;
            opts.retryConfig = err.config?.retryConfig;
            this.#appendTimeoutToSignal(opts);
            return this._request(opts);
          }
          if (opts.errorRedactor) {
            opts.errorRedactor(err);
          }
          throw err;
        }
      }
      async getResponseData(opts, res) {
        if (res.status === HTTP_STATUS_NO_CONTENT) {
          return "";
        }
        if (opts.maxContentLength && res.headers.has("content-length") && opts.maxContentLength < Number.parseInt(res.headers?.get("content-length") || "")) {
          throw new common_js_1.GaxiosError("Response's `Content-Length` is over the limit.", opts, Object.assign(res, { config: opts }));
        }
        switch (opts.responseType) {
          case "stream":
            return res.body;
          case "json": {
            const data = await res.text();
            try {
              return JSON.parse(data);
            } catch {
              return data;
            }
          }
          case "arraybuffer":
            return res.arrayBuffer();
          case "blob":
            return res.blob();
          case "text":
            return res.text();
          default:
            return this.getResponseDataFromContentType(res);
        }
      }
      #urlMayUseProxy(url2, noProxy = []) {
        const candidate = new URL(url2);
        const noProxyList = [...noProxy];
        const noProxyEnvList = (process.env.NO_PROXY ?? process.env.no_proxy)?.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) {
            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;
      }
      /**
       * Applies the request interceptors. The request interceptors are applied after the
       * call to prepareRequest is completed.
       *
       * @param {GaxiosOptionsPrepared} options The current set of options.
       *
       * @returns {Promise<GaxiosOptionsPrepared>} Promise that resolves to the set of options or response after interceptors are applied.
       */
      async #applyRequestInterceptors(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;
      }
      /**
       * Applies the response interceptors. The response interceptors are applied after the
       * call to request is made.
       *
       * @param {GaxiosOptionsPrepared} options The current set of options.
       *
       * @returns {Promise<GaxiosOptionsPrepared>} Promise that resolves to the set of options or response after interceptors are applied.
       */
      async #applyResponseInterceptors(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;
      }
      /**
       * 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
       */
      async #prepareRequest(options2) {
        const preparedHeaders = new Headers(this.defaults.headers);
        _a7.mergeHeaders(preparedHeaders, options2.headers);
        const opts = (0, extend_1.default)(true, {}, this.defaults, options2);
        if (!opts.url) {
          throw new Error("URL is required.");
        }
        if (opts.baseURL) {
          opts.url = new URL(opts.url, opts.baseURL);
        }
        opts.url = new URL(opts.url);
        if (opts.params) {
          if (opts.paramsSerializer) {
            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;
          } else {
            const url2 = opts.url instanceof URL ? opts.url : new URL(opts.url);
            for (const [key, value] of new URLSearchParams(opts.params)) {
              url2.searchParams.append(key, value);
            }
            opts.url = url2;
          }
        }
        if (typeof options2.maxContentLength === "number") {
          opts.size = options2.maxContentLength;
        }
        if (typeof options2.maxRedirects === "number") {
          opts.follow = options2.maxRedirects;
        }
        const shouldDirectlyPassData = typeof opts.data === "string" || opts.data instanceof ArrayBuffer || opts.data instanceof Blob || // Node 18 does not have a global `File` object
        globalThis.File && opts.data instanceof File || opts.data instanceof FormData || opts.data instanceof stream_1.Readable || opts.data instanceof ReadableStream || opts.data instanceof String || opts.data instanceof URLSearchParams || ArrayBuffer.isView(opts.data) || // `Buffer` (Node.js), `DataView`, `TypedArray`
        /**
         * @deprecated `node-fetch` or another third-party's request types
         */
        ["Blob", "File", "FormData"].includes(opts.data?.constructor?.name || "");
        if (opts.multipart?.length) {
          const boundary = await randomUUID10();
          preparedHeaders.set("content-type", `multipart/related; boundary=${boundary}`);
          opts.body = stream_1.Readable.from(this.getMultipartRequest(opts.multipart, boundary));
        } else if (shouldDirectlyPassData) {
          opts.body = opts.data;
        } else if (typeof opts.data === "object") {
          if (preparedHeaders.get("Content-Type") === "application/x-www-form-urlencoded") {
            opts.body = opts.paramsSerializer ? opts.paramsSerializer(opts.data) : new URLSearchParams(opts.data);
          } else {
            if (!preparedHeaders.has("content-type")) {
              preparedHeaders.set("content-type", "application/json");
            }
            opts.body = JSON.stringify(opts.data);
          }
        } else if (opts.data) {
          opts.body = opts.data;
        }
        opts.validateStatus = opts.validateStatus || this.validateStatus;
        opts.responseType = opts.responseType || "unknown";
        if (!preparedHeaders.has("accept") && opts.responseType === "json") {
          preparedHeaders.set("accept", "application/json");
        }
        const proxy = opts.proxy || process?.env?.HTTPS_PROXY || process?.env?.https_proxy || process?.env?.HTTP_PROXY || process?.env?.http_proxy;
        if (opts.agent) {
        } else if (proxy && this.#urlMayUseProxy(opts.url, opts.noProxy)) {
          const HttpsProxyAgent2 = await _a7.#getProxyAgent();
          if (this.agentCache.has(proxy)) {
            opts.agent = this.agentCache.get(proxy);
          } else {
            opts.agent = new HttpsProxyAgent2(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_js_1.defaultErrorRedactor;
        }
        if (opts.body && !("duplex" in opts)) {
          opts.duplex = "half";
        }
        this.#appendTimeoutToSignal(opts);
        return Object.assign(opts, {
          headers: preparedHeaders,
          url: opts.url instanceof URL ? opts.url : new URL(opts.url)
        });
      }
      #appendTimeoutToSignal(opts) {
        if (opts.timeout) {
          const timeoutSignal = AbortSignal.timeout(opts.timeout);
          if (opts.signal && !opts.signal.aborted) {
            opts.signal = AbortSignal.any([opts.signal, timeoutSignal]);
          } else {
            opts.signal = timeoutSignal;
          }
        }
      }
      /**
       * By default, throw for any non-2xx status code
       * @param status status code from the HTTP response
       */
      validateStatus(status) {
        return status >= 200 && status < 300;
      }
      /**
       * Attempts to parse a response by looking at the Content-Type header.
       * @param {Response} response the HTTP response.
       * @returns 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 {
          }
          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 {GaxiosMultipartOptions[]} 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.get("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;
      }
      /**
       * A cache for the lazily-loaded proxy agent.
       *
       * Should use {@link Gaxios[#getProxyAgent]} to retrieve.
       */
      // using `import` to dynamically import the types here
      static #proxyAgent;
      /**
       * A cache for the lazily-loaded fetch library.
       *
       * Should use {@link Gaxios[#getFetch]} to retrieve.
       */
      //
      static #fetch;
      /**
       * Imports, caches, and returns a proxy agent - if not already imported
       *
       * @returns A proxy agent
       */
      static async #getProxyAgent() {
        this.#proxyAgent ||= (await Promise.resolve().then(() => __toESM(require_dist2()))).HttpsProxyAgent;
        return this.#proxyAgent;
      }
      static async #getFetch() {
        const hasWindow = typeof window !== "undefined" && !!window;
        this.#fetch ||= hasWindow ? window.fetch : (await Promise.resolve().then(() => (init_src3(), src_exports2))).default;
        return this.#fetch;
      }
      /**
       * Merges headers.
       * If the base headers do not exist a new `Headers` object will be returned.
       *
       * @remarks
       *
       * Using this utility can be helpful when the headers are not known to exist:
       * - if they exist as `Headers`, that instance will be used
       *   - it improves performance and allows users to use their existing references to their `Headers`
       * - if they exist in another form (`HeadersInit`), they will be used to create a new `Headers` object
       * - if the base headers do not exist a new `Headers` object will be created
       *
       * @param base headers to append/overwrite to
       * @param append headers to append/overwrite with
       * @returns the base headers instance with merged `Headers`
       */
      static mergeHeaders(base, ...append2) {
        base = base instanceof Headers ? base : new Headers(base);
        for (const headers of append2) {
          const add = headers instanceof Headers ? headers : new Headers(headers);
          add.forEach((value, key) => {
            key === "set-cookie" ? base.append(key, value) : base.set(key, value);
          });
        }
        return base;
      }
    };
    exports2.Gaxios = Gaxios;
    _a7 = Gaxios;
  }
});

// packages/cli/node_modules/gaxios/build/cjs/src/index.js
var require_src40 = __commonJS({
  "packages/cli/node_modules/gaxios/build/cjs/src/index.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    var __createBinding = exports2 && exports2.__createBinding || (Object.create ? function(o3, m3, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc2 = Object.getOwnPropertyDescriptor(m3, k2);
      if (!desc2 || ("get" in desc2 ? !m3.__esModule : desc2.writable || desc2.configurable)) {
        desc2 = { enumerable: true, get: /* @__PURE__ */ __name(function() {
          return m3[k2];
        }, "get") };
      }
      Object.defineProperty(o3, k22, desc2);
    } : function(o3, m3, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o3[k22] = m3[k2];
    });
    var __exportStar = exports2 && exports2.__exportStar || function(m3, exports3) {
      for (var p2 in m3) if (p2 !== "default" && !Object.prototype.hasOwnProperty.call(exports3, p2)) __createBinding(exports3, m3, p2);
    };
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.instance = exports2.Gaxios = exports2.GaxiosError = void 0;
    exports2.request = request4;
    var gaxios_js_1 = require_gaxios2();
    Object.defineProperty(exports2, "Gaxios", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return gaxios_js_1.Gaxios;
    }, "get") });
    var common_js_1 = require_common6();
    Object.defineProperty(exports2, "GaxiosError", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return common_js_1.GaxiosError;
    }, "get") });
    __exportStar(require_interceptor2(), exports2);
    exports2.instance = new gaxios_js_1.Gaxios();
    async function request4(opts) {
      return exports2.instance.request(opts);
    }
    __name(request4, "request");
  }
});

// packages/cli/node_modules/gcp-metadata/build/src/gcp-residency.js
var require_gcp_residency2 = __commonJS({
  "packages/cli/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 {
        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");
  }
});

// packages/cli/node_modules/google-logging-utils/build/src/colours.js
var require_colours2 = __commonJS({
  "packages/cli/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 && // May happen in browsers.
        stream2.isTTY && (typeof stream2.getColorDepth === "function" ? stream2.getColorDepth() > 2 : true);
      }
      static refresh() {
        _Colours.enabled = _Colours.isEnabled(process === null || process === void 0 ? void 0 : 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();
  }
});

// packages/cli/node_modules/google-logging-utils/build/src/logging-utils.js
var require_logging_utils2 = __commonJS({
  "packages/cli/node_modules/google-logging-utils/build/src/logging-utils.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    var __createBinding = exports2 && exports2.__createBinding || (Object.create ? function(o3, m3, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc2 = Object.getOwnPropertyDescriptor(m3, k2);
      if (!desc2 || ("get" in desc2 ? !m3.__esModule : desc2.writable || desc2.configurable)) {
        desc2 = { enumerable: true, get: /* @__PURE__ */ __name(function() {
          return m3[k2];
        }, "get") };
      }
      Object.defineProperty(o3, k22, desc2);
    } : function(o3, m3, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o3[k22] = m3[k2];
    });
    var __setModuleDefault = exports2 && exports2.__setModuleDefault || (Object.create ? function(o3, v2) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v2 });
    } : function(o3, v2) {
      o3["default"] = v2;
    });
    var __importStar = exports2 && exports2.__importStar || /* @__PURE__ */ function() {
      var ownKeys2 = /* @__PURE__ */ __name(function(o3) {
        ownKeys2 = Object.getOwnPropertyNames || function(o4) {
          var ar2 = [];
          for (var k2 in o4) if (Object.prototype.hasOwnProperty.call(o4, k2)) ar2[ar2.length] = k2;
          return ar2;
        };
        return ownKeys2(o3);
      }, "ownKeys");
      return function(mod2) {
        if (mod2 && mod2.__esModule) return mod2;
        var result = {};
        if (mod2 != null) {
          for (var k2 = ownKeys2(mod2), i3 = 0; i3 < k2.length; i3++) if (k2[i3] !== "default") __createBinding(result, mod2, k2[i3]);
        }
        __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 events_1 = __require("events");
    var process50 = __importStar(__require("process"));
    var util3 = __importStar(__require("util"));
    var colours_1 = require_colours2();
    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 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) {
          try {
            this.upstream(fields, ...args);
          } catch (e4) {
          }
        }
        try {
          this.emit("log", fields, args);
        } catch (e4) {
        }
      }
      invokeSeverity(severity, ...args) {
        this.invoke({ severity }, ...args);
      }
    };
    exports2.AdhocDebugLogger = AdhocDebugLogger;
    exports2.placeholder = new AdhocDebugLogger("", () => {
    }).func;
    var DebugLogBackendBase = class {
      static {
        __name(this, "DebugLogBackendBase");
      }
      constructor() {
        var _a7;
        this.cached = /* @__PURE__ */ new Map();
        this.filters = [];
        this.filtersSet = false;
        let nodeFlag = (_a7 = process50.env[exports2.env.nodeEnables]) !== null && _a7 !== void 0 ? _a7 : "*";
        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 (e4) {
          console.error(e4);
        }
      }
    };
    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 _a7;
          const nscolour = `${colours_1.Colours.green}${namespace}${colours_1.Colours.reset}`;
          const pid = `${colours_1.Colours.yellow}${process50.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 = (_a7 = fields.severity) !== null && _a7 !== void 0 ? _a7 : LogSeverity.DEFAULT;
              break;
          }
          const msg = util3.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 debugLogger124 = this.debugPkg(namespace);
        return (fields, ...args) => {
          debugLogger124(args[0], ...args.slice(1));
        };
      }
      setFilters() {
        var _a7;
        const existingFilters = (_a7 = process50.env["NODE_DEBUG"]) !== null && _a7 !== void 0 ? _a7 : "";
        process50.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 _a7;
        super();
        this.upstream = (_a7 = upstream) !== null && _a7 !== void 0 ? _a7 : void 0;
      }
      makeLogger(namespace) {
        var _a7;
        const debugLogger124 = (_a7 = this.upstream) === null || _a7 === void 0 ? void 0 : _a7.makeLogger(namespace);
        return (fields, ...args) => {
          var _a8;
          const severity = (_a8 = fields.severity) !== null && _a8 !== void 0 ? _a8 : LogSeverity.INFO;
          const json2 = Object.assign({
            severity,
            message: util3.format(...args)
          }, fields);
          const jsonString = JSON.stringify(json2);
          if (debugLogger124) {
            debugLogger124(fields, jsonString);
          } else {
            console.log("%s", jsonString);
          }
        };
      }
      setFilters() {
        var _a7;
        (_a7 = this.upstream) === null || _a7 === void 0 ? void 0 : _a7.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) {
      if (!cachedBackend) {
        const enablesFlag = process50.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");
  }
});

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

// packages/cli/node_modules/gcp-metadata/build/src/index.js
var require_src42 = __commonJS({
  "packages/cli/node_modules/gcp-metadata/build/src/index.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    var __createBinding = exports2 && exports2.__createBinding || (Object.create ? function(o3, m3, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc2 = Object.getOwnPropertyDescriptor(m3, k2);
      if (!desc2 || ("get" in desc2 ? !m3.__esModule : desc2.writable || desc2.configurable)) {
        desc2 = { enumerable: true, get: /* @__PURE__ */ __name(function() {
          return m3[k2];
        }, "get") };
      }
      Object.defineProperty(o3, k22, desc2);
    } : function(o3, m3, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o3[k22] = m3[k2];
    });
    var __setModuleDefault = exports2 && exports2.__setModuleDefault || (Object.create ? function(o3, v2) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v2 });
    } : function(o3, v2) {
      o3["default"] = v2;
    });
    var __importStar = exports2 && exports2.__importStar || /* @__PURE__ */ function() {
      var ownKeys2 = /* @__PURE__ */ __name(function(o3) {
        ownKeys2 = Object.getOwnPropertyNames || function(o4) {
          var ar2 = [];
          for (var k2 in o4) if (Object.prototype.hasOwnProperty.call(o4, k2)) ar2[ar2.length] = k2;
          return ar2;
        };
        return ownKeys2(o3);
      }, "ownKeys");
      return function(mod2) {
        if (mod2 && mod2.__esModule) return mod2;
        var result = {};
        if (mod2 != null) {
          for (var k2 = ownKeys2(mod2), i3 = 0; i3 < k2.length; i3++) if (k2[i3] !== "default") __createBinding(result, mod2, k2[i3]);
        }
        __setModuleDefault(result, mod2);
        return result;
      };
    }();
    var __exportStar = exports2 && exports2.__exportStar || function(m3, exports3) {
      for (var p2 in m3) if (p2 !== "default" && !Object.prototype.hasOwnProperty.call(exports3, p2)) __createBinding(exports3, m3, p2);
    };
    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_src40();
    var jsonBigint = require_json_bigint();
    var gcp_residency_1 = require_gcp_residency2();
    var logger6 = __importStar(require_src41());
    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 validate3(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(validate3, "validate");
    async function metadataAccessor(type, options2 = {}, noResponseRetries = 3, fastFail = false) {
      const headers = new Headers(exports2.HEADERS);
      let metadataKey = "";
      let params = {};
      if (typeof type === "object") {
        const metadataAccessor2 = type;
        new Headers(metadataAccessor2.headers).forEach((value, key) => headers.set(key, value));
        metadataKey = metadataAccessor2.metadataKey;
        params = metadataAccessor2.params || params;
        noResponseRetries = metadataAccessor2.noResponseRetries || noResponseRetries;
        fastFail = metadataAccessor2.fastFail || fastFail;
      } else {
        metadataKey = type;
      }
      if (typeof options2 === "string") {
        metadataKey += `/${options2}`;
      } else {
        validate3(options2);
        if (options2.property) {
          metadataKey += `/${options2.property}`;
        }
        new Headers(options2.headers).forEach((value, key) => headers.set(key, value));
        params = options2.params || params;
      }
      const requestMethod = fastFail ? fastFailMetadataRequest : gaxios_1.request;
      const req = {
        url: `${getBaseUrl2()}/${metadataKey}`,
        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);
      const metadataFlavor = res.headers.get(exports2.HEADER_NAME);
      if (metadataFlavor !== exports2.HEADER_VALUE) {
        throw new RangeError(`Invalid response from metadata service: incorrect ${exports2.HEADER_NAME} header. Expected '${exports2.HEADER_VALUE}', got ${metadataFlavor ? `'${metadataFlavor}'` : "no header"}`);
      }
      if (typeof res.data === "string") {
        try {
          return jsonBigint.parse(res.data);
        } catch {
        }
      }
      return res.data;
    }
    __name(metadataAccessor, "metadataAccessor");
    async function fastFailMetadataRequest(options2) {
      const secondaryOptions = {
        ...options2,
        url: options2.url?.toString().replace(getBaseUrl2(), getBaseUrl2(exports2.SECONDARY_HOST_ADDRESS))
      };
      const r1 = (0, gaxios_1.request)(options2);
      const r22 = (0, gaxios_1.request)(secondaryOptions);
      return Promise.any([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 r5 = {};
      await Promise.all(properties.map((item) => {
        return (async () => {
          const res = await metadataAccessor(item);
          const key = item.metadataKey;
          r5[key] = res;
        })();
      }));
      return r5;
    }
    __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 (e4) {
        const err = e4;
        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.toString()))) {
            let code2 = "UNKNOWN";
            if (err.code)
              code2 = err.code.toString();
            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_residency2(), exports2);
  }
});

// packages/cli/node_modules/google-auth-library/build/src/crypto/shared.js
var require_shared3 = __commonJS({
  "packages/cli/node_modules/google-auth-library/build/src/crypto/shared.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.fromArrayBufferToHex = fromArrayBufferToHex;
    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");
  }
});

// packages/cli/node_modules/google-auth-library/build/src/crypto/browser/crypto.js
var require_crypto4 = __commonJS({
  "packages/cli/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 shared_1 = require_shared3();
    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 array2 = new Uint8Array(count);
        window.crypto.getRandomValues(array2);
        return base64js.fromByteArray(array2);
      }
      static padBase64(base642) {
        while (base642.length % 4 !== 0) {
          base642 += "=";
        }
        return base642;
      }
      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(base642) {
        const uint8array = base64js.toByteArray(_BrowserCrypto.padBase64(base642));
        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, shared_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;
  }
});

// packages/cli/node_modules/google-auth-library/build/src/crypto/node/crypto.js
var require_crypto5 = __commonJS({
  "packages/cli/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 crypto14 = __require("crypto");
    var NodeCrypto = class {
      static {
        __name(this, "NodeCrypto");
      }
      async sha256DigestBase64(str2) {
        return crypto14.createHash("sha256").update(str2).digest("base64");
      }
      randomBytesBase64(count) {
        return crypto14.randomBytes(count).toString("base64");
      }
      async verify(pubkey, data, signature) {
        const verifier = crypto14.createVerify("RSA-SHA256");
        verifier.update(data);
        verifier.end();
        return verifier.verify(pubkey, signature, "base64");
      }
      async sign(privateKey, data) {
        const signer = crypto14.createSign("RSA-SHA256");
        signer.update(data);
        signer.end();
        return signer.sign(privateKey, "base64");
      }
      decodeBase64StringUtf8(base642) {
        return Buffer.from(base642, "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 crypto14.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(crypto14.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");
  }
});

// packages/cli/node_modules/google-auth-library/build/src/crypto/crypto.js
var require_crypto6 = __commonJS({
  "packages/cli/node_modules/google-auth-library/build/src/crypto/crypto.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    var __createBinding = exports2 && exports2.__createBinding || (Object.create ? function(o3, m3, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc2 = Object.getOwnPropertyDescriptor(m3, k2);
      if (!desc2 || ("get" in desc2 ? !m3.__esModule : desc2.writable || desc2.configurable)) {
        desc2 = { enumerable: true, get: /* @__PURE__ */ __name(function() {
          return m3[k2];
        }, "get") };
      }
      Object.defineProperty(o3, k22, desc2);
    } : function(o3, m3, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o3[k22] = m3[k2];
    });
    var __exportStar = exports2 && exports2.__exportStar || function(m3, exports3) {
      for (var p2 in m3) if (p2 !== "default" && !Object.prototype.hasOwnProperty.call(exports3, p2)) __createBinding(exports3, m3, p2);
    };
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.createCrypto = createCrypto;
    exports2.hasBrowserCrypto = hasBrowserCrypto;
    var crypto_1 = require_crypto4();
    var crypto_2 = require_crypto5();
    __exportStar(require_shared3(), exports2);
    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");
  }
});

// packages/cli/node_modules/google-auth-library/build/src/util.js
var require_util31 = __commonJS({
  "packages/cli/node_modules/google-auth-library/build/src/util.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.LRUCache = void 0;
    exports2.snakeToCamel = snakeToCamel;
    exports2.originalOrCamelOptions = originalOrCamelOptions;
    exports2.removeUndefinedValuesInObject = removeUndefinedValuesInObject;
    exports2.isValidFile = isValidFile;
    exports2.getWellKnownCertificateConfigFileLocation = getWellKnownCertificateConfigFileLocation;
    var fs113 = __require("fs");
    var os47 = __require("os");
    var path125 = __require("path");
    var WELL_KNOWN_CERTIFICATE_CONFIG_FILE = "certificate_config.json";
    var CLOUDSDK_CONFIG_DIRECTORY = "gcloud";
    function snakeToCamel(str2) {
      return str2.replace(/([_][^_])/g, (match2) => match2.slice(1).toUpperCase());
    }
    __name(snakeToCamel, "snakeToCamel");
    function originalOrCamelOptions(obj) {
      function get4(key) {
        const o3 = obj || {};
        return o3[key] ?? o3[snakeToCamel(key)];
      }
      __name(get4, "get");
      return { get: get4 };
    }
    __name(originalOrCamelOptions, "originalOrCamelOptions");
    var LRUCache2 = class {
      static {
        __name(this, "LRUCache");
      }
      capacity;
      /**
       * Maps are in order. Thus, the older item is the first item.
       *
       * {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map}
       */
      #cache = /* @__PURE__ */ new Map();
      maxAge;
      constructor(options2) {
        this.capacity = options2.capacity;
        this.maxAge = options2.maxAge;
      }
      /**
       * Moves the key to the end of the cache.
       *
       * @param key the key to move
       * @param value the value of the key
       */
      #moveToEnd(key, value) {
        this.#cache.delete(key);
        this.#cache.set(key, {
          value,
          lastAccessed: Date.now()
        });
      }
      /**
       * Add an item to the cache.
       *
       * @param key the key to upsert
       * @param value the value of the key
       */
      set(key, value) {
        this.#moveToEnd(key, value);
        this.#evict();
      }
      /**
       * Get an item from the cache.
       *
       * @param key the key to retrieve
       */
      get(key) {
        const item = this.#cache.get(key);
        if (!item)
          return;
        this.#moveToEnd(key, item.value);
        this.#evict();
        return item.value;
      }
      /**
       * Maintain the cache based on capacity and TTL.
       */
      #evict() {
        const cutoffDate = this.maxAge ? Date.now() - this.maxAge : 0;
        let oldestItem = this.#cache.entries().next();
        while (!oldestItem.done && (this.#cache.size > this.capacity || // too many
        oldestItem.value[1].lastAccessed < cutoffDate)) {
          this.#cache.delete(oldestItem.value[0]);
          oldestItem = this.#cache.entries().next();
        }
      }
    };
    exports2.LRUCache = LRUCache2;
    function removeUndefinedValuesInObject(object3) {
      Object.entries(object3).forEach(([key, value]) => {
        if (value === void 0 || value === "undefined") {
          delete object3[key];
        }
      });
      return object3;
    }
    __name(removeUndefinedValuesInObject, "removeUndefinedValuesInObject");
    async function isValidFile(filePath) {
      try {
        const stats = await fs113.promises.lstat(filePath);
        return stats.isFile();
      } catch (e4) {
        return false;
      }
    }
    __name(isValidFile, "isValidFile");
    function getWellKnownCertificateConfigFileLocation() {
      const configDir = process.env.CLOUDSDK_CONFIG || (_isWindows() ? path125.join(process.env.APPDATA || "", CLOUDSDK_CONFIG_DIRECTORY) : path125.join(process.env.HOME || "", ".config", CLOUDSDK_CONFIG_DIRECTORY));
      return path125.join(configDir, WELL_KNOWN_CERTIFICATE_CONFIG_FILE);
    }
    __name(getWellKnownCertificateConfigFileLocation, "getWellKnownCertificateConfigFileLocation");
    function _isWindows() {
      return os47.platform().startsWith("win");
    }
    __name(_isWindows, "_isWindows");
  }
});

// packages/cli/node_modules/google-auth-library/package.json
var require_package7 = __commonJS({
  "packages/cli/node_modules/google-auth-library/package.json"(exports2, module2) {
    module2.exports = {
      name: "google-auth-library",
      version: "10.5.0",
      author: "Google Inc.",
      description: "Google APIs Authentication Client Library for Node.js",
      engines: {
        node: ">=18"
      },
      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: "^7.0.0",
        "gcp-metadata": "^8.0.0",
        "google-logging-utils": "^1.0.0",
        gtoken: "^8.0.0",
        jws: "^4.0.0"
      },
      devDependencies: {
        "@types/base64-js": "^1.2.5",
        "@types/jws": "^3.1.0",
        "@types/mocha": "^10.0.10",
        "@types/mv": "^2.1.0",
        "@types/ncp": "^2.0.1",
        "@types/node": "^22.0.0",
        "@types/sinon": "^17.0.0",
        "assert-rejects": "^1.0.0",
        c8: "^10.0.0",
        codecov: "^3.0.2",
        gts: "^6.0.0",
        "is-docker": "^3.0.0",
        jsdoc: "^4.0.0",
        "jsdoc-fresh": "^5.0.0",
        "jsdoc-region-tag": "^4.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.1",
        keypair: "^1.0.4",
        mocha: "^11.1.0",
        mv: "^2.1.1",
        ncp: "^2.0.0",
        nock: "^14.0.5",
        "null-loader": "^4.0.0",
        puppeteer: "^24.0.0",
        sinon: "^21.0.0",
        "ts-loader": "^8.0.0",
        typescript: "5.8.2",
        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 --no-inline-config",
        compile: "tsc -p .",
        fix: "gts fix",
        pretest: "npm run compile -- --sourceMap",
        docs: "jsdoc -c .jsdoc.js",
        "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": "echo 'disabled until linkinator is fixed'",
        "predocs-test": "npm run docs",
        prelint: "cd samples; npm link ../; npm install"
      },
      license: "Apache-2.0"
    };
  }
});

// packages/cli/node_modules/google-auth-library/build/src/shared.cjs
var require_shared4 = __commonJS({
  "packages/cli/node_modules/google-auth-library/build/src/shared.cjs"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.USER_AGENT = exports2.PRODUCT_NAME = exports2.pkg = void 0;
    var pkg2 = require_package7();
    exports2.pkg = pkg2;
    var PRODUCT_NAME = "google-api-nodejs-client";
    exports2.PRODUCT_NAME = PRODUCT_NAME;
    var USER_AGENT = `${PRODUCT_NAME}/${pkg2.version}`;
    exports2.USER_AGENT = USER_AGENT;
  }
});

// packages/cli/node_modules/google-auth-library/build/src/auth/authclient.js
var require_authclient2 = __commonJS({
  "packages/cli/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_src40();
    var util_1 = require_util31();
    var google_logging_utils_1 = require_src41();
    var shared_cjs_1 = require_shared4();
    exports2.DEFAULT_UNIVERSE = "googleapis.com";
    exports2.DEFAULT_EAGER_REFRESH_THRESHOLD_MILLIS = 5 * 60 * 1e3;
    var AuthClient = class _AuthClient extends events_1.EventEmitter {
      static {
        __name(this, "AuthClient");
      }
      apiKey;
      projectId;
      /**
       * The quota project ID. The quota project can be used by client libraries for the billing purpose.
       * See {@link https://cloud.google.com/docs/quota Working with quotas}
       */
      quotaProjectId;
      /**
       * The {@link Gaxios `Gaxios`} instance used for making requests.
       */
      transporter;
      credentials = {};
      eagerRefreshThresholdMillis = exports2.DEFAULT_EAGER_REFRESH_THRESHOLD_MILLIS;
      forceRefreshOnFailure = false;
      universeDomain = exports2.DEFAULT_UNIVERSE;
      /**
       * Symbols that can be added to GaxiosOptions to specify the method name that is
       * making an RPC call, for logging purposes, as well as a string ID that can be
       * used to correlate calls and responses.
       */
      static RequestMethodNameSymbol = Symbol("request method name");
      static RequestLogIdSymbol = Symbol("request log id");
      constructor(opts = {}) {
        super();
        const options2 = (0, util_1.originalOrCamelOptions)(opts);
        this.apiKey = opts.apiKey;
        this.projectId = options2.get("project_id") ?? null;
        this.quotaProjectId = options2.get("quota_project_id");
        this.credentials = options2.get("credentials") ?? {};
        this.universeDomain = options2.get("universe_domain") ?? exports2.DEFAULT_UNIVERSE;
        this.transporter = opts.transporter ?? new gaxios_1.Gaxios(opts.transporterOptions);
        if (options2.get("useAuthRequestParameters") !== false) {
          this.transporter.interceptors.request.add(_AuthClient.DEFAULT_REQUEST_INTERCEPTOR);
          this.transporter.interceptors.response.add(_AuthClient.DEFAULT_RESPONSE_INTERCEPTOR);
        }
        if (opts.eagerRefreshThresholdMillis) {
          this.eagerRefreshThresholdMillis = opts.eagerRefreshThresholdMillis;
        }
        this.forceRefreshOnFailure = opts.forceRefreshOnFailure ?? false;
      }
      /**
       * A {@link fetch `fetch`} compliant API for {@link AuthClient}.
       *
       * @see {@link AuthClient.request} for the classic method.
       *
       * @remarks
       *
       * This is useful as a drop-in replacement for `fetch` API usage.
       *
       * @example
       *
       * ```ts
       * const authClient = new AuthClient();
       * const fetchWithAuthClient: typeof fetch = (...args) => authClient.fetch(...args);
       * await fetchWithAuthClient('https://example.com');
       * ```
       *
       * @param args `fetch` API or {@link Gaxios.fetch `Gaxios#fetch`} parameters
       * @returns the {@link GaxiosResponse} with Gaxios-added properties
       */
      fetch(...args) {
        const input = args[0];
        const init = args[1];
        let url2 = void 0;
        const headers = new Headers();
        if (typeof input === "string") {
          url2 = new URL(input);
        } else if (input instanceof URL) {
          url2 = input;
        } else if (input && input.url) {
          url2 = new URL(input.url);
        }
        if (input && typeof input === "object" && "headers" in input) {
          gaxios_1.Gaxios.mergeHeaders(headers, input.headers);
        }
        if (init) {
          gaxios_1.Gaxios.mergeHeaders(headers, new Headers(init.headers));
        }
        if (typeof input === "object" && !(input instanceof URL)) {
          return this.request({ ...init, ...input, headers, url: url2 });
        } else {
          return this.request({ ...init, headers, url: url2 });
        }
      }
      /**
       * 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.has("x-goog-user-project") && // don't override a value the user sets.
        this.quotaProjectId) {
          headers.set("x-goog-user-project", this.quotaProjectId);
        }
        return headers;
      }
      /**
       * Adds the `x-goog-user-project` and `authorization` headers to the target Headers
       * object, if they exist on the source.
       *
       * @param target the headers to target
       * @param source the headers to source from
       * @returns the target headers
       */
      addUserProjectAndAuthHeaders(target, source2) {
        const xGoogUserProject = source2.get("x-goog-user-project");
        const authorizationHeader = source2.get("authorization");
        if (xGoogUserProject) {
          target.set("x-goog-user-project", xGoogUserProject);
        }
        if (authorizationHeader) {
          target.set("authorization", authorizationHeader);
        }
        return target;
      }
      static log = (0, google_logging_utils_1.log)("auth");
      static DEFAULT_REQUEST_INTERCEPTOR = {
        resolved: /* @__PURE__ */ __name(async (config2) => {
          if (!config2.headers.has("x-goog-api-client")) {
            const nodeVersion2 = process.version.replace(/^v/, "");
            config2.headers.set("x-goog-api-client", `gl-node/${nodeVersion2}`);
          }
          const userAgent2 = config2.headers.get("User-Agent");
          if (!userAgent2) {
            config2.headers.set("User-Agent", shared_cjs_1.USER_AGENT);
          } else if (!userAgent2.includes(`${shared_cjs_1.PRODUCT_NAME}/`)) {
            config2.headers.set("User-Agent", `${userAgent2} ${shared_cjs_1.USER_AGENT}`);
          }
          try {
            const symbols = config2;
            const methodName = symbols[_AuthClient.RequestMethodNameSymbol];
            const logId = `${Math.floor(Math.random() * 1e3)}`;
            symbols[_AuthClient.RequestLogIdSymbol] = logId;
            const logObject = {
              url: config2.url,
              headers: config2.headers
            };
            if (methodName) {
              _AuthClient.log.info("%s [%s] request %j", methodName, logId, logObject);
            } else {
              _AuthClient.log.info("[%s] request %j", logId, logObject);
            }
          } catch (e4) {
          }
          return config2;
        }, "resolved")
      };
      static DEFAULT_RESPONSE_INTERCEPTOR = {
        resolved: /* @__PURE__ */ __name(async (response) => {
          try {
            const symbols = response.config;
            const methodName = symbols[_AuthClient.RequestMethodNameSymbol];
            const logId = symbols[_AuthClient.RequestLogIdSymbol];
            if (methodName) {
              _AuthClient.log.info("%s [%s] response %j", methodName, logId, response.data);
            } else {
              _AuthClient.log.info("[%s] response %j", logId, response.data);
            }
          } catch (e4) {
          }
          return response;
        }, "resolved"),
        rejected: /* @__PURE__ */ __name(async (error2) => {
          try {
            const symbols = error2.config;
            const methodName = symbols[_AuthClient.RequestMethodNameSymbol];
            const logId = symbols[_AuthClient.RequestLogIdSymbol];
            if (methodName) {
              _AuthClient.log.info("%s [%s] error %j", methodName, logId, error2.response?.data);
            } else {
              _AuthClient.log.error("[%s] error %j", logId, error2.response?.data);
            }
          } catch (e4) {
          }
          throw error2;
        }, "rejected")
      };
      /**
       * Sets the method name that is making a Gaxios request, so that logging may tag
       * log lines with the operation.
       * @param config A Gaxios request config
       * @param methodName The method name making the call
       */
      static setMethodName(config2, methodName) {
        try {
          const symbols = config2;
          symbols[_AuthClient.RequestMethodNameSymbol] = methodName;
        } catch (e4) {
        }
      }
      /**
       * 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;
  }
});

// packages/cli/node_modules/google-auth-library/build/src/auth/loginticket.js
var require_loginticket2 = __commonJS({
  "packages/cli/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");
      }
      envelope;
      payload;
      /**
       * 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;
  }
});

// packages/cli/node_modules/google-auth-library/build/src/auth/oauth2client.js
var require_oauth2client2 = __commonJS({
  "packages/cli/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_src40();
    var querystring = __require("querystring");
    var stream2 = __require("stream");
    var formatEcdsa = require_ecdsa_sig_formatter();
    var util_1 = require_util31();
    var crypto_1 = require_crypto6();
    var authclient_1 = require_authclient2();
    var loginticket_1 = require_loginticket2();
    var CodeChallengeMethod;
    (function(CodeChallengeMethod2) {
      CodeChallengeMethod2["Plain"] = "plain";
      CodeChallengeMethod2["S256"] = "S256";
    })(CodeChallengeMethod || (exports2.CodeChallengeMethod = CodeChallengeMethod = {}));
    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 OAuth2Client = class _OAuth2Client extends authclient_1.AuthClient {
      static {
        __name(this, "OAuth2Client");
      }
      redirectUri;
      certificateCache = {};
      certificateExpiry = null;
      certificateCacheFormat = CertificateFormat.PEM;
      refreshTokenPromises = /* @__PURE__ */ new Map();
      endpoints;
      issuers;
      clientAuthentication;
      // TODO: refactor tests to make this private
      _clientId;
      // TODO: refactor tests to make this private
      _clientSecret;
      refreshHandler;
      /**
       * An OAuth2 Client for Google APIs.
       *
       * @param options The OAuth2 Client Options. Passing an `clientId` directly is **@DEPRECATED**.
       * @param clientSecret **@DEPRECATED**. Provide a {@link OAuth2ClientOptions `OAuth2ClientOptions`} object in the first parameter instead.
       * @param redirectUri **@DEPRECATED**. Provide a {@link OAuth2ClientOptions `OAuth2ClientOptions`} object in the first parameter instead.
       */
      constructor(options2 = {}, clientSecret, redirectUri) {
        super(typeof options2 === "object" ? options2 : {});
        if (typeof options2 !== "object") {
          options2 = {
            clientId: options2,
            clientSecret,
            redirectUri
          };
        }
        this._clientId = options2.clientId || options2.client_id;
        this._clientSecret = options2.clientSecret || options2.client_secret;
        this.redirectUri = options2.redirectUri || options2.redirect_uris?.[0];
        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",
          ...options2.endpoints
        };
        this.clientAuthentication = options2.clientAuthentication || ClientAuthentication.ClientSecretPost;
        this.issuers = options2.issuers || [
          "accounts.google.com",
          "https://accounts.google.com",
          this.universeDomain
        ];
      }
      /**
       * @deprecated use instance's {@link OAuth2Client.endpoints}
       */
      static GOOGLE_TOKEN_INFO_URL = "https://oauth2.googleapis.com/tokeninfo";
      /**
       * Clock skew - five minutes in seconds
       */
      static CLOCK_SKEW_SECS_ = 300;
      /**
       * The default max Token Lifetime is one day in seconds
       */
      static DEFAULT_MAX_TOKEN_LIFETIME_SECS_ = 86400;
      /**
       * 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 crypto14 = (0, crypto_1.createCrypto)();
        const randomString2 = crypto14.randomBytesBase64(96);
        const codeVerifier = randomString2.replace(/\+/g, "~").replace(/=/g, "_").replace(/\//g, "-");
        const unencodedCodeChallenge = await crypto14.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((r5) => callback(null, r5.tokens, r5.res), (e4) => callback(e4, null, e4.response));
        } else {
          return this.getTokenAsync(options2);
        }
      }
      async getTokenAsync(options2) {
        const url2 = this.endpoints.oauth2TokenUrl.toString();
        const headers = new Headers();
        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.set("authorization", `Basic ${basic.toString("base64")}`);
        }
        if (this.clientAuthentication === ClientAuthentication.ClientSecretPost) {
          values.client_secret = this._clientSecret;
        }
        const opts = {
          ..._OAuth2Client.RETRY_CONFIG,
          method: "POST",
          url: url2,
          data: new URLSearchParams((0, util_1.removeUndefinedValuesInObject)(values)),
          headers
        };
        authclient_1.AuthClient.setMethodName(opts, "getTokenAsync");
        const res = await this.transporter.request(opts);
        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 p2 = this.refreshTokenNoCache(refreshToken).then((r5) => {
          this.refreshTokenPromises.delete(refreshToken);
          return r5;
        }, (e4) => {
          this.refreshTokenPromises.delete(refreshToken);
          throw e4;
        });
        this.refreshTokenPromises.set(refreshToken, p2);
        return p2;
      }
      async refreshTokenNoCache(refreshToken) {
        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 {
          const opts = {
            ..._OAuth2Client.RETRY_CONFIG,
            method: "POST",
            url: url2,
            data: new URLSearchParams((0, util_1.removeUndefinedValuesInObject)(data))
          };
          authclient_1.AuthClient.setMethodName(opts, "refreshTokenNoCache");
          res = await this.transporter.request(opts);
        } catch (e4) {
          if (e4 instanceof gaxios_1.GaxiosError && e4.message === "invalid_grant" && e4.response?.data && /ReAuth/i.test(e4.response.data.error_description)) {
            e4.message = JSON.stringify(e4.response.data);
          }
          throw e4;
        }
        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((r5) => callback(null, r5.credentials, r5.res), callback);
        } else {
          return this.refreshAccessTokenAsync();
        }
      }
      async refreshAccessTokenAsync() {
        const r5 = await this.refreshToken(this.credentials.refresh_token);
        const tokens = r5.tokens;
        tokens.refresh_token = this.credentials.refresh_token;
        this.credentials = tokens;
        return { credentials: this.credentials, res: r5.res };
      }
      getAccessToken(callback) {
        if (callback) {
          this.getAccessTokenAsync().then((r5) => callback(null, r5.token, r5.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?.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 r5 = await this.refreshAccessTokenAsync();
          if (!r5.credentials || r5.credentials && !r5.credentials.access_token) {
            throw new Error("Could not refresh access token.");
          }
          return { token: r5.credentials.access_token, res: r5.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>' }
       */
      async getRequestHeaders(url2) {
        const headers = (await this.getRequestMetadataAsync(url2)).headers;
        return headers;
      }
      async getRequestMetadataAsync(url2) {
        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 = new Headers({
            authorization: thisCreds.token_type + " " + thisCreds.access_token
          });
          return { headers: this.addSharedMetadataHeaders(headers2) };
        }
        if (this.refreshHandler) {
          const refreshedAccessToken = await this.processAndValidateRefreshHandler();
          if (refreshedAccessToken?.access_token) {
            this.setCredentials(refreshedAccessToken);
            const headers2 = new Headers({
              authorization: "Bearer " + this.credentials.access_token
            });
            return { headers: this.addSharedMetadataHeaders(headers2) };
          }
        }
        if (this.apiKey) {
          return { headers: new Headers({ "X-Goog-Api-Key": this.apiKey }) };
        }
        let r5 = null;
        let tokens = null;
        try {
          r5 = await this.refreshToken(thisCreds.refresh_token);
          tokens = r5.tokens;
        } catch (err) {
          const e4 = err;
          if (e4.response && (e4.response.status === 403 || e4.response.status === 404)) {
            e4.message = `Could not refresh access token: ${e4.message}`;
          }
          throw e4;
        }
        const credentials = this.credentials;
        credentials.token_type = credentials.token_type || "Bearer";
        tokens.refresh_token = credentials.refresh_token;
        this.credentials = tokens;
        const headers = new Headers({
          authorization: credentials.token_type + " " + tokens.access_token
        });
        return { headers: this.addSharedMetadataHeaders(headers), res: r5.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"
        };
        authclient_1.AuthClient.setMethodName(opts, "revokeToken");
        if (callback) {
          this.transporter.request(opts).then((r5) => callback(null, r5), 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((r5) => callback(null, r5), (e4) => {
            return callback(e4, e4.response);
          });
        } else {
          return this.requestAsync(opts);
        }
      }
      async requestAsync(opts, reAuthRetried = false) {
        try {
          const r5 = await this.getRequestMetadataAsync();
          opts.headers = gaxios_1.Gaxios.mergeHeaders(opts.headers);
          this.addUserProjectAndAuthHeaders(opts.headers, r5.headers);
          if (this.apiKey) {
            opts.headers.set("X-Goog-Api-Key", this.apiKey);
          }
          return await this.transporter.request(opts);
        } catch (e4) {
          const res = e4.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?.access_token) {
                this.setCredentials(refreshedAccessToken);
              }
              return this.requestAsync(opts, true);
            }
          }
          throw e4;
        }
      }
      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((r5) => callback(null, r5), 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;charset=UTF-8",
            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((r5) => callback(null, r5.certs, r5.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 {
          const opts = {
            ..._OAuth2Client.RETRY_CONFIG,
            url: url2
          };
          authclient_1.AuthClient.setMethodName(opts, "getFederatedSignonCertsAsync");
          res = await this.transporter.request(opts);
        } catch (e4) {
          if (e4 instanceof Error) {
            e4.message = `Failed to retrieve verification certificates: ${e4.message}`;
          }
          throw e4;
        }
        const cacheControl = res?.headers.get("cache-control");
        let cacheAge = -1;
        if (cacheControl) {
          const maxAge = /max-age=(?<maxAge>[0-9]+)/.exec(cacheControl)?.groups?.maxAge;
          if (maxAge) {
            cacheAge = Number(maxAge) * 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((r5) => callback(null, r5.pubkeys, r5.res), callback);
        } else {
          return this.getIapPublicKeysAsync();
        }
      }
      async getIapPublicKeysAsync() {
        let res;
        const url2 = this.endpoints.oauth2IapPublicKeyUrl.toString();
        try {
          const opts = {
            ..._OAuth2Client.RETRY_CONFIG,
            url: url2
          };
          authclient_1.AuthClient.setMethodName(opts, "getIapPublicKeysAsync");
          res = await this.transporter.request(opts);
        } catch (e4) {
          if (e4 instanceof Error) {
            e4.message = `Failed to retrieve verification certificates: ${e4.message}`;
          }
          throw e4;
        }
        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 crypto14 = (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(crypto14.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(crypto14.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 crypto14.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 = OAuth2Client;
  }
});

// packages/cli/node_modules/google-auth-library/build/src/auth/computeclient.js
var require_computeclient2 = __commonJS({
  "packages/cli/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_src40();
    var gcpMetadata = require_src42();
    var oauth2client_1 = require_oauth2client2();
    var Compute = class extends oauth2client_1.OAuth2Client {
      static {
        __name(this, "Compute");
      }
      serviceAccountEmail;
      scopes;
      /**
       * 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() {
        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 (e4) {
          if (e4 instanceof gaxios_1.GaxiosError) {
            e4.message = `Could not refresh access token: ${e4.message}`;
            this.wrapError(e4);
          }
          throw e4;
        }
        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 (e4) {
          if (e4 instanceof Error) {
            e4.message = `Could not fetch ID token: ${e4.message}`;
          }
          throw e4;
        }
        return idToken;
      }
      wrapError(e4) {
        const res = e4.response;
        if (res && res.status) {
          e4.status = res.status;
          if (res.status === 403) {
            e4.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: " + e4.message;
          } else if (res.status === 404) {
            e4.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: " + e4.message;
          }
        }
      }
    };
    exports2.Compute = Compute;
  }
});

// packages/cli/node_modules/google-auth-library/build/src/auth/idtokenclient.js
var require_idtokenclient2 = __commonJS({
  "packages/cli/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_oauth2client2();
    var IdTokenClient = class extends oauth2client_1.OAuth2Client {
      static {
        __name(this, "IdTokenClient");
      }
      targetAudience;
      idTokenProvider;
      /**
       * 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() {
        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 = new 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;
  }
});

// packages/cli/node_modules/google-auth-library/build/src/auth/envDetect.js
var require_envDetect2 = __commonJS({
  "packages/cli/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_src42();
    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["CLOUD_RUN_JOBS"] = "CLOUD_RUN_JOBS";
      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 if (isCloudRunJob()) {
          env7 = GCPEnv.CLOUD_RUN_JOBS;
        } 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");
    function isCloudRunJob() {
      return !!process.env.CLOUD_RUN_JOB;
    }
    __name(isCloudRunJob, "isCloudRunJob");
    async function isKubernetesEngine() {
      try {
        await gcpMetadata.instance("attributes/cluster-name");
        return true;
      } catch (e4) {
        return false;
      }
    }
    __name(isKubernetesEngine, "isKubernetesEngine");
    async function isComputeEngine() {
      return gcpMetadata.isAvailable();
    }
    __name(isComputeEngine, "isComputeEngine");
  }
});

// packages/cli/node_modules/gtoken/build/cjs/src/index.cjs
var require_src43 = __commonJS({
  "packages/cli/node_modules/gtoken/build/cjs/src/index.cjs"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", {
      value: true
    });
    exports2.GoogleToken = void 0;
    var fs113 = _interopRequireWildcard(__require("fs"));
    var _gaxios = require_src40();
    var jws = _interopRequireWildcard(require_jws());
    var path125 = _interopRequireWildcard(__require("path"));
    var _util = __require("util");
    function _interopRequireWildcard(e4, t5) {
      if ("function" == typeof WeakMap) var r5 = /* @__PURE__ */ new WeakMap(), n3 = /* @__PURE__ */ new WeakMap();
      return (_interopRequireWildcard = /* @__PURE__ */ __name(function _interopRequireWildcard2(e5, t6) {
        if (!t6 && e5 && e5.__esModule) return e5;
        var o3, i3, f5 = { __proto__: null, "default": e5 };
        if (null === e5 || "object" != _typeof2(e5) && "function" != typeof e5) return f5;
        if (o3 = t6 ? n3 : r5) {
          if (o3.has(e5)) return o3.get(e5);
          o3.set(e5, f5);
        }
        for (var _t3 in e5) "default" !== _t3 && {}.hasOwnProperty.call(e5, _t3) && ((i3 = (o3 = Object.defineProperty) && Object.getOwnPropertyDescriptor(e5, _t3)) && (i3.get || i3.set) ? o3(f5, _t3, i3) : f5[_t3] = e5[_t3]);
        return f5;
      }, "_interopRequireWildcard"))(e4, t5);
    }
    __name(_interopRequireWildcard, "_interopRequireWildcard");
    function _typeof2(o3) {
      "@babel/helpers - typeof";
      return _typeof2 = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(o4) {
        return typeof o4;
      } : function(o4) {
        return o4 && "function" == typeof Symbol && o4.constructor === Symbol && o4 !== Symbol.prototype ? "symbol" : typeof o4;
      }, _typeof2(o3);
    }
    __name(_typeof2, "_typeof");
    function _classPrivateMethodInitSpec(e4, a2) {
      _checkPrivateRedeclaration(e4, a2), a2.add(e4);
    }
    __name(_classPrivateMethodInitSpec, "_classPrivateMethodInitSpec");
    function _classPrivateFieldInitSpec(e4, t5, a2) {
      _checkPrivateRedeclaration(e4, t5), t5.set(e4, a2);
    }
    __name(_classPrivateFieldInitSpec, "_classPrivateFieldInitSpec");
    function _checkPrivateRedeclaration(e4, t5) {
      if (t5.has(e4)) throw new TypeError("Cannot initialize the same private elements twice on an object");
    }
    __name(_checkPrivateRedeclaration, "_checkPrivateRedeclaration");
    function _classPrivateFieldSet(s5, a2, r5) {
      return s5.set(_assertClassBrand(s5, a2), r5), r5;
    }
    __name(_classPrivateFieldSet, "_classPrivateFieldSet");
    function _classPrivateFieldGet(s5, a2) {
      return s5.get(_assertClassBrand(s5, a2));
    }
    __name(_classPrivateFieldGet, "_classPrivateFieldGet");
    function _assertClassBrand(e4, t5, n3) {
      if ("function" == typeof e4 ? e4 === t5 : e4.has(t5)) return arguments.length < 3 ? t5 : n3;
      throw new TypeError("Private element is not present on this object");
    }
    __name(_assertClassBrand, "_assertClassBrand");
    function _defineProperties(e4, r5) {
      for (var t5 = 0; t5 < r5.length; t5++) {
        var o3 = r5[t5];
        o3.enumerable = o3.enumerable || false, o3.configurable = true, "value" in o3 && (o3.writable = true), Object.defineProperty(e4, _toPropertyKey2(o3.key), o3);
      }
    }
    __name(_defineProperties, "_defineProperties");
    function _createClass(e4, r5, t5) {
      return r5 && _defineProperties(e4.prototype, r5), t5 && _defineProperties(e4, t5), Object.defineProperty(e4, "prototype", { writable: false }), e4;
    }
    __name(_createClass, "_createClass");
    function _classCallCheck(a2, n3) {
      if (!(a2 instanceof n3)) throw new TypeError("Cannot call a class as a function");
    }
    __name(_classCallCheck, "_classCallCheck");
    function _callSuper(t5, o3, e4) {
      return o3 = _getPrototypeOf(o3), _possibleConstructorReturn(t5, _isNativeReflectConstruct() ? Reflect.construct(o3, e4 || [], _getPrototypeOf(t5).constructor) : o3.apply(t5, e4));
    }
    __name(_callSuper, "_callSuper");
    function _possibleConstructorReturn(t5, e4) {
      if (e4 && ("object" == _typeof2(e4) || "function" == typeof e4)) return e4;
      if (void 0 !== e4) throw new TypeError("Derived constructors may only return object or undefined");
      return _assertThisInitialized(t5);
    }
    __name(_possibleConstructorReturn, "_possibleConstructorReturn");
    function _assertThisInitialized(e4) {
      if (void 0 === e4) throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
      return e4;
    }
    __name(_assertThisInitialized, "_assertThisInitialized");
    function _inherits(t5, e4) {
      if ("function" != typeof e4 && null !== e4) throw new TypeError("Super expression must either be null or a function");
      t5.prototype = Object.create(e4 && e4.prototype, { constructor: { value: t5, writable: true, configurable: true } }), Object.defineProperty(t5, "prototype", { writable: false }), e4 && _setPrototypeOf(t5, e4);
    }
    __name(_inherits, "_inherits");
    function _wrapNativeSuper(t5) {
      var r5 = "function" == typeof Map ? /* @__PURE__ */ new Map() : void 0;
      return _wrapNativeSuper = /* @__PURE__ */ __name(function _wrapNativeSuper2(t6) {
        if (null === t6 || !_isNativeFunction(t6)) return t6;
        if ("function" != typeof t6) throw new TypeError("Super expression must either be null or a function");
        if (void 0 !== r5) {
          if (r5.has(t6)) return r5.get(t6);
          r5.set(t6, Wrapper);
        }
        function Wrapper() {
          return _construct(t6, arguments, _getPrototypeOf(this).constructor);
        }
        __name(Wrapper, "Wrapper");
        return Wrapper.prototype = Object.create(t6.prototype, { constructor: { value: Wrapper, enumerable: false, writable: true, configurable: true } }), _setPrototypeOf(Wrapper, t6);
      }, "_wrapNativeSuper"), _wrapNativeSuper(t5);
    }
    __name(_wrapNativeSuper, "_wrapNativeSuper");
    function _construct(t5, e4, r5) {
      if (_isNativeReflectConstruct()) return Reflect.construct.apply(null, arguments);
      var o3 = [null];
      o3.push.apply(o3, e4);
      var p2 = new (t5.bind.apply(t5, o3))();
      return r5 && _setPrototypeOf(p2, r5.prototype), p2;
    }
    __name(_construct, "_construct");
    function _isNativeReflectConstruct() {
      try {
        var t5 = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function() {
        }));
      } catch (t6) {
      }
      return (_isNativeReflectConstruct = /* @__PURE__ */ __name(function _isNativeReflectConstruct2() {
        return !!t5;
      }, "_isNativeReflectConstruct"))();
    }
    __name(_isNativeReflectConstruct, "_isNativeReflectConstruct");
    function _isNativeFunction(t5) {
      try {
        return -1 !== Function.toString.call(t5).indexOf("[native code]");
      } catch (n3) {
        return "function" == typeof t5;
      }
    }
    __name(_isNativeFunction, "_isNativeFunction");
    function _setPrototypeOf(t5, e4) {
      return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function(t6, e5) {
        return t6.__proto__ = e5, t6;
      }, _setPrototypeOf(t5, e4);
    }
    __name(_setPrototypeOf, "_setPrototypeOf");
    function _getPrototypeOf(t5) {
      return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function(t6) {
        return t6.__proto__ || Object.getPrototypeOf(t6);
      }, _getPrototypeOf(t5);
    }
    __name(_getPrototypeOf, "_getPrototypeOf");
    function _defineProperty2(e4, r5, t5) {
      return (r5 = _toPropertyKey2(r5)) in e4 ? Object.defineProperty(e4, r5, { value: t5, enumerable: true, configurable: true, writable: true }) : e4[r5] = t5, e4;
    }
    __name(_defineProperty2, "_defineProperty");
    function _toPropertyKey2(t5) {
      var i3 = _toPrimitive2(t5, "string");
      return "symbol" == _typeof2(i3) ? i3 : i3 + "";
    }
    __name(_toPropertyKey2, "_toPropertyKey");
    function _toPrimitive2(t5, r5) {
      if ("object" != _typeof2(t5) || !t5) return t5;
      var e4 = t5[Symbol.toPrimitive];
      if (void 0 !== e4) {
        var i3 = e4.call(t5, r5 || "default");
        if ("object" != _typeof2(i3)) return i3;
        throw new TypeError("@@toPrimitive must return a primitive value.");
      }
      return ("string" === r5 ? String : Number)(t5);
    }
    __name(_toPrimitive2, "_toPrimitive");
    function _regenerator() {
      var e4, t5, r5 = "function" == typeof Symbol ? Symbol : {}, n3 = r5.iterator || "@@iterator", o3 = r5.toStringTag || "@@toStringTag";
      function i3(r6, n4, o4, i4) {
        var c5 = n4 && n4.prototype instanceof Generator ? n4 : Generator, u3 = Object.create(c5.prototype);
        return _regeneratorDefine2(u3, "_invoke", function(r7, n5, o5) {
          var i5, c6, u4, f6 = 0, p2 = o5 || [], y2 = false, G2 = { p: 0, n: 0, v: e4, a: d2, f: d2.bind(e4, 4), d: /* @__PURE__ */ __name(function d3(t6, r8) {
            return i5 = t6, c6 = 0, u4 = e4, G2.n = r8, a2;
          }, "d") };
          function d2(r8, n6) {
            for (c6 = r8, u4 = n6, t5 = 0; !y2 && f6 && !o6 && t5 < p2.length; t5++) {
              var o6, i6 = p2[t5], d3 = G2.p, l3 = i6[2];
              r8 > 3 ? (o6 = l3 === n6) && (u4 = i6[(c6 = i6[4]) ? 5 : (c6 = 3, 3)], i6[4] = i6[5] = e4) : i6[0] <= d3 && ((o6 = r8 < 2 && d3 < i6[1]) ? (c6 = 0, G2.v = n6, G2.n = i6[1]) : d3 < l3 && (o6 = r8 < 3 || i6[0] > n6 || n6 > l3) && (i6[4] = r8, i6[5] = n6, G2.n = l3, c6 = 0));
            }
            if (o6 || r8 > 1) return a2;
            throw y2 = true, n6;
          }
          __name(d2, "d");
          return function(o6, p3, l3) {
            if (f6 > 1) throw TypeError("Generator is already running");
            for (y2 && 1 === p3 && d2(p3, l3), c6 = p3, u4 = l3; (t5 = c6 < 2 ? e4 : u4) || !y2; ) {
              i5 || (c6 ? c6 < 3 ? (c6 > 1 && (G2.n = -1), d2(c6, u4)) : G2.n = u4 : G2.v = u4);
              try {
                if (f6 = 2, i5) {
                  if (c6 || (o6 = "next"), t5 = i5[o6]) {
                    if (!(t5 = t5.call(i5, u4))) throw TypeError("iterator result is not an object");
                    if (!t5.done) return t5;
                    u4 = t5.value, c6 < 2 && (c6 = 0);
                  } else 1 === c6 && (t5 = i5["return"]) && t5.call(i5), c6 < 2 && (u4 = TypeError("The iterator does not provide a '" + o6 + "' method"), c6 = 1);
                  i5 = e4;
                } else if ((t5 = (y2 = G2.n < 0) ? u4 : r7.call(n5, G2)) !== a2) break;
              } catch (t6) {
                i5 = e4, c6 = 1, u4 = t6;
              } finally {
                f6 = 1;
              }
            }
            return { value: t5, done: y2 };
          };
        }(r6, o4, i4), true), u3;
      }
      __name(i3, "i");
      var a2 = {};
      function Generator() {
      }
      __name(Generator, "Generator");
      function GeneratorFunction() {
      }
      __name(GeneratorFunction, "GeneratorFunction");
      function GeneratorFunctionPrototype() {
      }
      __name(GeneratorFunctionPrototype, "GeneratorFunctionPrototype");
      t5 = Object.getPrototypeOf;
      var c4 = [][n3] ? t5(t5([][n3]())) : (_regeneratorDefine2(t5 = {}, n3, function() {
        return this;
      }), t5), u2 = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(c4);
      function f5(e5) {
        return Object.setPrototypeOf ? Object.setPrototypeOf(e5, GeneratorFunctionPrototype) : (e5.__proto__ = GeneratorFunctionPrototype, _regeneratorDefine2(e5, o3, "GeneratorFunction")), e5.prototype = Object.create(u2), e5;
      }
      __name(f5, "f");
      return GeneratorFunction.prototype = GeneratorFunctionPrototype, _regeneratorDefine2(u2, "constructor", GeneratorFunctionPrototype), _regeneratorDefine2(GeneratorFunctionPrototype, "constructor", GeneratorFunction), GeneratorFunction.displayName = "GeneratorFunction", _regeneratorDefine2(GeneratorFunctionPrototype, o3, "GeneratorFunction"), _regeneratorDefine2(u2), _regeneratorDefine2(u2, o3, "Generator"), _regeneratorDefine2(u2, n3, function() {
        return this;
      }), _regeneratorDefine2(u2, "toString", function() {
        return "[object Generator]";
      }), (_regenerator = /* @__PURE__ */ __name(function _regenerator2() {
        return { w: i3, m: f5 };
      }, "_regenerator"))();
    }
    __name(_regenerator, "_regenerator");
    function _regeneratorDefine2(e4, r5, n3, t5) {
      var i3 = Object.defineProperty;
      try {
        i3({}, "", {});
      } catch (e5) {
        i3 = 0;
      }
      _regeneratorDefine2 = /* @__PURE__ */ __name(function _regeneratorDefine(e5, r6, n4, t6) {
        if (r6) i3 ? i3(e5, r6, { value: n4, enumerable: !t6, configurable: !t6, writable: !t6 }) : e5[r6] = n4;
        else {
          var o3 = /* @__PURE__ */ __name(function o4(r7, n5) {
            _regeneratorDefine2(e5, r7, function(e6) {
              return this._invoke(r7, n5, e6);
            });
          }, "o");
          o3("next", 0), o3("throw", 1), o3("return", 2);
        }
      }, "_regeneratorDefine"), _regeneratorDefine2(e4, r5, n3, t5);
    }
    __name(_regeneratorDefine2, "_regeneratorDefine2");
    function asyncGeneratorStep(n3, t5, e4, r5, o3, a2, c4) {
      try {
        var i3 = n3[a2](c4), u2 = i3.value;
      } catch (n4) {
        return void e4(n4);
      }
      i3.done ? t5(u2) : Promise.resolve(u2).then(r5, o3);
    }
    __name(asyncGeneratorStep, "asyncGeneratorStep");
    function _asyncToGenerator(n3) {
      return function() {
        var t5 = this, e4 = arguments;
        return new Promise(function(r5, o3) {
          var a2 = n3.apply(t5, e4);
          function _next(n4) {
            asyncGeneratorStep(a2, r5, o3, _next, _throw, "next", n4);
          }
          __name(_next, "_next");
          function _throw(n4) {
            asyncGeneratorStep(a2, r5, o3, _next, _throw, "throw", n4);
          }
          __name(_throw, "_throw");
          _next(void 0);
        });
      };
    }
    __name(_asyncToGenerator, "_asyncToGenerator");
    var readFile13 = fs113.readFile ? (0, _util.promisify)(fs113.readFile) : /* @__PURE__ */ _asyncToGenerator(/* @__PURE__ */ _regenerator().m(/* @__PURE__ */ __name(function _callee() {
      return _regenerator().w(function(_context) {
        while (1) switch (_context.n) {
          case 0:
            throw new ErrorWithCode("use key rather than keyFile.", "MISSING_CREDENTIALS");
          case 1:
            return _context.a(2);
        }
      }, _callee);
    }, "_callee")));
    var GOOGLE_TOKEN_URL = "https://oauth2.googleapis.com/token";
    var GOOGLE_REVOKE_TOKEN_URL = "https://oauth2.googleapis.com/revoke?token=";
    var ErrorWithCode = /* @__PURE__ */ function(_Error) {
      function ErrorWithCode2(message, code2) {
        var _this;
        _classCallCheck(this, ErrorWithCode2);
        _this = _callSuper(this, ErrorWithCode2, [message]);
        _defineProperty2(_this, "code", void 0);
        _this.code = code2;
        return _this;
      }
      __name(ErrorWithCode2, "ErrorWithCode");
      _inherits(ErrorWithCode2, _Error);
      return _createClass(ErrorWithCode2);
    }(/* @__PURE__ */ _wrapNativeSuper(Error));
    var _inFlightRequest = /* @__PURE__ */ new WeakMap();
    var _GoogleToken_brand = /* @__PURE__ */ new WeakSet();
    var GoogleToken = exports2.GoogleToken = /* @__PURE__ */ function() {
      function GoogleToken2(_options) {
        _classCallCheck(this, GoogleToken2);
        _classPrivateMethodInitSpec(this, _GoogleToken_brand);
        _defineProperty2(this, "expiresAt", void 0);
        _defineProperty2(this, "key", void 0);
        _defineProperty2(this, "keyFile", void 0);
        _defineProperty2(this, "iss", void 0);
        _defineProperty2(this, "sub", void 0);
        _defineProperty2(this, "scope", void 0);
        _defineProperty2(this, "rawToken", void 0);
        _defineProperty2(this, "tokenExpires", void 0);
        _defineProperty2(this, "email", void 0);
        _defineProperty2(this, "additionalClaims", void 0);
        _defineProperty2(this, "eagerRefreshThresholdMillis", void 0);
        _defineProperty2(this, "transporter", {
          request: /* @__PURE__ */ __name(function request4(opts) {
            return (0, _gaxios.request)(opts);
          }, "request")
        });
        _classPrivateFieldInitSpec(this, _inFlightRequest, void 0);
        _assertClassBrand(_GoogleToken_brand, this, _configure).call(this, _options);
      }
      __name(GoogleToken2, "GoogleToken");
      return _createClass(GoogleToken2, [{
        key: "accessToken",
        get: /* @__PURE__ */ __name(function get4() {
          return this.rawToken ? this.rawToken.access_token : void 0;
        }, "get")
      }, {
        key: "idToken",
        get: /* @__PURE__ */ __name(function get4() {
          return this.rawToken ? this.rawToken.id_token : void 0;
        }, "get")
      }, {
        key: "tokenType",
        get: /* @__PURE__ */ __name(function get4() {
          return this.rawToken ? this.rawToken.token_type : void 0;
        }, "get")
      }, {
        key: "refreshToken",
        get: /* @__PURE__ */ __name(function get4() {
          return this.rawToken ? this.rawToken.refresh_token : void 0;
        }, "get")
      }, {
        key: "hasExpired",
        value: /* @__PURE__ */ __name(function hasExpired() {
          var now = (/* @__PURE__ */ new Date()).getTime();
          if (this.rawToken && this.expiresAt) {
            return now >= this.expiresAt;
          } else {
            return true;
          }
        }, "hasExpired")
        /**
         * Returns whether the token will expire within eagerRefreshThresholdMillis
         *
         * @return true if the token will be expired within eagerRefreshThresholdMillis, false otherwise.
         */
      }, {
        key: "isTokenExpiring",
        value: /* @__PURE__ */ __name(function isTokenExpiring() {
          var _this$eagerRefreshThr;
          var now = (/* @__PURE__ */ new Date()).getTime();
          var eagerRefreshThresholdMillis = (_this$eagerRefreshThr = this.eagerRefreshThresholdMillis) !== null && _this$eagerRefreshThr !== void 0 ? _this$eagerRefreshThr : 0;
          if (this.rawToken && this.expiresAt) {
            return this.expiresAt <= now + eagerRefreshThresholdMillis;
          } else {
            return true;
          }
        }, "isTokenExpiring")
        /**
         * Returns a cached token or retrieves a new one from Google.
         *
         * @param callback The callback function.
         */
      }, {
        key: "getToken",
        value: /* @__PURE__ */ __name(function getToken(callback) {
          var opts = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {};
          if (_typeof2(callback) === "object") {
            opts = callback;
            callback = void 0;
          }
          opts = Object.assign({
            forceRefresh: false
          }, opts);
          if (callback) {
            var cb = callback;
            _assertClassBrand(_GoogleToken_brand, this, _getTokenAsync).call(this, opts).then(function(t5) {
              return cb(null, t5);
            }, callback);
            return;
          }
          return _assertClassBrand(_GoogleToken_brand, this, _getTokenAsync).call(this, opts);
        }, "getToken")
        /**
         * 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
         */
      }, {
        key: "getCredentials",
        value: function() {
          var _getCredentials = _asyncToGenerator(/* @__PURE__ */ _regenerator().m(/* @__PURE__ */ __name(function _callee2(keyFile) {
            var ext2, key, body, privateKey, clientEmail, _privateKey, _t2;
            return _regenerator().w(function(_context2) {
              while (1) switch (_context2.n) {
                case 0:
                  ext2 = path125.extname(keyFile);
                  _t2 = ext2;
                  _context2.n = _t2 === ".json" ? 1 : _t2 === ".der" ? 4 : _t2 === ".crt" ? 4 : _t2 === ".pem" ? 4 : _t2 === ".p12" ? 6 : _t2 === ".pfx" ? 6 : 7;
                  break;
                case 1:
                  _context2.n = 2;
                  return readFile13(keyFile, "utf8");
                case 2:
                  key = _context2.v;
                  body = JSON.parse(key);
                  privateKey = body.private_key;
                  clientEmail = body.client_email;
                  if (!(!privateKey || !clientEmail)) {
                    _context2.n = 3;
                    break;
                  }
                  throw new ErrorWithCode("private_key and client_email are required.", "MISSING_CREDENTIALS");
                case 3:
                  return _context2.a(2, {
                    privateKey,
                    clientEmail
                  });
                case 4:
                  _context2.n = 5;
                  return readFile13(keyFile, "utf8");
                case 5:
                  _privateKey = _context2.v;
                  return _context2.a(2, {
                    privateKey: _privateKey
                  });
                case 6:
                  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");
                case 7:
                  throw new ErrorWithCode("Unknown certificate type. Type is determined based on file extension. Current supported extensions are *.json, and *.pem.", "UNKNOWN_CERTIFICATE_TYPE");
                case 8:
                  return _context2.a(2);
              }
            }, _callee2);
          }, "_callee2")));
          function getCredentials(_x) {
            return _getCredentials.apply(this, arguments);
          }
          __name(getCredentials, "getCredentials");
          return getCredentials;
        }()
      }, {
        key: "revokeToken",
        value: /* @__PURE__ */ __name(function revokeToken(callback) {
          if (callback) {
            _assertClassBrand(_GoogleToken_brand, this, _revokeTokenAsync).call(this).then(function() {
              return callback();
            }, callback);
            return;
          }
          return _assertClassBrand(_GoogleToken_brand, this, _revokeTokenAsync).call(this);
        }, "revokeToken")
      }]);
    }();
    function _getTokenAsync(_x2) {
      return _getTokenAsync2.apply(this, arguments);
    }
    __name(_getTokenAsync, "_getTokenAsync");
    function _getTokenAsync2() {
      _getTokenAsync2 = _asyncToGenerator(/* @__PURE__ */ _regenerator().m(/* @__PURE__ */ __name(function _callee3(opts) {
        return _regenerator().w(function(_context3) {
          while (1) switch (_context3.n) {
            case 0:
              if (!(_classPrivateFieldGet(_inFlightRequest, this) && !opts.forceRefresh)) {
                _context3.n = 1;
                break;
              }
              return _context3.a(2, _classPrivateFieldGet(_inFlightRequest, this));
            case 1:
              _context3.p = 1;
              _context3.n = 2;
              return _classPrivateFieldSet(_inFlightRequest, this, _assertClassBrand(_GoogleToken_brand, this, _getTokenAsyncInner).call(this, opts));
            case 2:
              return _context3.a(2, _context3.v);
            case 3:
              _context3.p = 3;
              _classPrivateFieldSet(_inFlightRequest, this, void 0);
              return _context3.f(3);
            case 4:
              return _context3.a(2);
          }
        }, _callee3, this, [[1, , 3, 4]]);
      }, "_callee3")));
      return _getTokenAsync2.apply(this, arguments);
    }
    __name(_getTokenAsync2, "_getTokenAsync2");
    function _getTokenAsyncInner(_x3) {
      return _getTokenAsyncInner2.apply(this, arguments);
    }
    __name(_getTokenAsyncInner, "_getTokenAsyncInner");
    function _getTokenAsyncInner2() {
      _getTokenAsyncInner2 = _asyncToGenerator(/* @__PURE__ */ _regenerator().m(/* @__PURE__ */ __name(function _callee4(opts) {
        var creds;
        return _regenerator().w(function(_context4) {
          while (1) switch (_context4.n) {
            case 0:
              if (!(this.isTokenExpiring() === false && opts.forceRefresh === false)) {
                _context4.n = 1;
                break;
              }
              return _context4.a(2, Promise.resolve(this.rawToken));
            case 1:
              if (!(!this.key && !this.keyFile)) {
                _context4.n = 2;
                break;
              }
              throw new Error("No key or keyFile set.");
            case 2:
              if (!(!this.key && this.keyFile)) {
                _context4.n = 4;
                break;
              }
              _context4.n = 3;
              return this.getCredentials(this.keyFile);
            case 3:
              creds = _context4.v;
              this.key = creds.privateKey;
              this.iss = creds.clientEmail || this.iss;
              if (!creds.clientEmail) {
                _assertClassBrand(_GoogleToken_brand, this, _ensureEmail).call(this);
              }
            case 4:
              return _context4.a(2, _assertClassBrand(_GoogleToken_brand, this, _requestToken).call(this));
          }
        }, _callee4, this);
      }, "_callee4")));
      return _getTokenAsyncInner2.apply(this, arguments);
    }
    __name(_getTokenAsyncInner2, "_getTokenAsyncInner2");
    function _ensureEmail() {
      if (!this.iss) {
        throw new ErrorWithCode("email is required.", "MISSING_CREDENTIALS");
      }
    }
    __name(_ensureEmail, "_ensureEmail");
    function _revokeTokenAsync() {
      return _revokeTokenAsync2.apply(this, arguments);
    }
    __name(_revokeTokenAsync, "_revokeTokenAsync");
    function _revokeTokenAsync2() {
      _revokeTokenAsync2 = _asyncToGenerator(/* @__PURE__ */ _regenerator().m(/* @__PURE__ */ __name(function _callee5() {
        var url2;
        return _regenerator().w(function(_context5) {
          while (1) switch (_context5.n) {
            case 0:
              if (this.accessToken) {
                _context5.n = 1;
                break;
              }
              throw new Error("No token to revoke.");
            case 1:
              url2 = GOOGLE_REVOKE_TOKEN_URL + this.accessToken;
              _context5.n = 2;
              return this.transporter.request({
                url: url2,
                retry: true
              });
            case 2:
              _assertClassBrand(_GoogleToken_brand, this, _configure).call(this, {
                email: this.iss,
                sub: this.sub,
                key: this.key,
                keyFile: this.keyFile,
                scope: this.scope,
                additionalClaims: this.additionalClaims
              });
            case 3:
              return _context5.a(2);
          }
        }, _callee5, this);
      }, "_callee5")));
      return _revokeTokenAsync2.apply(this, arguments);
    }
    __name(_revokeTokenAsync2, "_revokeTokenAsync2");
    function _configure() {
      var options2 = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {};
      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 (_typeof2(options2.scope) === "object") {
        this.scope = options2.scope.join(" ");
      } else {
        this.scope = options2.scope;
      }
      this.eagerRefreshThresholdMillis = options2.eagerRefreshThresholdMillis;
      if (options2.transporter) {
        this.transporter = options2.transporter;
      }
    }
    __name(_configure, "_configure");
    function _requestToken() {
      return _requestToken2.apply(this, arguments);
    }
    __name(_requestToken, "_requestToken");
    function _requestToken2() {
      _requestToken2 = _asyncToGenerator(/* @__PURE__ */ _regenerator().m(/* @__PURE__ */ __name(function _callee6() {
        var iat, additionalClaims, payload, signedJWT, r5, _response, _response2, body, desc2, _t2;
        return _regenerator().w(function(_context6) {
          while (1) switch (_context6.n) {
            case 0:
              iat = Math.floor((/* @__PURE__ */ new Date()).getTime() / 1e3);
              additionalClaims = this.additionalClaims || {};
              payload = Object.assign({
                iss: this.iss,
                scope: this.scope,
                aud: GOOGLE_TOKEN_URL,
                exp: iat + 3600,
                iat,
                sub: this.sub
              }, additionalClaims);
              signedJWT = jws.sign({
                header: {
                  alg: "RS256"
                },
                payload,
                secret: this.key
              });
              _context6.p = 1;
              _context6.n = 2;
              return this.transporter.request({
                method: "POST",
                url: GOOGLE_TOKEN_URL,
                data: new URLSearchParams({
                  grant_type: "urn:ietf:params:oauth:grant-type:jwt-bearer",
                  assertion: signedJWT
                }),
                responseType: "json",
                retryConfig: {
                  httpMethodsToRetry: ["POST"]
                }
              });
            case 2:
              r5 = _context6.v;
              this.rawToken = r5.data;
              this.expiresAt = r5.data.expires_in === null || r5.data.expires_in === void 0 ? void 0 : (iat + r5.data.expires_in) * 1e3;
              return _context6.a(2, this.rawToken);
            case 3:
              _context6.p = 3;
              _t2 = _context6.v;
              this.rawToken = void 0;
              this.tokenExpires = void 0;
              body = _t2.response && (_response = _t2.response) !== null && _response !== void 0 && _response.data ? (_response2 = _t2.response) === null || _response2 === void 0 ? void 0 : _response2.data : {};
              if (body.error) {
                desc2 = body.error_description ? ": ".concat(body.error_description) : "";
                _t2.message = "".concat(body.error).concat(desc2);
              }
              throw _t2;
            case 4:
              return _context6.a(2);
          }
        }, _callee6, this, [[1, 3]]);
      }, "_callee6")));
      return _requestToken2.apply(this, arguments);
    }
    __name(_requestToken2, "_requestToken2");
  }
});

// packages/cli/node_modules/google-auth-library/build/src/auth/jwtaccess.js
var require_jwtaccess2 = __commonJS({
  "packages/cli/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_util31();
    var DEFAULT_HEADER = {
      alg: "RS256",
      typ: "JWT"
    };
    var JWTAccess = class _JWTAccess {
      static {
        __name(this, "JWTAccess");
      }
      email;
      key;
      keyId;
      projectId;
      eagerRefreshThresholdMillis;
      cache = new util_1.LRUCache({
        capacity: 500,
        maxAge: 60 * 60 * 1e3
      });
      /**
       * 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(email2, key, keyId, eagerRefreshThresholdMillis) {
        this.email = email2;
        this.key = key;
        this.keyId = keyId;
        this.eagerRefreshThresholdMillis = 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 new Headers(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 = new 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((resolve30, reject) => {
          if (!inputStream) {
            reject(new Error("Must pass in a stream containing the service account auth settings."));
          }
          let s5 = "";
          inputStream.setEncoding("utf8").on("data", (chunk) => s5 += chunk).on("error", reject).on("end", () => {
            try {
              const data = JSON.parse(s5);
              this.fromJSON(data);
              resolve30();
            } catch (err) {
              reject(err);
            }
          });
        });
      }
    };
    exports2.JWTAccess = JWTAccess;
  }
});

// packages/cli/node_modules/google-auth-library/build/src/auth/jwtclient.js
var require_jwtclient2 = __commonJS({
  "packages/cli/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_src43();
    var jwtaccess_1 = require_jwtaccess2();
    var oauth2client_1 = require_oauth2client2();
    var authclient_1 = require_authclient2();
    var JWT = class _JWT extends oauth2client_1.OAuth2Client {
      static {
        __name(this, "JWT");
      }
      email;
      keyFile;
      key;
      keyId;
      defaultScopes;
      scopes;
      scope;
      subject;
      gtoken;
      additionalClaims;
      useJWTAccessWithScope;
      defaultServicePath;
      access;
      /**
       * JWT service account credentials.
       *
       * Retrieve access token using gtoken.
       *
       * @param options the
       */
      constructor(options2 = {}) {
        super(options2);
        this.email = options2.email;
        this.keyFile = options2.keyFile;
        this.key = options2.key;
        this.keyId = options2.keyId;
        this.scopes = options2.scopes;
        this.subject = options2.subject;
        this.additionalClaims = options2.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(new Headers({
                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 ?? 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: new 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((r5) => callback(null, r5), 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() {
        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((resolve30, reject) => {
          if (!inputStream) {
            throw new Error("Must pass in a stream containing the service account auth settings.");
          }
          let s5 = "";
          inputStream.setEncoding("utf8").on("error", reject).on("data", (chunk) => s5 += chunk).on("end", () => {
            try {
              const data = JSON.parse(s5);
              this.fromJSON(data);
              resolve30();
            } catch (e4) {
              reject(e4);
            }
          });
        });
      }
      /**
       * 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;
  }
});

// packages/cli/node_modules/google-auth-library/build/src/auth/refreshclient.js
var require_refreshclient2 = __commonJS({
  "packages/cli/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_oauth2client2();
    var authclient_1 = require_authclient2();
    exports2.USER_REFRESH_ACCOUNT_TYPE = "authorized_user";
    var UserRefreshClient = class _UserRefreshClient extends oauth2client_1.OAuth2Client {
      static {
        __name(this, "UserRefreshClient");
      }
      // TODO: refactor tests to make this private
      // In a future gts release, the _propertyName rule will be lifted.
      // This is also a hard one because `this.refreshToken` is a function.
      _refreshToken;
      /**
       * The User Refresh Token client.
       *
       * @param optionsOrClientId The User Refresh Token client options. Passing an `clientId` directly is **@DEPRECATED**.
       * @param clientSecret **@DEPRECATED**. Provide a {@link UserRefreshClientOptions `UserRefreshClientOptions`} object in the first parameter instead.
       * @param refreshToken **@DEPRECATED**. Provide a {@link UserRefreshClientOptions `UserRefreshClientOptions`} object in the first parameter instead.
       * @param eagerRefreshThresholdMillis **@DEPRECATED**. Provide a {@link UserRefreshClientOptions `UserRefreshClientOptions`} object in the first parameter instead.
       * @param forceRefreshOnFailure **@DEPRECATED**. Provide a {@link UserRefreshClientOptions `UserRefreshClientOptions`} object in the first parameter instead.
       */
      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() {
        return super.refreshTokenNoCache(this._refreshToken);
      }
      async fetchIdToken(targetAudience) {
        const opts = {
          ..._UserRefreshClient.RETRY_CONFIG,
          url: this.endpoints.oauth2TokenUrl,
          method: "POST",
          data: new URLSearchParams({
            client_id: this._clientId,
            client_secret: this._clientSecret,
            grant_type: "refresh_token",
            refresh_token: this._refreshToken,
            target_audience: targetAudience
          })
        };
        authclient_1.AuthClient.setMethodName(opts, "fetchIdToken");
        const res = await this.transporter.request(opts);
        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((resolve30, reject) => {
          if (!inputStream) {
            return reject(new Error("Must pass in a stream containing the user refresh token."));
          }
          let s5 = "";
          inputStream.setEncoding("utf8").on("error", reject).on("data", (chunk) => s5 += chunk).on("end", () => {
            try {
              const data = JSON.parse(s5);
              this.fromJSON(data);
              return resolve30();
            } 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;
  }
});

// packages/cli/node_modules/google-auth-library/build/src/auth/impersonated.js
var require_impersonated2 = __commonJS({
  "packages/cli/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_oauth2client2();
    var gaxios_1 = require_src40();
    var util_1 = require_util31();
    exports2.IMPERSONATED_ACCOUNT_TYPE = "impersonated_service_account";
    var Impersonated = class _Impersonated extends oauth2client_1.OAuth2Client {
      static {
        __name(this, "Impersonated");
      }
      sourceClient;
      targetPrincipal;
      targetScopes;
      delegates;
      lifetime;
      endpoint;
      /**
       * 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.
       *
       * **IMPORTANT**: This method does not validate the credential configuration.
       * A security risk occurs when a credential configuration configured with
       * malicious URLs is used. When the credential configuration is accepted from
       * an untrusted source, you should validate it before using it with this
       * method. For more details, see
       * https://cloud.google.com/docs/authentication/external/externally-sourced-credentials.
       *
       * @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 = {}) {
        super(options2);
        this.credentials = {
          expiry_date: 1,
          refresh_token: "impersonated-placeholder"
        };
        this.sourceClient = options2.sourceClient ?? new oauth2client_1.OAuth2Client();
        this.targetPrincipal = options2.targetPrincipal ?? "";
        this.delegates = options2.delegates ?? [];
        this.targetScopes = options2.targetScopes ?? [];
        this.lifetime = options2.lifetime ?? 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 = options2.endpoint ?? `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 u2 = `${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: u2,
          data: body,
          method: "POST"
        });
        return res.data;
      }
      /** The service account email to be impersonated. */
      getTargetPrincipal() {
        return this.targetPrincipal;
      }
      /**
       * Refreshes the access token.
       */
      async refreshToken() {
        try {
          await this.sourceClient.getAccessToken();
          const name3 = "projects/-/serviceAccounts/" + this.targetPrincipal;
          const u2 = `${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: u2,
            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 (error2) {
          if (!(error2 instanceof Error))
            throw error2;
          let status = 0;
          let message = "";
          if (error2 instanceof gaxios_1.GaxiosError) {
            status = error2?.response?.data?.error?.status;
            message = error2?.response?.data?.error?.message;
          }
          if (status && message) {
            error2.message = `${status}: unable to impersonate: ${message}`;
            throw error2;
          } else {
            error2.message = `unable to impersonate: ${error2}`;
            throw error2;
          }
        }
      }
      /**
       * 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) {
        await this.sourceClient.getAccessToken();
        const name3 = `projects/-/serviceAccounts/${this.targetPrincipal}`;
        const u2 = `${this.endpoint}/v1/${name3}:generateIdToken`;
        const body = {
          delegates: this.delegates,
          audience: targetAudience,
          includeEmail: options2?.includeEmail ?? true,
          useEmailAzp: options2?.includeEmail ?? true
        };
        const res = await this.sourceClient.request({
          ..._Impersonated.RETRY_CONFIG,
          url: u2,
          data: body,
          method: "POST"
        });
        return res.data.token;
      }
    };
    exports2.Impersonated = Impersonated;
  }
});

// packages/cli/node_modules/google-auth-library/build/src/auth/oauth2common.js
var require_oauth2common2 = __commonJS({
  "packages/cli/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 gaxios_1 = require_src40();
    var crypto_1 = require_crypto6();
    var METHODS_SUPPORTING_REQUEST_BODY = ["PUT", "POST", "PATCH"];
    var OAuthClientAuthHandler = class {
      static {
        __name(this, "OAuthClientAuthHandler");
      }
      #crypto = (0, crypto_1.createCrypto)();
      #clientAuthentication;
      transporter;
      /**
       * Instantiates an OAuth client authentication handler.
       * @param options The OAuth Client Auth Handler instance options. Passing an `ClientAuthentication` directly is **@DEPRECATED**.
       */
      constructor(options2) {
        if (options2 && "clientId" in options2) {
          this.#clientAuthentication = options2;
          this.transporter = new gaxios_1.Gaxios();
        } else {
          this.#clientAuthentication = options2?.clientAuthentication;
          this.transporter = options2?.transporter || new gaxios_1.Gaxios();
        }
      }
      /**
       * 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) {
        opts.headers = gaxios_1.Gaxios.mergeHeaders(opts.headers);
        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) {
        if (bearerToken) {
          opts.headers = gaxios_1.Gaxios.mergeHeaders(opts.headers, {
            authorization: `Bearer ${bearerToken}`
          });
        } else if (this.#clientAuthentication?.confidentialClientType === "basic") {
          opts.headers = gaxios_1.Gaxios.mergeHeaders(opts.headers);
          const clientId = this.#clientAuthentication.clientId;
          const clientSecret = this.#clientAuthentication.clientSecret || "";
          const base64EncodedCreds = this.#crypto.encodeBase64StringUtf8(`${clientId}:${clientSecret}`);
          gaxios_1.Gaxios.mergeHeaders(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) {
        if (this.#clientAuthentication?.confidentialClientType === "request-body") {
          const method = (opts.method || "GET").toUpperCase();
          if (!METHODS_SUPPORTING_REQUEST_BODY.includes(method)) {
            throw new Error(`${method} HTTP method does not support ${this.#clientAuthentication.confidentialClientType} client authentication`);
          }
          const headers = new Headers(opts.headers);
          const contentType = headers.get("content-type");
          if (contentType?.startsWith("application/x-www-form-urlencoded") || opts.data instanceof URLSearchParams) {
            const data = new URLSearchParams(opts.data ?? "");
            data.append("client_id", this.#clientAuthentication.clientId);
            data.append("client_secret", this.#clientAuthentication.clientSecret || "");
            opts.data = data;
          } else if (contentType?.startsWith("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`);
          }
        }
      }
      /**
       * 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, {
              value: err[key],
              writable: false,
              enumerable: true
            });
          }
        });
      }
      return newError;
    }
    __name(getErrorFromOAuthErrorResponse, "getErrorFromOAuthErrorResponse");
  }
});

// packages/cli/node_modules/google-auth-library/build/src/auth/stscredentials.js
var require_stscredentials2 = __commonJS({
  "packages/cli/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_src40();
    var authclient_1 = require_authclient2();
    var oauth2common_1 = require_oauth2common2();
    var util_1 = require_util31();
    var StsCredentials = class _StsCredentials extends oauth2common_1.OAuthClientAuthHandler {
      static {
        __name(this, "StsCredentials");
      }
      #tokenExchangeEndpoint;
      /**
       * Initializes an STS credentials instance.
       *
       * @param options The STS credentials instance options. Passing an `tokenExchangeEndpoint` directly is **@DEPRECATED**.
       * @param clientAuthentication **@DEPRECATED**. Provide a {@link StsCredentialsConstructionOptions `StsCredentialsConstructionOptions`} object in the first parameter instead.
       */
      constructor(options2 = {
        tokenExchangeEndpoint: ""
      }, clientAuthentication) {
        if (typeof options2 !== "object" || options2 instanceof URL) {
          options2 = {
            tokenExchangeEndpoint: options2,
            clientAuthentication
          };
        }
        super(options2);
        this.#tokenExchangeEndpoint = options2.tokenExchangeEndpoint;
      }
      /**
       * 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, headers, options2) {
        const values = {
          grant_type: stsCredentialsOptions.grantType,
          resource: stsCredentialsOptions.resource,
          audience: stsCredentialsOptions.audience,
          scope: stsCredentialsOptions.scope?.join(" "),
          requested_token_type: stsCredentialsOptions.requestedTokenType,
          subject_token: stsCredentialsOptions.subjectToken,
          subject_token_type: stsCredentialsOptions.subjectTokenType,
          actor_token: stsCredentialsOptions.actingParty?.actorToken,
          actor_token_type: stsCredentialsOptions.actingParty?.actorTokenType,
          // Non-standard GCP-specific options.
          options: options2 && JSON.stringify(options2)
        };
        const opts = {
          ..._StsCredentials.RETRY_CONFIG,
          url: this.#tokenExchangeEndpoint.toString(),
          method: "POST",
          headers,
          data: new URLSearchParams((0, util_1.removeUndefinedValuesInObject)(values))
        };
        authclient_1.AuthClient.setMethodName(opts, "exchangeToken");
        this.applyClientAuthenticationOptions(opts);
        try {
          const response = await this.transporter.request(opts);
          const stsSuccessfulResponse = response.data;
          stsSuccessfulResponse.res = response;
          return stsSuccessfulResponse;
        } catch (error2) {
          if (error2 instanceof gaxios_1.GaxiosError && error2.response) {
            throw (0, oauth2common_1.getErrorFromOAuthErrorResponse)(
              error2.response.data,
              // Preserve other fields from the original error.
              error2
            );
          }
          throw error2;
        }
      }
    };
    exports2.StsCredentials = StsCredentials;
  }
});

// packages/cli/node_modules/google-auth-library/build/src/auth/baseexternalclient.js
var require_baseexternalclient2 = __commonJS({
  "packages/cli/node_modules/google-auth-library/build/src/auth/baseexternalclient.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.BaseExternalAccountClient = exports2.CLOUD_RESOURCE_MANAGER = exports2.EXTERNAL_ACCOUNT_TYPE = exports2.EXPIRATION_TIME_OFFSET = void 0;
    var gaxios_1 = require_src40();
    var stream2 = __require("stream");
    var authclient_1 = require_authclient2();
    var sts = require_stscredentials2();
    var util_1 = require_util31();
    var shared_cjs_1 = require_shared4();
    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 BaseExternalAccountClient = class _BaseExternalAccountClient extends authclient_1.AuthClient {
      static {
        __name(this, "BaseExternalAccountClient");
      }
      /**
       * OAuth scopes for the GCP access token to use. When not provided,
       * the default https://www.googleapis.com/auth/cloud-platform is
       * used.
       */
      scopes;
      projectNumber;
      audience;
      subjectTokenType;
      stsCredential;
      clientAuth;
      credentialSourceType;
      cachedAccessToken;
      serviceAccountImpersonationUrl;
      serviceAccountImpersonationLifetime;
      workforcePoolUserProject;
      configLifetimeRequested;
      tokenUrl;
      /**
       * @example
       * ```ts
       * new URL('https://cloudresourcemanager.googleapis.com/v1/projects/');
       * ```
       */
      cloudResourceManagerURL;
      supplierContext;
      /**
       * A pending access token request. Used for concurrent calls.
       */
      #pendingAccessToken = null;
      /**
       * 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.
       */
      constructor(options2) {
        super(options2);
        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");
        this.tokenUrl = opts.get("token_url") ?? 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({
          tokenExchangeEndpoint: this.tokenUrl,
          clientAuthentication: 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() {
        if (this.serviceAccountImpersonationUrl) {
          if (this.serviceAccountImpersonationUrl.length > 256) {
            throw new RangeError(`URL is too long: ${this.serviceAccountImpersonationUrl}`);
          }
          const re3 = /serviceAccounts\/(?<email>[^:]+):generateAccessToken$/;
          const result = re3.exec(this.serviceAccountImpersonationUrl);
          return result?.groups?.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 = new Headers({
          authorization: `Bearer ${accessTokenResponse.token}`
        });
        return this.addSharedMetadataHeaders(headers);
      }
      request(opts, callback) {
        if (callback) {
          this.requestAsync(opts).then((r5) => callback(null, r5), (e4) => {
            return callback(e4, e4.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 opts = {
            ..._BaseExternalAccountClient.RETRY_CONFIG,
            headers,
            url: `${this.cloudResourceManagerURL.toString()}${projectNumber}`
          };
          authclient_1.AuthClient.setMethodName(opts, "getProjectId");
          const response = await this.transporter.request(opts);
          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 = gaxios_1.Gaxios.mergeHeaders(opts.headers);
          this.addUserProjectAndAuthHeaders(opts.headers, requestHeaders);
          response = await this.transporter.request(opts);
        } catch (e4) {
          const res = e4.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 e4;
        }
        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() {
        this.#pendingAccessToken = this.#pendingAccessToken || this.#internalRefreshAccessTokenAsync();
        try {
          return await this.#pendingAccessToken;
        } finally {
          this.#pendingAccessToken = null;
        }
      }
      async #internalRefreshAccessTokenAsync() {
        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 = new Headers({
          "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;
      }
      /**
       * 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"
          }
        };
        authclient_1.AuthClient.setMethodName(opts, "getImpersonatedAccessToken");
        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/${shared_cjs_1.pkg.version} google-byoid-sdk source/${credentialSourceType} sa-impersonation/${saImpersonation} config-lifetime/${this.configLifetimeRequested}`;
      }
      getTokenUrl() {
        return this.tokenUrl;
      }
    };
    exports2.BaseExternalAccountClient = BaseExternalAccountClient;
  }
});

// packages/cli/node_modules/google-auth-library/build/src/auth/filesubjecttokensupplier.js
var require_filesubjecttokensupplier2 = __commonJS({
  "packages/cli/node_modules/google-auth-library/build/src/auth/filesubjecttokensupplier.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.FileSubjectTokenSupplier = void 0;
    var util_1 = __require("util");
    var fs113 = __require("fs");
    var readFile13 = (0, util_1.promisify)(fs113.readFile ?? (() => {
    }));
    var realpath3 = (0, util_1.promisify)(fs113.realpath ?? (() => {
    }));
    var lstat6 = (0, util_1.promisify)(fs113.lstat ?? (() => {
    }));
    var FileSubjectTokenSupplier = class {
      static {
        __name(this, "FileSubjectTokenSupplier");
      }
      filePath;
      formatType;
      subjectTokenFieldName;
      /**
       * 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() {
        let parsedFilePath = this.filePath;
        try {
          parsedFilePath = await realpath3(parsedFilePath);
          if (!(await lstat6(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 readFile13(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;
  }
});

// packages/cli/node_modules/google-auth-library/build/src/auth/urlsubjecttokensupplier.js
var require_urlsubjecttokensupplier2 = __commonJS({
  "packages/cli/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 authclient_1 = require_authclient2();
    var UrlSubjectTokenSupplier = class {
      static {
        __name(this, "UrlSubjectTokenSupplier");
      }
      url;
      headers;
      formatType;
      subjectTokenFieldName;
      additionalGaxiosOptions;
      /**
       * 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
        };
        authclient_1.AuthClient.setMethodName(opts, "getSubjectToken");
        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;
  }
});

// packages/cli/node_modules/google-auth-library/build/src/auth/certificatesubjecttokensupplier.js
var require_certificatesubjecttokensupplier2 = __commonJS({
  "packages/cli/node_modules/google-auth-library/build/src/auth/certificatesubjecttokensupplier.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.CertificateSubjectTokenSupplier = exports2.InvalidConfigurationError = exports2.CertificateSourceUnavailableError = exports2.CERTIFICATE_CONFIGURATION_ENV_VARIABLE = void 0;
    var util_1 = require_util31();
    var fs113 = __require("fs");
    var crypto_1 = __require("crypto");
    var https7 = __require("https");
    exports2.CERTIFICATE_CONFIGURATION_ENV_VARIABLE = "GOOGLE_API_CERTIFICATE_CONFIG";
    var CertificateSourceUnavailableError = class extends Error {
      static {
        __name(this, "CertificateSourceUnavailableError");
      }
      constructor(message) {
        super(message);
        this.name = "CertificateSourceUnavailableError";
      }
    };
    exports2.CertificateSourceUnavailableError = CertificateSourceUnavailableError;
    var InvalidConfigurationError = class extends Error {
      static {
        __name(this, "InvalidConfigurationError");
      }
      constructor(message) {
        super(message);
        this.name = "InvalidConfigurationError";
      }
    };
    exports2.InvalidConfigurationError = InvalidConfigurationError;
    var CertificateSubjectTokenSupplier = class {
      static {
        __name(this, "CertificateSubjectTokenSupplier");
      }
      certificateConfigPath;
      trustChainPath;
      cert;
      key;
      /**
       * Initializes a new instance of the CertificateSubjectTokenSupplier.
       * @param opts The configuration options for the supplier.
       */
      constructor(opts) {
        if (!opts.useDefaultCertificateConfig && !opts.certificateConfigLocation) {
          throw new InvalidConfigurationError("Either `useDefaultCertificateConfig` must be true or a `certificateConfigLocation` must be provided.");
        }
        if (opts.useDefaultCertificateConfig && opts.certificateConfigLocation) {
          throw new InvalidConfigurationError("Both `useDefaultCertificateConfig` and `certificateConfigLocation` cannot be provided.");
        }
        this.trustChainPath = opts.trustChainPath;
        this.certificateConfigPath = opts.certificateConfigLocation ?? "";
      }
      /**
       * Creates an HTTPS agent configured with the client certificate and private key for mTLS.
       * @returns An mTLS-configured https.Agent.
       */
      async createMtlsHttpsAgent() {
        if (!this.key || !this.cert) {
          throw new InvalidConfigurationError("Cannot create mTLS Agent with missing certificate or key");
        }
        return new https7.Agent({ key: this.key, cert: this.cert });
      }
      /**
       * Constructs the subject token, which is the base64-encoded certificate chain.
       * @returns A promise that resolves with the subject token.
       */
      async getSubjectToken() {
        this.certificateConfigPath = await this.#resolveCertificateConfigFilePath();
        const { certPath, keyPath } = await this.#getCertAndKeyPaths();
        ({ cert: this.cert, key: this.key } = await this.#getKeyAndCert(certPath, keyPath));
        return await this.#processChainFromPaths(this.cert);
      }
      /**
       * Resolves the absolute path to the certificate configuration file
       * by checking the "certificate_config_location" provided in the ADC file,
       * or the "GOOGLE_API_CERTIFICATE_CONFIG" environment variable
       * or in the default gcloud path.
       * @param overridePath An optional path to check first.
       * @returns The resolved file path.
       */
      async #resolveCertificateConfigFilePath() {
        const overridePath = this.certificateConfigPath;
        if (overridePath) {
          if (await (0, util_1.isValidFile)(overridePath)) {
            return overridePath;
          }
          throw new CertificateSourceUnavailableError(`Provided certificate config path is invalid: ${overridePath}`);
        }
        const envPath = process.env[exports2.CERTIFICATE_CONFIGURATION_ENV_VARIABLE];
        if (envPath) {
          if (await (0, util_1.isValidFile)(envPath)) {
            return envPath;
          }
          throw new CertificateSourceUnavailableError(`Path from environment variable "${exports2.CERTIFICATE_CONFIGURATION_ENV_VARIABLE}" is invalid: ${envPath}`);
        }
        const wellKnownPath = (0, util_1.getWellKnownCertificateConfigFileLocation)();
        if (await (0, util_1.isValidFile)(wellKnownPath)) {
          return wellKnownPath;
        }
        throw new CertificateSourceUnavailableError(`Could not find certificate configuration file. Searched override path, the "${exports2.CERTIFICATE_CONFIGURATION_ENV_VARIABLE}" env var, and the gcloud path (${wellKnownPath}).`);
      }
      /**
       * Reads and parses the certificate config JSON file to extract the certificate and key paths.
       * @returns An object containing the certificate and key paths.
       */
      async #getCertAndKeyPaths() {
        const configPath = this.certificateConfigPath;
        let fileContents;
        try {
          fileContents = await fs113.promises.readFile(configPath, "utf8");
        } catch (err) {
          throw new CertificateSourceUnavailableError(`Failed to read certificate config file at: ${configPath}`);
        }
        try {
          const config2 = JSON.parse(fileContents);
          const certPath = config2?.cert_configs?.workload?.cert_path;
          const keyPath = config2?.cert_configs?.workload?.key_path;
          if (!certPath || !keyPath) {
            throw new InvalidConfigurationError(`Certificate config file (${configPath}) is missing required "cert_path" or "key_path" in the workload config.`);
          }
          return { certPath, keyPath };
        } catch (e4) {
          if (e4 instanceof InvalidConfigurationError)
            throw e4;
          throw new InvalidConfigurationError(`Failed to parse certificate config from ${configPath}: ${e4.message}`);
        }
      }
      /**
       * Reads and parses the cert and key files get their content and check valid format.
       * @returns An object containing the cert content and key content in buffer format.
       */
      async #getKeyAndCert(certPath, keyPath) {
        let cert, key;
        try {
          cert = await fs113.promises.readFile(certPath);
          new crypto_1.X509Certificate(cert);
        } catch (err) {
          const message = err instanceof Error ? err.message : String(err);
          throw new CertificateSourceUnavailableError(`Failed to read certificate file at ${certPath}: ${message}`);
        }
        try {
          key = await fs113.promises.readFile(keyPath);
          (0, crypto_1.createPrivateKey)(key);
        } catch (err) {
          const message = err instanceof Error ? err.message : String(err);
          throw new CertificateSourceUnavailableError(`Failed to read private key file at ${keyPath}: ${message}`);
        }
        return { cert, key };
      }
      /**
       * Reads the leaf certificate and trust chain, combines them,
       * and returns a JSON array of base64-encoded certificates.
       * @returns A stringified JSON array of the certificate chain.
       */
      async #processChainFromPaths(leafCertBuffer) {
        const leafCert = new crypto_1.X509Certificate(leafCertBuffer);
        if (!this.trustChainPath) {
          return JSON.stringify([leafCert.raw.toString("base64")]);
        }
        try {
          const chainPems = await fs113.promises.readFile(this.trustChainPath, "utf8");
          const pemBlocks = chainPems.match(/-----BEGIN CERTIFICATE-----[^-]+-----END CERTIFICATE-----/g) ?? [];
          const chainCerts = pemBlocks.map((pem, index) => {
            try {
              return new crypto_1.X509Certificate(pem);
            } catch (err) {
              const message = err instanceof Error ? err.message : String(err);
              throw new InvalidConfigurationError(`Failed to parse certificate at index ${index} in trust chain file ${this.trustChainPath}: ${message}`);
            }
          });
          const leafIndex = chainCerts.findIndex((chainCert) => leafCert.raw.equals(chainCert.raw));
          let finalChain;
          if (leafIndex === -1) {
            finalChain = [leafCert, ...chainCerts];
          } else if (leafIndex === 0) {
            finalChain = chainCerts;
          } else {
            throw new InvalidConfigurationError(`Leaf certificate exists in the trust chain but is not the first entry (found at index ${leafIndex}).`);
          }
          return JSON.stringify(finalChain.map((cert) => cert.raw.toString("base64")));
        } catch (err) {
          if (err instanceof InvalidConfigurationError)
            throw err;
          const message = err instanceof Error ? err.message : String(err);
          throw new CertificateSourceUnavailableError(`Failed to process certificate chain from ${this.trustChainPath}: ${message}`);
        }
      }
    };
    exports2.CertificateSubjectTokenSupplier = CertificateSubjectTokenSupplier;
  }
});

// packages/cli/node_modules/google-auth-library/build/src/auth/identitypoolclient.js
var require_identitypoolclient2 = __commonJS({
  "packages/cli/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_baseexternalclient2();
    var util_1 = require_util31();
    var filesubjecttokensupplier_1 = require_filesubjecttokensupplier2();
    var urlsubjecttokensupplier_1 = require_urlsubjecttokensupplier2();
    var certificatesubjecttokensupplier_1 = require_certificatesubjecttokensupplier2();
    var stscredentials_1 = require_stscredentials2();
    var gaxios_1 = require_src40();
    var IdentityPoolClient = class _IdentityPoolClient extends baseexternalclient_1.BaseExternalAccountClient {
      static {
        __name(this, "IdentityPoolClient");
      }
      subjectTokenSupplier;
      /**
       * 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.
       */
      constructor(options2) {
        super(options2);
        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 certificate = credentialSourceOpts.get("certificate");
          const headers = credentialSourceOpts.get("headers");
          if (file && url2 || url2 && certificate || file && certificate) {
            throw new Error('No valid Identity Pool "credential_source" provided, must be either file, url, or certificate.');
          } else if (file) {
            this.credentialSourceType = "file";
            this.subjectTokenSupplier = new filesubjecttokensupplier_1.FileSubjectTokenSupplier({
              filePath: file,
              formatType,
              subjectTokenFieldName: formatSubjectTokenFieldName
            });
          } else if (url2) {
            this.credentialSourceType = "url";
            this.subjectTokenSupplier = new urlsubjecttokensupplier_1.UrlSubjectTokenSupplier({
              url: url2,
              formatType,
              subjectTokenFieldName: formatSubjectTokenFieldName,
              headers,
              additionalGaxiosOptions: _IdentityPoolClient.RETRY_CONFIG
            });
          } else if (certificate) {
            this.credentialSourceType = "certificate";
            const certificateSubjecttokensupplier = new certificatesubjecttokensupplier_1.CertificateSubjectTokenSupplier({
              useDefaultCertificateConfig: certificate.use_default_certificate_config,
              certificateConfigLocation: certificate.certificate_config_location,
              trustChainPath: certificate.trust_chain_path
            });
            this.subjectTokenSupplier = certificateSubjecttokensupplier;
          } else {
            throw new Error('No valid Identity Pool "credential_source" provided, must be either file, url, or certificate.');
          }
        }
      }
      /**
       * 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() {
        const subjectToken = await this.subjectTokenSupplier.getSubjectToken(this.supplierContext);
        if (this.subjectTokenSupplier instanceof certificatesubjecttokensupplier_1.CertificateSubjectTokenSupplier) {
          const mtlsAgent = await this.subjectTokenSupplier.createMtlsHttpsAgent();
          this.stsCredential = new stscredentials_1.StsCredentials({
            tokenExchangeEndpoint: this.getTokenUrl(),
            clientAuthentication: this.clientAuth,
            transporter: new gaxios_1.Gaxios({ agent: mtlsAgent })
          });
          this.transporter = new gaxios_1.Gaxios({
            ...this.transporter.defaults || {},
            agent: mtlsAgent
          });
        }
        return subjectToken;
      }
    };
    exports2.IdentityPoolClient = IdentityPoolClient;
  }
});

// packages/cli/node_modules/google-auth-library/build/src/auth/awsrequestsigner.js
var require_awsrequestsigner2 = __commonJS({
  "packages/cli/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 gaxios_1 = require_src40();
    var crypto_1 = require_crypto6();
    var AWS_ALGORITHM = "AWS4-HMAC-SHA256";
    var AWS_REQUEST_TYPE = "aws4_request";
    var AwsRequestSigner = class {
      static {
        __name(this, "AwsRequestSigner");
      }
      getCredentials;
      region;
      crypto;
      /**
       * 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 RangeError('"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);
        if (typeof requestPayload !== "string" && requestPayload !== void 0) {
          throw new TypeError(`'requestPayload' is expected to be a string if provided. Got: ${requestPayload}`);
        }
        const headerMap = await generateAuthenticationHeaderMap({
          crypto: this.crypto,
          host: uri.host,
          canonicalUri: uri.pathname,
          canonicalQuerystring: uri.search.slice(1),
          method,
          region: this.region,
          securityCredentials: awsSecurityCredentials,
          requestPayload,
          additionalAmzHeaders
        });
        const headers = gaxios_1.Gaxios.mergeHeaders(
          // Add x-amz-date if available.
          headerMap.amzDate ? { "x-amz-date": headerMap.amzDate } : {},
          {
            authorization: headerMap.authorizationHeader,
            host: uri.host
          },
          additionalAmzHeaders || {}
        );
        if (awsSecurityCredentials.token) {
          gaxios_1.Gaxios.mergeHeaders(headers, {
            "x-amz-security-token": awsSecurityCredentials.token
          });
        }
        const awsSignedReq = {
          url: url2,
          method,
          headers
        };
        if (requestPayload !== void 0) {
          awsSignedReq.body = requestPayload;
        }
        return awsSignedReq;
      }
    };
    exports2.AwsRequestSigner = AwsRequestSigner;
    async function sign(crypto14, key, msg) {
      return await crypto14.signWithHmacSha256(key, msg);
    }
    __name(sign, "sign");
    async function getSigningKey(crypto14, key, dateStamp, region, serviceName) {
      const kDate = await sign(crypto14, `AWS4${key}`, dateStamp);
      const kRegion = await sign(crypto14, kDate, region);
      const kService = await sign(crypto14, kRegion, serviceName);
      const kSigning = await sign(crypto14, kService, "aws4_request");
      return kSigning;
    }
    __name(getSigningKey, "getSigningKey");
    async function generateAuthenticationHeaderMap(options2) {
      const additionalAmzHeaders = gaxios_1.Gaxios.mergeHeaders(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.*/, "");
      if (options2.securityCredentials.token) {
        additionalAmzHeaders.set("x-amz-security-token", options2.securityCredentials.token);
      }
      const amzHeaders = gaxios_1.Gaxios.mergeHeaders(
        {
          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
        additionalAmzHeaders.has("date") ? {} : { "x-amz-date": amzDate },
        additionalAmzHeaders
      );
      let canonicalHeaders = "";
      const signedHeadersList = [
        ...amzHeaders.keys()
      ].sort();
      signedHeadersList.forEach((key) => {
        canonicalHeaders += `${key}:${amzHeaders.get(key)}
`;
      });
      const signedHeaders = signedHeadersList.join(";");
      const payloadHash = await options2.crypto.sha256DigestHex(requestPayload);
      const canonicalRequest = `${options2.method.toUpperCase()}
${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: additionalAmzHeaders.has("date") ? void 0 : amzDate,
        authorizationHeader,
        canonicalQuerystring: options2.canonicalQuerystring
      };
    }
    __name(generateAuthenticationHeaderMap, "generateAuthenticationHeaderMap");
  }
});

// packages/cli/node_modules/google-auth-library/build/src/auth/defaultawssecuritycredentialssupplier.js
var require_defaultawssecuritycredentialssupplier2 = __commonJS({
  "packages/cli/node_modules/google-auth-library/build/src/auth/defaultawssecuritycredentialssupplier.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.DefaultAwsSecurityCredentialsSupplier = void 0;
    var authclient_1 = require_authclient2();
    var DefaultAwsSecurityCredentialsSupplier = class {
      static {
        __name(this, "DefaultAwsSecurityCredentialsSupplier");
      }
      regionUrl;
      securityCredentialsUrl;
      imdsV2SessionTokenUrl;
      additionalGaxiosOptions;
      /**
       * 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) {
        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 (this.#regionFromEnv) {
          return this.#regionFromEnv;
        }
        const metadataHeaders = new Headers();
        if (!this.#regionFromEnv && this.imdsV2SessionTokenUrl) {
          metadataHeaders.set("x-aws-ec2-metadata-token", await this.#getImdsV2SessionToken(context2.transporter));
        }
        if (!this.regionUrl) {
          throw new RangeError('Unable to determine AWS region due to missing "options.credential_source.region_url"');
        }
        const opts = {
          ...this.additionalGaxiosOptions,
          url: this.regionUrl,
          method: "GET",
          headers: metadataHeaders
        };
        authclient_1.AuthClient.setMethodName(opts, "getAwsRegion");
        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 (this.#securityCredentialsFromEnv) {
          return this.#securityCredentialsFromEnv;
        }
        const metadataHeaders = new Headers();
        if (this.imdsV2SessionTokenUrl) {
          metadataHeaders.set("x-aws-ec2-metadata-token", await this.#getImdsV2SessionToken(context2.transporter));
        }
        const roleName = await this.#getAwsRoleName(metadataHeaders, context2.transporter);
        const awsCreds = await this.#retrieveAwsSecurityCredentials(roleName, metadataHeaders, context2.transporter);
        return {
          accessKeyId: awsCreds.AccessKeyId,
          secretAccessKey: awsCreds.SecretAccessKey,
          token: awsCreds.Token
        };
      }
      /**
       * @param transporter The transporter to use for requests.
       * @return A promise that resolves with the IMDSv2 Session Token.
       */
      async #getImdsV2SessionToken(transporter) {
        const opts = {
          ...this.additionalGaxiosOptions,
          url: this.imdsV2SessionTokenUrl,
          method: "PUT",
          headers: { "x-aws-ec2-metadata-token-ttl-seconds": "300" }
        };
        authclient_1.AuthClient.setMethodName(opts, "#getImdsV2SessionToken");
        const response = await transporter.request(opts);
        return response.data;
      }
      /**
       * @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.
       */
      async #getAwsRoleName(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",
          headers
        };
        authclient_1.AuthClient.setMethodName(opts, "#getAwsRoleName");
        const response = await transporter.request(opts);
        return response.data;
      }
      /**
       * 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.
       */
      async #retrieveAwsSecurityCredentials(roleName, headers, transporter) {
        const opts = {
          ...this.additionalGaxiosOptions,
          url: `${this.securityCredentialsUrl}/${roleName}`,
          headers
        };
        authclient_1.AuthClient.setMethodName(opts, "#retrieveAwsSecurityCredentials");
        const response = await transporter.request(opts);
        return response.data;
      }
      get #regionFromEnv() {
        return process.env["AWS_REGION"] || process.env["AWS_DEFAULT_REGION"] || null;
      }
      get #securityCredentialsFromEnv() {
        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;
      }
    };
    exports2.DefaultAwsSecurityCredentialsSupplier = DefaultAwsSecurityCredentialsSupplier;
  }
});

// packages/cli/node_modules/google-auth-library/build/src/auth/awsclient.js
var require_awsclient2 = __commonJS({
  "packages/cli/node_modules/google-auth-library/build/src/auth/awsclient.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.AwsClient = void 0;
    var awsrequestsigner_1 = require_awsrequestsigner2();
    var baseexternalclient_1 = require_baseexternalclient2();
    var defaultawssecuritycredentialssupplier_1 = require_defaultawssecuritycredentialssupplier2();
    var util_1 = require_util31();
    var gaxios_1 = require_src40();
    var AwsClient = class _AwsClient extends baseexternalclient_1.BaseExternalAccountClient {
      static {
        __name(this, "AwsClient");
      }
      environmentId;
      awsSecurityCredentialsSupplier;
      regionalCredVerificationUrl;
      awsRequestSigner;
      region;
      static #DEFAULT_AWS_REGIONAL_CREDENTIAL_VERIFICATION_URL = "https://sts.{region}.amazonaws.com?Action=GetCallerIdentity&Version=2011-06-15";
      /**
       * @deprecated AWS client no validates the EC2 metadata address.
       **/
      static AWS_EC2_METADATA_IPV4_ADDRESS = "169.254.169.254";
      /**
       * @deprecated AWS client no validates the EC2 metadata address.
       **/
      static AWS_EC2_METADATA_IPV6_ADDRESS = "fd00:ec2::254";
      /**
       * 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.
       */
      constructor(options2) {
        super(options2);
        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 = _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() {
        const match2 = this.environmentId?.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({
          ..._AwsClient.RETRY_CONFIG,
          url: this.regionalCredVerificationUrl.replace("{region}", this.region),
          method: "POST"
        });
        const reformattedHeader = [];
        const extendedHeaders = gaxios_1.Gaxios.mergeHeaders({
          // 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);
        extendedHeaders.forEach((value, key) => reformattedHeader.push({ key, value }));
        return encodeURIComponent(JSON.stringify({
          url: options2.url,
          method: options2.method,
          headers: reformattedHeader
        }));
      }
    };
    exports2.AwsClient = AwsClient;
  }
});

// packages/cli/node_modules/google-auth-library/build/src/auth/executable-response.js
var require_executable_response2 = __commonJS({
  "packages/cli/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");
      }
      /**
       * The version of the Executable response. Only version 1 is currently supported.
       */
      version;
      /**
       * Whether the executable ran successfully.
       */
      success;
      /**
       * The epoch time for expiration of the token in seconds.
       */
      expirationTime;
      /**
       * The type of subject token in the response, currently supported values are:
       * urn:ietf:params:oauth:token-type:saml2
       * urn:ietf:params:oauth:token-type:id_token
       * urn:ietf:params:oauth:token-type:jwt
       */
      tokenType;
      /**
       * The error code from the executable.
       */
      errorCode;
      /**
       * The error message from the executable.
       */
      errorMessage;
      /**
       * The subject token from the executable, format depends on tokenType.
       */
      subjectToken;
      /**
       * 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;
  }
});

// packages/cli/node_modules/google-auth-library/build/src/auth/pluggable-auth-handler.js
var require_pluggable_auth_handler2 = __commonJS({
  "packages/cli/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 = exports2.ExecutableError = void 0;
    var executable_response_1 = require_executable_response2();
    var childProcess3 = __require("child_process");
    var fs113 = __require("fs");
    var ExecutableError = class extends Error {
      static {
        __name(this, "ExecutableError");
      }
      /**
       * The exit code returned by the executable.
       */
      code;
      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 PluggableAuthHandler = class _PluggableAuthHandler {
      static {
        __name(this, "PluggableAuthHandler");
      }
      commandComponents;
      timeoutMillis;
      outputFile;
      /**
       * 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((resolve30, 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 resolve30(response);
              } catch (error2) {
                if (error2 instanceof executable_response_1.ExecutableResponseError) {
                  return reject(error2);
                }
                return reject(new executable_response_1.ExecutableResponseError(`The executable returned an invalid response: ${output}`));
              }
            } else {
              return reject(new 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 fs113.promises.realpath(this.outputFile);
        } catch {
          return void 0;
        }
        if (!(await fs113.promises.lstat(filePath)).isFile()) {
          return void 0;
        }
        const responseString = await fs113.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 (error2) {
          if (error2 instanceof executable_response_1.ExecutableResponseError) {
            throw error2;
          }
          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 i3 = 0; i3 < components.length; i3++) {
          if (components[i3][0] === '"' && components[i3].slice(-1) === '"') {
            components[i3] = components[i3].slice(1, -1);
          }
        }
        return components;
      }
    };
    exports2.PluggableAuthHandler = PluggableAuthHandler;
  }
});

// packages/cli/node_modules/google-auth-library/build/src/auth/pluggable-auth-client.js
var require_pluggable_auth_client2 = __commonJS({
  "packages/cli/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_baseexternalclient2();
    var executable_response_1 = require_executable_response2();
    var pluggable_auth_handler_1 = require_pluggable_auth_handler2();
    var pluggable_auth_handler_2 = require_pluggable_auth_handler2();
    Object.defineProperty(exports2, "ExecutableError", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return pluggable_auth_handler_2.ExecutableError;
    }, "get") });
    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");
      }
      /**
       * The command used to retrieve the third party token.
       */
      command;
      /**
       * The timeout in milliseconds for running executable,
       * set to default if none provided.
       */
      timeoutMillis;
      /**
       * The path to file to check for cached executable response.
       */
      outputFile;
      /**
       * Executable and output file handler.
       */
      handler;
      /**
       * 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.
       */
      constructor(options2) {
        super(options2);
        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 pluggable_auth_handler_1.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;
  }
});

// packages/cli/node_modules/google-auth-library/build/src/auth/externalclient.js
var require_externalclient2 = __commonJS({
  "packages/cli/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_baseexternalclient2();
    var identitypoolclient_1 = require_identitypoolclient2();
    var awsclient_1 = require_awsclient2();
    var pluggable_auth_client_1 = require_pluggable_auth_client2();
    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.
       *
       * **IMPORTANT**: This method does not validate the credential configuration.
       * A security risk occurs when a credential configuration configured with
       * malicious URLs is used. When the credential configuration is accepted from
       * an untrusted source, you should validate it before using it with this
       * method. For more details, see
       * https://cloud.google.com/docs/authentication/external/externally-sourced-credentials.
       *
       * @param options The external account options object typically loaded
       *   from the external account JSON credential file.
       * @return A BaseExternalAccountClient instance or null if the options
       *   provided do not correspond to an external account credential.
       */
      static fromJSON(options2) {
        if (options2 && options2.type === baseexternalclient_1.EXTERNAL_ACCOUNT_TYPE) {
          if (options2.credential_source?.environment_id) {
            return new awsclient_1.AwsClient(options2);
          } else if (options2.credential_source?.executable) {
            return new pluggable_auth_client_1.PluggableAuthClient(options2);
          } else {
            return new identitypoolclient_1.IdentityPoolClient(options2);
          }
        } else {
          return null;
        }
      }
    };
    exports2.ExternalAccountClient = ExternalAccountClient;
  }
});

// packages/cli/node_modules/google-auth-library/build/src/auth/externalAccountAuthorizedUserClient.js
var require_externalAccountAuthorizedUserClient2 = __commonJS({
  "packages/cli/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_authclient2();
    var oauth2common_1 = require_oauth2common2();
    var gaxios_1 = require_src40();
    var stream2 = __require("stream");
    var baseexternalclient_1 = require_baseexternalclient2();
    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");
      }
      #tokenRefreshEndpoint;
      /**
       * 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(options2) {
        super(options2);
        this.#tokenRefreshEndpoint = options2.tokenRefreshEndpoint;
      }
      /**
       * 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, headers) {
        const opts = {
          ..._ExternalAccountAuthorizedUserHandler.RETRY_CONFIG,
          url: this.#tokenRefreshEndpoint,
          method: "POST",
          headers,
          data: new URLSearchParams({
            grant_type: "refresh_token",
            refresh_token: refreshToken
          })
        };
        authclient_1.AuthClient.setMethodName(opts, "refreshToken");
        this.applyClientAuthenticationOptions(opts);
        try {
          const response = await this.transporter.request(opts);
          const tokenRefreshResponse = response.data;
          tokenRefreshResponse.res = response;
          return tokenRefreshResponse;
        } catch (error2) {
          if (error2 instanceof gaxios_1.GaxiosError && error2.response) {
            throw (0, oauth2common_1.getErrorFromOAuthErrorResponse)(
              error2.response.data,
              // Preserve other fields from the original error.
              error2
            );
          }
          throw error2;
        }
      }
    };
    var ExternalAccountAuthorizedUserClient = class extends authclient_1.AuthClient {
      static {
        __name(this, "ExternalAccountAuthorizedUserClient");
      }
      cachedAccessToken;
      externalAccountAuthorizedUserHandler;
      refreshToken;
      /**
       * 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.
       */
      constructor(options2) {
        super(options2);
        if (options2.universe_domain) {
          this.universeDomain = options2.universe_domain;
        }
        this.refreshToken = options2.refresh_token;
        const clientAuthentication = {
          confidentialClientType: "basic",
          clientId: options2.client_id,
          clientSecret: options2.client_secret
        };
        this.externalAccountAuthorizedUserHandler = new ExternalAccountAuthorizedUserHandler({
          tokenRefreshEndpoint: options2.token_url ?? DEFAULT_TOKEN_URL.replace("{universeDomain}", this.universeDomain),
          transporter: this.transporter,
          clientAuthentication
        });
        this.cachedAccessToken = null;
        this.quotaProjectId = options2.quota_project_id;
        if (typeof options2?.eagerRefreshThresholdMillis !== "number") {
          this.eagerRefreshThresholdMillis = baseexternalclient_1.EXPIRATION_TIME_OFFSET;
        } else {
          this.eagerRefreshThresholdMillis = options2.eagerRefreshThresholdMillis;
        }
        this.forceRefreshOnFailure = !!options2?.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 = new Headers({
          authorization: `Bearer ${accessTokenResponse.token}`
        });
        return this.addSharedMetadataHeaders(headers);
      }
      request(opts, callback) {
        if (callback) {
          this.requestAsync(opts).then((r5) => callback(null, r5), (e4) => {
            return callback(e4, e4.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 = gaxios_1.Gaxios.mergeHeaders(opts.headers);
          this.addUserProjectAndAuthHeaders(opts.headers, requestHeaders);
          response = await this.transporter.request(opts);
        } catch (e4) {
          const res = e4.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 e4;
        }
        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;
  }
});

// packages/cli/node_modules/google-auth-library/build/src/auth/googleauth.js
var require_googleauth2 = __commonJS({
  "packages/cli/node_modules/google-auth-library/build/src/auth/googleauth.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.GoogleAuth = exports2.GoogleAuthExceptionMessages = void 0;
    var child_process_1 = __require("child_process");
    var fs113 = __require("fs");
    var gaxios_1 = require_src40();
    var gcpMetadata = require_src42();
    var os47 = __require("os");
    var path125 = __require("path");
    var crypto_1 = require_crypto6();
    var computeclient_1 = require_computeclient2();
    var idtokenclient_1 = require_idtokenclient2();
    var envDetect_1 = require_envDetect2();
    var jwtclient_1 = require_jwtclient2();
    var refreshclient_1 = require_refreshclient2();
    var impersonated_1 = require_impersonated2();
    var externalclient_1 = require_externalclient2();
    var baseexternalclient_1 = require_baseexternalclient2();
    var authclient_1 = require_authclient2();
    var externalAccountAuthorizedUserClient_1 = require_externalAccountAuthorizedUserClient2();
    var util_1 = require_util31();
    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 GoogleAuth5 = class {
      static {
        __name(this, "GoogleAuth");
      }
      /**
       * Caches a value indicating whether the auth layer is running on Google
       * Compute Engine.
       * @private
       */
      checkIsGCE = void 0;
      useJWTAccessWithScope;
      defaultServicePath;
      // Note:  this properly is only public to satisfy unit tests.
      // https://github.com/Microsoft/TypeScript/issues/5228
      get isGCE() {
        return this.checkIsGCE;
      }
      _findProjectIdPromise;
      _cachedProjectId;
      // To save the contents of the JSON credential file
      jsonContent = null;
      apiKey;
      cachedCredential = null;
      /**
       * A pending {@link AuthClient}. Used for concurrent {@link GoogleAuth.getClient} calls.
       */
      #pendingAuthClient = null;
      /**
       * Scopes populated by the client library by default. We differentiate between
       * these and user defined scopes when deciding whether to use a self-signed JWT.
       */
      defaultScopes;
      keyFilename;
      scopes;
      clientOptions = {};
      /**
       * 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 = {}) {
        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((r5) => callback(null, r5), 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 (e4) {
          if (e4 instanceof Error && e4.message === exports2.GoogleAuthExceptionMessages.NO_PROJECT_ID_FOUND) {
            return null;
          } else {
            throw e4;
          }
        }
      }
      /**
       * 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 ||= await this.getProductionProjectId();
        projectId ||= await this.getFileProjectId();
        projectId ||= await this.getDefaultServiceProjectId();
        projectId ||= await this.getGCEProjectId();
        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() {
        let universeDomain;
        try {
          universeDomain = await gcpMetadata.universe("universe-domain");
          universeDomain ||= authclient_1.DEFAULT_UNIVERSE;
        } catch (e4) {
          if (e4 && e4?.response?.status === 404) {
            universeDomain = authclient_1.DEFAULT_UNIVERSE;
          } else {
            throw e4;
          }
        }
        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 ??= (await this.getClient()).universeDomain;
        } catch {
          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((r5) => callback(null, r5.credential, r5.projectId), callback);
        } else {
          return this.getApplicationDefaultAsync(options2);
        }
      }
      async getApplicationDefaultAsync(options2 = {}) {
        if (this.cachedCredential) {
          return await this.#prepareAndCacheClient(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 this.#prepareAndCacheClient(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 this.#prepareAndCacheClient(credential);
        }
        if (await this._checkIsGCE()) {
          options2.scopes = this.getAnyScopes();
          return await this.#prepareAndCacheClient(new computeclient_1.Compute(options2));
        }
        throw new Error(exports2.GoogleAuthExceptionMessages.NO_ADC_FOUND);
      }
      async #prepareAndCacheClient(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 };
      }
      /**
       * 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 (e4) {
          if (e4 instanceof Error) {
            e4.message = `Unable to read the credential file specified by the GOOGLE_APPLICATION_CREDENTIALS environment variable: ${e4.message}`;
          }
          throw e4;
        }
      }
      /**
       * 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 = path125.join(home, ".config");
          }
        }
        if (location) {
          location = path125.join(location, "gcloud", "application_default_credentials.json");
          if (!fs113.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 = fs113.realpathSync(filePath);
          if (!fs113.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 = fs113.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) {
        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 (json2.service_account_impersonation_url?.length > 256) {
          throw new RangeError(`Target principal is too long: ${json2.service_account_impersonation_url}`);
        }
        const targetPrincipal = /(?<target>[^/]+):(generateAccessToken|generateIdToken)$/.exec(json2.service_account_impersonation_url)?.groups?.target;
        if (!targetPrincipal) {
          throw new RangeError(`Cannot extract target principal from ${json2.service_account_impersonation_url}`);
        }
        const targetScopes = (this.scopes || json2.scopes || this.defaultScopes) ?? [];
        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}.
       *
       * @deprecated This method is being deprecated because of a potential security risk.
       *
       * This method does not validate the credential configuration. The security
       * risk occurs when a credential configuration is accepted from a source that
       * is not under your control and used without validation on your side.
       *
       * If you know that you will be loading credential configurations of a
       * specific type, it is recommended to use a credential-type-specific
       * constructor. This will ensure that an unexpected credential type with
       * potential for malicious intent is not loaded unintentionally. You might
       * still have to do validation for certain credential types. Please follow
       * the recommendation for that method. For example, if you want to load only
       * service accounts, you can use the `JWT` constructor:
       * ```
       * const {JWT} = require('google-auth-library');
       * const keys = require('/path/to/key.json');
       * const client = new JWT({
       *   email: keys.client_email,
       *   key: keys.private_key,
       *   scopes: ['https://www.googleapis.com/auth/cloud-platform'],
       * });
       * ```
       *
       * If you are loading your credential configuration from an untrusted source and have
       * not mitigated the risks (e.g. by validating the configuration yourself), make
       * these changes as soon as possible to prevent security risks to your environment.
       *
       * Regardless of the method used, it is always your responsibility to validate
       * configurations received from external sources.
       *
       * For more details, see https://cloud.google.com/docs/authentication/external/externally-sourced-credentials.
       *
       * @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((r5) => callback(null, r5), callback);
        } else {
          return this.fromStreamAsync(inputStream, options2);
        }
      }
      fromStreamAsync(inputStream, options2) {
        return new Promise((resolve30, 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 r5 = this._cacheClientFromJSON(data, options2);
                return resolve30(r5);
              } 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 resolve30(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 = os47.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((resolve30) => {
          (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;
                resolve30(projectId);
                return;
              } catch (e4) {
              }
            }
            resolve30(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 r5 = await this._tryGetApplicationCredentialsFromEnvironmentVariable();
        if (r5) {
          return r5.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 r5 = await gcpMetadata.project("project-id");
          return r5;
        } catch (e4) {
          return null;
        }
      }
      getCredentials(callback) {
        if (callback) {
          this.getCredentialsAsync().then((r5) => callback(null, r5), 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;
        }
        this.#pendingAuthClient = this.#pendingAuthClient || this.#determineClient();
        try {
          return await this.#pendingAuthClient;
        } finally {
          this.#pendingAuthClient = null;
        }
      }
      async #determineClient() {
        if (this.jsonContent) {
          return this._cacheClientFromJSON(this.jsonContent, this.clientOptions);
        } else if (this.keyFilename) {
          const filePath = path125.resolve(this.keyFilename);
          const stream2 = fs113.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 this.#prepareAndCacheClient(client);
          return credential;
        } else {
          const { credential } = await this.getApplicationDefaultAsync(this.clientOptions);
          return credential;
        }
      }
      /**
       * 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 = {}) {
        const url2 = opts.url;
        const client = await this.getClient();
        const headers = await client.getRequestHeaders(url2);
        opts.headers = gaxios_1.Gaxios.mergeHeaders(opts.headers, headers);
        return opts;
      }
      /**
       * A {@link fetch `fetch`} compliant API for {@link GoogleAuth}.
       *
       * @see {@link GoogleAuth.request} for the classic method.
       *
       * @remarks
       *
       * This is useful as a drop-in replacement for `fetch` API usage.
       *
       * @example
       *
       * ```ts
       * const auth = new GoogleAuth();
       * const fetchWithAuth: typeof fetch = (...args) => auth.fetch(...args);
       * await fetchWithAuth('https://example.com');
       * ```
       *
       * @param args `fetch` API or {@link Gaxios.fetch `Gaxios#fetch`} parameters
       * @returns the {@link GaxiosResponse} with Gaxios-added properties
       */
      async fetch(...args) {
        const client = await this.getClient();
        return client.fetch(...args);
      }
      /**
       * Automatically obtain application default credentials, and make an
       * HTTP request using the given options.
       *
       * @see {@link GoogleAuth.fetch} for the modern method.
       *
       * @param opts Axios request options for the HTTP request.
       */
      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 crypto14 = (0, crypto_1.createCrypto)();
        if (client instanceof jwtclient_1.JWT && client.key) {
          const sign = await crypto14.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(crypto14, creds.client_email, data, endpoint);
      }
      async signBlob(crypto14, emailOrUniqueId, data, endpoint) {
        const url2 = new URL(endpoint + `${emailOrUniqueId}:signBlob`);
        const res = await this.request({
          method: "POST",
          url: url2.href,
          data: {
            payload: crypto14.encodeBase64StringUtf8(data)
          },
          retry: true,
          retryConfig: {
            httpMethodsToRetry: ["POST"]
          }
        });
        return res.data.signedBlob;
      }
    };
    exports2.GoogleAuth = GoogleAuth5;
  }
});

// packages/cli/node_modules/google-auth-library/build/src/auth/iam.js
var require_iam2 = __commonJS({
  "packages/cli/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");
      }
      selector;
      token;
      /**
       * 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;
  }
});

// packages/cli/node_modules/google-auth-library/build/src/auth/downscopedclient.js
var require_downscopedclient2 = __commonJS({
  "packages/cli/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 gaxios_1 = require_src40();
    var stream2 = __require("stream");
    var authclient_1 = require_authclient2();
    var sts = require_stscredentials2();
    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");
      }
      authClient;
      credentialAccessBoundary;
      cachedDownscopedAccessToken;
      stsCredential;
      /**
       * 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 options the {@link DownscopedClientOptions `DownscopedClientOptions`} to use. Passing an `AuthClient` directly is **@DEPRECATED**.
       * @param credentialAccessBoundary **@DEPRECATED**. Provide a {@link DownscopedClientOptions `DownscopedClientOptions`} object in the first parameter instead.
       */
      constructor(options2, credentialAccessBoundary = {
        accessBoundary: {
          accessBoundaryRules: []
        }
      }) {
        super(options2 instanceof authclient_1.AuthClient ? {} : options2);
        if (options2 instanceof authclient_1.AuthClient) {
          this.authClient = options2;
          this.credentialAccessBoundary = credentialAccessBoundary;
        } else {
          this.authClient = options2.authClient;
          this.credentialAccessBoundary = options2.credentialAccessBoundary;
        }
        if (this.credentialAccessBoundary.accessBoundary.accessBoundaryRules.length === 0) {
          throw new Error("At least one access boundary rule needs to be defined.");
        } else if (this.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 this.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({
          tokenExchangeEndpoint: `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 = new Headers({
          authorization: `Bearer ${accessTokenResponse.token}`
        });
        return this.addSharedMetadataHeaders(headers);
      }
      request(opts, callback) {
        if (callback) {
          this.requestAsync(opts).then((r5) => callback(null, r5), (e4) => {
            return callback(e4, e4.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 = gaxios_1.Gaxios.mergeHeaders(opts.headers);
          this.addUserProjectAndAuthHeaders(opts.headers, requestHeaders);
          response = await this.transporter.request(opts);
        } catch (e4) {
          const res = e4.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 e4;
        }
        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() {
        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 = this.authClient.credentials?.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;
  }
});

// packages/cli/node_modules/google-auth-library/build/src/auth/passthrough.js
var require_passthrough2 = __commonJS({
  "packages/cli/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_authclient2();
    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 new Headers();
      }
    };
    exports2.PassThroughClient = PassThroughClient;
  }
});

// packages/cli/node_modules/google-auth-library/build/src/index.js
var require_src44 = __commonJS({
  "packages/cli/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.PassThroughClient = exports2.ExternalAccountAuthorizedUserClient = exports2.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE = 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_googleauth2();
    Object.defineProperty(exports2, "GoogleAuth", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return googleauth_1.GoogleAuth;
    }, "get") });
    exports2.gcpMetadata = require_src42();
    exports2.gaxios = require_src40();
    var authclient_1 = require_authclient2();
    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_computeclient2();
    Object.defineProperty(exports2, "Compute", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return computeclient_1.Compute;
    }, "get") });
    var envDetect_1 = require_envDetect2();
    Object.defineProperty(exports2, "GCPEnv", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return envDetect_1.GCPEnv;
    }, "get") });
    var iam_1 = require_iam2();
    Object.defineProperty(exports2, "IAMAuth", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return iam_1.IAMAuth;
    }, "get") });
    var idtokenclient_1 = require_idtokenclient2();
    Object.defineProperty(exports2, "IdTokenClient", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return idtokenclient_1.IdTokenClient;
    }, "get") });
    var jwtaccess_1 = require_jwtaccess2();
    Object.defineProperty(exports2, "JWTAccess", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return jwtaccess_1.JWTAccess;
    }, "get") });
    var jwtclient_1 = require_jwtclient2();
    Object.defineProperty(exports2, "JWT", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return jwtclient_1.JWT;
    }, "get") });
    var impersonated_1 = require_impersonated2();
    Object.defineProperty(exports2, "Impersonated", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return impersonated_1.Impersonated;
    }, "get") });
    var oauth2client_1 = require_oauth2client2();
    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_loginticket2();
    Object.defineProperty(exports2, "LoginTicket", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return loginticket_1.LoginTicket;
    }, "get") });
    var refreshclient_1 = require_refreshclient2();
    Object.defineProperty(exports2, "UserRefreshClient", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return refreshclient_1.UserRefreshClient;
    }, "get") });
    var awsclient_1 = require_awsclient2();
    Object.defineProperty(exports2, "AwsClient", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return awsclient_1.AwsClient;
    }, "get") });
    var awsrequestsigner_1 = require_awsrequestsigner2();
    Object.defineProperty(exports2, "AwsRequestSigner", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return awsrequestsigner_1.AwsRequestSigner;
    }, "get") });
    var identitypoolclient_1 = require_identitypoolclient2();
    Object.defineProperty(exports2, "IdentityPoolClient", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return identitypoolclient_1.IdentityPoolClient;
    }, "get") });
    var externalclient_1 = require_externalclient2();
    Object.defineProperty(exports2, "ExternalAccountClient", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return externalclient_1.ExternalAccountClient;
    }, "get") });
    var baseexternalclient_1 = require_baseexternalclient2();
    Object.defineProperty(exports2, "BaseExternalAccountClient", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return baseexternalclient_1.BaseExternalAccountClient;
    }, "get") });
    var downscopedclient_1 = require_downscopedclient2();
    Object.defineProperty(exports2, "DownscopedClient", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return downscopedclient_1.DownscopedClient;
    }, "get") });
    var pluggable_auth_client_1 = require_pluggable_auth_client2();
    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 externalAccountAuthorizedUserClient_1 = require_externalAccountAuthorizedUserClient2();
    Object.defineProperty(exports2, "EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return externalAccountAuthorizedUserClient_1.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE;
    }, "get") });
    Object.defineProperty(exports2, "ExternalAccountAuthorizedUserClient", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return externalAccountAuthorizedUserClient_1.ExternalAccountAuthorizedUserClient;
    }, "get") });
    var passthrough_1 = require_passthrough2();
    Object.defineProperty(exports2, "PassThroughClient", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return passthrough_1.PassThroughClient;
    }, "get") });
    var auth2 = new googleauth_1.GoogleAuth();
    exports2.auth = auth2;
  }
});

// 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 platform16 = process.env.GRACEFUL_FS_PLATFORM || process.platform;
    process.cwd = function() {
      if (!cwd7)
        cwd7 = origCwd.call(process);
      return cwd7;
    };
    try {
      process.cwd();
    } catch (er2) {
    }
    if (typeof process.chdir === "function") {
      chdir = process.chdir;
      process.chdir = function(d2) {
        cwd7 = null;
        chdir.call(process, d2);
      };
      if (Object.setPrototypeOf) Object.setPrototypeOf(process.chdir, chdir);
    }
    var chdir;
    module2.exports = patch;
    function patch(fs113) {
      if (constants4.hasOwnProperty("O_SYMLINK") && process.version.match(/^v0\.6\.[0-2]|^v0\.5\./)) {
        patchLchmod(fs113);
      }
      if (!fs113.lutimes) {
        patchLutimes(fs113);
      }
      fs113.chown = chownFix(fs113.chown);
      fs113.fchown = chownFix(fs113.fchown);
      fs113.lchown = chownFix(fs113.lchown);
      fs113.chmod = chmodFix(fs113.chmod);
      fs113.fchmod = chmodFix(fs113.fchmod);
      fs113.lchmod = chmodFix(fs113.lchmod);
      fs113.chownSync = chownFixSync(fs113.chownSync);
      fs113.fchownSync = chownFixSync(fs113.fchownSync);
      fs113.lchownSync = chownFixSync(fs113.lchownSync);
      fs113.chmodSync = chmodFixSync(fs113.chmodSync);
      fs113.fchmodSync = chmodFixSync(fs113.fchmodSync);
      fs113.lchmodSync = chmodFixSync(fs113.lchmodSync);
      fs113.stat = statFix(fs113.stat);
      fs113.fstat = statFix(fs113.fstat);
      fs113.lstat = statFix(fs113.lstat);
      fs113.statSync = statFixSync(fs113.statSync);
      fs113.fstatSync = statFixSync(fs113.fstatSync);
      fs113.lstatSync = statFixSync(fs113.lstatSync);
      if (fs113.chmod && !fs113.lchmod) {
        fs113.lchmod = function(path125, mode, cb) {
          if (cb) process.nextTick(cb);
        };
        fs113.lchmodSync = function() {
        };
      }
      if (fs113.chown && !fs113.lchown) {
        fs113.lchown = function(path125, uid, gid, cb) {
          if (cb) process.nextTick(cb);
        };
        fs113.lchownSync = function() {
        };
      }
      if (platform16 === "win32") {
        fs113.rename = typeof fs113.rename !== "function" ? fs113.rename : function(fs$rename) {
          function rename(from, to, cb) {
            var start = Date.now();
            var backoff = 0;
            fs$rename(from, to, /* @__PURE__ */ __name(function CB(er2) {
              if (er2 && (er2.code === "EACCES" || er2.code === "EPERM" || er2.code === "EBUSY") && Date.now() - start < 6e4) {
                setTimeout(function() {
                  fs113.stat(to, function(stater, st2) {
                    if (stater && stater.code === "ENOENT")
                      fs$rename(from, to, CB);
                    else
                      cb(er2);
                  });
                }, backoff);
                if (backoff < 100)
                  backoff += 10;
                return;
              }
              if (cb) cb(er2);
            }, "CB"));
          }
          __name(rename, "rename");
          if (Object.setPrototypeOf) Object.setPrototypeOf(rename, fs$rename);
          return rename;
        }(fs113.rename);
      }
      fs113.read = typeof fs113.read !== "function" ? fs113.read : function(fs$read) {
        function read3(fd, buffer, offset, length, position, callback_) {
          var callback;
          if (callback_ && typeof callback_ === "function") {
            var eagCounter = 0;
            callback = /* @__PURE__ */ __name(function(er2, _2, __) {
              if (er2 && er2.code === "EAGAIN" && eagCounter < 10) {
                eagCounter++;
                return fs$read.call(fs113, fd, buffer, offset, length, position, callback);
              }
              callback_.apply(this, arguments);
            }, "callback");
          }
          return fs$read.call(fs113, fd, buffer, offset, length, position, callback);
        }
        __name(read3, "read");
        if (Object.setPrototypeOf) Object.setPrototypeOf(read3, fs$read);
        return read3;
      }(fs113.read);
      fs113.readSync = typeof fs113.readSync !== "function" ? fs113.readSync : /* @__PURE__ */ function(fs$readSync) {
        return function(fd, buffer, offset, length, position) {
          var eagCounter = 0;
          while (true) {
            try {
              return fs$readSync.call(fs113, fd, buffer, offset, length, position);
            } catch (er2) {
              if (er2.code === "EAGAIN" && eagCounter < 10) {
                eagCounter++;
                continue;
              }
              throw er2;
            }
          }
        };
      }(fs113.readSync);
      function patchLchmod(fs114) {
        fs114.lchmod = function(path125, mode, callback) {
          fs114.open(
            path125,
            constants4.O_WRONLY | constants4.O_SYMLINK,
            mode,
            function(err, fd) {
              if (err) {
                if (callback) callback(err);
                return;
              }
              fs114.fchmod(fd, mode, function(err2) {
                fs114.close(fd, function(err22) {
                  if (callback) callback(err2 || err22);
                });
              });
            }
          );
        };
        fs114.lchmodSync = function(path125, mode) {
          var fd = fs114.openSync(path125, constants4.O_WRONLY | constants4.O_SYMLINK, mode);
          var threw = true;
          var ret;
          try {
            ret = fs114.fchmodSync(fd, mode);
            threw = false;
          } finally {
            if (threw) {
              try {
                fs114.closeSync(fd);
              } catch (er2) {
              }
            } else {
              fs114.closeSync(fd);
            }
          }
          return ret;
        };
      }
      __name(patchLchmod, "patchLchmod");
      function patchLutimes(fs114) {
        if (constants4.hasOwnProperty("O_SYMLINK") && fs114.futimes) {
          fs114.lutimes = function(path125, at2, mt2, cb) {
            fs114.open(path125, constants4.O_SYMLINK, function(er2, fd) {
              if (er2) {
                if (cb) cb(er2);
                return;
              }
              fs114.futimes(fd, at2, mt2, function(er3) {
                fs114.close(fd, function(er22) {
                  if (cb) cb(er3 || er22);
                });
              });
            });
          };
          fs114.lutimesSync = function(path125, at2, mt2) {
            var fd = fs114.openSync(path125, constants4.O_SYMLINK);
            var ret;
            var threw = true;
            try {
              ret = fs114.futimesSync(fd, at2, mt2);
              threw = false;
            } finally {
              if (threw) {
                try {
                  fs114.closeSync(fd);
                } catch (er2) {
                }
              } else {
                fs114.closeSync(fd);
              }
            }
            return ret;
          };
        } else if (fs114.futimes) {
          fs114.lutimes = function(_a7, _b2, _c2, cb) {
            if (cb) process.nextTick(cb);
          };
          fs114.lutimesSync = function() {
          };
        }
      }
      __name(patchLutimes, "patchLutimes");
      function chmodFix(orig) {
        if (!orig) return orig;
        return function(target, mode, cb) {
          return orig.call(fs113, target, mode, function(er2) {
            if (chownErOk(er2)) er2 = 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(fs113, target, mode);
          } catch (er2) {
            if (!chownErOk(er2)) throw er2;
          }
        };
      }
      __name(chmodFixSync, "chmodFixSync");
      function chownFix(orig) {
        if (!orig) return orig;
        return function(target, uid, gid, cb) {
          return orig.call(fs113, target, uid, gid, function(er2) {
            if (chownErOk(er2)) er2 = 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(fs113, target, uid, gid);
          } catch (er2) {
            if (!chownErOk(er2)) throw er2;
          }
        };
      }
      __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(er2, 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(fs113, target, options2, callback) : orig.call(fs113, target, callback);
        };
      }
      __name(statFix, "statFix");
      function statFixSync(orig) {
        if (!orig) return orig;
        return function(target, options2) {
          var stats = options2 ? orig.call(fs113, target, options2) : orig.call(fs113, target);
          if (stats) {
            if (stats.uid < 0) stats.uid += 4294967296;
            if (stats.gid < 0) stats.gid += 4294967296;
          }
          return stats;
        };
      }
      __name(statFixSync, "statFixSync");
      function chownErOk(er2) {
        if (!er2)
          return true;
        if (er2.code === "ENOSYS")
          return true;
        var nonroot = !process.getuid || process.getuid() !== 0;
        if (nonroot) {
          if (er2.code === "EINVAL" || er2.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 Stream9 = __require("stream").Stream;
    module2.exports = legacy;
    function legacy(fs113) {
      return {
        ReadStream: ReadStream2,
        WriteStream: WriteStream2
      };
      function ReadStream2(path125, options2) {
        if (!(this instanceof ReadStream2)) return new ReadStream2(path125, options2);
        Stream9.call(this);
        var self2 = this;
        this.path = path125;
        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;
        }
        fs113.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(path125, options2) {
        if (!(this instanceof WriteStream2)) return new WriteStream2(path125, options2);
        Stream9.call(this);
        this.path = path125;
        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 = fs113.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 = clone4;
    var getPrototypeOf = Object.getPrototypeOf || function(obj) {
      return obj.__proto__;
    };
    function clone4(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(clone4, "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 fs113 = __require("fs");
    var polyfills = require_polyfills();
    var legacy = require_legacy_streams();
    var clone4 = require_clone();
    var util3 = __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 noop8() {
    }
    __name(noop8, "noop");
    function publishQueue(context2, queue2) {
      Object.defineProperty(context2, gracefulQueue, {
        get: /* @__PURE__ */ __name(function() {
          return queue2;
        }, "get")
      });
    }
    __name(publishQueue, "publishQueue");
    var debug3 = noop8;
    if (util3.debuglog)
      debug3 = util3.debuglog("gfs4");
    else if (/\bgfs4\b/i.test(process.env.NODE_DEBUG || ""))
      debug3 = /* @__PURE__ */ __name(function() {
        var m3 = util3.format.apply(util3, arguments);
        m3 = "GFS4: " + m3.split(/\n/).join("\nGFS4: ");
        console.error(m3);
      }, "debug");
    if (!fs113[gracefulQueue]) {
      queue = globalThis[gracefulQueue] || [];
      publishQueue(fs113, queue);
      fs113.close = function(fs$close) {
        function close(fd, cb) {
          return fs$close.call(fs113, 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;
      }(fs113.close);
      fs113.closeSync = function(fs$closeSync) {
        function closeSync(fd) {
          fs$closeSync.apply(fs113, arguments);
          resetQueue();
        }
        __name(closeSync, "closeSync");
        Object.defineProperty(closeSync, previousSymbol, {
          value: fs$closeSync
        });
        return closeSync;
      }(fs113.closeSync);
      if (/\bgfs4\b/i.test(process.env.NODE_DEBUG || "")) {
        process.on("exit", function() {
          debug3(fs113[gracefulQueue]);
          __require("assert").equal(fs113[gracefulQueue].length, 0);
        });
      }
    }
    var queue;
    if (!globalThis[gracefulQueue]) {
      publishQueue(globalThis, fs113[gracefulQueue]);
    }
    module2.exports = patch(clone4(fs113));
    if (process.env.TEST_GRACEFUL_FS_GLOBAL_PATCH && !fs113.__patched) {
      module2.exports = patch(fs113);
      fs113.__patched = true;
    }
    function patch(fs114) {
      polyfills(fs114);
      fs114.gracefulify = patch;
      fs114.createReadStream = createReadStream3;
      fs114.createWriteStream = createWriteStream5;
      var fs$readFile = fs114.readFile;
      fs114.readFile = readFile13;
      function readFile13(path125, options2, cb) {
        if (typeof options2 === "function")
          cb = options2, options2 = null;
        return go$readFile(path125, options2, cb);
        function go$readFile(path126, options3, cb2, startTime) {
          return fs$readFile(path126, options3, function(err) {
            if (err && (err.code === "EMFILE" || err.code === "ENFILE"))
              enqueue([go$readFile, [path126, options3, cb2], err, startTime || Date.now(), Date.now()]);
            else {
              if (typeof cb2 === "function")
                cb2.apply(this, arguments);
            }
          });
        }
        __name(go$readFile, "go$readFile");
      }
      __name(readFile13, "readFile");
      var fs$writeFile = fs114.writeFile;
      fs114.writeFile = writeFile14;
      function writeFile14(path125, data, options2, cb) {
        if (typeof options2 === "function")
          cb = options2, options2 = null;
        return go$writeFile(path125, data, options2, cb);
        function go$writeFile(path126, data2, options3, cb2, startTime) {
          return fs$writeFile(path126, data2, options3, function(err) {
            if (err && (err.code === "EMFILE" || err.code === "ENFILE"))
              enqueue([go$writeFile, [path126, data2, options3, cb2], err, startTime || Date.now(), Date.now()]);
            else {
              if (typeof cb2 === "function")
                cb2.apply(this, arguments);
            }
          });
        }
        __name(go$writeFile, "go$writeFile");
      }
      __name(writeFile14, "writeFile");
      var fs$appendFile = fs114.appendFile;
      if (fs$appendFile)
        fs114.appendFile = appendFile;
      function appendFile(path125, data, options2, cb) {
        if (typeof options2 === "function")
          cb = options2, options2 = null;
        return go$appendFile(path125, data, options2, cb);
        function go$appendFile(path126, data2, options3, cb2, startTime) {
          return fs$appendFile(path126, data2, options3, function(err) {
            if (err && (err.code === "EMFILE" || err.code === "ENFILE"))
              enqueue([go$appendFile, [path126, 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 = fs114.copyFile;
      if (fs$copyFile)
        fs114.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 = fs114.readdir;
      fs114.readdir = readdir12;
      var noReaddirOptionVersions = /^v[0-5]\./;
      function readdir12(path125, options2, cb) {
        if (typeof options2 === "function")
          cb = options2, options2 = null;
        var go$readdir = noReaddirOptionVersions.test(process.version) ? /* @__PURE__ */ __name(function go$readdir2(path126, options3, cb2, startTime) {
          return fs$readdir(path126, fs$readdirCallback(
            path126,
            options3,
            cb2,
            startTime
          ));
        }, "go$readdir") : /* @__PURE__ */ __name(function go$readdir2(path126, options3, cb2, startTime) {
          return fs$readdir(path126, options3, fs$readdirCallback(
            path126,
            options3,
            cb2,
            startTime
          ));
        }, "go$readdir");
        return go$readdir(path125, options2, cb);
        function fs$readdirCallback(path126, options3, cb2, startTime) {
          return function(err, files) {
            if (err && (err.code === "EMFILE" || err.code === "ENFILE"))
              enqueue([
                go$readdir,
                [path126, 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(readdir12, "readdir");
      if (process.version.substr(0, 4) === "v0.8") {
        var legStreams = legacy(fs114);
        ReadStream2 = legStreams.ReadStream;
        WriteStream2 = legStreams.WriteStream;
      }
      var fs$ReadStream = fs114.ReadStream;
      if (fs$ReadStream) {
        ReadStream2.prototype = Object.create(fs$ReadStream.prototype);
        ReadStream2.prototype.open = ReadStream$open;
      }
      var fs$WriteStream = fs114.WriteStream;
      if (fs$WriteStream) {
        WriteStream2.prototype = Object.create(fs$WriteStream.prototype);
        WriteStream2.prototype.open = WriteStream$open;
      }
      Object.defineProperty(fs114, "ReadStream", {
        get: /* @__PURE__ */ __name(function() {
          return ReadStream2;
        }, "get"),
        set: /* @__PURE__ */ __name(function(val) {
          ReadStream2 = val;
        }, "set"),
        enumerable: true,
        configurable: true
      });
      Object.defineProperty(fs114, "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(fs114, "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(fs114, "FileWriteStream", {
        get: /* @__PURE__ */ __name(function() {
          return FileWriteStream;
        }, "get"),
        set: /* @__PURE__ */ __name(function(val) {
          FileWriteStream = val;
        }, "set"),
        enumerable: true,
        configurable: true
      });
      function ReadStream2(path125, 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;
        open4(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(path125, 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;
        open4(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 createReadStream3(path125, options2) {
        return new fs114.ReadStream(path125, options2);
      }
      __name(createReadStream3, "createReadStream");
      function createWriteStream5(path125, options2) {
        return new fs114.WriteStream(path125, options2);
      }
      __name(createWriteStream5, "createWriteStream");
      var fs$open = fs114.open;
      fs114.open = open4;
      function open4(path125, flags, mode, cb) {
        if (typeof mode === "function")
          cb = mode, mode = null;
        return go$open(path125, flags, mode, cb);
        function go$open(path126, flags2, mode2, cb2, startTime) {
          return fs$open(path126, flags2, mode2, function(err, fd) {
            if (err && (err.code === "EMFILE" || err.code === "ENFILE"))
              enqueue([go$open, [path126, flags2, mode2, cb2], err, startTime || Date.now(), Date.now()]);
            else {
              if (typeof cb2 === "function")
                cb2.apply(this, arguments);
            }
          });
        }
        __name(go$open, "go$open");
      }
      __name(open4, "open");
      return fs114;
    }
    __name(patch, "patch");
    function enqueue(elem) {
      debug3("ENQUEUE", elem[0].name, elem[1]);
      fs113[gracefulQueue].push(elem);
      retry();
    }
    __name(enqueue, "enqueue");
    var retryTimer;
    function resetQueue() {
      var now = Date.now();
      for (var i3 = 0; i3 < fs113[gracefulQueue].length; ++i3) {
        if (fs113[gracefulQueue][i3].length > 2) {
          fs113[gracefulQueue][i3][3] = now;
          fs113[gracefulQueue][i3][4] = now;
        }
      }
      retry();
    }
    __name(resetQueue, "resetQueue");
    function retry() {
      clearTimeout(retryTimer);
      retryTimer = void 0;
      if (fs113[gracefulQueue].length === 0)
        return;
      var elem = fs113[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) {
        debug3("RETRY", fn.name, args);
        fn.apply(null, args);
      } else if (Date.now() - startTime >= 6e4) {
        debug3("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) {
          debug3("RETRY", fn.name, args);
          fn.apply(null, args.concat([startTime]));
        } else {
          fs113[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 parse14 = require_parse9();
    var diff4 = /* @__PURE__ */ __name((version1, version2) => {
      const v1 = parse14(version1, null, true);
      const v2 = parse14(version2, null, true);
      const comparison = v1.compare(v2);
      if (comparison === 0) {
        return null;
      }
      const v1Higher = comparison > 0;
      const highVersion = v1Higher ? v1 : v2;
      const lowVersion = v1Higher ? v2 : v1;
      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 (v1.major !== v2.major) {
        return prefix + "major";
      }
      if (v1.minor !== v2.minor) {
        return prefix + "minor";
      }
      if (v1.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((a2, b2, loose) => new SemVer(a2, loose).compare(new SemVer(b2, 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 gt2 = /* @__PURE__ */ __name((a2, b2, loose) => compare(a2, b2, loose) > 0, "gt");
    module2.exports = gt2;
  }
});

// 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(k2, _2, __) {
        var val = obj[k2];
        if (val && Array.isArray(val)) {
          val.forEach(function(item) {
            out += safe(k2 + "[]") + separator + safe(item) + "\n";
          });
        } else if (val && typeof val === "object")
          children.push(k2);
        else
          out += safe(k2) + separator + safe(val) + eol;
      });
      if (opt.section && out.length)
        out = "[" + safe(opt.section) + "]" + eol + out;
      children.forEach(function(k2, _2, __) {
        var nk = dotSplit(k2).join("\\.");
        var section = (opt.section ? opt.section + "." : "") + nk;
        var child = encode4(obj[k2], {
          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 p2 = out;
      var section = null;
      var re3 = /^\[([^\]]*)\]$|^([^=]+)(=(.*))?$/i;
      var lines = str2.split(/[\r\n]+/g);
      lines.forEach(function(line, _2, __) {
        if (!line || line.match(/^\s*[;#]/))
          return;
        var match2 = line.match(re3);
        if (!match2)
          return;
        if (match2[1] !== void 0) {
          section = unsafe(match2[1]);
          if (section === "__proto__") {
            p2 = {};
            return;
          }
          p2 = 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 (!p2[key])
            p2[key] = [];
          else if (!Array.isArray(p2[key]))
            p2[key] = [p2[key]];
        }
        if (Array.isArray(p2[key]))
          p2[key].push(value);
        else
          p2[key] = value;
      });
      Object.keys(out).filter(function(k2, _2, __) {
        if (!out[k2] || typeof out[k2] !== "object" || Array.isArray(out[k2]))
          return false;
        var parts = dotSplit(k2);
        var p3 = out;
        var l3 = parts.pop();
        var nl2 = l3.replace(/\\\./g, ".");
        parts.forEach(function(part, _3, __2) {
          if (part === "__proto__")
            return;
          if (!p3[part] || typeof p3[part] !== "object")
            p3[part] = {};
          p3 = p3[part];
        });
        if (p3 === out && nl2 === l3)
          return false;
        p3[nl2] = out[k2];
        return true;
      }).forEach(function(del, _2, __) {
        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 (_2) {
        }
      } else {
        var esc2 = false;
        var unesc = "";
        for (var i3 = 0, l3 = val.length; i3 < l3; i3++) {
          var c4 = val.charAt(i3);
          if (esc2) {
            if ("\\;#".indexOf(c4) !== -1)
              unesc += c4;
            else
              unesc += "\\" + c4;
            esc2 = false;
          } else if (";#".indexOf(c4) !== -1)
            break;
          else if (c4 === "\\")
            esc2 = true;
          else
            unesc += c4;
        }
        if (esc2)
          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 strip2 = opts.whitespace === false ? stripWithoutWhitespace : stripWithWhitespace;
      for (var i3 = 0; i3 < str2.length; i3++) {
        currentChar = str2[i3];
        nextChar = str2[i3 + 1];
        if (!insideComment && currentChar === '"') {
          var escaped = str2[i3 - 1] === "\\" && str2[i3 - 2] !== "\\";
          if (!escaped) {
            insideString = !insideString;
          }
        }
        if (insideString) {
          continue;
        }
        if (!insideComment && currentChar + nextChar === "//") {
          ret += str2.slice(offset, i3);
          offset = i3;
          insideComment = singleComment;
          i3++;
        } else if (insideComment === singleComment && currentChar + nextChar === "\r\n") {
          i3++;
          insideComment = false;
          ret += strip2(str2, offset, i3);
          offset = i3;
          continue;
        } else if (insideComment === singleComment && currentChar === "\n") {
          insideComment = false;
          ret += strip2(str2, offset, i3);
          offset = i3;
        } else if (!insideComment && currentChar + nextChar === "/*") {
          ret += str2.slice(offset, i3);
          offset = i3;
          insideComment = multiComment;
          i3++;
          continue;
        } else if (insideComment === multiComment && currentChar + nextChar === "*/") {
          i3++;
          insideComment = false;
          ret += strip2(str2, offset, i3 + 1);
          offset = i3 + 1;
          continue;
        }
      }
      return ret + (insideComment ? strip2(str2.substr(offset)) : str2.substr(offset));
    };
  }
});

// node_modules/rc/lib/utils.js
var require_utils17 = __commonJS({
  "node_modules/rc/lib/utils.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    var fs113 = __require("fs");
    var ini3 = require_ini();
    var path125 = __require("path");
    var stripJsonComments5 = require_strip_json_comments2();
    var parse14 = exports2.parse = function(content) {
      if (/^\s*{/.test(content))
        return JSON.parse(stripJsonComments5(content));
      return ini3.parse(content);
    };
    var file = exports2.file = function() {
      var args = [].slice.call(arguments).filter(function(arg) {
        return arg != null;
      });
      for (var i3 in args)
        if ("string" !== typeof args[i3])
          return;
      var file2 = path125.join.apply(null, args);
      var content;
      try {
        return fs113.readFileSync(file2, "utf-8");
      } catch (err) {
        return;
      }
    };
    var json2 = exports2.json = function() {
      var content = file.apply(null, arguments);
      return content ? parse14(content) : null;
    };
    var env7 = exports2.env = function(prefix, env8) {
      env8 = env8 || process.env;
      var obj = {};
      var l3 = prefix.length;
      for (var k2 in env8) {
        if (k2.toLowerCase().indexOf(prefix.toLowerCase()) === 0) {
          var keypath = k2.substring(l3).split("__");
          var _emptyStringIndex;
          while ((_emptyStringIndex = keypath.indexOf("")) > -1) {
            keypath.splice(_emptyStringIndex, 1);
          }
          var cursor = obj;
          keypath.forEach(/* @__PURE__ */ __name(function _buildSubObj(_subkey, i3) {
            if (!_subkey || typeof cursor !== "object")
              return;
            if (i3 === keypath.length - 1)
              cursor[_subkey] = env8[k2];
            if (cursor[_subkey] === void 0)
              cursor[_subkey] = {};
            cursor = cursor[_subkey];
          }, "_buildSubObj"));
        }
      }
      return obj;
    };
    var find = exports2.find = function() {
      var rel = path125.join.apply(null, [].slice.call(arguments));
      function find2(start, rel2) {
        var file2 = path125.join(start, rel2);
        try {
          fs113.statSync(file2);
          return file2;
        } catch (err) {
          if (path125.dirname(start) !== start)
            return find2(path125.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 x3 = Buffer.alloc ? Buffer.alloc(val.length) : new Buffer(val.length);
        val.copy(x3);
        return x3;
      } 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 clone4 = [];
      arr.forEach(function(item, index) {
        if (typeof item === "object" && item !== null) {
          if (Array.isArray(item)) {
            clone4[index] = deepCloneArray(item);
          } else if (isSpecificValue(item)) {
            clone4[index] = cloneSpecificValue(item);
          } else {
            clone4[index] = deepExtend({}, item);
          }
        } else {
          clone4[index] = item;
        }
      });
      return clone4;
    }
    __name(deepCloneArray, "deepCloneArray");
    function safeGetProperty(object3, property) {
      return property === "__proto__" ? void 0 : object3[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, clone4;
      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 o3 = obj;
      keys.slice(0, -1).forEach(function(key2) {
        o3 = o3[key2] || {};
      });
      var key = keys[keys.length - 1];
      return key in o3;
    }
    __name(hasKey2, "hasKey");
    function isNumber3(x3) {
      if (typeof x3 === "number") {
        return true;
      }
      if (/^0x[0-9a-f]+$/i.test(x3)) {
        return true;
      }
      return /^[-+]?(?:\d+(?:\.\d*)?|\.\d+)(e[-+]?\d+)?$/.test(x3);
    }
    __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(x3) {
          return flags.bools[x3];
        });
      }
      __name(aliasIsBoolean, "aliasIsBoolean");
      Object.keys(opts.alias || {}).forEach(function(key2) {
        aliases[key2] = [].concat(opts.alias[key2]);
        aliases[key2].forEach(function(x3) {
          aliases[x3] = [key2].concat(aliases[key2].filter(function(y2) {
            return x3 !== y2;
          }));
        });
      });
      [].concat(opts.string).filter(Boolean).forEach(function(key2) {
        flags.strings[key2] = true;
        if (aliases[key2]) {
          [].concat(aliases[key2]).forEach(function(k2) {
            flags.strings[k2] = 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 o3 = obj;
        for (var i4 = 0; i4 < keys.length - 1; i4++) {
          var key2 = keys[i4];
          if (isConstructorOrProto(o3, key2)) {
            return;
          }
          if (o3[key2] === void 0) {
            o3[key2] = {};
          }
          if (o3[key2] === Object.prototype || o3[key2] === Number.prototype || o3[key2] === String.prototype) {
            o3[key2] = {};
          }
          if (o3[key2] === Array.prototype) {
            o3[key2] = [];
          }
          o3 = o3[key2];
        }
        var lastKey = keys[keys.length - 1];
        if (isConstructorOrProto(o3, lastKey)) {
          return;
        }
        if (o3 === Object.prototype || o3 === Number.prototype || o3 === String.prototype) {
          o3 = {};
        }
        if (o3 === Array.prototype) {
          o3 = [];
        }
        if (o3[lastKey] === void 0 || flags.bools[lastKey] || typeof o3[lastKey] === "boolean") {
          o3[lastKey] = value2;
        } else if (Array.isArray(o3[lastKey])) {
          o3[lastKey].push(value2);
        } else {
          o3[lastKey] = [o3[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(x3) {
          setKey(argv, x3.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 i3 = 0; i3 < args.length; i3++) {
        var arg = args[i3];
        var key;
        var next;
        if (/^--.+=/.test(arg)) {
          var m3 = arg.match(/^--([^=]+)=([\s\S]*)$/);
          key = m3[1];
          var value = m3[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[i3 + 1];
          if (next !== void 0 && !/^(-|--)[^-]/.test(next) && !flags.bools[key] && !flags.allBools && (aliases[key] ? !aliasIsBoolean(key) : true)) {
            setArg(key, next, arg);
            i3 += 1;
          } else if (/^(true|false)$/.test(next)) {
            setArg(key, next === "true", arg);
            i3 += 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 j2 = 0; j2 < letters.length; j2++) {
            next = arg.slice(j2 + 2);
            if (next === "-") {
              setArg(letters[j2], next, arg);
              continue;
            }
            if (/[A-Za-z]/.test(letters[j2]) && next[0] === "=") {
              setArg(letters[j2], next.slice(1), arg);
              broken = true;
              break;
            }
            if (/[A-Za-z]/.test(letters[j2]) && /-?\d+(\.\d*)?(e-?\d+)?$/.test(next)) {
              setArg(letters[j2], next, arg);
              broken = true;
              break;
            }
            if (letters[j2 + 1] && letters[j2 + 1].match(/\W/)) {
              setArg(letters[j2], arg.slice(j2 + 2), arg);
              broken = true;
              break;
            } else {
              setArg(letters[j2], flags.strings[letters[j2]] ? "" : true, arg);
            }
          }
          key = arg.slice(-1)[0];
          if (!broken && key !== "-") {
            if (args[i3 + 1] && !/^(-|--)[^-]/.test(args[i3 + 1]) && !flags.bools[key] && (aliases[key] ? !aliasIsBoolean(key) : true)) {
              setArg(key, args[i3 + 1], arg);
              i3 += 1;
            } else if (args[i3 + 1] && /^(true|false)$/.test(args[i3 + 1])) {
              setArg(key, args[i3 + 1] === "true", arg);
              i3 += 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(i3 + 1));
            break;
          }
        }
      }
      Object.keys(defaults3).forEach(function(k2) {
        if (!hasKey2(argv, k2.split("."))) {
          setKey(argv, k2.split("."), defaults3[k2]);
          (aliases[k2] || []).forEach(function(x3) {
            setKey(argv, x3.split("."), defaults3[k2]);
          });
        }
      });
      if (opts["--"]) {
        argv["--"] = notFlags.slice();
      } else {
        notFlags.forEach(function(k2) {
          argv._.push(k2);
        });
      }
      return argv;
    };
  }
});

// node_modules/rc/index.js
var require_rc = __commonJS({
  "node_modules/rc/index.js"(exports2, module2) {
    init_esbuild_shims();
    var cc = require_utils17();
    var join45 = __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, parse14) {
      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) || {};
      parse14 = parse14 || 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(parse14(fileConfig));
          configFiles.push(file);
        }
      }
      __name(addConfigFile, "addConfigFile");
      if (!win2)
        [
          join45(etc, name3, "config"),
          join45(etc, name3 + "rc")
        ].forEach(addConfigFile);
      if (home)
        [
          join45(home, ".config", name3, "config"),
          join45(home, ".config", name3),
          join45(home, "." + name3, "config"),
          join45(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 platform16 = process.env.GRACEFUL_FS_PLATFORM || process.platform;
    process.cwd = function() {
      if (!cwd7)
        cwd7 = origCwd.call(process);
      return cwd7;
    };
    try {
      process.cwd();
    } catch (er2) {
    }
    if (typeof process.chdir === "function") {
      chdir = process.chdir;
      process.chdir = function(d2) {
        cwd7 = null;
        chdir.call(process, d2);
      };
      if (Object.setPrototypeOf) Object.setPrototypeOf(process.chdir, chdir);
    }
    var chdir;
    module2.exports = patch;
    function patch(fs113) {
      if (constants4.hasOwnProperty("O_SYMLINK") && process.version.match(/^v0\.6\.[0-2]|^v0\.5\./)) {
        patchLchmod(fs113);
      }
      if (!fs113.lutimes) {
        patchLutimes(fs113);
      }
      fs113.chown = chownFix(fs113.chown);
      fs113.fchown = chownFix(fs113.fchown);
      fs113.lchown = chownFix(fs113.lchown);
      fs113.chmod = chmodFix(fs113.chmod);
      fs113.fchmod = chmodFix(fs113.fchmod);
      fs113.lchmod = chmodFix(fs113.lchmod);
      fs113.chownSync = chownFixSync(fs113.chownSync);
      fs113.fchownSync = chownFixSync(fs113.fchownSync);
      fs113.lchownSync = chownFixSync(fs113.lchownSync);
      fs113.chmodSync = chmodFixSync(fs113.chmodSync);
      fs113.fchmodSync = chmodFixSync(fs113.fchmodSync);
      fs113.lchmodSync = chmodFixSync(fs113.lchmodSync);
      fs113.stat = statFix(fs113.stat);
      fs113.fstat = statFix(fs113.fstat);
      fs113.lstat = statFix(fs113.lstat);
      fs113.statSync = statFixSync(fs113.statSync);
      fs113.fstatSync = statFixSync(fs113.fstatSync);
      fs113.lstatSync = statFixSync(fs113.lstatSync);
      if (fs113.chmod && !fs113.lchmod) {
        fs113.lchmod = function(path125, mode, cb) {
          if (cb) process.nextTick(cb);
        };
        fs113.lchmodSync = function() {
        };
      }
      if (fs113.chown && !fs113.lchown) {
        fs113.lchown = function(path125, uid, gid, cb) {
          if (cb) process.nextTick(cb);
        };
        fs113.lchownSync = function() {
        };
      }
      if (platform16 === "win32") {
        fs113.rename = typeof fs113.rename !== "function" ? fs113.rename : function(fs$rename) {
          function rename(from, to, cb) {
            var start = Date.now();
            var backoff = 0;
            fs$rename(from, to, /* @__PURE__ */ __name(function CB(er2) {
              if (er2 && (er2.code === "EACCES" || er2.code === "EPERM") && Date.now() - start < 6e4) {
                setTimeout(function() {
                  fs113.stat(to, function(stater, st2) {
                    if (stater && stater.code === "ENOENT")
                      fs$rename(from, to, CB);
                    else
                      cb(er2);
                  });
                }, backoff);
                if (backoff < 100)
                  backoff += 10;
                return;
              }
              if (cb) cb(er2);
            }, "CB"));
          }
          __name(rename, "rename");
          if (Object.setPrototypeOf) Object.setPrototypeOf(rename, fs$rename);
          return rename;
        }(fs113.rename);
      }
      fs113.read = typeof fs113.read !== "function" ? fs113.read : function(fs$read) {
        function read3(fd, buffer, offset, length, position, callback_) {
          var callback;
          if (callback_ && typeof callback_ === "function") {
            var eagCounter = 0;
            callback = /* @__PURE__ */ __name(function(er2, _2, __) {
              if (er2 && er2.code === "EAGAIN" && eagCounter < 10) {
                eagCounter++;
                return fs$read.call(fs113, fd, buffer, offset, length, position, callback);
              }
              callback_.apply(this, arguments);
            }, "callback");
          }
          return fs$read.call(fs113, fd, buffer, offset, length, position, callback);
        }
        __name(read3, "read");
        if (Object.setPrototypeOf) Object.setPrototypeOf(read3, fs$read);
        return read3;
      }(fs113.read);
      fs113.readSync = typeof fs113.readSync !== "function" ? fs113.readSync : /* @__PURE__ */ function(fs$readSync) {
        return function(fd, buffer, offset, length, position) {
          var eagCounter = 0;
          while (true) {
            try {
              return fs$readSync.call(fs113, fd, buffer, offset, length, position);
            } catch (er2) {
              if (er2.code === "EAGAIN" && eagCounter < 10) {
                eagCounter++;
                continue;
              }
              throw er2;
            }
          }
        };
      }(fs113.readSync);
      function patchLchmod(fs114) {
        fs114.lchmod = function(path125, mode, callback) {
          fs114.open(
            path125,
            constants4.O_WRONLY | constants4.O_SYMLINK,
            mode,
            function(err, fd) {
              if (err) {
                if (callback) callback(err);
                return;
              }
              fs114.fchmod(fd, mode, function(err2) {
                fs114.close(fd, function(err22) {
                  if (callback) callback(err2 || err22);
                });
              });
            }
          );
        };
        fs114.lchmodSync = function(path125, mode) {
          var fd = fs114.openSync(path125, constants4.O_WRONLY | constants4.O_SYMLINK, mode);
          var threw = true;
          var ret;
          try {
            ret = fs114.fchmodSync(fd, mode);
            threw = false;
          } finally {
            if (threw) {
              try {
                fs114.closeSync(fd);
              } catch (er2) {
              }
            } else {
              fs114.closeSync(fd);
            }
          }
          return ret;
        };
      }
      __name(patchLchmod, "patchLchmod");
      function patchLutimes(fs114) {
        if (constants4.hasOwnProperty("O_SYMLINK") && fs114.futimes) {
          fs114.lutimes = function(path125, at2, mt2, cb) {
            fs114.open(path125, constants4.O_SYMLINK, function(er2, fd) {
              if (er2) {
                if (cb) cb(er2);
                return;
              }
              fs114.futimes(fd, at2, mt2, function(er3) {
                fs114.close(fd, function(er22) {
                  if (cb) cb(er3 || er22);
                });
              });
            });
          };
          fs114.lutimesSync = function(path125, at2, mt2) {
            var fd = fs114.openSync(path125, constants4.O_SYMLINK);
            var ret;
            var threw = true;
            try {
              ret = fs114.futimesSync(fd, at2, mt2);
              threw = false;
            } finally {
              if (threw) {
                try {
                  fs114.closeSync(fd);
                } catch (er2) {
                }
              } else {
                fs114.closeSync(fd);
              }
            }
            return ret;
          };
        } else if (fs114.futimes) {
          fs114.lutimes = function(_a7, _b2, _c2, cb) {
            if (cb) process.nextTick(cb);
          };
          fs114.lutimesSync = function() {
          };
        }
      }
      __name(patchLutimes, "patchLutimes");
      function chmodFix(orig) {
        if (!orig) return orig;
        return function(target, mode, cb) {
          return orig.call(fs113, target, mode, function(er2) {
            if (chownErOk(er2)) er2 = 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(fs113, target, mode);
          } catch (er2) {
            if (!chownErOk(er2)) throw er2;
          }
        };
      }
      __name(chmodFixSync, "chmodFixSync");
      function chownFix(orig) {
        if (!orig) return orig;
        return function(target, uid, gid, cb) {
          return orig.call(fs113, target, uid, gid, function(er2) {
            if (chownErOk(er2)) er2 = 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(fs113, target, uid, gid);
          } catch (er2) {
            if (!chownErOk(er2)) throw er2;
          }
        };
      }
      __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(er2, 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(fs113, target, options2, callback) : orig.call(fs113, target, callback);
        };
      }
      __name(statFix, "statFix");
      function statFixSync(orig) {
        if (!orig) return orig;
        return function(target, options2) {
          var stats = options2 ? orig.call(fs113, target, options2) : orig.call(fs113, target);
          if (stats) {
            if (stats.uid < 0) stats.uid += 4294967296;
            if (stats.gid < 0) stats.gid += 4294967296;
          }
          return stats;
        };
      }
      __name(statFixSync, "statFixSync");
      function chownErOk(er2) {
        if (!er2)
          return true;
        if (er2.code === "ENOSYS")
          return true;
        var nonroot = !process.getuid || process.getuid() !== 0;
        if (nonroot) {
          if (er2.code === "EINVAL" || er2.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 Stream9 = __require("stream").Stream;
    module2.exports = legacy;
    function legacy(fs113) {
      return {
        ReadStream: ReadStream2,
        WriteStream: WriteStream2
      };
      function ReadStream2(path125, options2) {
        if (!(this instanceof ReadStream2)) return new ReadStream2(path125, options2);
        Stream9.call(this);
        var self2 = this;
        this.path = path125;
        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;
        }
        fs113.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(path125, options2) {
        if (!(this instanceof WriteStream2)) return new WriteStream2(path125, options2);
        Stream9.call(this);
        this.path = path125;
        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 = fs113.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 = clone4;
    var getPrototypeOf = Object.getPrototypeOf || function(obj) {
      return obj.__proto__;
    };
    function clone4(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(clone4, "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 fs113 = __require("fs");
    var polyfills = require_polyfills2();
    var legacy = require_legacy_streams2();
    var clone4 = require_clone2();
    var util3 = __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 noop8() {
    }
    __name(noop8, "noop");
    function publishQueue(context2, queue2) {
      Object.defineProperty(context2, gracefulQueue, {
        get: /* @__PURE__ */ __name(function() {
          return queue2;
        }, "get")
      });
    }
    __name(publishQueue, "publishQueue");
    var debug3 = noop8;
    if (util3.debuglog)
      debug3 = util3.debuglog("gfs4");
    else if (/\bgfs4\b/i.test(process.env.NODE_DEBUG || ""))
      debug3 = /* @__PURE__ */ __name(function() {
        var m3 = util3.format.apply(util3, arguments);
        m3 = "GFS4: " + m3.split(/\n/).join("\nGFS4: ");
        console.error(m3);
      }, "debug");
    if (!fs113[gracefulQueue]) {
      queue = globalThis[gracefulQueue] || [];
      publishQueue(fs113, queue);
      fs113.close = function(fs$close) {
        function close(fd, cb) {
          return fs$close.call(fs113, 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;
      }(fs113.close);
      fs113.closeSync = function(fs$closeSync) {
        function closeSync(fd) {
          fs$closeSync.apply(fs113, arguments);
          resetQueue();
        }
        __name(closeSync, "closeSync");
        Object.defineProperty(closeSync, previousSymbol, {
          value: fs$closeSync
        });
        return closeSync;
      }(fs113.closeSync);
      if (/\bgfs4\b/i.test(process.env.NODE_DEBUG || "")) {
        process.on("exit", function() {
          debug3(fs113[gracefulQueue]);
          __require("assert").equal(fs113[gracefulQueue].length, 0);
        });
      }
    }
    var queue;
    if (!globalThis[gracefulQueue]) {
      publishQueue(globalThis, fs113[gracefulQueue]);
    }
    module2.exports = patch(clone4(fs113));
    if (process.env.TEST_GRACEFUL_FS_GLOBAL_PATCH && !fs113.__patched) {
      module2.exports = patch(fs113);
      fs113.__patched = true;
    }
    function patch(fs114) {
      polyfills(fs114);
      fs114.gracefulify = patch;
      fs114.createReadStream = createReadStream3;
      fs114.createWriteStream = createWriteStream5;
      var fs$readFile = fs114.readFile;
      fs114.readFile = readFile13;
      function readFile13(path125, options2, cb) {
        if (typeof options2 === "function")
          cb = options2, options2 = null;
        return go$readFile(path125, options2, cb);
        function go$readFile(path126, options3, cb2, startTime) {
          return fs$readFile(path126, options3, function(err) {
            if (err && (err.code === "EMFILE" || err.code === "ENFILE"))
              enqueue([go$readFile, [path126, options3, cb2], err, startTime || Date.now(), Date.now()]);
            else {
              if (typeof cb2 === "function")
                cb2.apply(this, arguments);
            }
          });
        }
        __name(go$readFile, "go$readFile");
      }
      __name(readFile13, "readFile");
      var fs$writeFile = fs114.writeFile;
      fs114.writeFile = writeFile14;
      function writeFile14(path125, data, options2, cb) {
        if (typeof options2 === "function")
          cb = options2, options2 = null;
        return go$writeFile(path125, data, options2, cb);
        function go$writeFile(path126, data2, options3, cb2, startTime) {
          return fs$writeFile(path126, data2, options3, function(err) {
            if (err && (err.code === "EMFILE" || err.code === "ENFILE"))
              enqueue([go$writeFile, [path126, data2, options3, cb2], err, startTime || Date.now(), Date.now()]);
            else {
              if (typeof cb2 === "function")
                cb2.apply(this, arguments);
            }
          });
        }
        __name(go$writeFile, "go$writeFile");
      }
      __name(writeFile14, "writeFile");
      var fs$appendFile = fs114.appendFile;
      if (fs$appendFile)
        fs114.appendFile = appendFile;
      function appendFile(path125, data, options2, cb) {
        if (typeof options2 === "function")
          cb = options2, options2 = null;
        return go$appendFile(path125, data, options2, cb);
        function go$appendFile(path126, data2, options3, cb2, startTime) {
          return fs$appendFile(path126, data2, options3, function(err) {
            if (err && (err.code === "EMFILE" || err.code === "ENFILE"))
              enqueue([go$appendFile, [path126, 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 = fs114.copyFile;
      if (fs$copyFile)
        fs114.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 = fs114.readdir;
      fs114.readdir = readdir12;
      var noReaddirOptionVersions = /^v[0-5]\./;
      function readdir12(path125, options2, cb) {
        if (typeof options2 === "function")
          cb = options2, options2 = null;
        var go$readdir = noReaddirOptionVersions.test(process.version) ? /* @__PURE__ */ __name(function go$readdir2(path126, options3, cb2, startTime) {
          return fs$readdir(path126, fs$readdirCallback(
            path126,
            options3,
            cb2,
            startTime
          ));
        }, "go$readdir") : /* @__PURE__ */ __name(function go$readdir2(path126, options3, cb2, startTime) {
          return fs$readdir(path126, options3, fs$readdirCallback(
            path126,
            options3,
            cb2,
            startTime
          ));
        }, "go$readdir");
        return go$readdir(path125, options2, cb);
        function fs$readdirCallback(path126, options3, cb2, startTime) {
          return function(err, files) {
            if (err && (err.code === "EMFILE" || err.code === "ENFILE"))
              enqueue([
                go$readdir,
                [path126, 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(readdir12, "readdir");
      if (process.version.substr(0, 4) === "v0.8") {
        var legStreams = legacy(fs114);
        ReadStream2 = legStreams.ReadStream;
        WriteStream2 = legStreams.WriteStream;
      }
      var fs$ReadStream = fs114.ReadStream;
      if (fs$ReadStream) {
        ReadStream2.prototype = Object.create(fs$ReadStream.prototype);
        ReadStream2.prototype.open = ReadStream$open;
      }
      var fs$WriteStream = fs114.WriteStream;
      if (fs$WriteStream) {
        WriteStream2.prototype = Object.create(fs$WriteStream.prototype);
        WriteStream2.prototype.open = WriteStream$open;
      }
      Object.defineProperty(fs114, "ReadStream", {
        get: /* @__PURE__ */ __name(function() {
          return ReadStream2;
        }, "get"),
        set: /* @__PURE__ */ __name(function(val) {
          ReadStream2 = val;
        }, "set"),
        enumerable: true,
        configurable: true
      });
      Object.defineProperty(fs114, "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(fs114, "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(fs114, "FileWriteStream", {
        get: /* @__PURE__ */ __name(function() {
          return FileWriteStream;
        }, "get"),
        set: /* @__PURE__ */ __name(function(val) {
          FileWriteStream = val;
        }, "set"),
        enumerable: true,
        configurable: true
      });
      function ReadStream2(path125, 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;
        open4(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(path125, 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;
        open4(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 createReadStream3(path125, options2) {
        return new fs114.ReadStream(path125, options2);
      }
      __name(createReadStream3, "createReadStream");
      function createWriteStream5(path125, options2) {
        return new fs114.WriteStream(path125, options2);
      }
      __name(createWriteStream5, "createWriteStream");
      var fs$open = fs114.open;
      fs114.open = open4;
      function open4(path125, flags, mode, cb) {
        if (typeof mode === "function")
          cb = mode, mode = null;
        return go$open(path125, flags, mode, cb);
        function go$open(path126, flags2, mode2, cb2, startTime) {
          return fs$open(path126, flags2, mode2, function(err, fd) {
            if (err && (err.code === "EMFILE" || err.code === "ENFILE"))
              enqueue([go$open, [path126, flags2, mode2, cb2], err, startTime || Date.now(), Date.now()]);
            else {
              if (typeof cb2 === "function")
                cb2.apply(this, arguments);
            }
          });
        }
        __name(go$open, "go$open");
      }
      __name(open4, "open");
      return fs114;
    }
    __name(patch, "patch");
    function enqueue(elem) {
      debug3("ENQUEUE", elem[0].name, elem[1]);
      fs113[gracefulQueue].push(elem);
      retry();
    }
    __name(enqueue, "enqueue");
    var retryTimer;
    function resetQueue() {
      var now = Date.now();
      for (var i3 = 0; i3 < fs113[gracefulQueue].length; ++i3) {
        if (fs113[gracefulQueue][i3].length > 2) {
          fs113[gracefulQueue][i3][3] = now;
          fs113[gracefulQueue][i3][4] = now;
        }
      }
      retry();
    }
    __name(resetQueue, "resetQueue");
    function retry() {
      clearTimeout(retryTimer);
      retryTimer = void 0;
      if (fs113[gracefulQueue].length === 0)
        return;
      var elem = fs113[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) {
        debug3("RETRY", fn.name, args);
        fn.apply(null, args);
      } else if (Date.now() - startTime >= 6e4) {
        debug3("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) {
          debug3("RETRY", fn.name, args);
          fn.apply(null, args.concat([startTime]));
        } else {
          fs113[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_dist8 = __commonJS({
  "node_modules/@pnpm/network.ca-file/dist/index.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    var __createBinding = exports2 && exports2.__createBinding || (Object.create ? function(o3, m3, k2, k22) {
      if (k22 === void 0) k22 = k2;
      var desc2 = Object.getOwnPropertyDescriptor(m3, k2);
      if (!desc2 || ("get" in desc2 ? !m3.__esModule : desc2.writable || desc2.configurable)) {
        desc2 = { enumerable: true, get: /* @__PURE__ */ __name(function() {
          return m3[k2];
        }, "get") };
      }
      Object.defineProperty(o3, k22, desc2);
    } : function(o3, m3, k2, k22) {
      if (k22 === void 0) k22 = k2;
      o3[k22] = m3[k2];
    });
    var __exportStar = exports2 && exports2.__exportStar || function(m3, exports3) {
      for (var p2 in m3) if (p2 !== "default" && !Object.prototype.hasOwnProperty.call(exports3, p2)) __createBinding(exports3, m3, p2);
    };
    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(r5) {
          root = r5;
          if (this.list.length) {
            setProto(this.list[this.list.length - 1], r5);
          }
        }, "set"),
        enumerable: true,
        configurable: true
      });
    }
    __name(ProtoList, "ProtoList");
    ProtoList.prototype = {
      get length() {
        return this.list.length;
      },
      get keys() {
        var k2 = [];
        for (var i3 in this.list[0]) k2.push(i3);
        return k2;
      },
      get snapshot() {
        var o3 = {};
        this.keys.forEach(function(k2) {
          o3[k2] = this.get(k2);
        }, this);
        return o3;
      },
      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 i3 = 0, l3 = this.list.length; i3 < l3; i3++) {
          setProto(this.list[i3], this.list[i3 + 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(k2, _2, __) {
        var val = obj[k2];
        if (val && Array.isArray(val)) {
          val.forEach(function(item) {
            out += safe(k2 + "[]") + separator + safe(item) + "\n";
          });
        } else if (val && typeof val === "object")
          children.push(k2);
        else
          out += safe(k2) + separator + safe(val) + eol;
      });
      if (opt.section && out.length)
        out = "[" + safe(opt.section) + "]" + eol + out;
      children.forEach(function(k2, _2, __) {
        var nk = dotSplit(k2).join("\\.");
        var section = (opt.section ? opt.section + "." : "") + nk;
        var child = encode4(obj[k2], {
          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 p2 = out;
      var section = null;
      var re3 = /^\[([^\]]*)\]$|^([^=]+)(=(.*))?$/i;
      var lines = str2.split(/[\r\n]+/g);
      lines.forEach(function(line, _2, __) {
        if (!line || line.match(/^\s*[;#]/))
          return;
        var match2 = line.match(re3);
        if (!match2)
          return;
        if (match2[1] !== void 0) {
          section = unsafe(match2[1]);
          if (section === "__proto__") {
            p2 = {};
            return;
          }
          p2 = 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 (!p2[key])
            p2[key] = [];
          else if (!Array.isArray(p2[key]))
            p2[key] = [p2[key]];
        }
        if (Array.isArray(p2[key]))
          p2[key].push(value);
        else
          p2[key] = value;
      });
      Object.keys(out).filter(function(k2, _2, __) {
        if (!out[k2] || typeof out[k2] !== "object" || Array.isArray(out[k2]))
          return false;
        var parts = dotSplit(k2);
        var p3 = out;
        var l3 = parts.pop();
        var nl2 = l3.replace(/\\\./g, ".");
        parts.forEach(function(part, _3, __2) {
          if (part === "__proto__")
            return;
          if (!p3[part] || typeof p3[part] !== "object")
            p3[part] = {};
          p3 = p3[part];
        });
        if (p3 === out && nl2 === l3)
          return false;
        p3[nl2] = out[k2];
        return true;
      }).forEach(function(del, _2, __) {
        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 (_2) {
        }
      } else {
        var esc2 = false;
        var unesc = "";
        for (var i3 = 0, l3 = val.length; i3 < l3; i3++) {
          var c4 = val.charAt(i3);
          if (esc2) {
            if ("\\;#".indexOf(c4) !== -1)
              unesc += c4;
            else
              unesc += "\\" + c4;
            esc2 = false;
          } else if (";#".indexOf(c4) !== -1)
            break;
          else if (c4 === "\\")
            esc2 = true;
          else
            unesc += c4;
        }
        if (esc2)
          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 path125 = __require("path");
    var fs113 = __require("fs");
    var ini3 = require_ini2();
    var EE3 = __require("events").EventEmitter;
    var url2 = __require("url");
    var http7 = __require("http");
    var exports2 = module2.exports = function() {
      var args = [].slice.call(arguments), conf = new ConfigChain();
      while (args.length) {
        var a2 = args.shift();
        if (a2) conf.push("string" === typeof a2 ? json2(a2) : a2);
      }
      return conf;
    };
    var find = exports2.find = function() {
      var rel = path125.join.apply(null, [].slice.call(arguments));
      function find2(start, rel2) {
        var file = path125.join(start, rel2);
        try {
          fs113.statSync(file);
          return file;
        } catch (err) {
          if (path125.dirname(start) !== start)
            return find2(path125.dirname(start), rel2);
        }
      }
      __name(find2, "find");
      return find2(__dirname, rel);
    };
    var parse14 = exports2.parse = function(content, file, type) {
      content = "" + content;
      if (!type) {
        try {
          return JSON.parse(content);
        } catch (er2) {
          return ini3.parse(content);
        }
      } else if (type === "json") {
        if (this.emit) {
          try {
            return JSON.parse(content);
          } catch (er2) {
            this.emit("error", er2);
          }
        } 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 = path125.join.apply(null, args);
      var content;
      try {
        content = fs113.readFileSync(file, "utf-8");
      } catch (err) {
        return;
      }
      return parse14(content, file, "json");
    };
    var env7 = exports2.env = function(prefix, env8) {
      env8 = env8 || process.env;
      var obj = {};
      var l3 = prefix.length;
      for (var k2 in env8) {
        if (k2.indexOf(prefix) === 0)
          obj[k2.substring(l3)] = env8[k2];
      }
      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(k2) {
      extras[k2] = Object.getOwnPropertyDescriptor(EE3.prototype, k2);
    });
    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 i3 = 0, l3 = this.list.length; i3 < l3; i3++) {
          delete this.list[i3][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(k2) {
          target.source[pref + k2] = target.data[k2];
        });
        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++;
      fs113.writeFile(target.path, data, "utf8", function(er2) {
        this._saving--;
        if (er2) {
          if (cb) return cb(er2);
          else return this.emit("error", er2);
        }
        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();
      fs113.readFile(file, "utf8", function(er2, data) {
        if (er2) this.emit("error", er2);
        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);
      http7.request(req, function(res) {
        var c4 = [];
        var ct2 = res.headers["content-type"];
        if (!type) {
          type = ct2.indexOf("json") !== -1 ? "json" : ct2.indexOf("ini") !== -1 ? "ini" : href.match(/\.json$/) ? "json" : href.match(/\.ini$/) ? "ini" : null;
          marker.type = type;
        }
        res.on("data", c4.push.bind(c4)).on("end", function() {
          this.addString(Buffer.concat(c4), 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 i3 = this.list.indexOf(marker);
        if (i3 === -1) {
          return this.emit("error", new Error("bad marker"));
        }
        this.splice(i3, 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(x3) {
      const colonIndex = x3.indexOf(":");
      if (colonIndex === -1) {
        return normalize12(x3);
      }
      const firstPart = x3.substr(0, colonIndex);
      const secondPart = x3.substr(colonIndex + 1);
      return `${normalize12(firstPart)}:${normalize12(secondPart)}`;
    };
    function normalize12(s5) {
      s5 = s5.toLowerCase();
      if (s5 === "_authtoken") return "_authToken";
      let r5 = s5[0];
      for (let i3 = 1; i3 < s5.length; i3++) {
        r5 += s5[i3] === "_" ? "-" : s5[i3];
      }
      return r5;
    }
    __name(normalize12, "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_dist9 = __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_util32 = __commonJS({
  "node_modules/@pnpm/npm-conf/lib/util.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    var fs113 = __require("fs");
    var path125 = __require("path");
    var { envReplace } = require_dist9();
    var parseKey = /* @__PURE__ */ __name((key) => {
      if (typeof key !== "string") {
        return key;
      }
      return envReplace(key, process.env);
    }, "parseKey");
    var parseField = /* @__PURE__ */ __name((types7, field, key) => {
      if (typeof field !== "string") {
        return field;
      }
      const typeList = [].concat(types7[key]);
      const isPath = typeList.indexOf(path125) !== -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 (error2) {
          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 = path125.resolve(process.env.HOME, field.substr(2));
        }
        field = path125.resolve(field);
      }
      if (isNumber3 && !isNaN(field)) {
        field = Number(field);
      }
      return field;
    }, "parseField");
    var findPrefix = /* @__PURE__ */ __name((name3) => {
      name3 = path125.resolve(name3);
      let walkedUp = false;
      while (path125.basename(name3) === "node_modules") {
        name3 = path125.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 = fs113.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 dirname26 = path125.dirname(name4);
          if (dirname26 === name4) {
            return original;
          }
          return find(dirname26, original);
        } catch (error2) {
          if (name4 === original) {
            if (error2.code === "ENOENT") {
              return original;
            }
            throw error2;
          }
          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_types10 = __commonJS({
  "node_modules/@pnpm/npm-conf/lib/types.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    var path125 = __require("path");
    var Stream9 = __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: path125,
      cache: path125,
      "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: path125,
      "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": path125,
      "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: Stream9,
      "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: path125,
      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: path125,
      unicode: Boolean,
      "unsafe-perm": Boolean,
      usage: Boolean,
      user: [Number, String],
      userconfig: path125,
      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_dist8();
    var fs113 = __require("fs");
    var path125 = __require("path");
    var { ConfigChain } = require_config_chain();
    var envKeyToSetting = require_envKeyToSetting();
    var util3 = require_util32();
    var Conf = class extends ConfigChain {
      static {
        __name(this, "Conf");
      }
      // https://github.com/npm/cli/blob/latest/lib/config/core.js#L203-L217
      constructor(base, types7) {
        super(base);
        this.root = base;
        this._parseField = util3.parseField.bind(null, types7 || require_types10());
      }
      // 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 = util3.parseKey(key);
            if (substKey !== key) {
              delete data[key];
            }
            data[substKey] = this._parseField(value, substKey);
          }
        } catch (error2) {
          throw error2;
        }
        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 = fs113.readFileSync(file, "utf8");
          this.addString(contents, file, "ini", marker);
        } catch (error2) {
          if (error2.code === "ENOENT") {
            this.add({}, marker);
          } else if (error2.code !== "EISDIR") {
            return `Issue while reading "${file}". ${error2.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((x3) => /^npm_config_/i.test(x3)).forEach((x3) => {
          if (!env7[x3]) {
            return;
          }
          const key = envKeyToSetting(x3.substr(11));
          const rawVal = env7[x3];
          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 g2 = this.get("global");
            this[g2 ? "globalPrefix" : "localPrefix"] = prefix;
          }, "set"),
          get: /* @__PURE__ */ __name(() => {
            const g2 = this.get("global");
            return g2 ? this.globalPrefix : this.localPrefix;
          }, "get")
        });
        Object.defineProperty(this, "globalPrefix", {
          enumerable: true,
          set: /* @__PURE__ */ __name((prefix) => {
            this.set("prefix", prefix);
          }, "set"),
          get: /* @__PURE__ */ __name(() => {
            return path125.resolve(this.get("prefix"));
          }, "get")
        });
        let p2;
        Object.defineProperty(this, "localPrefix", {
          enumerable: true,
          set: /* @__PURE__ */ __name((prefix) => {
            p2 = prefix;
          }, "set"),
          get: /* @__PURE__ */ __name(() => {
            return p2;
          }, "get")
        });
        if (Object.prototype.hasOwnProperty.call(cli, "prefix")) {
          p2 = path125.resolve(cli.prefix);
        } else {
          try {
            const prefix = util3.findPrefix(process.cwd());
            p2 = prefix;
          } catch (error2) {
            throw error2;
          }
        }
        return p2;
      }
      // 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 = path125.resolve(this.get("prefix"));
        try {
          const stats = fs113.statSync(prefix);
          defConf.user = stats.uid;
        } catch (error2) {
          if (error2.code === "ENOENT") {
            return;
          }
          throw error2;
        }
      }
    };
    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_defaults4 = __commonJS({
  "node_modules/@pnpm/npm-conf/lib/defaults.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    var os47 = __require("os");
    var path125 = __require("path");
    var temp = os47.tmpdir();
    var uidOrPid = process.getuid ? process.getuid() : process.pid;
    var hasUnicode = /* @__PURE__ */ __name(() => true, "hasUnicode");
    var isWindows9 = process.platform === "win32";
    var osenv = {
      editor: /* @__PURE__ */ __name(() => process.env.EDITOR || process.env.VISUAL || (isWindows9 ? "notepad.exe" : "vi"), "editor"),
      shell: /* @__PURE__ */ __name(() => isWindows9 ? process.env.COMSPEC || "cmd.exe" : process.env.SHELL || "/bin/bash", "shell")
    };
    var umask = {
      fromString: /* @__PURE__ */ __name(() => process.umask(), "fromString")
    };
    var home = os47.homedir();
    if (home) {
      process.env.HOME = home;
    } else {
      home = path125.resolve(temp, "npm-" + uidOrPid);
    }
    var cacheExtra = process.platform === "win32" ? "npm-cache" : ".npm";
    var cacheRoot = process.platform === "win32" && process.env.APPDATA || home;
    var cache5 = path125.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 = path125.dirname(process.execPath);
        } else {
          globalPrefix = path125.dirname(path125.dirname(process.execPath));
          if (process.env.DESTDIR) {
            globalPrefix = path125.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: path125.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": path125.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: path125.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 path125 = __require("path");
    var Conf = require_conf();
    var _defaults2 = require_defaults4();
    module2.exports = (opts, types7, defaults3) => {
      const conf = new Conf(Object.assign({}, _defaults2.defaults, defaults3), types7);
      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 (error2) {
          failedToLoadBuiltInConfig = true;
        }
        if (npmPath) {
          warnings.push(conf.addFile(path125.resolve(path125.dirname(npmPath), "..", "npmrc"), "builtin"));
        }
      }
      conf.addEnv();
      conf.loadPrefix();
      const projectConf = path125.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 = path125.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 = path125.resolve(conf.get("prefix"), "etc");
        conf.root.globalconfig = path125.resolve(etc, "npmrc");
        conf.root.globalignorefile = path125.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(normalizePath2(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 normalizePath2(path125) {
      return path125[path125.length - 1] === "/" ? path125 : path125 + "/";
    }
    __name(normalizePath2, "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 (er2) {
        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((a2, loose) => new SemVer(a2, 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((a2, loose) => new SemVer(a2, 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((a2, loose) => new SemVer(a2, 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 parse14 = require_parse9();
    var prerelease = /* @__PURE__ */ __name((version2, options2) => {
      const parsed = parse14(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((a2, b2, loose) => compare(b2, a2, 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((a2, b2) => compare(a2, b2, 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((a2, b2, loose) => {
      const versionA = new SemVer(a2, loose);
      const versionB = new SemVer(b2, 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((a2, b2) => compareBuild(a2, b2, 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((a2, b2) => compareBuild(b2, a2, 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 lt2 = /* @__PURE__ */ __name((a2, b2, loose) => compare(a2, b2, loose) < 0, "lt");
    module2.exports = lt2;
  }
});

// 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((a2, b2, loose) => compare(a2, b2, 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((a2, b2, loose) => compare(a2, b2, 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((a2, b2, loose) => compare(a2, b2, 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((a2, b2, loose) => compare(a2, b2, 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 gt2 = require_gt();
    var gte = require_gte();
    var lt2 = require_lt();
    var lte = require_lte();
    var cmp = /* @__PURE__ */ __name((a2, op, b2, loose) => {
      switch (op) {
        case "===":
          if (typeof a2 === "object") {
            a2 = a2.version;
          }
          if (typeof b2 === "object") {
            b2 = b2.version;
          }
          return a2 === b2;
        case "!==":
          if (typeof a2 === "object") {
            a2 = a2.version;
          }
          if (typeof b2 === "object") {
            b2 = b2.version;
          }
          return a2 !== b2;
        case "":
        case "=":
        case "==":
          return eq(a2, b2, loose);
        case "!=":
          return neq(a2, b2, loose);
        case ">":
          return gt2(a2, b2, loose);
        case ">=":
          return gte(a2, b2, loose);
        case "<":
          return lt2(a2, b2, loose);
        case "<=":
          return lte(a2, b2, 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 parse14 = require_parse9();
    var { safeRe: re3, t: t5 } = 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 ? re3[t5.COERCEFULL] : re3[t5.COERCE]);
      } else {
        const coerceRtlRegex = options2.includePrerelease ? re3[t5.COERCERTLFULL] : re3[t5.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 parse14(`${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((r5) => this.parseRange(r5.trim())).filter((c4) => c4.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((c4) => !isNullSet(c4[0]));
          if (this.set.length === 0) {
            this.set = [first2];
          } else if (this.set.length > 1) {
            for (const c4 of this.set) {
              if (c4.length === 1 && isAny(c4[0])) {
                this.set = [c4];
                break;
              }
            }
          }
        }
        this.formatted = void 0;
      }
      get range() {
        if (this.formatted === void 0) {
          this.formatted = "";
          for (let i3 = 0; i3 < this.set.length; i3++) {
            if (i3 > 0) {
              this.formatted += "||";
            }
            const comps = this.set[i3];
            for (let k2 = 0; k2 < comps.length; k2++) {
              if (k2 > 0) {
                this.formatted += " ";
              }
              this.formatted += comps[k2].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 cached2 = cache5.get(memoKey);
        if (cached2) {
          return cached2;
        }
        const loose = this.options.loose;
        const hr3 = loose ? re3[t5.HYPHENRANGELOOSE] : re3[t5.HYPHENRANGE];
        range = range.replace(hr3, hyphenReplace(this.options.includePrerelease));
        debug3("hyphen replace", range);
        range = range.replace(re3[t5.COMPARATORTRIM], comparatorTrimReplace);
        debug3("comparator trim", range);
        range = range.replace(re3[t5.TILDETRIM], tildeTrimReplace);
        debug3("tilde trim", range);
        range = range.replace(re3[t5.CARETTRIM], caretTrimReplace);
        debug3("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) => {
            debug3("loose invalid filter", comp, this.options);
            return !!comp.match(re3[t5.COMPARATORLOOSE]);
          });
        }
        debug3("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 (er2) {
            return false;
          }
        }
        for (let i3 = 0; i3 < this.set.length; i3++) {
          if (testSet(this.set[i3], 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 debug3 = require_debug();
    var SemVer = require_semver2();
    var {
      safeRe: re3,
      t: t5,
      comparatorTrimReplace,
      tildeTrimReplace,
      caretTrimReplace
    } = require_re();
    var { FLAG_INCLUDE_PRERELEASE, FLAG_LOOSE } = require_constants13();
    var isNullSet = /* @__PURE__ */ __name((c4) => c4.value === "<0.0.0-0", "isNullSet");
    var isAny = /* @__PURE__ */ __name((c4) => c4.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) => {
      comp = comp.replace(re3[t5.BUILD], "");
      debug3("comp", comp, options2);
      comp = replaceCarets(comp, options2);
      debug3("caret", comp);
      comp = replaceTildes(comp, options2);
      debug3("tildes", comp);
      comp = replaceXRanges(comp, options2);
      debug3("xrange", comp);
      comp = replaceStars(comp, options2);
      debug3("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((c4) => replaceTilde(c4, options2)).join(" ");
    }, "replaceTildes");
    var replaceTilde = /* @__PURE__ */ __name((comp, options2) => {
      const r5 = options2.loose ? re3[t5.TILDELOOSE] : re3[t5.TILDE];
      return comp.replace(r5, (_2, M2, m3, p2, pr2) => {
        debug3("tilde", comp, _2, M2, m3, p2, pr2);
        let ret;
        if (isX(M2)) {
          ret = "";
        } else if (isX(m3)) {
          ret = `>=${M2}.0.0 <${+M2 + 1}.0.0-0`;
        } else if (isX(p2)) {
          ret = `>=${M2}.${m3}.0 <${M2}.${+m3 + 1}.0-0`;
        } else if (pr2) {
          debug3("replaceTilde pr", pr2);
          ret = `>=${M2}.${m3}.${p2}-${pr2} <${M2}.${+m3 + 1}.0-0`;
        } else {
          ret = `>=${M2}.${m3}.${p2} <${M2}.${+m3 + 1}.0-0`;
        }
        debug3("tilde return", ret);
        return ret;
      });
    }, "replaceTilde");
    var replaceCarets = /* @__PURE__ */ __name((comp, options2) => {
      return comp.trim().split(/\s+/).map((c4) => replaceCaret(c4, options2)).join(" ");
    }, "replaceCarets");
    var replaceCaret = /* @__PURE__ */ __name((comp, options2) => {
      debug3("caret", comp, options2);
      const r5 = options2.loose ? re3[t5.CARETLOOSE] : re3[t5.CARET];
      const z2 = options2.includePrerelease ? "-0" : "";
      return comp.replace(r5, (_2, M2, m3, p2, pr2) => {
        debug3("caret", comp, _2, M2, m3, p2, pr2);
        let ret;
        if (isX(M2)) {
          ret = "";
        } else if (isX(m3)) {
          ret = `>=${M2}.0.0${z2} <${+M2 + 1}.0.0-0`;
        } else if (isX(p2)) {
          if (M2 === "0") {
            ret = `>=${M2}.${m3}.0${z2} <${M2}.${+m3 + 1}.0-0`;
          } else {
            ret = `>=${M2}.${m3}.0${z2} <${+M2 + 1}.0.0-0`;
          }
        } else if (pr2) {
          debug3("replaceCaret pr", pr2);
          if (M2 === "0") {
            if (m3 === "0") {
              ret = `>=${M2}.${m3}.${p2}-${pr2} <${M2}.${m3}.${+p2 + 1}-0`;
            } else {
              ret = `>=${M2}.${m3}.${p2}-${pr2} <${M2}.${+m3 + 1}.0-0`;
            }
          } else {
            ret = `>=${M2}.${m3}.${p2}-${pr2} <${+M2 + 1}.0.0-0`;
          }
        } else {
          debug3("no pr");
          if (M2 === "0") {
            if (m3 === "0") {
              ret = `>=${M2}.${m3}.${p2}${z2} <${M2}.${m3}.${+p2 + 1}-0`;
            } else {
              ret = `>=${M2}.${m3}.${p2}${z2} <${M2}.${+m3 + 1}.0-0`;
            }
          } else {
            ret = `>=${M2}.${m3}.${p2} <${+M2 + 1}.0.0-0`;
          }
        }
        debug3("caret return", ret);
        return ret;
      });
    }, "replaceCaret");
    var replaceXRanges = /* @__PURE__ */ __name((comp, options2) => {
      debug3("replaceXRanges", comp, options2);
      return comp.split(/\s+/).map((c4) => replaceXRange(c4, options2)).join(" ");
    }, "replaceXRanges");
    var replaceXRange = /* @__PURE__ */ __name((comp, options2) => {
      comp = comp.trim();
      const r5 = options2.loose ? re3[t5.XRANGELOOSE] : re3[t5.XRANGE];
      return comp.replace(r5, (ret, gtlt, M2, m3, p2, pr2) => {
        debug3("xRange", comp, ret, gtlt, M2, m3, p2, pr2);
        const xM = isX(M2);
        const xm = xM || isX(m3);
        const xp = xm || isX(p2);
        const anyX = xp;
        if (gtlt === "=" && anyX) {
          gtlt = "";
        }
        pr2 = options2.includePrerelease ? "-0" : "";
        if (xM) {
          if (gtlt === ">" || gtlt === "<") {
            ret = "<0.0.0-0";
          } else {
            ret = "*";
          }
        } else if (gtlt && anyX) {
          if (xm) {
            m3 = 0;
          }
          p2 = 0;
          if (gtlt === ">") {
            gtlt = ">=";
            if (xm) {
              M2 = +M2 + 1;
              m3 = 0;
              p2 = 0;
            } else {
              m3 = +m3 + 1;
              p2 = 0;
            }
          } else if (gtlt === "<=") {
            gtlt = "<";
            if (xm) {
              M2 = +M2 + 1;
            } else {
              m3 = +m3 + 1;
            }
          }
          if (gtlt === "<") {
            pr2 = "-0";
          }
          ret = `${gtlt + M2}.${m3}.${p2}${pr2}`;
        } else if (xm) {
          ret = `>=${M2}.0.0${pr2} <${+M2 + 1}.0.0-0`;
        } else if (xp) {
          ret = `>=${M2}.${m3}.0${pr2} <${M2}.${+m3 + 1}.0-0`;
        }
        debug3("xRange return", ret);
        return ret;
      });
    }, "replaceXRange");
    var replaceStars = /* @__PURE__ */ __name((comp, options2) => {
      debug3("replaceStars", comp, options2);
      return comp.trim().replace(re3[t5.STAR], "");
    }, "replaceStars");
    var replaceGTE0 = /* @__PURE__ */ __name((comp, options2) => {
      debug3("replaceGTE0", comp, options2);
      return comp.trim().replace(re3[options2.includePrerelease ? t5.GTE0PRE : t5.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 i3 = 0; i3 < set.length; i3++) {
        if (!set[i3].test(version2)) {
          return false;
        }
      }
      if (version2.prerelease.length && !options2.includePrerelease) {
        for (let i3 = 0; i3 < set.length; i3++) {
          debug3(set[i3].semver);
          if (set[i3].semver === Comparator.ANY) {
            continue;
          }
          if (set[i3].semver.prerelease.length > 0) {
            const allowed = set[i3].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(" ");
        debug3("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;
        }
        debug3("comp", this);
      }
      parse(comp) {
        const r5 = this.options.loose ? re3[t5.COMPARATORLOOSE] : re3[t5.COMPARATOR];
        const m3 = comp.match(r5);
        if (!m3) {
          throw new TypeError(`Invalid comparator: ${comp}`);
        }
        this.operator = m3[1] !== void 0 ? m3[1] : "";
        if (this.operator === "=") {
          this.operator = "";
        }
        if (!m3[2]) {
          this.semver = ANY;
        } else {
          this.semver = new SemVer(m3[2], this.options.loose);
        }
      }
      toString() {
        return this.value;
      }
      test(version2) {
        debug3("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 (er2) {
            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: re3, t: t5 } = require_re();
    var cmp = require_cmp();
    var debug3 = 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 (er2) {
        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((c4) => c4.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 (er2) {
        return null;
      }
      versions.forEach((v2) => {
        if (rangeObj.test(v2)) {
          if (!max || maxSV.compare(v2) === -1) {
            max = v2;
            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 (er2) {
        return null;
      }
      versions.forEach((v2) => {
        if (rangeObj.test(v2)) {
          if (!min || minSV.compare(v2) === 1) {
            min = v2;
            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 gt2 = 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 i3 = 0; i3 < range.set.length; ++i3) {
        const comparators = range.set[i3];
        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 || gt2(compver, setMin)) {
                setMin = compver;
              }
              break;
            case "<":
            case "<=":
              break;
            /* istanbul ignore next */
            default:
              throw new Error(`Unexpected operation: ${comparator.operator}`);
          }
        });
        if (setMin && (!minver || gt2(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 (er2) {
        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 gt2 = require_gt();
    var lt2 = 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 = gt2;
          ltefn = lte;
          ltfn = lt2;
          comp = ">";
          ecomp = ">=";
          break;
        case "<":
          gtfn = lt2;
          ltefn = gte;
          ltfn = gt2;
          comp = "<";
          ecomp = "<=";
          break;
        default:
          throw new TypeError('Must provide a hilo val of "<" or ">"');
      }
      if (satisfies(version2, range, options2)) {
        return false;
      }
      for (let i3 = 0; i3 < range.set.length; ++i3) {
        const comparators = range.set[i3];
        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 v2 = versions.sort((a2, b2) => compare(a2, b2, options2));
      for (const version2 of v2) {
        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 === v2[0]) {
          ranges2.push("*");
        } else if (!max) {
          ranges2.push(`>=${min}`);
        } else if (min === v2[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 gt2, lt2;
      for (const c4 of sub) {
        if (c4.operator === ">" || c4.operator === ">=") {
          gt2 = higherGT(gt2, c4, options2);
        } else if (c4.operator === "<" || c4.operator === "<=") {
          lt2 = lowerLT(lt2, c4, options2);
        } else {
          eqSet.add(c4.semver);
        }
      }
      if (eqSet.size > 1) {
        return null;
      }
      let gtltComp;
      if (gt2 && lt2) {
        gtltComp = compare(gt2.semver, lt2.semver, options2);
        if (gtltComp > 0) {
          return null;
        } else if (gtltComp === 0 && (gt2.operator !== ">=" || lt2.operator !== "<=")) {
          return null;
        }
      }
      for (const eq of eqSet) {
        if (gt2 && !satisfies(eq, String(gt2), options2)) {
          return null;
        }
        if (lt2 && !satisfies(eq, String(lt2), options2)) {
          return null;
        }
        for (const c4 of dom) {
          if (!satisfies(eq, String(c4), options2)) {
            return false;
          }
        }
        return true;
      }
      let higher, lower3;
      let hasDomLT, hasDomGT;
      let needDomLTPre = lt2 && !options2.includePrerelease && lt2.semver.prerelease.length ? lt2.semver : false;
      let needDomGTPre = gt2 && !options2.includePrerelease && gt2.semver.prerelease.length ? gt2.semver : false;
      if (needDomLTPre && needDomLTPre.prerelease.length === 1 && lt2.operator === "<" && needDomLTPre.prerelease[0] === 0) {
        needDomLTPre = false;
      }
      for (const c4 of dom) {
        hasDomGT = hasDomGT || c4.operator === ">" || c4.operator === ">=";
        hasDomLT = hasDomLT || c4.operator === "<" || c4.operator === "<=";
        if (gt2) {
          if (needDomGTPre) {
            if (c4.semver.prerelease && c4.semver.prerelease.length && c4.semver.major === needDomGTPre.major && c4.semver.minor === needDomGTPre.minor && c4.semver.patch === needDomGTPre.patch) {
              needDomGTPre = false;
            }
          }
          if (c4.operator === ">" || c4.operator === ">=") {
            higher = higherGT(gt2, c4, options2);
            if (higher === c4 && higher !== gt2) {
              return false;
            }
          } else if (gt2.operator === ">=" && !satisfies(gt2.semver, String(c4), options2)) {
            return false;
          }
        }
        if (lt2) {
          if (needDomLTPre) {
            if (c4.semver.prerelease && c4.semver.prerelease.length && c4.semver.major === needDomLTPre.major && c4.semver.minor === needDomLTPre.minor && c4.semver.patch === needDomLTPre.patch) {
              needDomLTPre = false;
            }
          }
          if (c4.operator === "<" || c4.operator === "<=") {
            lower3 = lowerLT(lt2, c4, options2);
            if (lower3 === c4 && lower3 !== lt2) {
              return false;
            }
          } else if (lt2.operator === "<=" && !satisfies(lt2.semver, String(c4), options2)) {
            return false;
          }
        }
        if (!c4.operator && (lt2 || gt2) && gtltComp !== 0) {
          return false;
        }
      }
      if (gt2 && hasDomLT && !lt2 && gtltComp !== 0) {
        return false;
      }
      if (lt2 && hasDomGT && !gt2 && gtltComp !== 0) {
        return false;
      }
      if (needDomGTPre || needDomLTPre) {
        return false;
      }
      return true;
    }, "simpleSubset");
    var higherGT = /* @__PURE__ */ __name((a2, b2, options2) => {
      if (!a2) {
        return b2;
      }
      const comp = compare(a2.semver, b2.semver, options2);
      return comp > 0 ? a2 : comp < 0 ? b2 : b2.operator === ">" && a2.operator === ">=" ? b2 : a2;
    }, "higherGT");
    var lowerLT = /* @__PURE__ */ __name((a2, b2, options2) => {
      if (!a2) {
        return b2;
      }
      const comp = compare(a2.semver, b2.semver, options2);
      return comp < 0 ? a2 : comp > 0 ? b2 : b2.operator === "<" && a2.operator === "<=" ? b2 : a2;
    }, "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_constants13();
    var SemVer = require_semver2();
    var identifiers = require_identifiers();
    var parse14 = require_parse9();
    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 gt2 = require_gt();
    var lt2 = 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: parse14,
      valid,
      clean,
      inc,
      diff: diff4,
      major: major2,
      minor,
      patch,
      prerelease,
      compare,
      rcompare,
      compareLoose,
      compareBuild,
      sort,
      rsort,
      gt: gt2,
      lt: lt2,
      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((k2) => obj[k2] === null || Array.isArray(obj[k2]) || typeof obj[k2] !== "object").map((k2) => Array.isArray(obj[k2]) ? `${k2}[]` : k2).concat([""]).reduce((a2, b2) => safe(a2).length >= safe(b2).length ? a2 : b2)
        ).length;
      }
      let out = "";
      const arraySuffix = opt.bracketedArray ? "[]" : "";
      for (const k2 of keys) {
        const val = obj[k2];
        if (val && Array.isArray(val)) {
          for (const item of val) {
            out += safe(`${k2}${arraySuffix}`).padEnd(padToChars, " ") + separator + safe(item) + eol;
          }
        } else if (val && typeof val === "object") {
          children.push(k2);
        } else {
          out += safe(k2).padEnd(padToChars, " ") + separator + safe(val) + eol;
        }
      }
      if (opt.section && out.length) {
        out = "[" + safe(opt.section) + "]" + (opt.newline ? eol + eol : eol) + out;
      }
      for (const k2 of children) {
        const nk = splitSections(k2, ".").join("\\.");
        const section = (opt.section ? opt.section + "." : "") + nk;
        const child = encode4(obj[k2], {
          ...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 p2 = out;
      let section = null;
      const re3 = /^\[([^\]]*)\]\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(re3);
        if (!match2) {
          continue;
        }
        if (match2[1] !== void 0) {
          section = unsafe(match2[1]);
          if (section === "__proto__") {
            p2 = /* @__PURE__ */ Object.create(null);
            continue;
          }
          p2 = 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(p2, key)) {
            p2[key] = [];
          } else if (!Array.isArray(p2[key])) {
            p2[key] = [p2[key]];
          }
        }
        if (Array.isArray(p2[key])) {
          p2[key].push(value);
        } else {
          p2[key] = value;
        }
      }
      const remove2 = [];
      for (const k2 of Object.keys(out)) {
        if (!hasOwnProperty2.call(out, k2) || typeof out[k2] !== "object" || Array.isArray(out[k2])) {
          continue;
        }
        const parts = splitSections(k2, ".");
        p2 = out;
        const l3 = parts.pop();
        const nl2 = l3.replace(/\\\./g, ".");
        for (const part of parts) {
          if (part === "__proto__") {
            continue;
          }
          if (!hasOwnProperty2.call(p2, part) || typeof p2[part] !== "object") {
            p2[part] = /* @__PURE__ */ Object.create(null);
          }
          p2 = p2[part];
        }
        if (p2 === out && nl2 === l3) {
          continue;
        }
        p2[nl2] = out[k2];
        remove2.push(k2);
      }
      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 esc2 = false;
        let unesc = "";
        for (let i3 = 0, l3 = val.length; i3 < l3; i3++) {
          const c4 = val.charAt(i3);
          if (esc2) {
            if ("\\;#".indexOf(c4) !== -1) {
              unesc += c4;
            } else {
              unesc += "\\" + c4;
            }
            esc2 = false;
          } else if (";#".indexOf(c4) !== -1) {
            break;
          } else if (c4 === "\\") {
            esc2 = true;
          } else {
            unesc += c4;
          }
        }
        if (esc2) {
          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 = (string4) => typeof string4 === "string" ? string4.replace(ansiRegex3(), "") : string4;
  }
});

// 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((string4) => {
      if (typeof string4 !== "string" || string4.length === 0) {
        return 0;
      }
      string4 = stripAnsi3(string4);
      if (string4.length === 0) {
        return 0;
      }
      string4 = string4.replace(emojiRegex7(), "  ");
      let width = 0;
      for (let i3 = 0; i3 < string4.length; i3++) {
        const code2 = string4.codePointAt(i3);
        if (code2 <= 31 || code2 >= 127 && code2 <= 159) {
          continue;
        }
        if (code2 >= 768 && code2 <= 879) {
          continue;
        }
        if (code2 > 65535) {
          i3++;
        }
        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();

// packages/core/dist/index.js
init_esbuild_shims();
init_src2();

// node_modules/ink/build/index.js
init_esbuild_shims();

// node_modules/ink/build/render.js
init_esbuild_shims();
import { Stream as Stream6 } from "node:stream";
import process26 from "node:process";

// node_modules/ink/build/ink.js
init_esbuild_shims();
var import_react13 = __toESM(require_react(), 1);
import process25 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: () => link2,
  scrollDown: () => scrollDown,
  scrollUp: () => scrollUp
});
init_esbuild_shims();
import process16 from "node:process";

// node_modules/environment/index.js
init_esbuild_shims();
var isBrowser = globalThis.window?.document !== void 0;
var isNode2 = globalThis.process?.versions?.node !== void 0;
var isBun = globalThis.process?.versions?.bun !== void 0;
var isDeno = globalThis.Deno?.version?.deno !== void 0;
var isElectron2 = 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 platform12 = globalThis.navigator?.userAgentData?.platform;
var isMacOs = platform12 === "macOS" || globalThis.navigator?.platform === "MacIntel" || globalThis.navigator?.userAgent?.includes(" Mac ") === true || globalThis.process?.platform === "darwin";
var isWindows6 = platform12 === "Windows" || globalThis.navigator?.platform === "Win32" || globalThis.process?.platform === "win32";
var isLinux2 = platform12 === "Linux" || globalThis.navigator?.platform?.startsWith("Linux") === true || globalThis.navigator?.userAgent?.includes(" Linux ") === true || globalThis.process?.platform === "linux";
var isIos = platform12 === "iOS" || globalThis.navigator?.platform === "MacIntel" && globalThis.navigator?.maxTouchPoints > 1 || /iPad|iPhone|iPod/.test(globalThis.navigator?.platform);
var isAndroid = platform12 === "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 && process16.env.TERM_PROGRAM === "Apple_Terminal";
var isWindows7 = !isBrowser && process16.platform === "win32";
var cwdFunction = isBrowser ? () => {
  throw new Error("`process.cwd()` only works in Node.js, not the browser.");
} : process16.cwd;
var cursorTo = /* @__PURE__ */ __name((x3, y2) => {
  if (typeof x3 !== "number") {
    throw new TypeError("The `x` argument is required");
  }
  if (typeof y2 !== "number") {
    return ESC + (x3 + 1) + "G";
  }
  return ESC + (y2 + 1) + SEP + (x3 + 1) + "H";
}, "cursorTo");
var cursorMove = /* @__PURE__ */ __name((x3, y2) => {
  if (typeof x3 !== "number") {
    throw new TypeError("The `x` argument is required");
  }
  let returnValue = "";
  if (x3 < 0) {
    returnValue += ESC + -x3 + "D";
  } else if (x3 > 0) {
    returnValue += ESC + x3 + "C";
  }
  if (y2 < 0) {
    returnValue += ESC + -y2 + "A";
  } else if (y2 > 0) {
    returnValue += ESC + y2 + "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 i3 = 0; i3 < count; i3++) {
    clear += eraseLine + (i3 < 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 = isWindows7 ? `${eraseScreen}${ESC}0f` : `${eraseScreen}${ESC}3J${ESC}H`;
var enterAlternativeScreen = ESC + "?1049h";
var exitAlternativeScreen = ESC + "?1049l";
var beep = BEL;
var link2 = /* @__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((object3) => {
  const properties = /* @__PURE__ */ new Set();
  do {
    for (const key of Reflect.ownKeys(object3)) {
      properties.add([object3, key]);
    }
  } while ((object3 = Reflect.getPrototypeOf(object3)) && object3 !== 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 [object3, key] of getAllProperties(self2.constructor.prototype)) {
    if (key === "constructor" || !filter4(key)) {
      continue;
    }
    const descriptor2 = Reflect.getOwnPropertyDescriptor(object3, 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 as PassThrough4 } 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 PassThrough4();
  const stderr = new PassThrough4();
  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_default2 = patchConsole;

// node_modules/ink/build/ink.js
var import_constants33 = __toESM(require_constants12(), 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 h3;
    h3 || (h3 = typeof loadYoga2 !== "undefined" ? loadYoga2 : {});
    var aa, ca;
    h3.ready = new Promise(function(a2, b2) {
      aa = a2;
      ca = b2;
    });
    var da = Object.assign({}, h3), q2 = "";
    "undefined" != typeof document && document.currentScript && (q2 = document.currentScript.src);
    _scriptDir && (q2 = _scriptDir);
    0 !== q2.indexOf("blob:") ? q2 = q2.substr(0, q2.replace(/[?#].*/, "").lastIndexOf("/") + 1) : q2 = "";
    var ea = h3.print || console.log.bind(console), v2 = h3.printErr || console.warn.bind(console);
    Object.assign(h3, da);
    da = null;
    var w2;
    h3.wasmBinary && (w2 = h3.wasmBinary);
    var noExitRuntime = h3.noExitRuntime || true;
    "object" != typeof WebAssembly && x3("no native wasm support detected");
    var fa, ha = false;
    function z2(a2, b2, c4) {
      c4 = b2 + c4;
      for (var d2 = ""; !(b2 >= c4); ) {
        var e4 = a2[b2++];
        if (!e4) break;
        if (e4 & 128) {
          var f5 = a2[b2++] & 63;
          if (192 == (e4 & 224)) d2 += String.fromCharCode((e4 & 31) << 6 | f5);
          else {
            var g2 = a2[b2++] & 63;
            e4 = 224 == (e4 & 240) ? (e4 & 15) << 12 | f5 << 6 | g2 : (e4 & 7) << 18 | f5 << 12 | g2 << 6 | a2[b2++] & 63;
            65536 > e4 ? d2 += String.fromCharCode(e4) : (e4 -= 65536, d2 += String.fromCharCode(55296 | e4 >> 10, 56320 | e4 & 1023));
          }
        } else d2 += String.fromCharCode(e4);
      }
      return d2;
    }
    __name(z2, "z");
    var ia, ja, A4, C2, ka, D2, E2, la, ma;
    function na() {
      var a2 = fa.buffer;
      ia = a2;
      h3.HEAP8 = ja = new Int8Array(a2);
      h3.HEAP16 = C2 = new Int16Array(a2);
      h3.HEAP32 = D2 = new Int32Array(a2);
      h3.HEAPU8 = A4 = new Uint8Array(a2);
      h3.HEAPU16 = ka = new Uint16Array(a2);
      h3.HEAPU32 = E2 = new Uint32Array(a2);
      h3.HEAPF32 = la = new Float32Array(a2);
      h3.HEAPF64 = ma = new Float64Array(a2);
    }
    __name(na, "na");
    var oa, pa = [], qa = [], ra = [];
    function sa() {
      var a2 = h3.preRun.shift();
      pa.unshift(a2);
    }
    __name(sa, "sa");
    var F4 = 0, ta2 = null, G2 = null;
    function x3(a2) {
      if (h3.onAbort) h3.onAbort(a2);
      a2 = "Aborted(" + a2 + ")";
      v2(a2);
      ha = true;
      a2 = new WebAssembly.RuntimeError(a2 + ". Build with -sASSERTIONS for more info.");
      ca(a2);
      throw a2;
    }
    __name(x3, "x");
    function ua(a2) {
      return a2.startsWith("data:application/octet-stream;base64,");
    }
    __name(ua, "ua");
    var H2;
    H2 = "data:application/octet-stream;base64, ";
    if (!ua(H2)) {
      var va = H2;
      H2 = h3.locateFile ? h3.locateFile(va, q2) : q2 + va;
    }
    function wa() {
      var a2 = H2;
      try {
        if (a2 == H2 && w2) return new Uint8Array(w2);
        if (ua(a2)) try {
          var b2 = xa(a2.slice(37)), c4 = new Uint8Array(b2.length);
          for (a2 = 0; a2 < b2.length; ++a2) c4[a2] = b2.charCodeAt(a2);
          var d2 = c4;
        } catch (f5) {
          throw Error("Converting base64 string to bytes failed.");
        }
        else d2 = void 0;
        var e4 = d2;
        if (e4) return e4;
        throw "both async and sync fetching of the wasm failed";
      } catch (f5) {
        x3(f5);
      }
    }
    __name(wa, "wa");
    function ya() {
      return w2 || "function" != typeof fetch ? Promise.resolve().then(function() {
        return wa();
      }) : fetch(H2, { credentials: "same-origin" }).then(function(a2) {
        if (!a2.ok) throw "failed to load wasm binary file at '" + H2 + "'";
        return a2.arrayBuffer();
      }).catch(function() {
        return wa();
      });
    }
    __name(ya, "ya");
    function za(a2) {
      for (; 0 < a2.length; ) a2.shift()(h3);
    }
    __name(za, "za");
    function Aa(a2) {
      if (void 0 === a2) return "_unknown";
      a2 = a2.replace(/[^a-zA-Z0-9_]/g, "$");
      var b2 = a2.charCodeAt(0);
      return 48 <= b2 && 57 >= b2 ? "_" + a2 : a2;
    }
    __name(Aa, "Aa");
    function Ba(a2, b2) {
      a2 = Aa(a2);
      return function() {
        return b2.apply(this, arguments);
      };
    }
    __name(Ba, "Ba");
    var J2 = [{}, { value: void 0 }, { value: null }, { value: true }, { value: false }], Ca = [];
    function Da(a2) {
      var b2 = Error, c4 = Ba(a2, function(d2) {
        this.name = a2;
        this.message = d2;
        d2 = Error(d2).stack;
        void 0 !== d2 && (this.stack = this.toString() + "\n" + d2.replace(/^Error(:[^\n]*)?\n/, ""));
      });
      c4.prototype = Object.create(b2.prototype);
      c4.prototype.constructor = c4;
      c4.prototype.toString = function() {
        return void 0 === this.message ? this.name : this.name + ": " + this.message;
      };
      return c4;
    }
    __name(Da, "Da");
    var K2 = void 0;
    function L2(a2) {
      throw new K2(a2);
    }
    __name(L2, "L");
    var M2 = /* @__PURE__ */ __name((a2) => {
      a2 || L2("Cannot use deleted val. handle = " + a2);
      return J2[a2].value;
    }, "M"), Ea = /* @__PURE__ */ __name((a2) => {
      switch (a2) {
        case void 0:
          return 1;
        case null:
          return 2;
        case true:
          return 3;
        case false:
          return 4;
        default:
          var b2 = Ca.length ? Ca.pop() : J2.length;
          J2[b2] = { ga: 1, value: a2 };
          return b2;
      }
    }, "Ea"), Fa = void 0, Ga = void 0;
    function N2(a2) {
      for (var b2 = ""; A4[a2]; ) b2 += Ga[A4[a2++]];
      return b2;
    }
    __name(N2, "N");
    var O2 = [];
    function Ha() {
      for (; O2.length; ) {
        var a2 = O2.pop();
        a2.M.$ = false;
        a2["delete"]();
      }
    }
    __name(Ha, "Ha");
    var P2 = void 0, Q2 = {};
    function Ia(a2, b2) {
      for (void 0 === b2 && L2("ptr should not be undefined"); a2.R; ) b2 = a2.ba(b2), a2 = a2.R;
      return b2;
    }
    __name(Ia, "Ia");
    var R2 = {};
    function Ja(a2) {
      a2 = Ka(a2);
      var b2 = N2(a2);
      S4(a2);
      return b2;
    }
    __name(Ja, "Ja");
    function La(a2, b2) {
      var c4 = R2[a2];
      void 0 === c4 && L2(b2 + " has unknown type " + Ja(a2));
      return c4;
    }
    __name(La, "La");
    function Ma() {
    }
    __name(Ma, "Ma");
    var Na = false;
    function Oa(a2) {
      --a2.count.value;
      0 === a2.count.value && (a2.T ? a2.U.W(a2.T) : a2.P.N.W(a2.O));
    }
    __name(Oa, "Oa");
    function Pa(a2, b2, c4) {
      if (b2 === c4) return a2;
      if (void 0 === c4.R) return null;
      a2 = Pa(a2, b2, c4.R);
      return null === a2 ? null : c4.na(a2);
    }
    __name(Pa, "Pa");
    var Qa = {};
    function Ra(a2, b2) {
      b2 = Ia(a2, b2);
      return Q2[b2];
    }
    __name(Ra, "Ra");
    var Sa = void 0;
    function Ta(a2) {
      throw new Sa(a2);
    }
    __name(Ta, "Ta");
    function Ua(a2, b2) {
      b2.P && b2.O || Ta("makeClassHandle requires ptr and ptrType");
      !!b2.U !== !!b2.T && Ta("Both smartPtrType and smartPtr must be specified");
      b2.count = { value: 1 };
      return T2(Object.create(a2, { M: { value: b2 } }));
    }
    __name(Ua, "Ua");
    function T2(a2) {
      if ("undefined" === typeof FinalizationRegistry) return T2 = /* @__PURE__ */ __name((b2) => b2, "T"), a2;
      Na = new FinalizationRegistry((b2) => {
        Oa(b2.M);
      });
      T2 = /* @__PURE__ */ __name((b2) => {
        var c4 = b2.M;
        c4.T && Na.register(b2, { M: c4 }, b2);
        return b2;
      }, "T");
      Ma = /* @__PURE__ */ __name((b2) => {
        Na.unregister(b2);
      }, "Ma");
      return T2(a2);
    }
    __name(T2, "T");
    var Va = {};
    function Wa(a2) {
      for (; a2.length; ) {
        var b2 = a2.pop();
        a2.pop()(b2);
      }
    }
    __name(Wa, "Wa");
    function Xa(a2) {
      return this.fromWireType(D2[a2 >> 2]);
    }
    __name(Xa, "Xa");
    var U2 = {}, Ya = {};
    function V3(a2, b2, c4) {
      function d2(k2) {
        k2 = c4(k2);
        k2.length !== a2.length && Ta("Mismatched type converter count");
        for (var m3 = 0; m3 < a2.length; ++m3) W2(a2[m3], k2[m3]);
      }
      __name(d2, "d");
      a2.forEach(function(k2) {
        Ya[k2] = b2;
      });
      var e4 = Array(b2.length), f5 = [], g2 = 0;
      b2.forEach((k2, m3) => {
        R2.hasOwnProperty(k2) ? e4[m3] = R2[k2] : (f5.push(k2), U2.hasOwnProperty(k2) || (U2[k2] = []), U2[k2].push(() => {
          e4[m3] = R2[k2];
          ++g2;
          g2 === f5.length && d2(e4);
        }));
      });
      0 === f5.length && d2(e4);
    }
    __name(V3, "V");
    function Za(a2) {
      switch (a2) {
        case 1:
          return 0;
        case 2:
          return 1;
        case 4:
          return 2;
        case 8:
          return 3;
        default:
          throw new TypeError("Unknown type size: " + a2);
      }
    }
    __name(Za, "Za");
    function W2(a2, b2, c4 = {}) {
      if (!("argPackAdvance" in b2)) throw new TypeError("registerType registeredInstance requires argPackAdvance");
      var d2 = b2.name;
      a2 || L2('type "' + d2 + '" must have a positive integer typeid pointer');
      if (R2.hasOwnProperty(a2)) {
        if (c4.ua) return;
        L2("Cannot register type '" + d2 + "' twice");
      }
      R2[a2] = b2;
      delete Ya[a2];
      U2.hasOwnProperty(a2) && (b2 = U2[a2], delete U2[a2], b2.forEach((e4) => e4()));
    }
    __name(W2, "W");
    function $a(a2) {
      L2(a2.M.P.N.name + " instance already deleted");
    }
    __name($a, "$a");
    function X2() {
    }
    __name(X2, "X");
    function ab2(a2, b2, c4) {
      if (void 0 === a2[b2].S) {
        var d2 = a2[b2];
        a2[b2] = function() {
          a2[b2].S.hasOwnProperty(arguments.length) || L2("Function '" + c4 + "' called with an invalid number of arguments (" + arguments.length + ") - expects one of (" + a2[b2].S + ")!");
          return a2[b2].S[arguments.length].apply(this, arguments);
        };
        a2[b2].S = [];
        a2[b2].S[d2.Z] = d2;
      }
    }
    __name(ab2, "ab");
    function bb(a2, b2) {
      h3.hasOwnProperty(a2) ? (L2("Cannot register public name '" + a2 + "' twice"), ab2(h3, a2, a2), h3.hasOwnProperty(void 0) && L2("Cannot register multiple overloads of a function with the same number of arguments (undefined)!"), h3[a2].S[void 0] = b2) : h3[a2] = b2;
    }
    __name(bb, "bb");
    function cb(a2, b2, c4, d2, e4, f5, g2, k2) {
      this.name = a2;
      this.constructor = b2;
      this.X = c4;
      this.W = d2;
      this.R = e4;
      this.pa = f5;
      this.ba = g2;
      this.na = k2;
      this.ja = [];
    }
    __name(cb, "cb");
    function db(a2, b2, c4) {
      for (; b2 !== c4; ) b2.ba || L2("Expected null or instance of " + c4.name + ", got an instance of " + b2.name), a2 = b2.ba(a2), b2 = b2.R;
      return a2;
    }
    __name(db, "db");
    function eb(a2, b2) {
      if (null === b2) return this.ea && L2("null is not a valid " + this.name), 0;
      b2.M || L2('Cannot pass "' + fb(b2) + '" as a ' + this.name);
      b2.M.O || L2("Cannot pass deleted object as a pointer of type " + this.name);
      return db(b2.M.O, b2.M.P.N, this.N);
    }
    __name(eb, "eb");
    function gb(a2, b2) {
      if (null === b2) {
        this.ea && L2("null is not a valid " + this.name);
        if (this.da) {
          var c4 = this.fa();
          null !== a2 && a2.push(this.W, c4);
          return c4;
        }
        return 0;
      }
      b2.M || L2('Cannot pass "' + fb(b2) + '" as a ' + this.name);
      b2.M.O || L2("Cannot pass deleted object as a pointer of type " + this.name);
      !this.ca && b2.M.P.ca && L2("Cannot convert argument of type " + (b2.M.U ? b2.M.U.name : b2.M.P.name) + " to parameter type " + this.name);
      c4 = db(b2.M.O, b2.M.P.N, this.N);
      if (this.da) switch (void 0 === b2.M.T && L2("Passing raw pointer to smart pointer is illegal"), this.Ba) {
        case 0:
          b2.M.U === this ? c4 = b2.M.T : L2("Cannot convert argument of type " + (b2.M.U ? b2.M.U.name : b2.M.P.name) + " to parameter type " + this.name);
          break;
        case 1:
          c4 = b2.M.T;
          break;
        case 2:
          if (b2.M.U === this) c4 = b2.M.T;
          else {
            var d2 = b2.clone();
            c4 = this.xa(c4, Ea(function() {
              d2["delete"]();
            }));
            null !== a2 && a2.push(this.W, c4);
          }
          break;
        default:
          L2("Unsupporting sharing policy");
      }
      return c4;
    }
    __name(gb, "gb");
    function hb(a2, b2) {
      if (null === b2) return this.ea && L2("null is not a valid " + this.name), 0;
      b2.M || L2('Cannot pass "' + fb(b2) + '" as a ' + this.name);
      b2.M.O || L2("Cannot pass deleted object as a pointer of type " + this.name);
      b2.M.P.ca && L2("Cannot convert argument of type " + b2.M.P.name + " to parameter type " + this.name);
      return db(b2.M.O, b2.M.P.N, this.N);
    }
    __name(hb, "hb");
    function Y2(a2, b2, c4, d2) {
      this.name = a2;
      this.N = b2;
      this.ea = c4;
      this.ca = d2;
      this.da = false;
      this.W = this.xa = this.fa = this.ka = this.Ba = this.wa = void 0;
      void 0 !== b2.R ? this.toWireType = gb : (this.toWireType = d2 ? eb : hb, this.V = null);
    }
    __name(Y2, "Y");
    function ib(a2, b2) {
      h3.hasOwnProperty(a2) || Ta("Replacing nonexistant public symbol");
      h3[a2] = b2;
      h3[a2].Z = void 0;
    }
    __name(ib, "ib");
    function jb(a2, b2) {
      var c4 = [];
      return function() {
        c4.length = 0;
        Object.assign(c4, arguments);
        if (a2.includes("j")) {
          var d2 = h3["dynCall_" + a2];
          d2 = c4 && c4.length ? d2.apply(null, [b2].concat(c4)) : d2.call(null, b2);
        } else d2 = oa.get(b2).apply(null, c4);
        return d2;
      };
    }
    __name(jb, "jb");
    function Z4(a2, b2) {
      a2 = N2(a2);
      var c4 = a2.includes("j") ? jb(a2, b2) : oa.get(b2);
      "function" != typeof c4 && L2("unknown function pointer with signature " + a2 + ": " + b2);
      return c4;
    }
    __name(Z4, "Z");
    var mb = void 0;
    function nb(a2, b2) {
      function c4(f5) {
        e4[f5] || R2[f5] || (Ya[f5] ? Ya[f5].forEach(c4) : (d2.push(f5), e4[f5] = true));
      }
      __name(c4, "c");
      var d2 = [], e4 = {};
      b2.forEach(c4);
      throw new mb(a2 + ": " + d2.map(Ja).join([", "]));
    }
    __name(nb, "nb");
    function ob(a2, b2, c4, d2, e4) {
      var f5 = b2.length;
      2 > f5 && L2("argTypes array size mismatch! Must at least get return value and 'this' types!");
      var g2 = null !== b2[1] && null !== c4, k2 = false;
      for (c4 = 1; c4 < b2.length; ++c4) if (null !== b2[c4] && void 0 === b2[c4].V) {
        k2 = true;
        break;
      }
      var m3 = "void" !== b2[0].name, l3 = f5 - 2, n3 = Array(l3), p2 = [], r5 = [];
      return function() {
        arguments.length !== l3 && L2("function " + a2 + " called with " + arguments.length + " arguments, expected " + l3 + " args!");
        r5.length = 0;
        p2.length = g2 ? 2 : 1;
        p2[0] = e4;
        if (g2) {
          var u2 = b2[1].toWireType(r5, this);
          p2[1] = u2;
        }
        for (var t5 = 0; t5 < l3; ++t5) n3[t5] = b2[t5 + 2].toWireType(r5, arguments[t5]), p2.push(n3[t5]);
        t5 = d2.apply(null, p2);
        if (k2) Wa(r5);
        else for (var y2 = g2 ? 1 : 2; y2 < b2.length; y2++) {
          var B2 = 1 === y2 ? u2 : n3[y2 - 2];
          null !== b2[y2].V && b2[y2].V(B2);
        }
        u2 = m3 ? b2[0].fromWireType(t5) : void 0;
        return u2;
      };
    }
    __name(ob, "ob");
    function pb(a2, b2) {
      for (var c4 = [], d2 = 0; d2 < a2; d2++) c4.push(E2[b2 + 4 * d2 >> 2]);
      return c4;
    }
    __name(pb, "pb");
    function qb(a2) {
      4 < a2 && 0 === --J2[a2].ga && (J2[a2] = void 0, Ca.push(a2));
    }
    __name(qb, "qb");
    function fb(a2) {
      if (null === a2) return "null";
      var b2 = typeof a2;
      return "object" === b2 || "array" === b2 || "function" === b2 ? a2.toString() : "" + a2;
    }
    __name(fb, "fb");
    function rb(a2, b2) {
      switch (b2) {
        case 2:
          return function(c4) {
            return this.fromWireType(la[c4 >> 2]);
          };
        case 3:
          return function(c4) {
            return this.fromWireType(ma[c4 >> 3]);
          };
        default:
          throw new TypeError("Unknown float type: " + a2);
      }
    }
    __name(rb, "rb");
    function sb(a2, b2, c4) {
      switch (b2) {
        case 0:
          return c4 ? function(d2) {
            return ja[d2];
          } : function(d2) {
            return A4[d2];
          };
        case 1:
          return c4 ? function(d2) {
            return C2[d2 >> 1];
          } : function(d2) {
            return ka[d2 >> 1];
          };
        case 2:
          return c4 ? function(d2) {
            return D2[d2 >> 2];
          } : function(d2) {
            return E2[d2 >> 2];
          };
        default:
          throw new TypeError("Unknown integer type: " + a2);
      }
    }
    __name(sb, "sb");
    function tb(a2, b2) {
      for (var c4 = "", d2 = 0; !(d2 >= b2 / 2); ++d2) {
        var e4 = C2[a2 + 2 * d2 >> 1];
        if (0 == e4) break;
        c4 += String.fromCharCode(e4);
      }
      return c4;
    }
    __name(tb, "tb");
    function ub(a2, b2, c4) {
      void 0 === c4 && (c4 = 2147483647);
      if (2 > c4) return 0;
      c4 -= 2;
      var d2 = b2;
      c4 = c4 < 2 * a2.length ? c4 / 2 : a2.length;
      for (var e4 = 0; e4 < c4; ++e4) C2[b2 >> 1] = a2.charCodeAt(e4), b2 += 2;
      C2[b2 >> 1] = 0;
      return b2 - d2;
    }
    __name(ub, "ub");
    function vb(a2) {
      return 2 * a2.length;
    }
    __name(vb, "vb");
    function wb(a2, b2) {
      for (var c4 = 0, d2 = ""; !(c4 >= b2 / 4); ) {
        var e4 = D2[a2 + 4 * c4 >> 2];
        if (0 == e4) break;
        ++c4;
        65536 <= e4 ? (e4 -= 65536, d2 += String.fromCharCode(55296 | e4 >> 10, 56320 | e4 & 1023)) : d2 += String.fromCharCode(e4);
      }
      return d2;
    }
    __name(wb, "wb");
    function xb(a2, b2, c4) {
      void 0 === c4 && (c4 = 2147483647);
      if (4 > c4) return 0;
      var d2 = b2;
      c4 = d2 + c4 - 4;
      for (var e4 = 0; e4 < a2.length; ++e4) {
        var f5 = a2.charCodeAt(e4);
        if (55296 <= f5 && 57343 >= f5) {
          var g2 = a2.charCodeAt(++e4);
          f5 = 65536 + ((f5 & 1023) << 10) | g2 & 1023;
        }
        D2[b2 >> 2] = f5;
        b2 += 4;
        if (b2 + 4 > c4) break;
      }
      D2[b2 >> 2] = 0;
      return b2 - d2;
    }
    __name(xb, "xb");
    function yb(a2) {
      for (var b2 = 0, c4 = 0; c4 < a2.length; ++c4) {
        var d2 = a2.charCodeAt(c4);
        55296 <= d2 && 57343 >= d2 && ++c4;
        b2 += 4;
      }
      return b2;
    }
    __name(yb, "yb");
    var zb = {};
    function Ab(a2) {
      var b2 = zb[a2];
      return void 0 === b2 ? N2(a2) : b2;
    }
    __name(Ab, "Ab");
    var Bb = [];
    function Cb(a2) {
      var b2 = Bb.length;
      Bb.push(a2);
      return b2;
    }
    __name(Cb, "Cb");
    function Db(a2, b2) {
      for (var c4 = Array(a2), d2 = 0; d2 < a2; ++d2) c4[d2] = La(E2[b2 + 4 * d2 >> 2], "parameter " + d2);
      return c4;
    }
    __name(Db, "Db");
    var Eb = [], Fb = [null, [], []];
    K2 = h3.BindingError = Da("BindingError");
    h3.count_emval_handles = function() {
      for (var a2 = 0, b2 = 5; b2 < J2.length; ++b2) void 0 !== J2[b2] && ++a2;
      return a2;
    };
    h3.get_first_emval = function() {
      for (var a2 = 5; a2 < J2.length; ++a2) if (void 0 !== J2[a2]) return J2[a2];
      return null;
    };
    Fa = h3.PureVirtualError = Da("PureVirtualError");
    for (var Gb = Array(256), Hb = 0; 256 > Hb; ++Hb) Gb[Hb] = String.fromCharCode(Hb);
    Ga = Gb;
    h3.getInheritedInstanceCount = function() {
      return Object.keys(Q2).length;
    };
    h3.getLiveInheritedInstances = function() {
      var a2 = [], b2;
      for (b2 in Q2) Q2.hasOwnProperty(b2) && a2.push(Q2[b2]);
      return a2;
    };
    h3.flushPendingDeletes = Ha;
    h3.setDelayFunction = function(a2) {
      P2 = a2;
      O2.length && P2 && P2(Ha);
    };
    Sa = h3.InternalError = Da("InternalError");
    X2.prototype.isAliasOf = function(a2) {
      if (!(this instanceof X2 && a2 instanceof X2)) return false;
      var b2 = this.M.P.N, c4 = this.M.O, d2 = a2.M.P.N;
      for (a2 = a2.M.O; b2.R; ) c4 = b2.ba(c4), b2 = b2.R;
      for (; d2.R; ) a2 = d2.ba(a2), d2 = d2.R;
      return b2 === d2 && c4 === a2;
    };
    X2.prototype.clone = function() {
      this.M.O || $a(this);
      if (this.M.aa) return this.M.count.value += 1, this;
      var a2 = T2, b2 = Object, c4 = b2.create, d2 = Object.getPrototypeOf(this), e4 = this.M;
      a2 = a2(c4.call(b2, d2, { M: { value: { count: e4.count, $: e4.$, aa: e4.aa, O: e4.O, P: e4.P, T: e4.T, U: e4.U } } }));
      a2.M.count.value += 1;
      a2.M.$ = false;
      return a2;
    };
    X2.prototype["delete"] = function() {
      this.M.O || $a(this);
      this.M.$ && !this.M.aa && L2("Object already scheduled for deletion");
      Ma(this);
      Oa(this.M);
      this.M.aa || (this.M.T = void 0, this.M.O = void 0);
    };
    X2.prototype.isDeleted = function() {
      return !this.M.O;
    };
    X2.prototype.deleteLater = function() {
      this.M.O || $a(this);
      this.M.$ && !this.M.aa && L2("Object already scheduled for deletion");
      O2.push(this);
      1 === O2.length && P2 && P2(Ha);
      this.M.$ = true;
      return this;
    };
    Y2.prototype.qa = function(a2) {
      this.ka && (a2 = this.ka(a2));
      return a2;
    };
    Y2.prototype.ha = function(a2) {
      this.W && this.W(a2);
    };
    Y2.prototype.argPackAdvance = 8;
    Y2.prototype.readValueFromPointer = Xa;
    Y2.prototype.deleteObject = function(a2) {
      if (null !== a2) a2["delete"]();
    };
    Y2.prototype.fromWireType = function(a2) {
      function b2() {
        return this.da ? Ua(this.N.X, { P: this.wa, O: c4, U: this, T: a2 }) : Ua(this.N.X, { P: this, O: a2 });
      }
      __name(b2, "b");
      var c4 = this.qa(a2);
      if (!c4) return this.ha(a2), null;
      var d2 = Ra(this.N, c4);
      if (void 0 !== d2) {
        if (0 === d2.M.count.value) return d2.M.O = c4, d2.M.T = a2, d2.clone();
        d2 = d2.clone();
        this.ha(a2);
        return d2;
      }
      d2 = this.N.pa(c4);
      d2 = Qa[d2];
      if (!d2) return b2.call(this);
      d2 = this.ca ? d2.la : d2.pointerType;
      var e4 = Pa(c4, this.N, d2.N);
      return null === e4 ? b2.call(this) : this.da ? Ua(d2.N.X, { P: d2, O: e4, U: this, T: a2 }) : Ua(d2.N.X, { P: d2, O: e4 });
    };
    mb = h3.UnboundTypeError = Da("UnboundTypeError");
    var xa = "function" == typeof atob ? atob : function(a2) {
      var b2 = "", c4 = 0;
      a2 = a2.replace(/[^A-Za-z0-9\+\/=]/g, "");
      do {
        var d2 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(a2.charAt(c4++));
        var e4 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(a2.charAt(c4++));
        var f5 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(a2.charAt(c4++));
        var g2 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(a2.charAt(c4++));
        d2 = d2 << 2 | e4 >> 4;
        e4 = (e4 & 15) << 4 | f5 >> 2;
        var k2 = (f5 & 3) << 6 | g2;
        b2 += String.fromCharCode(d2);
        64 !== f5 && (b2 += String.fromCharCode(e4));
        64 !== g2 && (b2 += String.fromCharCode(k2));
      } while (c4 < a2.length);
      return b2;
    }, Jb = {
      l: /* @__PURE__ */ __name(function(a2, b2, c4, d2) {
        x3("Assertion failed: " + (a2 ? z2(A4, a2) : "") + ", at: " + [b2 ? b2 ? z2(A4, b2) : "" : "unknown filename", c4, d2 ? d2 ? z2(A4, d2) : "" : "unknown function"]);
      }, "l"),
      q: /* @__PURE__ */ __name(function(a2, b2, c4) {
        a2 = N2(a2);
        b2 = La(b2, "wrapper");
        c4 = M2(c4);
        var d2 = [].slice, e4 = b2.N, f5 = e4.X, g2 = e4.R.X, k2 = e4.R.constructor;
        a2 = Ba(a2, function() {
          e4.R.ja.forEach(function(l3) {
            if (this[l3] === g2[l3]) throw new Fa("Pure virtual function " + l3 + " must be implemented in JavaScript");
          }.bind(this));
          Object.defineProperty(this, "__parent", { value: f5 });
          this.__construct.apply(this, d2.call(arguments));
        });
        f5.__construct = function() {
          this === f5 && L2("Pass correct 'this' to __construct");
          var l3 = k2.implement.apply(void 0, [this].concat(d2.call(arguments)));
          Ma(l3);
          var n3 = l3.M;
          l3.notifyOnDestruction();
          n3.aa = true;
          Object.defineProperties(this, { M: { value: n3 } });
          T2(this);
          l3 = n3.O;
          l3 = Ia(e4, l3);
          Q2.hasOwnProperty(l3) ? L2("Tried to register registered instance: " + l3) : Q2[l3] = this;
        };
        f5.__destruct = function() {
          this === f5 && L2("Pass correct 'this' to __destruct");
          Ma(this);
          var l3 = this.M.O;
          l3 = Ia(e4, l3);
          Q2.hasOwnProperty(l3) ? delete Q2[l3] : L2("Tried to unregister unregistered instance: " + l3);
        };
        a2.prototype = Object.create(f5);
        for (var m3 in c4) a2.prototype[m3] = c4[m3];
        return Ea(a2);
      }, "q"),
      j: /* @__PURE__ */ __name(function(a2) {
        var b2 = Va[a2];
        delete Va[a2];
        var c4 = b2.fa, d2 = b2.W, e4 = b2.ia, f5 = e4.map((g2) => g2.ta).concat(e4.map((g2) => g2.za));
        V3([a2], f5, (g2) => {
          var k2 = {};
          e4.forEach((m3, l3) => {
            var n3 = g2[l3], p2 = m3.ra, r5 = m3.sa, u2 = g2[l3 + e4.length], t5 = m3.ya, y2 = m3.Aa;
            k2[m3.oa] = { read: /* @__PURE__ */ __name((B2) => n3.fromWireType(p2(r5, B2)), "read"), write: /* @__PURE__ */ __name((B2, ba) => {
              var I3 = [];
              t5(
                y2,
                B2,
                u2.toWireType(I3, ba)
              );
              Wa(I3);
            }, "write") };
          });
          return [{ name: b2.name, fromWireType: /* @__PURE__ */ __name(function(m3) {
            var l3 = {}, n3;
            for (n3 in k2) l3[n3] = k2[n3].read(m3);
            d2(m3);
            return l3;
          }, "fromWireType"), toWireType: /* @__PURE__ */ __name(function(m3, l3) {
            for (var n3 in k2) if (!(n3 in l3)) throw new TypeError('Missing field:  "' + n3 + '"');
            var p2 = c4();
            for (n3 in k2) k2[n3].write(p2, l3[n3]);
            null !== m3 && m3.push(d2, p2);
            return p2;
          }, "toWireType"), argPackAdvance: 8, readValueFromPointer: Xa, V: d2 }];
        });
      }, "j"),
      v: /* @__PURE__ */ __name(function() {
      }, "v"),
      B: /* @__PURE__ */ __name(function(a2, b2, c4, d2, e4) {
        var f5 = Za(c4);
        b2 = N2(b2);
        W2(a2, {
          name: b2,
          fromWireType: /* @__PURE__ */ __name(function(g2) {
            return !!g2;
          }, "fromWireType"),
          toWireType: /* @__PURE__ */ __name(function(g2, k2) {
            return k2 ? d2 : e4;
          }, "toWireType"),
          argPackAdvance: 8,
          readValueFromPointer: /* @__PURE__ */ __name(function(g2) {
            if (1 === c4) var k2 = ja;
            else if (2 === c4) k2 = C2;
            else if (4 === c4) k2 = D2;
            else throw new TypeError("Unknown boolean type size: " + b2);
            return this.fromWireType(k2[g2 >> f5]);
          }, "readValueFromPointer"),
          V: null
        });
      }, "B"),
      f: /* @__PURE__ */ __name(function(a2, b2, c4, d2, e4, f5, g2, k2, m3, l3, n3, p2, r5) {
        n3 = N2(n3);
        f5 = Z4(e4, f5);
        k2 && (k2 = Z4(g2, k2));
        l3 && (l3 = Z4(m3, l3));
        r5 = Z4(p2, r5);
        var u2 = Aa(n3);
        bb(u2, function() {
          nb("Cannot construct " + n3 + " due to unbound types", [d2]);
        });
        V3([a2, b2, c4], d2 ? [d2] : [], function(t5) {
          t5 = t5[0];
          if (d2) {
            var y2 = t5.N;
            var B2 = y2.X;
          } else B2 = X2.prototype;
          t5 = Ba(u2, function() {
            if (Object.getPrototypeOf(this) !== ba) throw new K2("Use 'new' to construct " + n3);
            if (void 0 === I3.Y) throw new K2(n3 + " has no accessible constructor");
            var kb = I3.Y[arguments.length];
            if (void 0 === kb) throw new K2("Tried to invoke ctor of " + n3 + " with invalid number of parameters (" + arguments.length + ") - expected (" + Object.keys(I3.Y).toString() + ") parameters instead!");
            return kb.apply(this, arguments);
          });
          var ba = Object.create(B2, { constructor: { value: t5 } });
          t5.prototype = ba;
          var I3 = new cb(n3, t5, ba, r5, y2, f5, k2, l3);
          y2 = new Y2(n3, I3, true, false);
          B2 = new Y2(n3 + "*", I3, false, false);
          var lb = new Y2(n3 + " const*", I3, false, true);
          Qa[a2] = {
            pointerType: B2,
            la: lb
          };
          ib(u2, t5);
          return [y2, B2, lb];
        });
      }, "f"),
      d: /* @__PURE__ */ __name(function(a2, b2, c4, d2, e4, f5, g2) {
        var k2 = pb(c4, d2);
        b2 = N2(b2);
        f5 = Z4(e4, f5);
        V3([], [a2], function(m3) {
          function l3() {
            nb("Cannot call " + n3 + " due to unbound types", k2);
          }
          __name(l3, "l");
          m3 = m3[0];
          var n3 = m3.name + "." + b2;
          b2.startsWith("@@") && (b2 = Symbol[b2.substring(2)]);
          var p2 = m3.N.constructor;
          void 0 === p2[b2] ? (l3.Z = c4 - 1, p2[b2] = l3) : (ab2(p2, b2, n3), p2[b2].S[c4 - 1] = l3);
          V3([], k2, function(r5) {
            r5 = ob(n3, [r5[0], null].concat(r5.slice(1)), null, f5, g2);
            void 0 === p2[b2].S ? (r5.Z = c4 - 1, p2[b2] = r5) : p2[b2].S[c4 - 1] = r5;
            return [];
          });
          return [];
        });
      }, "d"),
      p: /* @__PURE__ */ __name(function(a2, b2, c4, d2, e4, f5) {
        0 < b2 || x3();
        var g2 = pb(
          b2,
          c4
        );
        e4 = Z4(d2, e4);
        V3([], [a2], function(k2) {
          k2 = k2[0];
          var m3 = "constructor " + k2.name;
          void 0 === k2.N.Y && (k2.N.Y = []);
          if (void 0 !== k2.N.Y[b2 - 1]) throw new K2("Cannot register multiple constructors with identical number of parameters (" + (b2 - 1) + ") for class '" + k2.name + "'! Overload resolution is currently only performed using the parameter count, not actual type info!");
          k2.N.Y[b2 - 1] = () => {
            nb("Cannot construct " + k2.name + " due to unbound types", g2);
          };
          V3([], g2, function(l3) {
            l3.splice(1, 0, null);
            k2.N.Y[b2 - 1] = ob(m3, l3, null, e4, f5);
            return [];
          });
          return [];
        });
      }, "p"),
      a: /* @__PURE__ */ __name(function(a2, b2, c4, d2, e4, f5, g2, k2) {
        var m3 = pb(c4, d2);
        b2 = N2(b2);
        f5 = Z4(e4, f5);
        V3([], [a2], function(l3) {
          function n3() {
            nb("Cannot call " + p2 + " due to unbound types", m3);
          }
          __name(n3, "n");
          l3 = l3[0];
          var p2 = l3.name + "." + b2;
          b2.startsWith("@@") && (b2 = Symbol[b2.substring(2)]);
          k2 && l3.N.ja.push(b2);
          var r5 = l3.N.X, u2 = r5[b2];
          void 0 === u2 || void 0 === u2.S && u2.className !== l3.name && u2.Z === c4 - 2 ? (n3.Z = c4 - 2, n3.className = l3.name, r5[b2] = n3) : (ab2(r5, b2, p2), r5[b2].S[c4 - 2] = n3);
          V3([], m3, function(t5) {
            t5 = ob(p2, t5, l3, f5, g2);
            void 0 === r5[b2].S ? (t5.Z = c4 - 2, r5[b2] = t5) : r5[b2].S[c4 - 2] = t5;
            return [];
          });
          return [];
        });
      }, "a"),
      A: /* @__PURE__ */ __name(function(a2, b2) {
        b2 = N2(b2);
        W2(
          a2,
          { name: b2, fromWireType: /* @__PURE__ */ __name(function(c4) {
            var d2 = M2(c4);
            qb(c4);
            return d2;
          }, "fromWireType"), toWireType: /* @__PURE__ */ __name(function(c4, d2) {
            return Ea(d2);
          }, "toWireType"), argPackAdvance: 8, readValueFromPointer: Xa, V: null }
        );
      }, "A"),
      n: /* @__PURE__ */ __name(function(a2, b2, c4) {
        c4 = Za(c4);
        b2 = N2(b2);
        W2(a2, { name: b2, fromWireType: /* @__PURE__ */ __name(function(d2) {
          return d2;
        }, "fromWireType"), toWireType: /* @__PURE__ */ __name(function(d2, e4) {
          return e4;
        }, "toWireType"), argPackAdvance: 8, readValueFromPointer: rb(b2, c4), V: null });
      }, "n"),
      e: /* @__PURE__ */ __name(function(a2, b2, c4, d2, e4) {
        b2 = N2(b2);
        -1 === e4 && (e4 = 4294967295);
        e4 = Za(c4);
        var f5 = /* @__PURE__ */ __name((k2) => k2, "f");
        if (0 === d2) {
          var g2 = 32 - 8 * c4;
          f5 = /* @__PURE__ */ __name((k2) => k2 << g2 >>> g2, "f");
        }
        c4 = b2.includes("unsigned") ? function(k2, m3) {
          return m3 >>> 0;
        } : function(k2, m3) {
          return m3;
        };
        W2(a2, { name: b2, fromWireType: f5, toWireType: c4, argPackAdvance: 8, readValueFromPointer: sb(b2, e4, 0 !== d2), V: null });
      }, "e"),
      b: /* @__PURE__ */ __name(function(a2, b2, c4) {
        function d2(f5) {
          f5 >>= 2;
          var g2 = E2;
          return new e4(ia, g2[f5 + 1], g2[f5]);
        }
        __name(d2, "d");
        var e4 = [Int8Array, Uint8Array, Int16Array, Uint16Array, Int32Array, Uint32Array, Float32Array, Float64Array][b2];
        c4 = N2(c4);
        W2(a2, { name: c4, fromWireType: d2, argPackAdvance: 8, readValueFromPointer: d2 }, { ua: true });
      }, "b"),
      o: /* @__PURE__ */ __name(function(a2, b2) {
        b2 = N2(b2);
        var c4 = "std::string" === b2;
        W2(a2, { name: b2, fromWireType: /* @__PURE__ */ __name(function(d2) {
          var e4 = E2[d2 >> 2], f5 = d2 + 4;
          if (c4) for (var g2 = f5, k2 = 0; k2 <= e4; ++k2) {
            var m3 = f5 + k2;
            if (k2 == e4 || 0 == A4[m3]) {
              g2 = g2 ? z2(A4, g2, m3 - g2) : "";
              if (void 0 === l3) var l3 = g2;
              else l3 += String.fromCharCode(0), l3 += g2;
              g2 = m3 + 1;
            }
          }
          else {
            l3 = Array(e4);
            for (k2 = 0; k2 < e4; ++k2) l3[k2] = String.fromCharCode(A4[f5 + k2]);
            l3 = l3.join("");
          }
          S4(d2);
          return l3;
        }, "fromWireType"), toWireType: /* @__PURE__ */ __name(function(d2, e4) {
          e4 instanceof ArrayBuffer && (e4 = new Uint8Array(e4));
          var f5, g2 = "string" == typeof e4;
          g2 || e4 instanceof Uint8Array || e4 instanceof Uint8ClampedArray || e4 instanceof Int8Array || L2("Cannot pass non-string to std::string");
          if (c4 && g2) {
            var k2 = 0;
            for (f5 = 0; f5 < e4.length; ++f5) {
              var m3 = e4.charCodeAt(f5);
              127 >= m3 ? k2++ : 2047 >= m3 ? k2 += 2 : 55296 <= m3 && 57343 >= m3 ? (k2 += 4, ++f5) : k2 += 3;
            }
            f5 = k2;
          } else f5 = e4.length;
          k2 = Ib(4 + f5 + 1);
          m3 = k2 + 4;
          E2[k2 >> 2] = f5;
          if (c4 && g2) {
            if (g2 = m3, m3 = f5 + 1, f5 = A4, 0 < m3) {
              m3 = g2 + m3 - 1;
              for (var l3 = 0; l3 < e4.length; ++l3) {
                var n3 = e4.charCodeAt(l3);
                if (55296 <= n3 && 57343 >= n3) {
                  var p2 = e4.charCodeAt(++l3);
                  n3 = 65536 + ((n3 & 1023) << 10) | p2 & 1023;
                }
                if (127 >= n3) {
                  if (g2 >= m3) break;
                  f5[g2++] = n3;
                } else {
                  if (2047 >= n3) {
                    if (g2 + 1 >= m3) break;
                    f5[g2++] = 192 | n3 >> 6;
                  } else {
                    if (65535 >= n3) {
                      if (g2 + 2 >= m3) break;
                      f5[g2++] = 224 | n3 >> 12;
                    } else {
                      if (g2 + 3 >= m3) break;
                      f5[g2++] = 240 | n3 >> 18;
                      f5[g2++] = 128 | n3 >> 12 & 63;
                    }
                    f5[g2++] = 128 | n3 >> 6 & 63;
                  }
                  f5[g2++] = 128 | n3 & 63;
                }
              }
              f5[g2] = 0;
            }
          } else if (g2) for (g2 = 0; g2 < f5; ++g2) l3 = e4.charCodeAt(g2), 255 < l3 && (S4(m3), L2("String has UTF-16 code units that do not fit in 8 bits")), A4[m3 + g2] = l3;
          else for (g2 = 0; g2 < f5; ++g2) A4[m3 + g2] = e4[g2];
          null !== d2 && d2.push(S4, k2);
          return k2;
        }, "toWireType"), argPackAdvance: 8, readValueFromPointer: Xa, V: /* @__PURE__ */ __name(function(d2) {
          S4(d2);
        }, "V") });
      }, "o"),
      i: /* @__PURE__ */ __name(function(a2, b2, c4) {
        c4 = N2(c4);
        if (2 === b2) {
          var d2 = tb;
          var e4 = ub;
          var f5 = vb;
          var g2 = /* @__PURE__ */ __name(() => ka, "g");
          var k2 = 1;
        } else 4 === b2 && (d2 = wb, e4 = xb, f5 = yb, g2 = /* @__PURE__ */ __name(() => E2, "g"), k2 = 2);
        W2(a2, { name: c4, fromWireType: /* @__PURE__ */ __name(function(m3) {
          for (var l3 = E2[m3 >> 2], n3 = g2(), p2, r5 = m3 + 4, u2 = 0; u2 <= l3; ++u2) {
            var t5 = m3 + 4 + u2 * b2;
            if (u2 == l3 || 0 == n3[t5 >> k2]) r5 = d2(r5, t5 - r5), void 0 === p2 ? p2 = r5 : (p2 += String.fromCharCode(0), p2 += r5), r5 = t5 + b2;
          }
          S4(m3);
          return p2;
        }, "fromWireType"), toWireType: /* @__PURE__ */ __name(function(m3, l3) {
          "string" != typeof l3 && L2("Cannot pass non-string to C++ string type " + c4);
          var n3 = f5(l3), p2 = Ib(4 + n3 + b2);
          E2[p2 >> 2] = n3 >> k2;
          e4(l3, p2 + 4, n3 + b2);
          null !== m3 && m3.push(S4, p2);
          return p2;
        }, "toWireType"), argPackAdvance: 8, readValueFromPointer: Xa, V: /* @__PURE__ */ __name(function(m3) {
          S4(m3);
        }, "V") });
      }, "i"),
      k: /* @__PURE__ */ __name(function(a2, b2, c4, d2, e4, f5) {
        Va[a2] = { name: N2(b2), fa: Z4(c4, d2), W: Z4(e4, f5), ia: [] };
      }, "k"),
      h: /* @__PURE__ */ __name(function(a2, b2, c4, d2, e4, f5, g2, k2, m3, l3) {
        Va[a2].ia.push({ oa: N2(b2), ta: c4, ra: Z4(d2, e4), sa: f5, za: g2, ya: Z4(k2, m3), Aa: l3 });
      }, "h"),
      C: /* @__PURE__ */ __name(function(a2, b2) {
        b2 = N2(b2);
        W2(a2, {
          va: true,
          name: b2,
          argPackAdvance: 0,
          fromWireType: /* @__PURE__ */ __name(function() {
          }, "fromWireType"),
          toWireType: /* @__PURE__ */ __name(function() {
          }, "toWireType")
        });
      }, "C"),
      s: /* @__PURE__ */ __name(function(a2, b2, c4, d2, e4) {
        a2 = Bb[a2];
        b2 = M2(b2);
        c4 = Ab(c4);
        var f5 = [];
        E2[d2 >> 2] = Ea(f5);
        return a2(b2, c4, f5, e4);
      }, "s"),
      t: /* @__PURE__ */ __name(function(a2, b2, c4, d2) {
        a2 = Bb[a2];
        b2 = M2(b2);
        c4 = Ab(c4);
        a2(b2, c4, null, d2);
      }, "t"),
      g: qb,
      m: /* @__PURE__ */ __name(function(a2, b2) {
        var c4 = Db(a2, b2), d2 = c4[0];
        b2 = d2.name + "_$" + c4.slice(1).map(function(g2) {
          return g2.name;
        }).join("_") + "$";
        var e4 = Eb[b2];
        if (void 0 !== e4) return e4;
        var f5 = Array(a2 - 1);
        e4 = Cb((g2, k2, m3, l3) => {
          for (var n3 = 0, p2 = 0; p2 < a2 - 1; ++p2) f5[p2] = c4[p2 + 1].readValueFromPointer(l3 + n3), n3 += c4[p2 + 1].argPackAdvance;
          g2 = g2[k2].apply(
            g2,
            f5
          );
          for (p2 = 0; p2 < a2 - 1; ++p2) c4[p2 + 1].ma && c4[p2 + 1].ma(f5[p2]);
          if (!d2.va) return d2.toWireType(m3, g2);
        });
        return Eb[b2] = e4;
      }, "m"),
      D: /* @__PURE__ */ __name(function(a2) {
        4 < a2 && (J2[a2].ga += 1);
      }, "D"),
      r: /* @__PURE__ */ __name(function(a2) {
        var b2 = M2(a2);
        Wa(b2);
        qb(a2);
      }, "r"),
      c: /* @__PURE__ */ __name(function() {
        x3("");
      }, "c"),
      x: /* @__PURE__ */ __name(function(a2, b2, c4) {
        A4.copyWithin(a2, b2, b2 + c4);
      }, "x"),
      w: /* @__PURE__ */ __name(function(a2) {
        var b2 = A4.length;
        a2 >>>= 0;
        if (2147483648 < a2) return false;
        for (var c4 = 1; 4 >= c4; c4 *= 2) {
          var d2 = b2 * (1 + 0.2 / c4);
          d2 = Math.min(d2, a2 + 100663296);
          var e4 = Math;
          d2 = Math.max(a2, d2);
          e4 = e4.min.call(e4, 2147483648, d2 + (65536 - d2 % 65536) % 65536);
          a: {
            try {
              fa.grow(e4 - ia.byteLength + 65535 >>> 16);
              na();
              var f5 = 1;
              break a;
            } catch (g2) {
            }
            f5 = void 0;
          }
          if (f5) return true;
        }
        return false;
      }, "w"),
      z: /* @__PURE__ */ __name(function() {
        return 52;
      }, "z"),
      u: /* @__PURE__ */ __name(function() {
        return 70;
      }, "u"),
      y: /* @__PURE__ */ __name(function(a2, b2, c4, d2) {
        for (var e4 = 0, f5 = 0; f5 < c4; f5++) {
          var g2 = E2[b2 >> 2], k2 = E2[b2 + 4 >> 2];
          b2 += 8;
          for (var m3 = 0; m3 < k2; m3++) {
            var l3 = A4[g2 + m3], n3 = Fb[a2];
            0 === l3 || 10 === l3 ? ((1 === a2 ? ea : v2)(z2(n3, 0)), n3.length = 0) : n3.push(l3);
          }
          e4 += k2;
        }
        E2[d2 >> 2] = e4;
        return 0;
      }, "y")
    };
    (function() {
      function a2(e4) {
        h3.asm = e4.exports;
        fa = h3.asm.E;
        na();
        oa = h3.asm.J;
        qa.unshift(h3.asm.F);
        F4--;
        h3.monitorRunDependencies && h3.monitorRunDependencies(F4);
        0 == F4 && (null !== ta2 && (clearInterval(ta2), ta2 = null), G2 && (e4 = G2, G2 = null, e4()));
      }
      __name(a2, "a");
      function b2(e4) {
        a2(e4.instance);
      }
      __name(b2, "b");
      function c4(e4) {
        return ya().then(function(f5) {
          return WebAssembly.instantiate(f5, d2);
        }).then(function(f5) {
          return f5;
        }).then(e4, function(f5) {
          v2("failed to asynchronously prepare wasm: " + f5);
          x3(f5);
        });
      }
      __name(c4, "c");
      var d2 = { a: Jb };
      F4++;
      h3.monitorRunDependencies && h3.monitorRunDependencies(F4);
      if (h3.instantiateWasm) try {
        return h3.instantiateWasm(
          d2,
          a2
        );
      } catch (e4) {
        v2("Module.instantiateWasm callback failed with error: " + e4), ca(e4);
      }
      (function() {
        return w2 || "function" != typeof WebAssembly.instantiateStreaming || ua(H2) || "function" != typeof fetch ? c4(b2) : fetch(H2, { credentials: "same-origin" }).then(function(e4) {
          return WebAssembly.instantiateStreaming(e4, d2).then(b2, function(f5) {
            v2("wasm streaming compile failed: " + f5);
            v2("falling back to ArrayBuffer instantiation");
            return c4(b2);
          });
        });
      })().catch(ca);
      return {};
    })();
    h3.___wasm_call_ctors = function() {
      return (h3.___wasm_call_ctors = h3.asm.F).apply(null, arguments);
    };
    var Ka = h3.___getTypeName = function() {
      return (Ka = h3.___getTypeName = h3.asm.G).apply(null, arguments);
    };
    h3.__embind_initialize_bindings = function() {
      return (h3.__embind_initialize_bindings = h3.asm.H).apply(null, arguments);
    };
    var Ib = h3._malloc = function() {
      return (Ib = h3._malloc = h3.asm.I).apply(null, arguments);
    }, S4 = h3._free = function() {
      return (S4 = h3._free = h3.asm.K).apply(null, arguments);
    };
    h3.dynCall_jiji = function() {
      return (h3.dynCall_jiji = h3.asm.L).apply(null, arguments);
    };
    var Kb;
    G2 = /* @__PURE__ */ __name(function Lb() {
      Kb || Mb();
      Kb || (G2 = Lb);
    }, "Lb");
    function Mb() {
      function a2() {
        if (!Kb && (Kb = true, h3.calledRun = true, !ha)) {
          za(qa);
          aa(h3);
          if (h3.onRuntimeInitialized) h3.onRuntimeInitialized();
          if (h3.postRun) for ("function" == typeof h3.postRun && (h3.postRun = [h3.postRun]); h3.postRun.length; ) {
            var b2 = h3.postRun.shift();
            ra.unshift(b2);
          }
          za(ra);
        }
      }
      __name(a2, "a");
      if (!(0 < F4)) {
        if (h3.preRun) for ("function" == typeof h3.preRun && (h3.preRun = [h3.preRun]); h3.preRun.length; ) sa();
        za(pa);
        0 < F4 || (h3.setStatus ? (h3.setStatus("Running..."), setTimeout(function() {
          setTimeout(function() {
            h3.setStatus("");
          }, 1);
          a2();
        }, 1)) : a2());
      }
    }
    __name(Mb, "Mb");
    if (h3.preInit) for ("function" == typeof h3.preInit && (h3.preInit = [h3.preInit]); 0 < h3.preInit.length; ) h3.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 constants3 = {
  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 = constants3;

// 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", (_2, config2) => {
    return config2 ? lib.Node.createWithConfig(config2) : lib.Node.createDefault();
  });
  patch(lib.Node.prototype, "free", function() {
    lib.Node.destroy(this);
  });
  patch(lib.Node.prototype, "freeRecursive", function() {
    for (let t5 = 0, T2 = this.getChildCount(); t5 < T2; ++t5) {
      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(x3) {
  return x3 === 161 || x3 === 164 || x3 === 167 || x3 === 168 || x3 === 170 || x3 === 173 || x3 === 174 || x3 >= 176 && x3 <= 180 || x3 >= 182 && x3 <= 186 || x3 >= 188 && x3 <= 191 || x3 === 198 || x3 === 208 || x3 === 215 || x3 === 216 || x3 >= 222 && x3 <= 225 || x3 === 230 || x3 >= 232 && x3 <= 234 || x3 === 236 || x3 === 237 || x3 === 240 || x3 === 242 || x3 === 243 || x3 >= 247 && x3 <= 250 || x3 === 252 || x3 === 254 || x3 === 257 || x3 === 273 || x3 === 275 || x3 === 283 || x3 === 294 || x3 === 295 || x3 === 299 || x3 >= 305 && x3 <= 307 || x3 === 312 || x3 >= 319 && x3 <= 322 || x3 === 324 || x3 >= 328 && x3 <= 331 || x3 === 333 || x3 === 338 || x3 === 339 || x3 === 358 || x3 === 359 || x3 === 363 || x3 === 462 || x3 === 464 || x3 === 466 || x3 === 468 || x3 === 470 || x3 === 472 || x3 === 474 || x3 === 476 || x3 === 593 || x3 === 609 || x3 === 708 || x3 === 711 || x3 >= 713 && x3 <= 715 || x3 === 717 || x3 === 720 || x3 >= 728 && x3 <= 731 || x3 === 733 || x3 === 735 || x3 >= 768 && x3 <= 879 || x3 >= 913 && x3 <= 929 || x3 >= 931 && x3 <= 937 || x3 >= 945 && x3 <= 961 || x3 >= 963 && x3 <= 969 || x3 === 1025 || x3 >= 1040 && x3 <= 1103 || x3 === 1105 || x3 === 8208 || x3 >= 8211 && x3 <= 8214 || x3 === 8216 || x3 === 8217 || x3 === 8220 || x3 === 8221 || x3 >= 8224 && x3 <= 8226 || x3 >= 8228 && x3 <= 8231 || x3 === 8240 || x3 === 8242 || x3 === 8243 || x3 === 8245 || x3 === 8251 || x3 === 8254 || x3 === 8308 || x3 === 8319 || x3 >= 8321 && x3 <= 8324 || x3 === 8364 || x3 === 8451 || x3 === 8453 || x3 === 8457 || x3 === 8467 || x3 === 8470 || x3 === 8481 || x3 === 8482 || x3 === 8486 || x3 === 8491 || x3 === 8531 || x3 === 8532 || x3 >= 8539 && x3 <= 8542 || x3 >= 8544 && x3 <= 8555 || x3 >= 8560 && x3 <= 8569 || x3 === 8585 || x3 >= 8592 && x3 <= 8601 || x3 === 8632 || x3 === 8633 || x3 === 8658 || x3 === 8660 || x3 === 8679 || x3 === 8704 || x3 === 8706 || x3 === 8707 || x3 === 8711 || x3 === 8712 || x3 === 8715 || x3 === 8719 || x3 === 8721 || x3 === 8725 || x3 === 8730 || x3 >= 8733 && x3 <= 8736 || x3 === 8739 || x3 === 8741 || x3 >= 8743 && x3 <= 8748 || x3 === 8750 || x3 >= 8756 && x3 <= 8759 || x3 === 8764 || x3 === 8765 || x3 === 8776 || x3 === 8780 || x3 === 8786 || x3 === 8800 || x3 === 8801 || x3 >= 8804 && x3 <= 8807 || x3 === 8810 || x3 === 8811 || x3 === 8814 || x3 === 8815 || x3 === 8834 || x3 === 8835 || x3 === 8838 || x3 === 8839 || x3 === 8853 || x3 === 8857 || x3 === 8869 || x3 === 8895 || x3 === 8978 || x3 >= 9312 && x3 <= 9449 || x3 >= 9451 && x3 <= 9547 || x3 >= 9552 && x3 <= 9587 || x3 >= 9600 && x3 <= 9615 || x3 >= 9618 && x3 <= 9621 || x3 === 9632 || x3 === 9633 || x3 >= 9635 && x3 <= 9641 || x3 === 9650 || x3 === 9651 || x3 === 9654 || x3 === 9655 || x3 === 9660 || x3 === 9661 || x3 === 9664 || x3 === 9665 || x3 >= 9670 && x3 <= 9672 || x3 === 9675 || x3 >= 9678 && x3 <= 9681 || x3 >= 9698 && x3 <= 9701 || x3 === 9711 || x3 === 9733 || x3 === 9734 || x3 === 9737 || x3 === 9742 || x3 === 9743 || x3 === 9756 || x3 === 9758 || x3 === 9792 || x3 === 9794 || x3 === 9824 || x3 === 9825 || x3 >= 9827 && x3 <= 9829 || x3 >= 9831 && x3 <= 9834 || x3 === 9836 || x3 === 9837 || x3 === 9839 || x3 === 9886 || x3 === 9887 || x3 === 9919 || x3 >= 9926 && x3 <= 9933 || x3 >= 9935 && x3 <= 9939 || x3 >= 9941 && x3 <= 9953 || x3 === 9955 || x3 === 9960 || x3 === 9961 || x3 >= 9963 && x3 <= 9969 || x3 === 9972 || x3 >= 9974 && x3 <= 9977 || x3 === 9979 || x3 === 9980 || x3 === 9982 || x3 === 9983 || x3 === 10045 || x3 >= 10102 && x3 <= 10111 || x3 >= 11094 && x3 <= 11097 || x3 >= 12872 && x3 <= 12879 || x3 >= 57344 && x3 <= 63743 || x3 >= 65024 && x3 <= 65039 || x3 === 65533 || x3 >= 127232 && x3 <= 127242 || x3 >= 127248 && x3 <= 127277 || x3 >= 127280 && x3 <= 127337 || x3 >= 127344 && x3 <= 127373 || x3 === 127375 || x3 === 127376 || x3 >= 127387 && x3 <= 127404 || x3 >= 917760 && x3 <= 917999 || x3 >= 983040 && x3 <= 1048573 || x3 >= 1048576 && x3 <= 1114109;
}
__name(isAmbiguous, "isAmbiguous");
function isFullWidth(x3) {
  return x3 === 12288 || x3 >= 65281 && x3 <= 65376 || x3 >= 65504 && x3 <= 65510;
}
__name(isFullWidth, "isFullWidth");
function isWide(x3) {
  return x3 >= 4352 && x3 <= 4447 || x3 === 8986 || x3 === 8987 || x3 === 9001 || x3 === 9002 || x3 >= 9193 && x3 <= 9196 || x3 === 9200 || x3 === 9203 || x3 === 9725 || x3 === 9726 || x3 === 9748 || x3 === 9749 || x3 >= 9776 && x3 <= 9783 || x3 >= 9800 && x3 <= 9811 || x3 === 9855 || x3 >= 9866 && x3 <= 9871 || x3 === 9875 || x3 === 9889 || x3 === 9898 || x3 === 9899 || x3 === 9917 || x3 === 9918 || x3 === 9924 || x3 === 9925 || x3 === 9934 || x3 === 9940 || x3 === 9962 || x3 === 9970 || x3 === 9971 || x3 === 9973 || x3 === 9978 || x3 === 9981 || x3 === 9989 || x3 === 9994 || x3 === 9995 || x3 === 10024 || x3 === 10060 || x3 === 10062 || x3 >= 10067 && x3 <= 10069 || x3 === 10071 || x3 >= 10133 && x3 <= 10135 || x3 === 10160 || x3 === 10175 || x3 === 11035 || x3 === 11036 || x3 === 11088 || x3 === 11093 || x3 >= 11904 && x3 <= 11929 || x3 >= 11931 && x3 <= 12019 || x3 >= 12032 && x3 <= 12245 || x3 >= 12272 && x3 <= 12287 || x3 >= 12289 && x3 <= 12350 || x3 >= 12353 && x3 <= 12438 || x3 >= 12441 && x3 <= 12543 || x3 >= 12549 && x3 <= 12591 || x3 >= 12593 && x3 <= 12686 || x3 >= 12688 && x3 <= 12773 || x3 >= 12783 && x3 <= 12830 || x3 >= 12832 && x3 <= 12871 || x3 >= 12880 && x3 <= 42124 || x3 >= 42128 && x3 <= 42182 || x3 >= 43360 && x3 <= 43388 || x3 >= 44032 && x3 <= 55203 || x3 >= 63744 && x3 <= 64255 || x3 >= 65040 && x3 <= 65049 || x3 >= 65072 && x3 <= 65106 || x3 >= 65108 && x3 <= 65126 || x3 >= 65128 && x3 <= 65131 || x3 >= 94176 && x3 <= 94180 || x3 === 94192 || x3 === 94193 || x3 >= 94208 && x3 <= 100343 || x3 >= 100352 && x3 <= 101589 || x3 >= 101631 && x3 <= 101640 || x3 >= 110576 && x3 <= 110579 || x3 >= 110581 && x3 <= 110587 || x3 === 110589 || x3 === 110590 || x3 >= 110592 && x3 <= 110882 || x3 === 110898 || x3 >= 110928 && x3 <= 110930 || x3 === 110933 || x3 >= 110948 && x3 <= 110951 || x3 >= 110960 && x3 <= 111355 || x3 >= 119552 && x3 <= 119638 || x3 >= 119648 && x3 <= 119670 || x3 === 126980 || x3 === 127183 || x3 === 127374 || x3 >= 127377 && x3 <= 127386 || x3 >= 127488 && x3 <= 127490 || x3 >= 127504 && x3 <= 127547 || x3 >= 127552 && x3 <= 127560 || x3 === 127568 || x3 === 127569 || x3 >= 127584 && x3 <= 127589 || x3 >= 127744 && x3 <= 127776 || x3 >= 127789 && x3 <= 127797 || x3 >= 127799 && x3 <= 127868 || x3 >= 127870 && x3 <= 127891 || x3 >= 127904 && x3 <= 127946 || x3 >= 127951 && x3 <= 127955 || x3 >= 127968 && x3 <= 127984 || x3 === 127988 || x3 >= 127992 && x3 <= 128062 || x3 === 128064 || x3 >= 128066 && x3 <= 128252 || x3 >= 128255 && x3 <= 128317 || x3 >= 128331 && x3 <= 128334 || x3 >= 128336 && x3 <= 128359 || x3 === 128378 || x3 === 128405 || x3 === 128406 || x3 === 128420 || x3 >= 128507 && x3 <= 128591 || x3 >= 128640 && x3 <= 128709 || x3 === 128716 || x3 >= 128720 && x3 <= 128722 || x3 >= 128725 && x3 <= 128727 || x3 >= 128732 && x3 <= 128735 || x3 === 128747 || x3 === 128748 || x3 >= 128756 && x3 <= 128764 || x3 >= 128992 && x3 <= 129003 || x3 === 129008 || x3 >= 129292 && x3 <= 129338 || x3 >= 129340 && x3 <= 129349 || x3 >= 129351 && x3 <= 129535 || x3 >= 129648 && x3 <= 129660 || x3 >= 129664 && x3 <= 129673 || x3 >= 129679 && x3 <= 129734 || x3 >= 129742 && x3 <= 129756 || x3 >= 129759 && x3 <= 129769 || x3 >= 129776 && x3 <= 129784 || x3 >= 131072 && x3 <= 196605 || x3 >= 196608 && x3 <= 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(string4, options2 = {}) {
  if (typeof string4 !== "string" || string4.length === 0) {
    return 0;
  }
  const {
    ambiguousIsNarrow = true,
    countAnsiEscapeCodes = false
  } = options2;
  if (!countAnsiEscapeCodes) {
    string4 = stripAnsi(string4);
  }
  if (string4.length === 0) {
    return 0;
  }
  let width = 0;
  const eastAsianWidthOptions = { ambiguousAsWide: !ambiguousIsNarrow };
  for (const { segment: character } of segmenter.segment(string4)) {
    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 integer2 = Number.parseInt(colorString, 16);
        return [
          /* eslint-disable no-bitwise */
          integer2 >> 16 & 255,
          integer2 >> 8 & 255,
          integer2 & 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((string4) => string4.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((string4) => {
  const words = string4.split(" ");
  let last2 = words.length;
  while (last2 > 0) {
    if (stringWidth(words[last2 - 1]) > 0) {
      break;
    }
    last2--;
  }
  if (last2 === words.length) {
    return string4;
  }
  return words.slice(0, last2).join(" ") + words.slice(last2).join("");
}, "stringVisibleTrimSpacesRight");
var exec2 = /* @__PURE__ */ __name((string4, columns, options2 = {}) => {
  if (options2.trim !== false && string4.trim() === "") {
    return "";
  }
  let returnValue = "";
  let escapeCode;
  let escapeUrl;
  const lengths = wordLengths(string4);
  let rows = [""];
  for (const [index, word] of string4.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(string4, columns, options2) {
  return String(string4).normalize().replaceAll("\r\n", "\n").split("\n").map((line) => exec2(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_constants32 = __toESM(require_constants12(), 1);
import process17 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(string4, options2 = {}) {
  if (typeof string4 !== "string" || string4.length === 0) {
    return 0;
  }
  const {
    ambiguousIsNarrow = true,
    countAnsiEscapeCodes = false
  } = options2;
  if (!countAnsiEscapeCodes) {
    string4 = stripAnsi(string4);
  }
  if (string4.length === 0) {
    return 0;
  }
  let width = 0;
  const eastAsianWidthOptions = { ambiguousAsWide: !ambiguousIsNarrow };
  for (const { segment: character } of segmenter2.segment(string4)) {
    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(string4) {
  let lineWidth = 0;
  for (const line of string4.split("\n")) {
    lineWidth = Math.max(lineWidth, stringWidth2(line));
  }
  return lineWidth;
}
__name(widestLine, "widestLine");

// node_modules/ink/build/measure-text.js
var cache3 = /* @__PURE__ */ new Map();
var measureText = /* @__PURE__ */ __name((text) => {
  if (text.length === 0) {
    return {
      width: 0,
      height: 0
    };
  }
  const cachedDimensions = cache3.get(text);
  if (cachedDimensions) {
    return cachedDimensions;
  }
  const width = widestLine(text);
  const height = text.split("\n").length;
  const dimensions = { width, height };
  cache3.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 integer2 = Number.parseInt(colorString, 16);
        return [
          /* eslint-disable no-bitwise */
          integer2 >> 16 & 255,
          integer2 >> 8 & 255,
          integer2 & 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(string4, begin, end) {
  const characters = [...string4];
  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(string4.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(string4, options2 = {}) {
  if (typeof string4 !== "string" || string4.length === 0) {
    return 0;
  }
  const {
    ambiguousIsNarrow = true,
    countAnsiEscapeCodes = false
  } = options2;
  if (!countAnsiEscapeCodes) {
    string4 = stripAnsi(string4);
  }
  if (string4.length === 0) {
    return 0;
  }
  let width = 0;
  const eastAsianWidthOptions = { ambiguousAsWide: !ambiguousIsNarrow };
  for (const { segment: character } of segmenter3.segment(string4)) {
    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(string4, wantedIndex, shouldSearchRight) {
  if (string4.charAt(wantedIndex) === " ") {
    return wantedIndex;
  }
  const direction = shouldSearchRight ? 1 : -1;
  for (let index = 0; index <= 3; index++) {
    const finalIndex = wantedIndex + index * direction;
    if (string4.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 cache4 = {};
var wrapText = /* @__PURE__ */ __name((text, maxWidth, wrapType) => {
  const cacheKey = text + String(maxWidth) + String(wrapType);
  const cachedText = cache4[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 });
  }
  cache4[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 (process17.env["DEV"] === "true") {
  try {
    await Promise.resolve().then(() => (init_devtools(), devtools_exports));
  } catch (error2) {
    if (error2.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 error2;
    }
  }
}
var diff2 = /* @__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_constants32.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 = diff2(oldProps, newProps);
    const style = diff2(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_constants32.NoEventPriority) {
      return currentUpdatePriority;
    }
    return import_constants32.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(string4, count = 1, options2 = {}) {
  const {
    indent = " ",
    includeEmptyLines = false
  } = options2;
  if (typeof string4 !== "string") {
    throw new TypeError(
      `Expected \`input\` to be a \`string\`, got \`${typeof string4}\``
    );
  }
  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 string4;
  }
  const regex3 = includeEmptyLines ? /^/gm : /^(?!\s*$)/gm;
  return string4.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 integer2 = Number.parseInt(colorString, 16);
        return [
          /* eslint-disable no-bitwise */
          integer2 >> 16 & 255,
          integer2 >> 8 & 255,
          integer2 & 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 process18 from "node:process";
import os24 from "node:os";
import tty from "node:tty";
function hasFlag(flag, argv = globalThis.Deno ? globalThis.Deno.args : process18.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: env3 } = process18;
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 env3) {
    if (env3.FORCE_COLOR === "true") {
      return 1;
    }
    if (env3.FORCE_COLOR === "false") {
      return 0;
    }
    return env3.FORCE_COLOR.length === 0 ? 1 : Math.min(Number.parseInt(env3.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 env3 && "AGENT_NAME" in env3) {
    return 1;
  }
  if (haveStream && !streamIsTTY && forceColor === void 0) {
    return 0;
  }
  const min = forceColor || 0;
  if (env3.TERM === "dumb") {
    return min;
  }
  if (process18.platform === "win32") {
    const osRelease = os24.release().split(".");
    if (Number(osRelease[0]) >= 10 && Number(osRelease[2]) >= 10586) {
      return Number(osRelease[2]) >= 14931 ? 3 : 2;
    }
    return 1;
  }
  if ("CI" in env3) {
    if (["GITHUB_ACTIONS", "GITEA_ACTIONS", "CIRCLECI"].some((key) => key in env3)) {
      return 3;
    }
    if (["TRAVIS", "APPVEYOR", "GITLAB_CI", "BUILDKITE", "DRONE"].some((sign) => sign in env3) || env3.CI_NAME === "codeship") {
      return 1;
    }
    return min;
  }
  if ("TEAMCITY_VERSION" in env3) {
    return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env3.TEAMCITY_VERSION) ? 1 : 0;
  }
  if (env3.COLORTERM === "truecolor") {
    return 3;
  }
  if (env3.TERM === "xterm-kitty") {
    return 3;
  }
  if (env3.TERM === "xterm-ghostty") {
    return 3;
  }
  if (env3.TERM === "wezterm") {
    return 3;
  }
  if ("TERM_PROGRAM" in env3) {
    const version2 = Number.parseInt((env3.TERM_PROGRAM_VERSION || "").split(".")[0], 10);
    switch (env3.TERM_PROGRAM) {
      case "iTerm.app": {
        return version2 >= 3 ? 3 : 2;
      }
      case "Apple_Terminal": {
        return 2;
      }
    }
  }
  if (/-256(color)?$/i.test(env3.TERM)) {
    return 2;
  }
  if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env3.TERM)) {
    return 1;
  }
  if ("COLORTERM" in env3) {
    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(string4, substring, replacer) {
  let index = string4.indexOf(substring);
  if (index === -1) {
    return string4;
  }
  const substringLength = substring.length;
  let endIndex = 0;
  let returnValue = "";
  do {
    returnValue += string4.slice(endIndex, index) + substring + replacer;
    endIndex = index + substringLength;
    index = string4.indexOf(substring, endIndex);
  } while (index !== -1);
  returnValue += string4.slice(endIndex);
  return returnValue;
}
__name(stringReplaceAll, "stringReplaceAll");
function stringEncaseCRLFWithFirstIndex(string4, prefix, postfix, index) {
  let endIndex = 0;
  let returnValue = "";
  do {
    const gotCR = string4[index - 1] === "\r";
    returnValue += string4.slice(endIndex, gotCR ? index - 1 : index) + prefix + (gotCR ? "\r\n" : "\n") + postfix;
    endIndex = index + 1;
    index = string4.indexOf("\n", endIndex);
  } while (index !== -1);
  returnValue += string4.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((object3, 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;
  object3.level = options2.level === void 0 ? colorLevel : options2.level;
}, "applyOptions");
var chalkFactory = /* @__PURE__ */ __name((options2) => {
  const chalk9 = /* @__PURE__ */ __name((...strings) => strings.join(" "), "chalk");
  applyOptions(chalk9, options2);
  Object.setPrototypeOf(chalk9, createChalk.prototype);
  return chalk9;
}, "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((open4, close, parent) => {
  let openAll;
  let closeAll;
  if (parent === void 0) {
    openAll = open4;
    closeAll = close;
  } else {
    openAll = parent.openAll + open4;
    closeAll = close + parent.closeAll;
  }
  return {
    open: open4,
    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, string4) => {
  if (self2.level <= 0 || !string4) {
    return self2[IS_EMPTY] ? "" : string4;
  }
  let styler = self2[STYLER];
  if (styler === void 0) {
    return string4;
  }
  const { openAll, closeAll } = styler;
  if (string4.includes("\x1B")) {
    while (styler !== void 0) {
      string4 = stringReplaceAll(string4, styler.close, styler.open);
      styler = styler.parent;
    }
  }
  const lfIndex = string4.indexOf("\n");
  if (lfIndex !== -1) {
    string4 = stringEncaseCRLFWithFirstIndex(string4, closeAll, openAll, lfIndex);
  }
  return openAll + string4 + 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((x3, y2, 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(x3, y2, topBorder, { transformers: [] });
    }
    if (showLeftBorder) {
      output.write(x3, y2 + offsetY, leftBorder, { transformers: [] });
    }
    if (showRightBorder) {
      output.write(x3 + width - 1, y2 + offsetY, rightBorder, {
        transformers: []
      });
    }
    if (bottomBorder) {
      output.write(x3, y2 + height - 1, bottomBorder, { transformers: [] });
    }
  }
}, "renderBorder");
var render_border_default = renderBorder;

// node_modules/ink/build/render-background.js
init_esbuild_shims();
var renderBackground = /* @__PURE__ */ __name((x3, y2, 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(x3 + leftBorderWidth, y2 + 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 x3 = offsetX + yogaNode.getComputedLeft();
    const y2 = 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(x3, y2, text, { transformers: newTransformers });
      }
      return;
    }
    let clipped = false;
    if (node.nodeName === "ink-box") {
      render_background_default(x3, y2, node, output);
      render_border_default(x3, y2, 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 ? x3 + yogaNode.getComputedBorder(src_default.EDGE_LEFT) : void 0;
        const x22 = clipHorizontally ? x3 + yogaNode.getComputedWidth() - yogaNode.getComputedBorder(src_default.EDGE_RIGHT) : void 0;
        const y1 = clipVertically ? y2 + yogaNode.getComputedBorder(src_default.EDGE_TOP) : void 0;
        const y22 = clipVertically ? y2 + yogaNode.getComputedHeight() - yogaNode.getComputedBorder(src_default.EDGE_BOTTOM) : void 0;
        output.clip({ x1, x2: x22, y1, y2: y22 });
        clipped = true;
      }
    }
    if (node.nodeName === "ink-root" || node.nodeName === "ink-box") {
      for (const childNode of node.childNodes) {
        renderNodeToOutput(childNode, output, {
          offsetX: x3,
          offsetY: y2,
          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 integer2 = Number.parseInt(colorString, 16);
        return [
          /* eslint-disable no-bitwise */
          integer2 >> 16 & 255,
          integer2 >> 8 & 255,
          integer2 & 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(string4) {
  for (let index = 0; index < string4.length; index++) {
    const codePoint = string4.codePointAt(index);
    if (codePoint >= CODE_POINT_0 && codePoint <= CODE_POINT_9) {
      return index;
    }
  }
  return -1;
}
__name(findNumberIndex, "findNumberIndex");
function parseAnsiCode(string4, offset) {
  string4 = string4.slice(offset, offset + 19);
  const startIndex = findNumberIndex(string4);
  if (startIndex !== -1) {
    let endIndex = string4.indexOf("m", startIndex);
    if (endIndex === -1) {
      endIndex = string4.length;
    }
    return string4.slice(0, endIndex + 1);
  }
}
__name(parseAnsiCode, "parseAnsiCode");
function tokenize3(string4, endCharacter = Number.POSITIVE_INFINITY) {
  const returnValue = [];
  let index = 0;
  let visibleCount = 0;
  while (index < string4.length) {
    const codePoint = string4.codePointAt(index);
    if (ESCAPES3.has(codePoint)) {
      const code2 = parseAnsiCode(string4, 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(tokenize3, "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(string4, start, end) {
  const tokens = tokenize3(string4, 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 integer2 = Number.parseInt(colorString, 16);
        return [
          /* eslint-disable no-bitwise */
          integer2 >> 16 & 255,
          integer2 >> 8 & 255,
          integer2 & 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 i3 = 0; i3 < chars.length; i3++) {
    const char = chars[i3];
    if (i3 === 0) {
      ret += ansiCodesToString(char.styles);
    } else {
      ret += ansiCodesToString(diffAnsiCodes(chars[i3 - 1].styles, char.styles));
    }
    ret += char.value;
    if (i3 === 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(string4, offset) {
  string4 = string4.slice(offset);
  for (let index = 1; index < linkStartCodePrefixCharCodes.length; index++) {
    if (string4.charCodeAt(index) !== linkStartCodePrefixCharCodes[index]) {
      return void 0;
    }
  }
  const endIndex = string4.indexOf("\x07", linkStartCodePrefix.length);
  if (endIndex === -1)
    return void 0;
  return string4.slice(0, endIndex + 1);
}
__name(parseLinkCode, "parseLinkCode");
function parseAnsiCode2(string4, offset) {
  string4 = string4.slice(offset, offset + 19);
  const startIndex = findNumberIndex2(string4);
  if (startIndex !== -1) {
    let endIndex = string4.indexOf("m", startIndex);
    if (endIndex === -1) {
      endIndex = string4.length;
    }
    return string4.slice(0, endIndex + 1);
  }
}
__name(parseAnsiCode2, "parseAnsiCode");
function tokenize4(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(tokenize4, "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(x3, y2, text, options2) {
    const { transformers } = options2;
    if (!text) {
      return;
    }
    this.operations.push({
      type: "write",
      x: x3,
      y: y2,
      text,
      transformers
    });
  }
  clip(clip) {
    this.operations.push({
      type: "clip",
      clip
    });
  }
  unclip() {
    this.operations.push({
      type: "unclip"
    });
  }
  get() {
    const output = [];
    for (let y2 = 0; y2 < this.height; y2++) {
      const row = [];
      for (let x3 = 0; x3 < this.width; x3++) {
        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: x3, y: y2 } = 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 (x3 + width < clip.x1 || x3 > clip.x2) {
              continue;
            }
          }
          if (clipVertically) {
            const height = lines.length;
            if (y2 + height < clip.y1 || y2 > clip.y2) {
              continue;
            }
          }
          if (clipHorizontally) {
            lines = lines.map((line) => {
              const from = x3 < clip.x1 ? clip.x1 - x3 : 0;
              const width = stringWidth2(line);
              const to = x3 + width > clip.x2 ? clip.x2 - x3 : width;
              return sliceAnsi2(line, from, to);
            });
            if (x3 < clip.x1) {
              x3 = clip.x1;
            }
          }
          if (clipVertically) {
            const from = y2 < clip.y1 ? clip.y1 - y2 : 0;
            const height = lines.length;
            const to = y2 + height > clip.y2 ? clip.y2 - y2 : height;
            lines = lines.slice(from, to);
            if (y2 < clip.y1) {
              y2 = clip.y1;
            }
          }
        }
        let offsetY = 0;
        for (let [index, line] of lines.entries()) {
          const currentLine = output[y2 + offsetY];
          if (!currentLine) {
            continue;
          }
          for (const transformer of transformers) {
            line = transformer(line, index);
          }
          const characters = styledCharsFromTokens(tokenize4(line));
          let offsetX = x3;
          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 process20 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 process19 from "node:process";
var restoreCursor = (0, import_onetime.default)(() => {
  (0, import_signal_exit.default)(() => {
    process19.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 = process20.stderr) => {
  if (!writableStream.isTTY) {
    return;
  }
  isHidden = false;
  writableStream.write("\x1B[?25h");
};
cliCursor.hide = (writableStream = process20.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 create2 = /* @__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: create2 };
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 EventEmitter8 } from "node:events";
import process24 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 as EventEmitter7 } from "node:events";
import process21 from "node:process";
var StdinContext = (0, import_react3.createContext)({
  stdin: process21.stdin,
  // eslint-disable-next-line @typescript-eslint/naming-convention
  internal_eventEmitter: new EventEmitter7(),
  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 process22 from "node:process";
var StdoutContext = (0, import_react4.createContext)({
  stdout: process22.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 process23 from "node:process";
var StderrContext = (0, import_react5.createContext)({
  stderr: process23.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 fs76 from "node:fs";
import { cwd as cwd3 } 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_default3 = 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 _a7;
  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_default3(source2).split(/\r?\n/);
  if (line > lines.length) {
    return;
  }
  return generateLineNumbers(line, (_a7 = options2.around) !== null && _a7 !== void 0 ? _a7 : 3).filter((line2) => lines[line2 - 1] !== void 0).map((line2) => ({ line: line2, value: lines[line2 - 1] }));
}, "codeExcerpt");
var dist_default4 = 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 Text3({ 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 transform2 = /* @__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: transform2 }, isScreenReaderEnabled && ariaLabel ? ariaLabel : children);
}
__name(Text3, "Text");

// node_modules/ink/build/components/ErrorOverview.js
var cleanupPath = /* @__PURE__ */ __name((path125) => {
  return path125?.replace(`file://${cwd3()}/`, "");
}, "cleanupPath");
var stackUtils = new import_stack_utils.default({
  cwd: cwd3(),
  internals: import_stack_utils.default.nodeInternals()
});
function ErrorOverview({ error: error2 }) {
  const stack = error2.stack ? error2.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 && fs76.existsSync(filePath)) {
    const sourceCode = fs76.readFileSync(filePath, "utf8");
    excerpt = dist_default4(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(
        Text3,
        { backgroundColor: "red", color: "white" },
        " ",
        "ERROR",
        " "
      ),
      import_react11.default.createElement(
        Text3,
        null,
        " ",
        error2.message
      )
    ),
    origin && filePath && import_react11.default.createElement(
      Box_default,
      { marginTop: 1 },
      import_react11.default.createElement(
        Text3,
        { 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(
          Text3,
          { 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(Text3, { key: line, backgroundColor: line === origin.line ? "red" : void 0, color: line === origin.line ? "white" : void 0 }, " " + value)
    ))),
    error2.stack && import_react11.default.createElement(Box_default, { marginTop: 1, flexDirection: "column" }, error2.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(Text3, { dimColor: true }, "- "),
          import_react11.default.createElement(
            Text3,
            { dimColor: true, bold: true },
            line,
            "\\t",
            " "
          )
        );
      }
      return import_react11.default.createElement(
        Box_default,
        { key: line },
        import_react11.default.createElement(Text3, { dimColor: true }, "- "),
        import_react11.default.createElement(Text3, { dimColor: true, bold: true }, parsedLine.function),
        import_react11.default.createElement(
          Text3,
          { 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 escape6 = "\x1B";
var App = class extends import_react12.PureComponent {
  static {
    __name(this, "App");
  }
  static displayName = "InternalApp";
  static getDerivedStateFromError(error2) {
    return { error: error2 };
  }
  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 EventEmitter8();
  // 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(error2) {
    this.handleExit(error2);
  }
  handleSetRawMode = /* @__PURE__ */ __name((isEnabled2) => {
    const { stdin } = this.props;
    if (!this.isRawModeSupported()) {
      if (stdin === process24.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 === escape6 && 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((error2) => {
    if (this.isRawModeSupported()) {
      this.handleSetRawMode(false);
    }
    this.props.onExit(error2);
  }, "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 noop6 = /* @__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 ?? process25.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_constants33.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 (process25.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, noop6);
    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(error2) {
    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, noop6);
    reconciler_default.flushSyncWork();
    instances_default.delete(this.options.stdout);
    if (error2 instanceof Error) {
      this.rejectExitPromise(error2);
    } else {
      this.resolveExitPromise();
    }
  }
  async waitUntilExit() {
    this.exitPromise ||= new Promise((resolve30, reject) => {
      this.resolveExitPromise = resolve30;
      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_default2((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 render2 = /* @__PURE__ */ __name((node, options2) => {
  const inkOptions = {
    stdout: process26.stdout,
    stdin: process26.stdin,
    stderr: process26.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 = render2;
var getOptions = /* @__PURE__ */ __name((stdout = {}) => {
  if (stdout instanceof Stream6) {
    return {
      stdout,
      stdin: process26.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: transform2, 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: transform2 }, 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);
var useApp = /* @__PURE__ */ __name(() => (0, import_react20.useContext)(AppContext_default), "useApp");
var use_app_default = useApp;

// 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/gemini.tsx
var import_react136 = __toESM(require_react(), 1);
import dns from "node:dns";
import os46 from "node:os";
import { basename as basename25 } from "node:path";
import v8 from "node:v8";

// packages/cli/src/config/auth.ts
init_esbuild_shims();

// packages/cli/src/config/settings.ts
init_esbuild_shims();
var dotenv2 = __toESM(require_main(), 1);
import * as fs79 from "node:fs";
import * as path81 from "node:path";
import { homedir as homedir15, platform as platform13 } from "node:os";
import process27 from "node:process";
var import_strip_json_comments2 = __toESM(require_strip_json_comments(), 1);

// packages/cli/src/ui/themes/default-light.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 debugLogger70 = createDebugLogger("COLOR_UTILS");
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];
  }
  debugLogger70.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",
  AccentYellowDim: "#8B7000",
  AccentRedDim: "#993333",
  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",
  AccentYellowDim: "#8B7530",
  AccentRedDim: "#8B3A4A",
  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",
  AccentYellowDim: "yellow",
  AccentRedDim: "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,
        errorDim: this.colors.AccentRedDim,
        warningDim: this.colors.AccentYellowDim
      }
    };
    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 ?? "",
    AccentYellowDim: customTheme.status?.warningDim ?? customTheme.AccentYellowDim ?? "",
    AccentRedDim: customTheme.status?.errorDim ?? customTheme.AccentRedDim ?? "",
    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,
      errorDim: customTheme.status?.errorDim ?? colors.AccentRedDim,
      warningDim: customTheme.status?.warningDim ?? colors.AccentYellowDim
    }
  };
  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/default-light.ts
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/config/trustedFolders.ts
init_esbuild_shims();
import * as fs77 from "node:fs";
import * as path80 from "node:path";
import { homedir as homedir14 } from "node:os";
var import_strip_json_comments = __toESM(require_strip_json_comments(), 1);

// packages/cli/src/utils/stdioHelpers.ts
init_esbuild_shims();
var writeStdoutLine = /* @__PURE__ */ __name((message) => {
  process.stdout.write(message.endsWith("\n") ? message : `${message}
`);
}, "writeStdoutLine");
var writeStderrLine = /* @__PURE__ */ __name((message) => {
  process.stderr.write(message.endsWith("\n") ? message : `${message}
`);
}, "writeStderrLine");
var clearScreen2 = /* @__PURE__ */ __name(() => {
  console.clear();
}, "clearScreen");

// packages/cli/src/config/trustedFolders.ts
var TRUSTED_FOLDERS_FILENAME = "trustedFolders.json";
var SETTINGS_DIRECTORY_NAME = ".qwen";
var USER_SETTINGS_DIR = path80.join(homedir14(), SETTINGS_DIRECTORY_NAME);
function getTrustedFoldersPath() {
  if (process.env["GEMINI_CLI_TRUSTED_FOLDERS_PATH"]) {
    return process.env["GEMINI_CLI_TRUSTED_FOLDERS_PATH"];
  }
  return path80.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(([path125, trustLevel]) => ({
      path: path125,
      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(path80.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 (path80.normalize(location) === path80.normalize(untrustedPath)) {
        return false;
      }
    }
    return void 0;
  }
  setValue(path125, trustLevel) {
    this.user.config[path125] = trustLevel;
    saveTrustedFolders(this.user);
  }
};
var loadedTrustedFolders;
function loadTrustedFolders() {
  if (loadedTrustedFolders) {
    return loadedTrustedFolders;
  }
  const errors = [];
  let userConfig = {};
  const userPath = getTrustedFoldersPath();
  try {
    if (fs77.existsSync(userPath)) {
      const content = fs77.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 (error2) {
    errors.push({
      message: getErrorMessage(error2),
      path: userPath
    });
  }
  loadedTrustedFolders = new LoadedTrustedFolders(
    { path: userPath, config: userConfig },
    errors
  );
  return loadedTrustedFolders;
}
__name(loadTrustedFolders, "loadTrustedFolders");
function saveTrustedFolders(trustedFoldersFile) {
  try {
    const dirPath = path80.dirname(trustedFoldersFile.path);
    if (!fs77.existsSync(dirPath)) {
      fs77.mkdirSync(dirPath, { recursive: true });
    }
    fs77.writeFileSync(
      trustedFoldersFile.path,
      JSON.stringify(trustedFoldersFile.config, null, 2),
      { encoding: "utf-8", mode: 384 }
    );
  } catch (error2) {
    writeStderrLine("Error saving trusted folders file.");
    writeStderrLine(error2 instanceof Error ? error2.message : String(error2));
  }
}
__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(
      (error2) => `Error in ${error2.path}: ${error2.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/config/settingsSchema.ts
init_esbuild_shims();

// packages/cli/src/i18n/languages.ts
init_esbuild_shims();
var SUPPORTED_LANGUAGES = [
  {
    code: "en",
    id: "en-US",
    fullName: "English",
    nativeName: "English"
  },
  {
    code: "zh",
    id: "zh-CN",
    fullName: "Chinese",
    nativeName: "\u4E2D\u6587"
  },
  {
    code: "ru",
    id: "ru-RU",
    fullName: "Russian",
    nativeName: "\u0420\u0443\u0441\u0441\u043A\u0438\u0439"
  },
  {
    code: "de",
    id: "de-DE",
    fullName: "German",
    nativeName: "Deutsch"
  },
  {
    code: "ja",
    id: "ja-JP",
    fullName: "Japanese",
    nativeName: "\u65E5\u672C\u8A9E"
  },
  {
    code: "pt",
    id: "pt-BR",
    fullName: "Portuguese",
    nativeName: "Portugu\xEAs"
  }
];
function getLanguageNameFromLocale(locale) {
  const lang = SUPPORTED_LANGUAGES.find((l3) => l3.code === locale);
  return lang?.fullName || "English";
}
__name(getLanguageNameFromLocale, "getLanguageNameFromLocale");
function getLanguageSettingsOptions() {
  return [
    { value: "auto", label: "Auto (detect from system)" },
    ...SUPPORTED_LANGUAGES.map((l3) => ({
      value: l3.code,
      label: l3.nativeName ? `${l3.nativeName} (${l3.fullName})` : `${l3.fullName} (${l3.id})`
    }))
  ];
}
__name(getLanguageSettingsOptions, "getLanguageSettingsOptions");
function getSupportedLanguageIds(separator = "|") {
  return SUPPORTED_LANGUAGES.map((l3) => l3.id).join(separator);
}
__name(getSupportedLanguageIds, "getSupportedLanguageIds");

// packages/cli/src/config/settingsSchema.ts
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 */
  },
  // Model providers configuration grouped by authType
  modelProviders: {
    type: "object",
    label: "Model Providers",
    category: "Model",
    requiresRestart: false,
    default: {},
    description: "Model providers configuration grouped by authType. Each authType contains an array of model configurations.",
    showInDialog: false,
    mergeStrategy: "replace" /* REPLACE */
  },
  // Coding Plan configuration
  codingPlan: {
    type: "object",
    label: "Coding Plan",
    category: "Model",
    requiresRestart: false,
    default: {},
    description: "Coding Plan template version tracking and configuration.",
    showInDialog: false,
    properties: {
      version: {
        type: "string",
        label: "Coding Plan Template Version",
        category: "Model",
        requiresRestart: false,
        default: void 0,
        description: "SHA256 hash of the Coding Plan template. Used to detect template updates.",
        showInDialog: false
      }
    }
  },
  // Environment variables fallback
  env: {
    type: "object",
    label: "Environment Variables",
    category: "Advanced",
    requiresRestart: true,
    default: {},
    description: "Environment variables to set as fallback defaults. These are loaded with the lowest priority: system environment variables > .env files > settings.json env field.",
    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: true
      },
      vimMode: {
        type: "boolean",
        label: "Vim Mode",
        category: "General",
        requiresRestart: false,
        default: false,
        description: "Enable Vim keybindings",
        showInDialog: true
      },
      enableAutoUpdate: {
        type: "boolean",
        label: "Enable Auto Update",
        category: "General",
        requiresRestart: false,
        default: true,
        description: "Enable automatic update checks and installations on startup.",
        showInDialog: true
      },
      gitCoAuthor: {
        type: "boolean",
        label: "Attribution: commit",
        category: "General",
        requiresRestart: false,
        default: true,
        description: "Automatically add a Co-authored-by trailer to git commit messages when commits are made through Qwen Code.",
        showInDialog: true
      },
      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: false
      },
      language: {
        type: "enum",
        label: "Language: UI",
        category: "General",
        requiresRestart: true,
        default: "auto",
        description: 'The language for the user interface. Use "auto" to detect from system settings. You can also use custom language codes (e.g., "es", "fr") by placing JS language files in ~/.qwen/locales/ (e.g., ~/.qwen/locales/es.js).',
        showInDialog: true,
        options: []
      },
      outputLanguage: {
        type: "string",
        label: "Language: Model",
        category: "General",
        requiresRestart: true,
        default: "auto",
        description: 'The language for LLM output. Use "auto" to detect from system settings, or set a specific language.',
        showInDialog: true
      },
      terminalBell: {
        type: "boolean",
        label: "Terminal Bell Notification",
        category: "General",
        requiresRestart: false,
        default: true,
        description: "Play terminal bell sound when response completes or needs approval.",
        showInDialog: true
      },
      chatRecording: {
        type: "boolean",
        label: "Chat Recording",
        category: "General",
        requiresRestart: true,
        default: true,
        description: "Enable saving chat history to disk. Disabling this will also prevent --continue and --resume from working.",
        showInDialog: false
      },
      defaultFileEncoding: {
        type: "enum",
        label: "Default File Encoding",
        category: "General",
        requiresRestart: false,
        default: "utf-8",
        description: 'Default encoding for new files. Use "utf-8" (default) for UTF-8 without BOM, or "utf-8-bom" for UTF-8 with BOM. Only change this if your project specifically requires BOM.',
        showInDialog: false,
        options: [
          { value: "utf-8", label: "UTF-8 (without BOM)" },
          { value: "utf-8-bom", label: "UTF-8 with BOM" }
        ]
      }
    }
  },
  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: false,
        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: "Qwen Dark",
        description: "The color theme for the UI.",
        showInDialog: true
      },
      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: false
      },
      showStatusInTitle: {
        type: "boolean",
        label: "Show Status in Title",
        category: "UI",
        requiresRestart: false,
        default: false,
        description: "Show Qwen Code status and thoughts in the terminal window title",
        showInDialog: false
      },
      hideTips: {
        type: "boolean",
        label: "Hide Tips",
        category: "UI",
        requiresRestart: false,
        default: false,
        description: "Hide helpful tips in the UI",
        showInDialog: true
      },
      showLineNumbers: {
        type: "boolean",
        label: "Show Line Numbers in Code",
        category: "UI",
        requiresRestart: false,
        default: true,
        description: "Show line numbers in the code output.",
        showInDialog: true
      },
      showCitations: {
        type: "boolean",
        label: "Show Citations",
        category: "UI",
        requiresRestart: false,
        default: false,
        description: "Show citations for generated text in the chat.",
        showInDialog: false
      },
      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: "Show Welcome Back Dialog",
        category: "UI",
        requiresRestart: false,
        default: true,
        description: "Show welcome back dialog when returning to a project with conversation history.",
        showInDialog: true
      },
      enableUserFeedback: {
        type: "boolean",
        label: "Enable User Feedback",
        category: "UI",
        requiresRestart: false,
        default: true,
        description: "Show optional feedback dialog after conversations to help improve Qwen performance.",
        showInDialog: true
      },
      accessibility: {
        type: "object",
        label: "Accessibility",
        category: "UI",
        requiresRestart: true,
        default: {},
        description: "Accessibility settings.",
        showInDialog: false,
        properties: {
          enableLoadingPhrases: {
            type: "boolean",
            label: "Enable Loading Phrases",
            category: "UI",
            requiresRestart: true,
            default: true,
            description: "Enable loading phrases (disable 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: false
          }
        }
      },
      feedbackLastShownTimestamp: {
        type: "number",
        label: "Feedback Last Shown Timestamp",
        category: "UI",
        requiresRestart: false,
        default: 0,
        description: "The last time the feedback dialog was shown.",
        showInDialog: false
      }
    }
  },
  ide: {
    type: "object",
    label: "IDE",
    category: "IDE",
    requiresRestart: true,
    default: {},
    description: "IDE integration settings.",
    showInDialog: false,
    properties: {
      enabled: {
        type: "boolean",
        label: "Auto-connect to IDE",
        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: true
      }
    }
  },
  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 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: false
      },
      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: false
      },
      skipLoopDetection: {
        type: "boolean",
        label: "Skip Loop Detection",
        category: "Model",
        requiresRestart: false,
        default: false,
        description: "Disable all loop detection checks (streaming and LLM).",
        showInDialog: false
      },
      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: false
      },
      enableOpenAILogging: {
        type: "boolean",
        label: "Enable OpenAI Logging",
        category: "Model",
        requiresRestart: false,
        default: false,
        description: "Enable OpenAI logging.",
        showInDialog: false
      },
      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: false
      },
      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",
            showInDialog: false
          },
          maxRetries: {
            type: "number",
            label: "Max Retries",
            category: "Generation Configuration",
            requiresRestart: false,
            default: void 0,
            description: "Maximum number of retries for failed requests.",
            parentKey: "generationConfig",
            showInDialog: false
          },
          enableCacheControl: {
            type: "boolean",
            label: "Enable Cache Control",
            category: "Generation Configuration",
            requiresRestart: false,
            default: true,
            description: "Enable cache control for DashScope providers.",
            parentKey: "generationConfig",
            showInDialog: false
          },
          schemaCompliance: {
            type: "enum",
            label: "Tool Schema Compliance",
            category: "Generation Configuration",
            requiresRestart: false,
            default: "auto",
            description: 'The compliance mode for tool schemas sent to the model. Use "openapi_30" for strict OpenAPI 3.0 compatibility (e.g., for Gemini).',
            parentKey: "generationConfig",
            showInDialog: false,
            options: [
              { value: "auto", label: "Auto (Default)" },
              { value: "openapi_30", label: "OpenAPI 3.0 Strict" }
            ]
          },
          contextWindowSize: {
            type: "number",
            label: "Context Window Size",
            category: "Generation Configuration",
            requiresRestart: false,
            default: void 0,
            description: "Overrides the default context window size for the selected model. Use this setting when a provider's effective context limit differs from Qwen Code's default. This value defines the model's assumed maximum context capacity, not a per-request token limit.",
            parentKey: "generationConfig",
            showInDialog: false
          }
        }
      }
    }
  },
  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
      },
      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 */
      },
      loadFromIncludeDirectories: {
        type: "boolean",
        label: "Load Memory From Include Directories",
        category: "Context",
        requiresRestart: false,
        default: false,
        description: "Whether to load memory files from include directories.",
        showInDialog: false
      },
      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: false
          },
          enableFuzzySearch: {
            type: "boolean",
            label: "Enable Fuzzy Search",
            category: "Context",
            requiresRestart: true,
            default: true,
            description: "Enable 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: "Interactive Shell (PTY)",
            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: false
          }
        }
      },
      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: "Tool 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" }
        ]
      },
      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) without explicit user confirmation.",
        showInDialog: false
      },
      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: false
      },
      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: false
      },
      enableToolOutputTruncation: {
        type: "boolean",
        label: "Enable Tool Output Truncation",
        category: "General",
        requiresRestart: true,
        default: true,
        description: "Enable truncation of large tool outputs.",
        showInDialog: false
      },
      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: false
      },
      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: false
      }
    }
  },
  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
      }
    }
  },
  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: false
          }
        }
      },
      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
  }
};
function getSettingsSchema() {
  const schema = SETTINGS_SCHEMA;
  if (schema["general"]?.properties?.["language"]) {
    schema["general"].properties["language"].options = getLanguageSettingsOptions();
  }
  return SETTINGS_SCHEMA;
}
__name(getSettingsSchema, "getSettingsSchema");

// packages/cli/src/utils/envVarResolver.ts
init_esbuild_shims();
function resolveEnvVarsInString2(value, customEnv) {
  const envVarRegex = /\$(?:(\w+)|{([^}]+)})/g;
  return value.replace(envVarRegex, (match2, varName1, varName2) => {
    const varName = varName1 || varName2;
    if (customEnv && typeof customEnv[varName] === "string") {
      return customEnv[varName];
    }
    if (process && process.env && typeof process.env[varName] === "string") {
      return process.env[varName];
    }
    return match2;
  });
}
__name(resolveEnvVarsInString2, "resolveEnvVarsInString");
function resolveEnvVarsInObject2(obj, customEnv) {
  return resolveEnvVarsInObjectInternal2(obj, /* @__PURE__ */ new WeakSet(), customEnv);
}
__name(resolveEnvVarsInObject2, "resolveEnvVarsInObject");
function resolveEnvVarsInObjectInternal2(obj, visited, customEnv) {
  if (obj === null || obj === void 0 || typeof obj === "boolean" || typeof obj === "number") {
    return obj;
  }
  if (typeof obj === "string") {
    return resolveEnvVarsInString2(obj, customEnv);
  }
  if (Array.isArray(obj)) {
    if (visited.has(obj)) {
      return [...obj];
    }
    visited.add(obj);
    const result = obj.map(
      (item) => resolveEnvVarsInObjectInternal2(item, visited, customEnv)
    );
    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] = resolveEnvVarsInObjectInternal2(
          newObj[key],
          visited,
          customEnv
        );
      }
    }
    visited.delete(obj);
    return newObj;
  }
  return obj;
}
__name(resolveEnvVarsInObjectInternal2, "resolveEnvVarsInObjectInternal");

// packages/cli/src/utils/deepMerge.ts
init_esbuild_shims();
function isPlainObject5(item) {
  return !!item && typeof item === "object" && !Array.isArray(item);
}
__name(isPlainObject5, "isPlainObject");
function mergeRecursively(target, source2, getMergeStrategyForPath2, path125 = []) {
  for (const key of Object.keys(source2)) {
    if (key === "__proto__" || key === "constructor" || key === "prototype") {
      continue;
    }
    const newPath = [...path125, 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 (isPlainObject5(objValue) && isPlainObject5(srcValue)) {
      mergeRecursively(objValue, srcValue, getMergeStrategyForPath2, newPath);
    } else if (isPlainObject5(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_src39(), 1);
import * as fs78 from "node:fs";
function updateSettingsFilePreservingFormat(filePath, updates) {
  if (!fs78.existsSync(filePath)) {
    fs78.writeFileSync(filePath, JSON.stringify(updates, null, 2), "utf-8");
    return;
  }
  const originalContent = fs78.readFileSync(filePath, "utf-8");
  let parsed;
  try {
    parsed = (0, import_comment_json.parse)(originalContent);
  } catch (error2) {
    writeStderrLine("Error parsing settings file.");
    writeStderrLine(error2 instanceof Error ? error2.message : String(error2));
    writeStderrLine(
      "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);
  fs78.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) && Object.keys(value).length > 0 && 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/settings.ts
function getMergeStrategyForPath(path125) {
  let current = void 0;
  let currentSchema = getSettingsSchema();
  for (const key of path125) {
    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 = path81.dirname(USER_SETTINGS_PATH);
var DEFAULT_EXCLUDED_ENV_VARS = ["DEBUG", "DEBUG_MODE"];
var MIGRATE_V2_OVERWRITE = true;
var SETTINGS_VERSION = 3;
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",
  dnsResolutionOrder: "advanced.dnsResolutionOrder",
  enforcedAuthType: "security.auth.enforcedType",
  excludeTools: "tools.exclude",
  excludeMCPServers: "mcp.excluded",
  excludedProjectEnvVars: "advanced.excludedEnvVars",
  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",
  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",
  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"
};
var INVERTED_BOOLEAN_MIGRATIONS = {
  disableAutoUpdate: "general.enableAutoUpdate",
  disableUpdateNag: "general.enableAutoUpdate",
  disableLoadingPhrases: "ui.accessibility.enableLoadingPhrases",
  disableFuzzySearch: "context.fileFiltering.enableFuzzySearch",
  disableCacheControl: "model.generationConfig.enableCacheControl"
};
var CONSOLIDATED_SETTINGS = {
  "general.enableAutoUpdate": ["disableAutoUpdate", "disableUpdateNag"]
};
var INVERTED_V2_PATHS = {
  "general.disableAutoUpdate": "general.enableAutoUpdate",
  "general.disableUpdateNag": "general.enableAutoUpdate",
  "ui.accessibility.disableLoadingPhrases": "ui.accessibility.enableLoadingPhrases",
  "context.fileFiltering.disableFuzzySearch": "context.fileFiltering.enableFuzzySearch",
  "model.generationConfig.disableCacheControl": "model.generationConfig.enableCacheControl"
};
var CONSOLIDATED_V2_PATHS = {
  "general.enableAutoUpdate": [
    "general.disableAutoUpdate",
    "general.disableUpdateNag"
  ]
};
function getSystemSettingsPath() {
  if (process27.env["QWEN_CODE_SYSTEM_SETTINGS_PATH"]) {
    return process27.env["QWEN_CODE_SYSTEM_SETTINGS_PATH"];
  }
  if (platform13() === "darwin") {
    return "/Library/Application Support/QwenCode/settings.json";
  } else if (platform13() === "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 path81.join(
    path81.dirname(getSystemSettingsPath()),
    "system-defaults.json"
  );
}
__name(getSystemDefaultsPath, "getSystemDefaultsPath");
var SettingScope2 = /* @__PURE__ */ ((SettingScope3) => {
  SettingScope3["User"] = "User";
  SettingScope3["Workspace"] = "Workspace";
  SettingScope3["System"] = "System";
  SettingScope3["SystemDefaults"] = "SystemDefaults";
  return SettingScope3;
})(SettingScope2 || {});
function setNestedProperty(obj, path125, value) {
  const keys = path125.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");
var KNOWN_V2_CONTAINERS = /* @__PURE__ */ new Set([
  ...Object.values(MIGRATION_MAP).map((path125) => path125.split(".")[0]),
  ...Object.values(INVERTED_BOOLEAN_MIGRATIONS).map(
    (path125) => path125.split(".")[0]
  )
]);
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;
  });
  const hasInvertedBooleanKeys = Object.keys(INVERTED_BOOLEAN_MIGRATIONS).some(
    (v1Key) => v1Key in settings
  );
  return hasV1Keys || hasInvertedBooleanKeys;
}
__name(needsMigration, "needsMigration");
function migrateV1ToV3(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);
    }
  }
  for (const [newPath, oldKeys] of Object.entries(CONSOLIDATED_SETTINGS)) {
    let hasAnyDisable = false;
    let hasAnyValue = false;
    for (const oldKey of oldKeys) {
      if (flatKeys.has(oldKey)) {
        hasAnyValue = true;
        const oldValue = flatSettings[oldKey];
        if (typeof oldValue === "boolean" && oldValue === true) {
          hasAnyDisable = true;
        }
        flatKeys.delete(oldKey);
      }
    }
    if (hasAnyValue) {
      setNestedProperty(v2Settings, newPath, !hasAnyDisable);
    }
  }
  const consolidatedKeys = new Set(Object.values(CONSOLIDATED_SETTINGS).flat());
  for (const [oldKey, newPath] of Object.entries(INVERTED_BOOLEAN_MIGRATIONS)) {
    if (consolidatedKeys.has(oldKey)) {
      continue;
    }
    if (flatKeys.has(oldKey)) {
      const oldValue = flatSettings[oldKey];
      if (typeof oldValue === "boolean") {
        setNestedProperty(v2Settings, newPath, !oldValue);
      }
      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((path125) => getMergeStrategyForPath([remainingKey, ...path125]), "pathAwareGetStrategy");
      v2Settings[remainingKey] = customDeepMerge(
        pathAwareGetStrategy,
        {},
        newValue,
        existingValue
      );
    } else {
      v2Settings[remainingKey] = newValue;
    }
  }
  v2Settings[SETTINGS_VERSION_KEY] = SETTINGS_VERSION;
  return v2Settings;
}
__name(migrateV1ToV3, "migrateV1ToV3");
function migrateV2ToV3(settings) {
  const version2 = settings[SETTINGS_VERSION_KEY];
  if (typeof version2 === "number" && version2 >= 3) {
    return null;
  }
  let changed = false;
  const result = structuredClone(settings);
  const processedPaths = /* @__PURE__ */ new Set();
  for (const [newPath, oldPaths] of Object.entries(CONSOLIDATED_V2_PATHS)) {
    let hasAnyDisable = false;
    let hasAnyValue = false;
    for (const oldPath of oldPaths) {
      const oldValue = getNestedProperty(result, oldPath);
      if (typeof oldValue === "boolean") {
        hasAnyValue = true;
        if (oldValue === true) {
          hasAnyDisable = true;
        }
        deleteNestedProperty(result, oldPath);
        processedPaths.add(oldPath);
        changed = true;
      }
    }
    if (hasAnyValue) {
      setNestedProperty(result, newPath, !hasAnyDisable);
    }
  }
  for (const [oldPath, newPath] of Object.entries(INVERTED_V2_PATHS)) {
    if (processedPaths.has(oldPath)) {
      continue;
    }
    const oldValue = getNestedProperty(result, oldPath);
    if (typeof oldValue === "boolean") {
      deleteNestedProperty(result, oldPath);
      setNestedProperty(result, newPath, !oldValue);
      changed = true;
    }
  }
  if (changed) {
    result[SETTINGS_VERSION_KEY] = SETTINGS_VERSION;
    return result;
  }
  if (typeof version2 === "number" && version2 < SETTINGS_VERSION) {
    result[SETTINGS_VERSION_KEY] = SETTINGS_VERSION;
    return result;
  }
  return null;
}
__name(migrateV2ToV3, "migrateV2ToV3");
function deleteNestedProperty(obj, path125) {
  const keys = path125.split(".");
  const lastKey = keys.pop();
  if (!lastKey) return;
  let current = obj;
  for (const key of keys) {
    const next = current[key];
    if (typeof next !== "object" || next === null) {
      return;
    }
    current = next;
  }
  delete current[lastKey];
}
__name(deleteNestedProperty, "deleteNestedProperty");
function getNestedProperty(obj, path125) {
  const keys = path125.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 OLD_V2_TO_V1_MAP = {};
for (const [oldV2Path, newV3Path] of Object.entries(INVERTED_V2_PATHS)) {
  for (const [v1Key, v3Path] of Object.entries(INVERTED_BOOLEAN_MIGRATIONS)) {
    if (v3Path === newV3Path) {
      OLD_V2_TO_V1_MAP[oldV2Path] = v1Key;
      break;
    }
  }
}
var V3_TO_V1_INVERTED_MAP = Object.fromEntries(
  Object.entries(INVERTED_BOOLEAN_MIGRATIONS).map(([v1Key, v3Path]) => [
    v3Path,
    v1Key
  ])
);
function getSettingsFileKeyWarnings(settings, settingsFilePath) {
  const version2 = settings[SETTINGS_VERSION_KEY];
  if (typeof version2 !== "number" || version2 < SETTINGS_VERSION) {
    return [];
  }
  const warnings = [];
  const ignoredLegacyKeys = /* @__PURE__ */ new Set();
  for (const [oldKey, newPath] of Object.entries(MIGRATION_MAP)) {
    if (oldKey === newPath) {
      continue;
    }
    if (!(oldKey in settings)) {
      continue;
    }
    const oldValue = settings[oldKey];
    if (KNOWN_V2_CONTAINERS.has(oldKey) && typeof oldValue === "object" && oldValue !== null && !Array.isArray(oldValue)) {
      continue;
    }
    ignoredLegacyKeys.add(oldKey);
    warnings.push(
      `Warning: Legacy setting '${oldKey}' will be ignored in ${settingsFilePath}. Please use '${newPath}' instead.`
    );
  }
  const schemaKeys = new Set(Object.keys(getSettingsSchema()));
  for (const key of Object.keys(settings)) {
    if (key === SETTINGS_VERSION_KEY) {
      continue;
    }
    if (ignoredLegacyKeys.has(key)) {
      continue;
    }
    if (schemaKeys.has(key)) {
      continue;
    }
    warnings.push(
      `Warning: Unknown setting '${key}' will be ignored in ${settingsFilePath}.`
    );
  }
  return warnings;
}
__name(getSettingsFileKeyWarnings, "getSettingsFileKeyWarnings");
function getSettingsWarnings(loadedSettings) {
  const warningSet = /* @__PURE__ */ new Set();
  for (const scope of ["User" /* User */, "Workspace" /* Workspace */]) {
    const settingsFile = loadedSettings.forScope(scope);
    if (settingsFile.rawJson === void 0) {
      continue;
    }
    const settingsObject = settingsFile.originalSettings;
    for (const warning of getSettingsFileKeyWarnings(
      settingsObject,
      settingsFile.path
    )) {
      warningSet.add(warning);
    }
  }
  return [...warningSet];
}
__name(getSettingsWarnings, "getSettingsWarnings");
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]);
    }
  }
  for (const [oldV2Path, v1Key] of Object.entries(OLD_V2_TO_V1_MAP)) {
    const value = getNestedProperty(v2Settings, oldV2Path);
    if (value !== void 0) {
      v1Settings[v1Key] = value;
      v2Keys.delete(oldV2Path.split(".")[0]);
    }
  }
  for (const [v3Path, v1Key] of Object.entries(V3_TO_V1_INVERTED_MAP)) {
    const value = getNestedProperty(v2Settings, v3Path);
    if (value !== void 0 && typeof value === "boolean") {
      v1Settings[v1Key] = !value;
      v2Keys.delete(v3Path.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 createMinimalSettings() {
  const emptySettingsFile = {
    path: "",
    settings: {},
    originalSettings: {},
    rawJson: "{}"
  };
  return new LoadedSettings(
    emptySettingsFile,
    emptySettingsFile,
    emptySettingsFile,
    emptySettingsFile,
    false,
    /* @__PURE__ */ new Set()
  );
}
__name(createMinimalSettings, "createMinimalSettings");
function findEnvFile(settings, startDir) {
  const homeDir = homedir15();
  const isTrusted = isWorkspaceTrusted(settings).isTrusted;
  const userLevelPaths = /* @__PURE__ */ new Set([
    path81.normalize(path81.join(homeDir, ".env")),
    path81.normalize(path81.join(homeDir, QWEN_DIR, ".env"))
  ]);
  const canUseEnvFile = /* @__PURE__ */ __name((filePath) => isTrusted !== false || userLevelPaths.has(path81.normalize(filePath)), "canUseEnvFile");
  let currentDir = path81.resolve(startDir);
  while (true) {
    const geminiEnvPath = path81.join(currentDir, QWEN_DIR, ".env");
    if (fs79.existsSync(geminiEnvPath) && canUseEnvFile(geminiEnvPath)) {
      return geminiEnvPath;
    }
    const envPath = path81.join(currentDir, ".env");
    if (fs79.existsSync(envPath) && canUseEnvFile(envPath)) {
      return envPath;
    }
    const parentDir = path81.dirname(currentDir);
    if (parentDir === currentDir || !parentDir) {
      const homeGeminiEnvPath = path81.join(homeDir, QWEN_DIR, ".env");
      if (fs79.existsSync(homeGeminiEnvPath)) {
        return homeGeminiEnvPath;
      }
      const homeEnvPath = path81.join(homeDir, ".env");
      if (fs79.existsSync(homeEnvPath)) {
        return homeEnvPath;
      }
      return null;
    }
    currentDir = parentDir;
  }
}
__name(findEnvFile, "findEnvFile");
function setUpCloudShellEnvironment(envFilePath) {
  if (envFilePath && fs79.existsSync(envFilePath)) {
    const envFileContent = fs79.readFileSync(envFilePath);
    const parsedEnv = dotenv2.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(settings, process27.cwd());
  if (process27.env["CLOUD_SHELL"] === "true") {
    setUpCloudShellEnvironment(envFilePath);
  }
  if (envFilePath) {
    try {
      const envFileContent = fs79.readFileSync(envFilePath, "utf-8");
      const parsedEnv = dotenv2.parse(envFileContent);
      const excludedVars = settings?.advanced?.excludedEnvVars || DEFAULT_EXCLUDED_ENV_VARS;
      const isProjectEnvFile = !envFilePath.includes(QWEN_DIR);
      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 (_e2) {
    }
  }
  if (settings.env) {
    for (const [key, value] of Object.entries(settings.env)) {
      if (!Object.hasOwn(process27.env, key) && typeof value === "string") {
        process27.env[key] = value;
      }
    }
  }
}
__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 = path81.resolve(workspaceDir);
  const resolvedHomeDir = path81.resolve(homedir15());
  let realWorkspaceDir = resolvedWorkspaceDir;
  try {
    realWorkspaceDir = fs79.realpathSync(resolvedWorkspaceDir);
  } catch (_e2) {
  }
  const realHomeDir = fs79.realpathSync(resolvedHomeDir);
  const workspaceSettingsPath = new Storage(
    workspaceDir
  ).getWorkspaceSettingsPath();
  const loadAndMigrate = /* @__PURE__ */ __name((filePath, scope) => {
    try {
      if (fs79.existsSync(filePath)) {
        const content = fs79.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 = migrateV1ToV3(settingsObject);
          if (migratedSettings) {
            if (MIGRATE_V2_OVERWRITE) {
              try {
                fs79.renameSync(filePath, `${filePath}.orig`);
                fs79.writeFileSync(
                  filePath,
                  JSON.stringify(migratedSettings, null, 2),
                  "utf-8"
                );
              } catch (e4) {
                writeStderrLine(
                  `Error migrating settings file on disk: ${getErrorMessage(
                    e4
                  )}`
                );
              }
            } else {
              migratedInMemorScopes.add(scope);
            }
            settingsObject = migratedSettings;
          }
        } else if (!(SETTINGS_VERSION_KEY in settingsObject)) {
          settingsObject[SETTINGS_VERSION_KEY] = SETTINGS_VERSION;
          if (MIGRATE_V2_OVERWRITE) {
            try {
              fs79.writeFileSync(
                filePath,
                JSON.stringify(settingsObject, null, 2),
                "utf-8"
              );
            } catch (e4) {
              writeStderrLine(
                `Error adding version to settings file: ${getErrorMessage(e4)}`
              );
            }
          }
        }
        const v3Migrated = migrateV2ToV3(settingsObject);
        if (v3Migrated) {
          if (MIGRATE_V2_OVERWRITE) {
            try {
              const backupPath = `${filePath}.orig`;
              if (!fs79.existsSync(backupPath)) {
                fs79.renameSync(filePath, backupPath);
              }
              fs79.writeFileSync(
                filePath,
                JSON.stringify(v3Migrated, null, 2),
                "utf-8"
              );
            } catch (e4) {
              writeStderrLine(
                `Error migrating settings file to V3: ${getErrorMessage(e4)}`
              );
            }
          } else {
            migratedInMemorScopes.add(scope);
          }
          settingsObject = v3Migrated;
        }
        return { settings: settingsObject, rawJson: content };
      }
    } catch (error2) {
      settingsErrors.push({
        message: getErrorMessage(error2),
        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 = resolveEnvVarsInObject2(systemResult.settings);
  systemDefaultSettings = resolveEnvVarsInObject2(systemDefaultsResult.settings);
  userSettings = resolveEnvVarsInObject2(userResult.settings);
  workspaceSettings = resolveEnvVarsInObject2(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(
      (error2) => `Error in ${error2.path}: ${error2.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 saveSettings(settingsFile) {
  try {
    const dirPath = path81.dirname(settingsFile.path);
    if (!fs79.existsSync(dirPath)) {
      fs79.mkdirSync(dirPath, { recursive: true });
    }
    let settingsToSave = settingsFile.originalSettings;
    if (!MIGRATE_V2_OVERWRITE) {
      settingsToSave = migrateSettingsToV1(
        settingsToSave
      );
    }
    updateSettingsFilePreservingFormat(
      settingsFile.path,
      settingsToSave
    );
  } catch (error2) {
    writeStderrLine("Error saving user settings file.");
    writeStderrLine(error2 instanceof Error ? error2.message : String(error2));
    throw error2;
  }
}
__name(saveSettings, "saveSettings");

// packages/cli/src/i18n/index.ts
init_esbuild_shims();
import * as fs80 from "node:fs";
import * as path82 from "node:path";
import { fileURLToPath as fileURLToPath8, pathToFileURL as pathToFileURL5 } from "node:url";
import { homedir as homedir16 } from "node:os";

// import("./locales/**/*.js") in packages/cli/src/i18n/index.ts
var globImport_locales_js = __glob({
  "./locales/de.js": () => Promise.resolve().then(() => (init_de(), de_exports)),
  "./locales/en.js": () => Promise.resolve().then(() => (init_en3(), en_exports)),
  "./locales/ja.js": () => Promise.resolve().then(() => (init_ja(), ja_exports)),
  "./locales/pt.js": () => Promise.resolve().then(() => (init_pt(), pt_exports)),
  "./locales/ru.js": () => Promise.resolve().then(() => (init_ru(), ru_exports)),
  "./locales/zh.js": () => Promise.resolve().then(() => (init_zh(), zh_exports))
});

// packages/cli/src/i18n/index.ts
var currentLanguage = "en";
var translations = {};
var translationCache = {};
var loadingPromises = {};
var getBuiltinLocalesDir = /* @__PURE__ */ __name(() => {
  const __filename5 = fileURLToPath8(import.meta.url);
  return path82.join(path82.dirname(__filename5), "locales");
}, "getBuiltinLocalesDir");
var getUserLocalesDir = /* @__PURE__ */ __name(() => path82.join(homedir16(), ".qwen", "locales"), "getUserLocalesDir");
var getLocalePath = /* @__PURE__ */ __name((lang, useUserDir = false) => {
  const baseDir = useUserDir ? getUserLocalesDir() : getBuiltinLocalesDir();
  return path82.join(baseDir, `${lang}.js`);
}, "getLocalePath");
function detectSystemLanguage() {
  const envLang = process.env["QWEN_CODE_LANG"] || process.env["LANG"];
  if (envLang) {
    for (const lang of SUPPORTED_LANGUAGES) {
      if (envLang.startsWith(lang.code)) return lang.code;
    }
  }
  try {
    const locale = Intl.DateTimeFormat().resolvedOptions().locale;
    for (const lang of SUPPORTED_LANGUAGES) {
      if (locale.startsWith(lang.code)) return lang.code;
    }
  } catch {
  }
  return "en";
}
__name(detectSystemLanguage, "detectSystemLanguage");
async function loadTranslationsAsync(lang) {
  if (translationCache[lang]) {
    return translationCache[lang];
  }
  const existingPromise = loadingPromises[lang];
  if (existingPromise) {
    return existingPromise;
  }
  const loadPromise = (async () => {
    const searchDirs = [
      { dir: getUserLocalesDir(), isUser: true },
      { dir: getBuiltinLocalesDir(), isUser: false }
    ];
    for (const { dir, isUser } of searchDirs) {
      if (!fs80.existsSync(dir)) {
        continue;
      }
      const jsPath = getLocalePath(lang, isUser);
      if (!fs80.existsSync(jsPath)) {
        continue;
      }
      try {
        const fileUrl = pathToFileURL5(jsPath).href;
        try {
          const module2 = await import(fileUrl);
          const result = module2.default || module2;
          if (result && typeof result === "object" && Object.keys(result).length > 0) {
            translationCache[lang] = result;
            return result;
          } else {
            throw new Error("Module loaded but result is empty or invalid");
          }
        } catch {
          if (!isUser) {
            try {
              const module2 = await globImport_locales_js(`./locales/${lang}.js`);
              const result = module2.default || module2;
              if (result && typeof result === "object" && Object.keys(result).length > 0) {
                translationCache[lang] = result;
                return result;
              }
            } catch {
            }
          }
          continue;
        }
      } catch (error2) {
        if (isUser) {
          writeStderrLine(
            `Failed to load translations from user directory for ${lang}: ${error2 instanceof Error ? error2.message : String(error2)}`
          );
        } else {
          writeStderrLine(
            `Failed to load JS translations for ${lang}: ${error2 instanceof Error ? error2.message : String(error2)}`
          );
        }
        continue;
      }
    }
    translationCache[lang] = {};
    return {};
  })();
  loadingPromises[lang] = loadPromise;
  loadPromise.finally(() => {
    delete loadingPromises[lang];
  });
  return loadPromise;
}
__name(loadTranslationsAsync, "loadTranslationsAsync");
function interpolate(template, params) {
  if (!params) return template;
  return template.replace(
    /\{\{(\w+)\}\}/g,
    (match2, key) => params[key] ?? match2
  );
}
__name(interpolate, "interpolate");
function resolveLanguage(lang) {
  return lang === "auto" ? detectSystemLanguage() : lang;
}
__name(resolveLanguage, "resolveLanguage");
async function setLanguageAsync(lang) {
  currentLanguage = resolveLanguage(lang);
  translations = await loadTranslationsAsync(currentLanguage);
}
__name(setLanguageAsync, "setLanguageAsync");
function getCurrentLanguage() {
  return currentLanguage;
}
__name(getCurrentLanguage, "getCurrentLanguage");
function t4(key, params) {
  const translation = translations[key] ?? key;
  if (Array.isArray(translation)) {
    return key;
  }
  return interpolate(translation, params);
}
__name(t4, "t");
function ta(key) {
  const translation = translations[key];
  if (Array.isArray(translation)) {
    return translation;
  }
  return [];
}
__name(ta, "ta");
async function initializeI18n(lang) {
  await setLanguageAsync(lang ?? "auto");
}
__name(initializeI18n, "initializeI18n");

// packages/cli/src/config/auth.ts
var DEFAULT_ENV_KEYS = {
  [AuthType2.USE_OPENAI]: "OPENAI_API_KEY",
  [AuthType2.USE_ANTHROPIC]: "ANTHROPIC_API_KEY",
  [AuthType2.USE_GEMINI]: "GEMINI_API_KEY",
  [AuthType2.USE_VERTEX_AI]: "GOOGLE_API_KEY"
};
function findModelConfig(modelProviders, authType, modelId) {
  if (!modelProviders || !modelId) {
    return void 0;
  }
  const models = modelProviders[authType];
  if (!Array.isArray(models)) {
    return void 0;
  }
  return models.find((m3) => m3.id === modelId);
}
__name(findModelConfig, "findModelConfig");
function hasApiKeyForAuth(authType, settings, config2) {
  const modelProviders = settings.modelProviders;
  const modelId = config2?.getModelsConfig().getModel() ?? settings.model?.name;
  const modelConfig = findModelConfig(modelProviders, authType, modelId);
  if (modelConfig?.envKey) {
    const hasKey2 = !!process.env[modelConfig.envKey];
    return {
      hasKey: hasKey2,
      checkedEnvKey: modelConfig.envKey,
      isExplicitEnvKey: true
    };
  }
  const defaultEnvKey = DEFAULT_ENV_KEYS[authType];
  if (defaultEnvKey) {
    const hasKey2 = !!process.env[defaultEnvKey];
    if (hasKey2) {
      return { hasKey: hasKey2, checkedEnvKey: defaultEnvKey, isExplicitEnvKey: false };
    }
  }
  if (settings.security?.auth?.apiKey) {
    return {
      hasKey: true,
      checkedEnvKey: defaultEnvKey || void 0,
      isExplicitEnvKey: false
    };
  }
  return {
    hasKey: false,
    checkedEnvKey: defaultEnvKey,
    isExplicitEnvKey: false
  };
}
__name(hasApiKeyForAuth, "hasApiKeyForAuth");
function getApiKeyError(authMethod, settings, config2) {
  const { hasKey: hasKey2, checkedEnvKey, isExplicitEnvKey } = hasApiKeyForAuth(
    authMethod,
    settings,
    config2
  );
  if (hasKey2) {
    return null;
  }
  const envKeyHint = checkedEnvKey || DEFAULT_ENV_KEYS[authMethod];
  if (isExplicitEnvKey) {
    return t4(
      "{{envKeyHint}} environment variable not found. Please set it in your .env file or environment variables.",
      { envKeyHint }
    );
  }
  return t4(
    "{{envKeyHint}} environment variable not found (or set settings.security.auth.apiKey). Please set it in your .env file or environment variables.",
    { envKeyHint }
  );
}
__name(getApiKeyError, "getApiKeyError");
function validateAuthMethod(authMethod, config2) {
  const settings = loadSettings();
  loadEnvironment(settings.merged);
  if (authMethod === AuthType2.USE_OPENAI) {
    const { hasKey: hasKey2, checkedEnvKey, isExplicitEnvKey } = hasApiKeyForAuth(
      authMethod,
      settings.merged,
      config2
    );
    if (!hasKey2) {
      const envKeyHint = checkedEnvKey ? `'${checkedEnvKey}'` : "'OPENAI_API_KEY'";
      if (isExplicitEnvKey) {
        return t4(
          "Missing API key for OpenAI-compatible auth. Set the {{envKeyHint}} environment variable.",
          { envKeyHint }
        );
      }
      return t4(
        "Missing API key for OpenAI-compatible auth. Set settings.security.auth.apiKey, or set the {{envKeyHint}} environment variable.",
        { envKeyHint }
      );
    }
    return null;
  }
  if (authMethod === AuthType2.QWEN_OAUTH) {
    return null;
  }
  if (authMethod === AuthType2.USE_ANTHROPIC) {
    const apiKeyError = getApiKeyError(authMethod, settings.merged, config2);
    if (apiKeyError) {
      return apiKeyError;
    }
    const modelProviders = settings.merged.modelProviders;
    const modelId = config2?.getModelsConfig().getModel() ?? settings.merged.model?.name;
    const modelConfig = findModelConfig(modelProviders, authMethod, modelId);
    if (modelConfig && !modelConfig.baseUrl) {
      return t4(
        "Anthropic provider missing required baseUrl in modelProviders[].baseUrl."
      );
    }
    if (!modelConfig && !process.env["ANTHROPIC_BASE_URL"]) {
      return t4("ANTHROPIC_BASE_URL environment variable not found.");
    }
    return null;
  }
  if (authMethod === AuthType2.USE_GEMINI) {
    const apiKeyError = getApiKeyError(authMethod, settings.merged, config2);
    if (apiKeyError) {
      return apiKeyError;
    }
    return null;
  }
  if (authMethod === AuthType2.USE_VERTEX_AI) {
    const apiKeyError = getApiKeyError(authMethod, settings.merged, config2);
    if (apiKeyError) {
      return apiKeyError;
    }
    process.env["GOOGLE_GENAI_USE_VERTEXAI"] = "true";
    return null;
  }
  return t4("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();

// packages/cli/src/utils/errors.ts
init_esbuild_shims();
var debugLogger71 = createDebugLogger("CLI_ERRORS");
function getErrorMessage3(error2) {
  if (error2 instanceof Error) {
    return error2.message;
  }
  if (error2 !== null && typeof error2 === "object" && "message" in error2 && typeof error2.message === "string") {
    return error2.message;
  }
  if (error2 !== null && typeof error2 === "object") {
    try {
      const stringified = JSON.stringify(error2);
      return stringified ?? String(error2);
    } catch {
      return String(error2);
    }
  }
  return String(error2);
}
__name(getErrorMessage3, "getErrorMessage");
function extractErrorCode(error2) {
  const errorWithCode = error2;
  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(error2, config2, customErrorCode) {
  const errorMessage = parseAndFormatApiError(
    error2,
    config2.getContentGeneratorConfig()?.authType
  );
  if (config2.getOutputFormat() === OutputFormat.JSON) {
    const formatter = new JsonFormatter();
    const errorCode = customErrorCode ?? extractErrorCode(error2);
    const formattedError = formatter.formatError(
      error2 instanceof Error ? error2 : new Error(getErrorMessage3(error2)),
      errorCode
    );
    writeStderrLine(formattedError);
    process.exit(getNumericExitCode(errorCode));
  } else {
    writeStderrLine(errorMessage);
    throw error2;
  }
}
__name(handleError, "handleError");
function handleToolError(toolName, toolError, config2, errorCode, resultDisplay) {
  const isExecutionDenied = errorCode === ToolErrorType.EXECUTION_DENIED;
  const isNonInteractive = !config2.isInteractive();
  const isTextMode = config2.getOutputFormat() === OutputFormat.TEXT;
  if (isExecutionDenied && isNonInteractive && isTextMode) {
    const warningMessage = `Warning: Tool "${toolName}" requires user approval but cannot execute in non-interactive mode.
To enable automatic tool execution, use the -y flag (YOLO mode):
Example: qwen -p 'your prompt' -y

`;
    process.stderr.write(warningMessage);
  }
  debugLogger71.error(
    `Error executing tool ${toolName}: ${resultDisplay || toolError.message}`
  );
}
__name(handleToolError, "handleToolError");
function handleCancellationError(config2) {
  const cancellationError = new FatalCancellationError("Operation cancelled.");
  if (config2.getOutputFormat() === OutputFormat.JSON) {
    const formatter = new JsonFormatter();
    const formattedError = formatter.formatError(
      cancellationError,
      cancellationError.exitCode
    );
    writeStderrLine(formattedError);
    process.exit(cancellationError.exitCode);
  } else {
    writeStderrLine(cancellationError.message);
    process.exit(cancellationError.exitCode);
  }
}
__name(handleCancellationError, "handleCancellationError");
function handleMaxTurnsExceededError(config2) {
  const maxTurnsError = new FatalTurnLimitedError(
    "Reached max session turns for this session. Increase the number of turns by specifying maxSessionTurns in settings.json."
  );
  if (config2.getOutputFormat() === OutputFormat.JSON) {
    const formatter = new JsonFormatter();
    const formattedError = formatter.formatError(
      maxTurnsError,
      maxTurnsError.exitCode
    );
    writeStderrLine(formattedError);
    process.exit(maxTurnsError.exitCode);
  } else {
    writeStderrLine(maxTurnsError.message);
    process.exit(maxTurnsError.exitCode);
  }
}
__name(handleMaxTurnsExceededError, "handleMaxTurnsExceededError");

// packages/cli/src/commands/extensions/consent.ts
init_esbuild_shims();
var import_chalk4 = __toESM(require_source(), 1);
var import_prompts5 = __toESM(require_prompts3(), 1);
async function requestConsentNonInteractive(consentDescription) {
  writeStdoutLine(consentDescription);
  const result = await promptForConsentNonInteractive(
    t4("Do you want to continue? [Y/n]: ")
  );
  return result;
}
__name(requestConsentNonInteractive, "requestConsentNonInteractive");
async function requestChoicePluginNonInteractive(marketplace) {
  const plugins = marketplace.plugins;
  if (plugins.length === 0) {
    throw new Error(t4("No plugins available in this marketplace."));
  }
  const choices = plugins.map((plugin) => ({
    title: import_chalk4.default.green(import_chalk4.default.bold(`[${plugin.name}]`)),
    value: plugin.name
  }));
  const response = await (0, import_prompts5.default)({
    type: "select",
    name: "plugin",
    message: t4('Select a plugin to install from marketplace "{{name}}":', {
      name: marketplace.name
    }),
    choices,
    initial: 0
  });
  if (response.plugin === void 0) {
    throw new Error(t4("Plugin selection cancelled."));
  }
  return response.plugin;
}
__name(requestChoicePluginNonInteractive, "requestChoicePluginNonInteractive");
async function requestConsentInteractive(consentDescription, addExtensionUpdateConfirmationRequest) {
  return promptForConsentInteractive(
    consentDescription + "\n\n" + t4("Do 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((resolve30) => {
    rl.question(prompt, (answer) => {
      rl.close();
      resolve30(["y", ""].includes(answer.trim().toLowerCase()));
    });
  });
}
__name(promptForConsentNonInteractive, "promptForConsentNonInteractive");
async function promptForConsentInteractive(prompt, addExtensionUpdateConfirmationRequest) {
  return new Promise((resolve30) => {
    addExtensionUpdateConfirmationRequest({
      prompt,
      onConfirm: /* @__PURE__ */ __name((resolvedConfirmed) => {
        resolve30(resolvedConfirmed);
      }, "onConfirm")
    });
  });
}
__name(promptForConsentInteractive, "promptForConsentInteractive");
function extensionConsentString(extensionConfig, commands = [], skills = [], subagents = [], originSource = "QwenCode") {
  const output = [];
  if (originSource !== "QwenCode") {
    output.push(
      t4(
        "You are installing an extension from {{originSource}}. Some features may not work perfectly with Qwen Code.",
        { originSource }
      )
    );
  }
  const mcpServerEntries = Object.entries(extensionConfig.mcpServers || {});
  output.push(
    t4('Installing extension "{{name}}".', { name: extensionConfig.name })
  );
  output.push(
    t4(
      "**Extensions may introduce unexpected behavior. Ensure you have investigated the extension source and trust the author.**"
    )
  );
  if (mcpServerEntries.length) {
    output.push(t4("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 ? t4("local") : t4("remote")}): ${source2}`
      );
    }
  }
  if (commands && commands.length > 0) {
    output.push(
      t4("This extension will add the following commands: {{commands}}.", {
        commands: commands.join(", ")
      })
    );
  }
  if (extensionConfig.contextFileName) {
    const fileName = Array.isArray(extensionConfig.contextFileName) ? extensionConfig.contextFileName.join(", ") : extensionConfig.contextFileName;
    output.push(
      t4(
        "This extension will append info to your QWEN.md context using {{fileName}}",
        { fileName }
      )
    );
  }
  if (skills.length > 0) {
    output.push(t4("This extension will install the following skills:"));
    for (const skill of skills) {
      output.push(`  * ${import_chalk4.default.bold(skill.name)}: ${skill.description}`);
    }
  }
  if (subagents.length > 0) {
    output.push(t4("This extension will install the following subagents:"));
    for (const subagent of subagents) {
      output.push(`  * ${import_chalk4.default.bold(subagent.name)}: ${subagent.description}`);
    }
  }
  return output.join("\n");
}
__name(extensionConsentString, "extensionConsentString");
var requestConsentOrFail = /* @__PURE__ */ __name(async (requestConsent, options2) => {
  if (!options2) return;
  const {
    extensionConfig,
    originSource = "QwenCode",
    commands = [],
    skills = [],
    subagents = [],
    previousExtensionConfig,
    previousCommands = [],
    previousSkills = [],
    previousSubagents = []
  } = options2;
  const extensionConsent = extensionConsentString(
    extensionConfig,
    commands,
    skills,
    subagents,
    originSource
  );
  if (previousExtensionConfig) {
    const previousExtensionConsent = extensionConsentString(
      previousExtensionConfig,
      previousCommands,
      previousSkills,
      previousSubagents,
      originSource
    );
    if (previousExtensionConsent === extensionConsent) {
      return;
    }
  }
  if (!await requestConsent(extensionConsent)) {
    throw new Error(
      t4('Installation cancelled for "{{name}}".', {
        name: extensionConfig.name
      })
    );
  }
}, "requestConsentOrFail");

// packages/cli/src/commands/extensions/install.ts
async function handleInstall(args) {
  try {
    const installMetadata = await parseInstallSource(args.source);
    if (installMetadata.type !== "git" && installMetadata.type !== "github-release") {
      if (args.ref || args.autoUpdate) {
        throw new Error(
          t4(
            "--ref and --auto-update are not applicable for marketplace extensions."
          )
        );
      }
    }
    const requestConsent = args.consent ? () => Promise.resolve() : requestConsentOrFail.bind(null, requestConsentNonInteractive);
    const workspaceDir = process.cwd();
    const extensionManager = new ExtensionManager({
      workspaceDir,
      isWorkspaceTrusted: !!isWorkspaceTrusted(
        loadSettings(workspaceDir).merged
      ),
      requestConsent,
      requestChoicePlugin: requestChoicePluginNonInteractive
    });
    await extensionManager.refreshCache();
    const extension = await extensionManager.installExtension(
      {
        ...installMetadata,
        ref: args.ref,
        autoUpdate: args.autoUpdate,
        allowPreRelease: args.allowPreRelease
      },
      requestConsent
    );
    writeStdoutLine(
      t4('Extension "{{name}}" installed successfully and enabled.', {
        name: extension.name
      })
    );
  } catch (error2) {
    writeStderrLine(getErrorMessage3(error2));
    process.exit(1);
  }
}
__name(handleInstall, "handleInstall");
var installCommand = {
  command: "install <source>",
  describe: t4(
    "Installs an extension from a git repository URL, local path, or claude marketplace (marketplace-url:plugin-name)."
  ),
  builder: /* @__PURE__ */ __name((yargs) => yargs.positional("source", {
    describe: t4(
      "The github URL, local path, or marketplace source (marketplace-url:plugin-name) of the extension to install."
    ),
    type: "string",
    demandOption: true
  }).option("ref", {
    describe: t4("The git ref to install from."),
    type: "string"
  }).option("auto-update", {
    describe: t4("Enable auto-update for this extension."),
    type: "boolean"
  }).option("pre-release", {
    describe: t4("Enable pre-release versions for this extension."),
    type: "boolean"
  }).option("consent", {
    describe: t4(
      "Acknowledge the security risks of installing an extension and skip the confirmation prompt."
    ),
    type: "boolean",
    default: false
  }).check((argv) => {
    if (!argv.source) {
      throw new Error(t4("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"],
      allowPreRelease: argv["pre-release"],
      consent: argv["consent"]
    });
  }, "handler")
};

// packages/cli/src/commands/extensions/uninstall.ts
init_esbuild_shims();
async function handleUninstall(args) {
  try {
    const workspaceDir = process.cwd();
    const extensionManager = new ExtensionManager({
      workspaceDir,
      requestConsent: requestConsentOrFail.bind(
        null,
        requestConsentNonInteractive
      ),
      isWorkspaceTrusted: !!isWorkspaceTrusted(
        loadSettings(workspaceDir).merged
      )
    });
    await extensionManager.refreshCache();
    await extensionManager.uninstallExtension(args.name, false);
    writeStdoutLine(
      t4('Extension "{{name}}" successfully uninstalled.', { name: args.name })
    );
  } catch (error2) {
    writeStderrLine(getErrorMessage3(error2));
    process.exit(1);
  }
}
__name(handleUninstall, "handleUninstall");
var uninstallCommand = {
  command: "uninstall <name>",
  describe: t4("Uninstalls an extension."),
  builder: /* @__PURE__ */ __name((yargs) => yargs.positional("name", {
    describe: t4("The name or source path of the extension to uninstall."),
    type: "string"
  }).check((argv) => {
    if (!argv.name) {
      throw new Error(
        t4(
          "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();

// packages/cli/src/commands/extensions/utils.ts
init_esbuild_shims();
var import_chalk5 = __toESM(require_source(), 1);
import * as os25 from "node:os";
async function getExtensionManager() {
  const workspaceDir = process.cwd();
  const extensionManager = new ExtensionManager({
    workspaceDir,
    requestConsent: requestConsentOrFail.bind(
      null,
      requestConsentNonInteractive
    ),
    requestChoicePlugin: requestChoicePluginNonInteractive,
    isWorkspaceTrusted: !!isWorkspaceTrusted(loadSettings(workspaceDir).merged)
  });
  await extensionManager.refreshCache();
  return extensionManager;
}
__name(getExtensionManager, "getExtensionManager");
function extensionToOutputString(extension, extensionManager, workspaceDir, inline2 = false) {
  const cwd7 = workspaceDir;
  const userEnabled = extensionManager.isEnabled(
    extension.config.name,
    os25.homedir()
  );
  const workspaceEnabled = extensionManager.isEnabled(
    extension.config.name,
    cwd7
  );
  const status = workspaceEnabled ? import_chalk5.default.green("\u2713") : import_chalk5.default.red("\u2717");
  let output = `${inline2 ? "" : status} ${extension.config.name} (${extension.config.version})`;
  output += `
 ${t4("Path:")} ${extension.path}`;
  if (extension.installMetadata) {
    output += `
 ${t4("Source:")} ${extension.installMetadata.source} (${t4("Type:")} ${extension.installMetadata.type})`;
    if (extension.installMetadata.ref) {
      output += `
 ${t4("Ref:")} ${extension.installMetadata.ref}`;
    }
    if (extension.installMetadata.releaseTag) {
      output += `
 ${t4("Release tag:")} ${extension.installMetadata.releaseTag}`;
    }
  }
  output += `
 ${t4("Enabled (User):")} ${userEnabled}`;
  output += `
 ${t4("Enabled (Workspace):")} ${workspaceEnabled}`;
  if (extension.contextFiles.length > 0) {
    output += `
 ${t4("Context files:")}`;
    extension.contextFiles.forEach((contextFile) => {
      output += `
  ${contextFile}`;
    });
  }
  if (extension.commands && extension.commands.length > 0) {
    output += `
 ${t4("Commands:")}`;
    extension.commands.forEach((command2) => {
      output += `
  /${command2}`;
    });
  }
  if (extension.skills && extension.skills.length > 0) {
    output += `
 ${t4("Skills:")}`;
    extension.skills.forEach((skill) => {
      output += `
  ${skill.name}`;
    });
  }
  if (extension.agents && extension.agents.length > 0) {
    output += `
 ${t4("Agents:")}`;
    extension.agents.forEach((agent) => {
      output += `
  ${agent.name}`;
    });
  }
  if (extension.config.mcpServers) {
    output += `
 ${t4("MCP servers:")}`;
    Object.keys(extension.config.mcpServers).forEach((key) => {
      output += `
  ${key}`;
    });
  }
  return output;
}
__name(extensionToOutputString, "extensionToOutputString");

// packages/cli/src/commands/extensions/list.ts
async function handleList() {
  try {
    const extensionManager = await getExtensionManager();
    const extensions = extensionManager.getLoadedExtensions();
    if (!extensions || extensions.length === 0) {
      writeStdoutLine(t4("No extensions installed."));
      return;
    }
    writeStdoutLine(
      extensions.map(
        (extension, _2) => extensionToOutputString(extension, extensionManager, process.cwd())
      ).join("\n\n")
    );
  } catch (error2) {
    writeStderrLine(getErrorMessage3(error2));
    process.exit(1);
  }
}
__name(handleList, "handleList");
var listCommand = {
  command: "list",
  describe: t4("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/ui/state/extensions.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/state/extensions.ts
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/commands/extensions/update.ts
var updateOutput = /* @__PURE__ */ __name((info) => t4(
  'Extension "{{name}}" successfully updated: {{oldVersion}} \u2192 {{newVersion}}.',
  {
    name: info.name,
    oldVersion: info.originalVersion,
    newVersion: info.updatedVersion
  }
), "updateOutput");
async function handleUpdate(args) {
  const extensionManager = await getExtensionManager();
  const extensions = extensionManager.getLoadedExtensions();
  if (args.name) {
    try {
      const extension = extensions.find(
        (extension2) => extension2.name === args.name
      );
      if (!extension) {
        writeStdoutLine(
          t4('Extension "{{name}}" not found.', { name: args.name })
        );
        return;
      }
      if (!extension.installMetadata) {
        writeStdoutLine(
          t4(
            'Unable to install extension "{{name}}" due to missing install metadata',
            { name: args.name }
          )
        );
        return;
      }
      const updateState = await checkForExtensionUpdate(
        extension,
        extensionManager
      );
      if (updateState !== "update available" /* UPDATE_AVAILABLE */) {
        writeStdoutLine(
          t4('Extension "{{name}}" is already up to date.', { name: args.name })
        );
        return;
      }
      const updatedExtensionInfo = await extensionManager.updateExtension(
        extension,
        updateState,
        () => {
        }
      );
      if (updatedExtensionInfo.originalVersion !== updatedExtensionInfo.updatedVersion) {
        writeStdoutLine(
          t4(
            'Extension "{{name}}" successfully updated: {{oldVersion}} \u2192 {{newVersion}}.',
            {
              name: args.name,
              oldVersion: updatedExtensionInfo.originalVersion,
              newVersion: updatedExtensionInfo.updatedVersion
            }
          )
        );
      } else {
        writeStdoutLine(
          t4('Extension "{{name}}" is already up to date.', { name: args.name })
        );
      }
    } catch (error2) {
      writeStderrLine(getErrorMessage3(error2));
    }
  }
  if (args.all) {
    try {
      const extensionState = /* @__PURE__ */ new Map();
      await extensionManager.checkForAllExtensionUpdates(
        (extensionName, state) => {
          extensionState.set(extensionName, {
            status: state,
            processed: true
            // No need to process as we will force the update.
          });
        }
      );
      let updateInfos = await extensionManager.updateAllUpdatableExtensions(
        extensionState,
        () => {
        }
      );
      updateInfos = updateInfos.filter(
        (info) => info.originalVersion !== info.updatedVersion
      );
      if (updateInfos.length === 0) {
        writeStdoutLine(t4("No extensions to update."));
        return;
      }
      writeStdoutLine(updateInfos.map((info) => updateOutput(info)).join("\n"));
    } catch (error2) {
      writeStderrLine(getErrorMessage3(error2));
    }
  }
}
__name(handleUpdate, "handleUpdate");
var updateCommand = {
  command: "update [<name>] [--all]",
  describe: t4(
    "Updates all extensions or a named extension to the latest version."
  ),
  builder: /* @__PURE__ */ __name((yargs) => yargs.positional("name", {
    describe: t4("The name of the extension to update."),
    type: "string"
  }).option("all", {
    describe: t4("Update all extensions."),
    type: "boolean"
  }).conflicts("name", "all").check((argv) => {
    if (!argv.all && !argv.name) {
      throw new Error(
        t4("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 _a7;
    this.width = opts.width;
    this.wrap = (_a7 = opts.wrap) !== null && _a7 !== void 0 ? _a7 : 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((r5, i3) => {
        return {
          text: r5.trim(),
          padding: this.measurePadding(r5),
          width: i3 === 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, r5) => {
      let str2 = "";
      rrow.forEach((col, c4) => {
        const { width } = row[c4];
        const wrapWidth = this.negatePadding(row[c4]);
        let ts = col;
        if (wrapWidth > mixin.stringWidth(col)) {
          ts += " ".repeat(wrapWidth - mixin.stringWidth(col));
        }
        if (row[c4].align && row[c4].align !== "left" && this.wrap) {
          const fn = align[row[c4].align];
          ts = fn(ts, wrapWidth);
          if (mixin.stringWidth(ts) < wrapWidth) {
            ts += " ".repeat((width || 0) - mixin.stringWidth(ts) - 1);
          }
        }
        const padding = row[c4].padding || [0, 0, 0, 0];
        if (padding[left2]) {
          str2 += " ".repeat(padding[left2]);
        }
        str2 += addBorder(row[c4], ts, "| ");
        str2 += ts;
        str2 += addBorder(row[c4], ts, " |");
        if (padding[right2]) {
          str2 += " ".repeat(padding[right2]);
        }
        if (r5 === 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, c4) => {
      col.width = widths[c4];
      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, r5) => {
        if (!rrows[r5]) {
          rrows.push([]);
        }
        const rrow = rrows[r5];
        for (let i3 = 0; i3 < c4; i3++) {
          if (rrow[i3] === 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((w2, i3) => {
      if (w2 === void 0) {
        return Math.max(unsetWidth, _minWidth(row[i3]));
      }
      return w2;
    });
  }
};
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 i3 = 0; i3 < str2.length; i3++) {
    if (i3 !== 0 && i3 % width === 0) {
      wrapped += "\n";
    }
    wrapped += str2.charAt(i3);
  }
  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 dirname20, resolve as resolve23 } from "path";
import { readdirSync as readdirSync4, statSync as statSync7 } from "fs";
function sync_default(start, callback) {
  let dir = resolve23(".", start);
  let tmp, stats = statSync7(dir);
  if (!stats.isDirectory()) {
    dir = dirname20(dir);
  }
  while (true) {
    tmp = callback(dir, readdirSync4(dir));
    if (tmp) return resolve23(dir, tmp);
    dir = dirname20(tmp = dir);
    if (tmp === dir) break;
  }
}
__name(sync_default, "default");

// node_modules/yargs/lib/platform-shims/esm.mjs
import { inspect as inspect2 } from "util";
import { readFileSync as readFileSync17 } from "fs";
import { fileURLToPath as fileURLToPath9 } from "url";

// node_modules/yargs-parser/build/lib/index.js
init_esbuild_shims();
import { format } from "util";
import { normalize as normalize9, resolve as resolve24 } 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 i3 = leadingHyphens ? leadingHyphens[0].length : 0; i3 < str2.length; i3++) {
      let chr = str2.charAt(i3);
      if (nextChrUpper) {
        nextChrUpper = false;
        chr = chr.toUpperCase();
      }
      if (i3 !== 0 && (chr === "-" || chr === "_")) {
        nextChrUpper = true;
      } else if (chr !== "-" && chr !== "_") {
        camelcase += chr;
      }
    }
    return camelcase;
  }
}
__name(camelCase, "camelCase");
function decamelize(str2, joinString) {
  const lowercase2 = str2.toLowerCase();
  joinString = joinString || "-";
  let notCamelcase = "";
  for (let i3 = 0; i3 < str2.length; i3++) {
    const chrLower = lowercase2.charAt(i3);
    const chrString = str2.charAt(i3);
    if (chrLower !== chrString && i3 > 0) {
      notCamelcase += `${joinString}${lowercase2.charAt(i3)}`;
    } else {
      notCamelcase += chrString;
    }
  }
  return notCamelcase;
}
__name(decamelize, "decamelize");
function looksLikeNumber(x3) {
  if (x3 === null || x3 === void 0)
    return false;
  if (typeof x3 === "number")
    return true;
  if (/^0x[0-9a-f]+$/i.test(x3))
    return true;
  if (/^0[^.]/.test(x3))
    return false;
  return /^[-]?(?:\d+(?:\.\d*)?|\.\d+)(e[-+]?\d+)?$/.test(x3);
}
__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((e4) => typeof e4 !== "string" ? e4 + "" : e4);
  }
  argString = argString.trim();
  let i3 = 0;
  let prevC = null;
  let c4 = null;
  let opening = null;
  const args = [];
  for (let ii = 0; ii < argString.length; ii++) {
    prevC = c4;
    c4 = argString.charAt(ii);
    if (c4 === " " && !opening) {
      if (!(prevC === " ")) {
        i3++;
      }
      continue;
    }
    if (c4 === opening) {
      opening = null;
    } else if ((c4 === "'" || c4 === '"') && !opening) {
      opening = c4;
    }
    if (!args[i3])
      args[i3] = "";
    args[i3] += c4;
  }
  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 error2 = null;
    checkConfiguration();
    let notFlags = [];
    const argv = Object.assign(/* @__PURE__ */ Object.create(null), { _: [] });
    const argvReturn = {};
    for (let i3 = 0; i3 < args.length; i3++) {
      const arg = args[i3];
      const truncatedArg = arg.replace(/^-{3,}/, "---");
      let broken;
      let key;
      let letters;
      let m3;
      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(/^-.+=/)) {
        m3 = arg.match(/^--?([^=]+)=([\s\S]*)$/);
        if (m3 !== null && Array.isArray(m3) && m3.length >= 3) {
          if (checkAllAliases(m3[1], flags.arrays)) {
            i3 = eatArray(i3, m3[1], args, m3[2]);
          } else if (checkAllAliases(m3[1], flags.nargs) !== false) {
            i3 = eatNargs(i3, m3[1], args, m3[2]);
          } else {
            setArg(m3[1], m3[2], true);
          }
        }
      } else if (arg.match(negatedBoolean) && configuration["boolean-negation"]) {
        m3 = arg.match(negatedBoolean);
        if (m3 !== null && Array.isArray(m3) && m3.length >= 2) {
          key = m3[1];
          setArg(key, checkAllAliases(key, flags.arrays) ? [false] : false);
        }
      } else if (arg.match(/^--.+/) || !configuration["short-option-groups"] && arg.match(/^-[^-]+/)) {
        m3 = arg.match(/^--?(.+)/);
        if (m3 !== null && Array.isArray(m3) && m3.length >= 2) {
          key = m3[1];
          if (checkAllAliases(key, flags.arrays)) {
            i3 = eatArray(i3, key, args);
          } else if (checkAllAliases(key, flags.nargs) !== false) {
            i3 = eatNargs(i3, key, args);
          } else {
            next = args[i3 + 1];
            if (next !== void 0 && (!next.match(/^-/) || next.match(negative)) && !checkAllAliases(key, flags.bools) && !checkAllAliases(key, flags.counts)) {
              setArg(key, next);
              i3++;
            } else if (/^(true|false)$/.test(next)) {
              setArg(key, next);
              i3++;
            } else {
              setArg(key, defaultValue(key));
            }
          }
        }
      } else if (arg.match(/^-.\..+=/)) {
        m3 = arg.match(/^-([^=]+)=([\s\S]*)$/);
        if (m3 !== null && Array.isArray(m3) && m3.length >= 3) {
          setArg(m3[1], m3[2]);
        }
      } else if (arg.match(/^-.\..+/) && !arg.match(negative)) {
        next = args[i3 + 1];
        m3 = arg.match(/^-(.\..+)/);
        if (m3 !== null && Array.isArray(m3) && m3.length >= 2) {
          key = m3[1];
          if (next !== void 0 && !next.match(/^-/) && !checkAllAliases(key, flags.bools) && !checkAllAliases(key, flags.counts)) {
            setArg(key, next);
            i3++;
          } else {
            setArg(key, defaultValue(key));
          }
        }
      } else if (arg.match(/^-[^-]+/) && !arg.match(negative)) {
        letters = arg.slice(1, -1).split("");
        broken = false;
        for (let j2 = 0; j2 < letters.length; j2++) {
          next = arg.slice(j2 + 2);
          if (letters[j2 + 1] && letters[j2 + 1] === "=") {
            value = arg.slice(j2 + 3);
            key = letters[j2];
            if (checkAllAliases(key, flags.arrays)) {
              i3 = eatArray(i3, key, args, value);
            } else if (checkAllAliases(key, flags.nargs) !== false) {
              i3 = eatNargs(i3, key, args, value);
            } else {
              setArg(key, value);
            }
            broken = true;
            break;
          }
          if (next === "-") {
            setArg(letters[j2], next);
            continue;
          }
          if (/[A-Za-z]/.test(letters[j2]) && /^-?\d+(\.\d*)?(e-?\d+)?$/.test(next) && checkAllAliases(next, flags.bools) === false) {
            setArg(letters[j2], next);
            broken = true;
            break;
          }
          if (letters[j2 + 1] && letters[j2 + 1].match(/\W/)) {
            setArg(letters[j2], next);
            broken = true;
            break;
          } else {
            setArg(letters[j2], defaultValue(letters[j2]));
          }
        }
        key = arg.slice(-1)[0];
        if (!broken && key !== "-") {
          if (checkAllAliases(key, flags.arrays)) {
            i3 = eatArray(i3, key, args);
          } else if (checkAllAliases(key, flags.nargs) !== false) {
            i3 = eatNargs(i3, key, args);
          } else {
            next = args[i3 + 1];
            if (next !== void 0 && (!/^(-|--)[^-]/.test(next) || next.match(negative)) && !checkAllAliases(key, flags.bools) && !checkAllAliases(key, flags.counts)) {
              setArg(key, next);
              i3++;
            } else if (/^(true|false)$/.test(next)) {
              setArg(key, next);
              i3++;
            } 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(i3 + 1);
        break;
      } else if (configuration["halt-at-non-option"]) {
        notFlags = args.slice(i3);
        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((k2) => aliases[k2])).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(i3, 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)) {
          error2 = Error(__("Argument unexpected for: %s", key));
        }
        setArg(key, defaultValue(key));
        return i3;
      }
      let available = isUndefined2(argAfterEqualSign) ? 0 : 1;
      if (configuration["nargs-eats-options"]) {
        if (args2.length - (i3 + 1) + available < toEat) {
          error2 = Error(__("Not enough arguments following: %s", key));
        }
        available = toEat;
      } else {
        for (ii = i3 + 1; ii < args2.length; ii++) {
          if (!args2[ii].match(/^-[^0-9]/) || args2[ii].match(negative) || isUnknownOptionAsArg(args2[ii]))
            available++;
          else
            break;
        }
        if (available < toEat)
          error2 = Error(__("Not enough arguments following: %s", key));
      }
      let consumed = Math.min(available, toEat);
      if (!isUndefined2(argAfterEqualSign) && consumed > 0) {
        setArg(key, argAfterEqualSign);
        consumed--;
      }
      for (ii = i3 + 1; ii < consumed + i3 + 1; ii++) {
        setArg(key, args2[ii]);
      }
      return i3 + consumed;
    }
    __name(eatNargs, "eatNargs");
    function eatArray(i3, key, args2, argAfterEqualSign) {
      let argsToSet = [];
      let next = argAfterEqualSign || args2[i3 + 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 = i3 + 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;
          i3 = ii;
          argsToSet.push(processValue(key, next, inputIsString));
        }
      }
      if (typeof nargsCount === "number" && (nargsCount && argsToSet.length < nargsCount || isNaN(nargsCount) && argsToSet.length === 0)) {
        error2 = Error(__("Not enough arguments following: %s", key));
      }
      setArg(key, argsToSet);
      return i3;
    }
    __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(x3) {
          const keyProperties = x3.split(".");
          setKey(argv, keyProperties, value);
        });
      }
      if (splitKey.length > 1 && configuration["dot-notation"]) {
        ;
        (flags.aliases[splitKey[0]] || []).forEach(function(x3) {
          let keyProperties = x3.split(".");
          const a2 = [].concat(splitKey);
          a2.shift();
          keyProperties = keyProperties.concat(a2);
          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(v2) {
        return maybeCoerceNumber(key, v2);
      }) : 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 config2 = null;
            const resolvedConfigPath = mixin2.resolve(mixin2.cwd(), configPath);
            const resolveConfig = flags.configs[configKey];
            if (typeof resolveConfig === "function") {
              try {
                config2 = resolveConfig(resolvedConfigPath);
              } catch (e4) {
                config2 = e4;
              }
              if (config2 instanceof Error) {
                error2 = config2;
                return;
              }
            } else {
              config2 = mixin2.require(resolvedConfigPath);
            }
            setConfigObject(config2);
          } catch (ex) {
            if (ex.name === "PermissionDenied")
              error2 = ex;
            else if (argv2[configKey])
              error2 = Error(__("Invalid JSON config file: %s", configPath));
          }
        }
      });
    }
    __name(setConfig, "setConfig");
    function setConfigObject(config2, prev) {
      Object.keys(config2).forEach(function(key) {
        const value = config2[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, i3) {
            if (i3 === 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) {
              error2 = 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(x3) {
            if (hasKey2(obj, x3.split(".")))
              return;
            setKey(obj, x3.split("."), defaults4[key]);
          });
        }
      });
    }
    __name(applyDefaultsAndAliases, "applyDefaultsAndAliases");
    function hasKey2(obj, keys) {
      let o3 = obj;
      if (!configuration["dot-notation"])
        keys = [keys.join(".")];
      keys.slice(0, -1).forEach(function(key2) {
        o3 = o3[key2] || {};
      });
      const key = keys[keys.length - 1];
      if (typeof o3 !== "object")
        return false;
      else
        return key in o3;
    }
    __name(hasKey2, "hasKey");
    function setKey(obj, keys, value) {
      let o3 = obj;
      if (!configuration["dot-notation"])
        keys = [keys.join(".")];
      keys.slice(0, -1).forEach(function(key2) {
        key2 = sanitizeKey(key2);
        if (typeof o3 === "object" && o3[key2] === void 0) {
          o3[key2] = {};
        }
        if (typeof o3[key2] !== "object" || Array.isArray(o3[key2])) {
          if (Array.isArray(o3[key2])) {
            o3[key2].push({});
          } else {
            o3[key2] = [o3[key2], {}];
          }
          o3 = o3[key2][o3[key2].length - 1];
        } else {
          o3 = o3[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(o3[key]) && flags.nargs[key] === 1 || Array.isArray(o3[key]) && o3[key].length === flags.nargs[key]) {
          o3[key] = void 0;
        }
      }
      if (value === increment()) {
        o3[key] = increment(o3[key]);
      } else if (Array.isArray(o3[key])) {
        if (duplicate && isTypeArray && isValueArray) {
          o3[key] = configuration["flatten-duplicate-arrays"] ? o3[key].concat(value) : (Array.isArray(o3[key][0]) ? o3[key] : [o3[key]]).concat([value]);
        } else if (!duplicate && Boolean(isTypeArray) === Boolean(isValueArray)) {
          o3[key] = value;
        } else {
          o3[key] = o3[key].concat([value]);
        }
      } else if (o3[key] === void 0 && isTypeArray) {
        o3[key] = isValueArray ? value : [value];
      } else if (duplicate && !(o3[key] === void 0 || checkAllAliases(key, flags.counts) || checkAllAliases(key, flags.bools))) {
        o3[key] = [o3[key], value];
      } else {
        o3[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(x3) {
            if (/-/.test(x3) && configuration["camel-case-expansion"]) {
              const c4 = camelCase(x3);
              if (c4 !== key && flags.aliases[key].indexOf(c4) === -1) {
                flags.aliases[key].push(c4);
                newAliases[c4] = true;
              }
            }
          });
          flags.aliases[key].concat(key).forEach(function(x3) {
            if (x3.length > 1 && /[A-Z]/.test(x3) && configuration["camel-case-expansion"]) {
              const c4 = decamelize(x3, "-");
              if (c4 !== key && flags.aliases[key].indexOf(c4) === -1) {
                flags.aliases[key].push(c4);
                newAliases[c4] = true;
              }
            }
          });
          flags.aliases[key].forEach(function(x3) {
            flags.aliases[x3] = [key].concat(flags.aliases[key].filter(function(y2) {
              return x3 !== y2;
            }));
          });
        });
      });
    }
    __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((k2) => flags[k2]));
      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 j2 = 0; j2 < letters.length; j2++) {
        next = arg.slice(j2 + 2);
        if (!hasAnyFlag(letters[j2])) {
          hasAllFlags = false;
          break;
        }
        if (letters[j2 + 1] && letters[j2 + 1] === "=" || next === "-" || /[A-Za-z]/.test(letters[j2]) && /^-?\d+(\.\d*)?(e-?\d+)?$/.test(next) || letters[j2 + 1] && letters[j2 + 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)) {
          error2 = Error(__("Invalid configuration: %s, opts.count excludes opts.array.", key));
          return true;
        } else if (checkAllAliases(key, flags.nargs)) {
          error2 = 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: error2,
      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 i3 = 0; i3 < aliasArrays.length; i3++) {
      for (let ii = i3 + 1; ii < aliasArrays.length; ii++) {
        const intersect = aliasArrays[i3].filter(function(v2) {
          return aliasArrays[ii].indexOf(v2) !== -1;
        });
        if (intersect.length) {
          aliasArrays[i3] = aliasArrays[i3].concat(aliasArrays[ii]);
          aliasArrays.splice(ii, 1);
          change = true;
          break;
        }
      }
    }
  }
  aliasArrays.forEach(function(aliasArray) {
    aliasArray = aliasArray.filter(function(v2, i3, self2) {
      return self2.indexOf(v2) === i3;
    });
    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 readFileSync15 } from "fs";
var _a6;
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 = (_a6 = process === null || process === void 0 ? void 0 : process.versions) === null || _a6 === void 0 ? void 0 : _a6.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: normalize9,
  resolve: resolve24,
  // TODO: figure  out a  way to combine ESM and CJS coverage, such  that
  // we can exercise all the lines below:
  require: /* @__PURE__ */ __name((path125) => {
    if (typeof __require !== "undefined") {
      return __require(path125);
    } else if (path125.match(/\.json$/)) {
      return JSON.parse(readFileSync15(path125, "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 basename18, dirname as dirname21, extname as extname5, relative as relative9, resolve as resolve26 } 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 readFileSync16, statSync as statSync8, writeFile as writeFile8 } from "fs";
import { format as format2 } from "util";
import { resolve as resolve25 } from "path";
var node_default = {
  fs: {
    readFileSync: readFileSync16,
    writeFile: writeFile8
  },
  format: format2,
  resolve: resolve25,
  exists: /* @__PURE__ */ __name((file) => {
    try {
      return statSync8(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, i3) {
      const arg = args[i3 + 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 = fileURLToPath9(import.meta.url);
} catch (e4) {
  __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: inspect2,
  getCallerFile: /* @__PURE__ */ __name(() => {
    throw new YError(REQUIRE_DIRECTORY_ERROR);
  }, "getCallerFile"),
  getProcessArgvBin,
  mainFilename: mainFilename || process.cwd(),
  Parser: lib_default,
  path: {
    basename: basename18,
    dirname: dirname21,
    extname: extname5,
    relative: relative9,
    resolve: resolve26
  },
  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: readFileSync17,
  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: resolve26(__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(object3) {
  return Object.keys(object3);
}
__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, i3) => {
    let variadic = false;
    cmd2 = cmd2.replace(/\s/g, "");
    if (/\.+[\]>]/.test(cmd2) && i3 === 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, _length2] = parseArgs();
    const args = [].slice.call(callerArguments);
    while (args.length && args[args.length - 1] === void 0)
      args.pop();
    const length = _length2 || 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((optional2) => {
      if (args.length === 0)
        return;
      const arg = args.shift();
      const observedType = guessType(arg);
      const matchingTypes = optional2.cmd.filter((type) => type === observedType || type === "*");
      if (matchingTypes.length === 0)
        argumentTypeError(observedType, optional2.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 i3 = 0; i3 < callback.length; i3++) {
        if (typeof callback[i3] !== "function") {
          throw Error("middleware must be a function");
        }
        const m3 = callback[i3];
        m3.applyBeforeValidation = applyBeforeValidation;
        m3.global = global2;
      }
      Array.prototype.push.apply(this.globalMiddleware, callback);
    } else if (typeof callback === "function") {
      const m3 = callback;
      m3.applyBeforeValidation = applyBeforeValidation;
      m3.global = global2;
      m3.mutates = mutates;
      this.globalMiddleware.push(callback);
    }
    return this.yargs;
  }
  addCoerceMiddleware(callback, option2) {
    const aliases = this.yargs.getAliases();
    this.globalMiddleware = this.globalMiddleware.filter((m3) => {
      const toCheck = [...aliases[option2] || [], option2];
      if (!m3.option)
        return true;
      else
        return !toCheck.includes(m3.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((m3) => m3.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 = isFunction3(getResult) ? getResult() : getResult;
    return isPromise(result) ? result.then((result2) => resultHandler(result2)) : resultHandler(result);
  } catch (err) {
    return errorHandler(err);
  }
}
__name(maybeAsyncResult, "maybeAsyncResult");
function isFunction3(arg) {
  return typeof arg === "function";
}
__name(isFunction3, "isFunction");

// node_modules/yargs/build/lib/utils/which-module.js
init_esbuild_shims();
function whichModule(exported) {
  if (typeof __require === "undefined")
    return null;
  for (let i3 = 0, files = Object.keys(__require.cache), mod2; i3 < files.length; i3++) {
    mod2 = __require.cache[files[i3]];
    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 : (o3) => o3;
    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((c4) => {
        if (DEFAULT_MARKER.test(c4)) {
          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 c4 = DEFAULT_MARKER.test(commandHandler.original) ? commandHandler.original.replace(DEFAULT_MARKER, "").trim() : commandHandler.original;
    const pc = parentCommands.filter((c5) => {
      return !DEFAULT_MARKER.test(c5);
    });
    pc.push(c4);
    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((error2) => {
          try {
            yargs.getInternalMethods().getUsageInstance().fail(null, error2);
          } 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 optional2 = 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 (optional2.length) {
      const maybe = optional2.shift();
      this.populatePositional(maybe, argv, positionalMap);
    }
    argv._ = context2.commands.concat(argv._.map((a2) => "" + a2));
    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((d2) => {
      const [cmd, ...aliases] = d2.cmd;
      if (d2.variadic) {
        parseOptions.array.push(cmd);
        parseOptions.default[cmd] = [];
      }
      parseOptions.alias[cmd] = aliases;
      parseOptions.demand[cmd] = true;
    });
    parsed.optional.forEach((o3) => {
      const [cmd, ...aliases] = o3.cmd;
      if (o3.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 config2 = Object.assign({}, options2.configuration, {
      "populate--": false
    });
    const parsed = this.shim.Parser.detailed(unparsed, Object.assign({}, options2, {
      configuration: config2
    }));
    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((c4) => Object.prototype.hasOwnProperty.call(c4, key)) || configObjects.some((c4) => Object.prototype.hasOwnProperty.call(c4, 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((c4) => typeof c4 === "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(f5) {
    fails.push(f5);
  }, "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 i3 = fails.length - 1; i3 >= 0; --i3) {
        const fail2 = fails[i3];
        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((k2) => {
        self2.describe(k2, desc2);
      });
    } else if (typeof keyOrKeys === "object") {
      Object.keys(keyOrKeys).forEach((k2) => {
        self2.describe(k2, keyOrKeys[k2]);
      });
    } 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 u2 = null;
        if (demandedCommands._) {
          u2 = `${base$0} <${__("command")}>
`;
        } else {
          u2 = `${base$0} [${__("command")}]
`;
        }
        ui2.div(`${u2}`);
      }
    }
    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((a2, b2) => a2[0].localeCompare(b2[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 i3 = 0, aliasKey; (aliasKey = aliasKeys[i3]) !== void 0; i3++) {
          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 e4 = epilogs.map((epilog) => epilog.replace(/\$0/g, base$0)).join("\n");
      ui2.div(`${e4}
`);
    }
    return ui2.toString().replace(/\s*$/, "");
  }, "help");
  function maxWidth(table, theWrap, modifier) {
    let width = 0;
    if (!Array.isArray(table)) {
      table = Object.values(table).map((v2) => [v2]);
    }
    table.forEach((v2) => {
      width = Math.max(shim3.stringWidth(modifier ? `${modifier} ${getText2(v2[0])}` : getText2(v2[0])) + getIndentation(v2[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((k2) => groupedKeys.indexOf(k2) !== -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 string4 = "";
    const sep9 = separator || ", ";
    const array2 = [].concat(values);
    if (!values || !array2.length)
      return string4;
    array2.forEach((value) => {
      if (string4.length)
        string4 += sep9;
      string4 += JSON.stringify(value);
    });
    return string4;
  }, "stringifiedValues");
  function defaultString(value, defaultDescription) {
    let string4 = `[${__("default:")} `;
    if (value === void 0 && !defaultDescription)
      return null;
    if (defaultDescription) {
      string4 += defaultDescription;
    } else {
      switch (typeof value) {
        case "string":
          string4 += `"${value}"`;
          break;
        case "object":
          string4 += JSON.stringify(value);
          break;
        default:
          string4 += value;
      }
    }
    return `${string4}]`;
  }
  __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, (k2) => !localLookup[k2]);
    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 _a7, _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 = ((_a7 = this.shim.getEnv("SHELL")) === null || _a7 === void 0 ? void 0 : _a7.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 i3 = 0, ii = args.length; i3 < ii; ++i3) {
      if (handlers[args[i3]] && handlers[args[i3]].builder) {
        const builder = handlers[args[i3]].builder;
        if (isCommandBuilderCallback(builder)) {
          this.indexAfterLastReset = i3 + 1;
          const y2 = this.yargs.getInternalMethods().reset();
          builder(y2, true);
          return y2.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((c4) => c4.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((s5) => args.indexOf((/^[^0-9]$/.test(s5) ? "-" : "--") + s5) !== -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 _a7, _b2, _c2, _d;
    let keyWithDesc = key;
    if (this.zshShell) {
      const descs = this.usage.getDescriptions();
      const aliasKey = (_b2 = (_a7 = this === null || this === void 0 ? void 0 : this.aliases) === null || _a7 === void 0 ? void 0 : _a7[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((s5) => /^--/.test(s5), "startsByTwoDashes");
    const isShortOption = /* @__PURE__ */ __name((s5) => /^[^0-9]$/.test(s5), "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(a2, b2) {
  if (a2.length === 0)
    return b2.length;
  if (b2.length === 0)
    return a2.length;
  const matrix = [];
  let i3;
  for (i3 = 0; i3 <= b2.length; i3++) {
    matrix[i3] = [i3];
  }
  let j2;
  for (j2 = 0; j2 <= a2.length; j2++) {
    matrix[0][j2] = j2;
  }
  for (i3 = 1; i3 <= b2.length; i3++) {
    for (j2 = 1; j2 <= a2.length; j2++) {
      if (b2.charAt(i3 - 1) === a2.charAt(j2 - 1)) {
        matrix[i3][j2] = matrix[i3 - 1][j2 - 1];
      } else {
        if (i3 > 1 && j2 > 1 && b2.charAt(i3 - 2) === a2.charAt(j2 - 1) && b2.charAt(i3 - 1) === a2.charAt(j2 - 2)) {
          matrix[i3][j2] = matrix[i3 - 2][j2 - 2] + 1;
        } else {
          matrix[i3][j2] = Math.min(matrix[i3 - 1][j2 - 1] + 1, Math.min(matrix[i3][j2 - 1] + 1, matrix[i3 - 1][j2] + 1));
        }
      }
    }
  }
  return matrix[b2.length][a2.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(required2, observed) {
    if (observed < required2) {
      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 + "", required2 + ""));
    }
  }, "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 _a7;
    const commandKeys = yargs.getInternalMethods().getCommandInstance().getCommands();
    const unknown2 = [];
    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)) {
        unknown2.push(key);
      }
    });
    if (checkPositionals && (currentContext.commands.length > 0 || commandKeys.length > 0 || isDefaultCommand)) {
      argv._.slice(currentContext.commands.length).forEach((key) => {
        if (!commandKeys.includes("" + key)) {
          unknown2.push("" + key);
        }
      });
    }
    if (checkPositionals) {
      const demandedCommands = yargs.getDemandedCommands();
      const maxNonOptDemanded = ((_a7 = demandedCommands._) === null || _a7 === void 0 ? void 0 : _a7.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) && !unknown2.includes(key)) {
            unknown2.push(key);
          }
        });
      }
    }
    if (unknown2.length) {
      usage2.fail(__n("Unknown argument: %s", "Unknown arguments: %s", unknown2.length, unknown2.map((s5) => s5.trim() ? s5 : `"${s5}"`).join(", ")));
    }
  }, "unknownArguments");
  self2.unknownCommands = /* @__PURE__ */ __name(function unknownCommands(argv) {
    const commandKeys = yargs.getInternalMethods().getCommandInstance().getCommands();
    const unknown2 = [];
    const currentContext = yargs.getInternalMethods().getContext();
    if (currentContext.commands.length > 0 || commandKeys.length > 0) {
      argv._.slice(currentContext.commands.length).forEach((key) => {
        if (!commandKeys.includes("" + key)) {
          unknown2.push("" + key);
        }
      });
    }
    if (unknown2.length > 0) {
      usage2.fail(__n("Unknown command: %s", "Unknown commands: %s", unknown2.length, unknown2.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((a2) => !Object.prototype.hasOwnProperty.call(newAliases, a2) || !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((k2) => {
        self2.implies(k2, key[k2]);
      });
    } else {
      yargs.global(key);
      if (!implied[key]) {
        implied[key] = [];
      }
      if (Array.isArray(value)) {
        value.forEach((i3) => self2.implies(key, i3));
      } 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((k2) => {
        self2.conflicts(k2, key[k2]);
      });
    } else {
      yargs.global(key);
      if (!conflicting[key]) {
        conflicting[key] = [];
      }
      if (Array.isArray(value)) {
        value.forEach((i3) => self2.conflicts(key, i3));
      } 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((a2, b2) => b2.length - a2.length);
    let recommended = null;
    let bestDistance = Infinity;
    for (let i3 = 0, candidate; (candidate = potentialCommands[i3]) !== void 0; i3++) {
      const d2 = levenshtein2(cmd, candidate);
      if (d2 <= threshold && d2 < bestDistance) {
        bestDistance = d2;
        recommended = candidate;
      }
    }
    if (recommended)
      usage2.fail(__("Did you mean %s?", recommended));
  }, "recommendCommands");
  self2.reset = /* @__PURE__ */ __name(function reset(localLookup) {
    implied = objFilter(implied, (k2) => !localLookup[k2]);
    conflicting = objFilter(conflicting, (k2) => !localLookup[k2]);
    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(config2, cwd7, mergeExtends, _shim) {
  shim2 = _shim;
  let defaultConfig = {};
  if (Object.prototype.hasOwnProperty.call(config2, "extends")) {
    if (typeof config2.extends !== "string")
      return defaultConfig;
    const isPath = /\.json|\..*rc$/.test(config2.extends);
    let pathToDefault = null;
    if (!isPath) {
      try {
        pathToDefault = __require.resolve(config2.extends);
      } catch (_err) {
        return config2;
      }
    } else {
      pathToDefault = getPathToDefaultConfig(cwd7, config2.extends);
    }
    checkForCircularExtends(pathToDefault);
    previouslyVisitedConfigs.push(pathToDefault);
    defaultConfig = isPath ? JSON.parse(shim2.readFileSync(pathToDefault, "utf8")) : __require(config2.extends);
    delete config2.extends;
    defaultConfig = applyExtends(defaultConfig, shim2.path.dirname(pathToDefault), mergeExtends, shim2);
  }
  previouslyVisitedConfigs = [];
  return mergeExtends ? mergeDeep(defaultConfig, config2) : Object.assign({}, defaultConfig, config2);
}
__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 isObject4(obj) {
    return obj && typeof obj === "object" && !Array.isArray(obj);
  }
  __name(isObject4, "isObject");
  Object.assign(target, config1);
  for (const key of Object.keys(config2)) {
    if (isObject4(config2[key]) && isObject4(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 __classPrivateFieldSet9 = function(receiver, state, value, kind2, f5) {
  if (kind2 === "m") throw new TypeError("Private method is not writable");
  if (kind2 === "a" && !f5) throw new TypeError("Private accessor was defined without a setter");
  if (typeof state === "function" ? receiver !== state || !f5 : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
  return kind2 === "a" ? f5.call(receiver, value) : f5 ? f5.value = value : state.set(receiver, value), value;
};
var __classPrivateFieldGet11 = function(receiver, state, kind2, f5) {
  if (kind2 === "a" && !f5) throw new TypeError("Private accessor was defined without a getter");
  if (typeof state === "function" ? receiver !== state || !f5 : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
  return kind2 === "m" ? f5 : kind2 === "a" ? f5.call(receiver) : f5 ? f5.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);
    __classPrivateFieldSet9(this, _YargsInstance_shim, shim3, "f");
    __classPrivateFieldSet9(this, _YargsInstance_processArgs, processArgs, "f");
    __classPrivateFieldSet9(this, _YargsInstance_cwd, cwd7, "f");
    __classPrivateFieldSet9(this, _YargsInstance_parentRequire, parentRequire, "f");
    __classPrivateFieldSet9(this, _YargsInstance_globalMiddleware, new GlobalMiddleware(this), "f");
    this.$0 = this[kGetDollarZero]();
    this[kReset]();
    __classPrivateFieldSet9(this, _YargsInstance_command, __classPrivateFieldGet11(this, _YargsInstance_command, "f"), "f");
    __classPrivateFieldSet9(this, _YargsInstance_usage, __classPrivateFieldGet11(this, _YargsInstance_usage, "f"), "f");
    __classPrivateFieldSet9(this, _YargsInstance_validation, __classPrivateFieldGet11(this, _YargsInstance_validation, "f"), "f");
    __classPrivateFieldSet9(this, _YargsInstance_options, __classPrivateFieldGet11(this, _YargsInstance_options, "f"), "f");
    __classPrivateFieldGet11(this, _YargsInstance_options, "f").showHiddenOpt = __classPrivateFieldGet11(this, _YargsInstance_defaultShowHiddenOpt, "f");
    __classPrivateFieldSet9(this, _YargsInstance_logger, this[kCreateLogger](), "f");
  }
  addHelpOpt(opt, msg) {
    const defaultHelpOpt = "help";
    argsert("[string|boolean] [string]", [opt, msg], arguments.length);
    if (__classPrivateFieldGet11(this, _YargsInstance_helpOpt, "f")) {
      this[kDeleteFromParserHintObject](__classPrivateFieldGet11(this, _YargsInstance_helpOpt, "f"));
      __classPrivateFieldSet9(this, _YargsInstance_helpOpt, null, "f");
    }
    if (opt === false && msg === void 0)
      return this;
    __classPrivateFieldSet9(this, _YargsInstance_helpOpt, typeof opt === "string" ? opt : defaultHelpOpt, "f");
    this.boolean(__classPrivateFieldGet11(this, _YargsInstance_helpOpt, "f"));
    this.describe(__classPrivateFieldGet11(this, _YargsInstance_helpOpt, "f"), msg || __classPrivateFieldGet11(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 : __classPrivateFieldGet11(this, _YargsInstance_defaultShowHiddenOpt, "f");
    this.boolean(showHiddenOpt);
    this.describe(showHiddenOpt, msg || __classPrivateFieldGet11(this, _YargsInstance_usage, "f").deferY18nLookup("Show hidden options"));
    __classPrivateFieldGet11(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(f5, global2) {
    argsert("<function> [boolean]", [f5, global2], arguments.length);
    this.middleware((argv, _yargs) => {
      return maybeAsyncResult(() => {
        return f5(argv, _yargs.getOptions());
      }, (result) => {
        if (!result) {
          __classPrivateFieldGet11(this, _YargsInstance_usage, "f").fail(__classPrivateFieldGet11(this, _YargsInstance_shim, "f").y18n.__("Argument check failed: %s", f5.toString()));
        } else if (typeof result === "string" || result instanceof Error) {
          __classPrivateFieldGet11(this, _YargsInstance_usage, "f").fail(result.toString(), result);
        }
        return argv;
      }, (err) => {
        __classPrivateFieldGet11(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");
    }
    __classPrivateFieldGet11(this, _YargsInstance_options, "f").key[keys] = true;
    __classPrivateFieldGet11(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);
    __classPrivateFieldGet11(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, __classPrivateFieldGet11(this, _YargsInstance_cwd, "f"), this[kGetParserConfiguration]()["deep-merge-config"] || false, __classPrivateFieldGet11(this, _YargsInstance_shim, "f"));
      __classPrivateFieldGet11(this, _YargsInstance_options, "f").configObjects = (__classPrivateFieldGet11(this, _YargsInstance_options, "f").configObjects || []).concat(key);
      return this;
    }
    if (typeof msg === "function") {
      parseFn = msg;
      msg = void 0;
    }
    this.describe(key, msg || __classPrivateFieldGet11(this, _YargsInstance_usage, "f").deferY18nLookup("Path to JSON config file"));
    (Array.isArray(key) ? key : [key]).forEach((k2) => {
      __classPrivateFieldGet11(this, _YargsInstance_options, "f").config[k2] = 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;
    }
    __classPrivateFieldSet9(this, _YargsInstance_completionCommand, cmd || __classPrivateFieldGet11(this, _YargsInstance_completionCommand, "f") || "completion", "f");
    if (!desc2 && desc2 !== false) {
      desc2 = "generate completion script";
    }
    this.command(__classPrivateFieldGet11(this, _YargsInstance_completionCommand, "f"), desc2);
    if (fn)
      __classPrivateFieldGet11(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);
    __classPrivateFieldGet11(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 = __classPrivateFieldGet11(this, _YargsInstance_parentRequire, "f") || __classPrivateFieldGet11(this, _YargsInstance_shim, "f").require;
    __classPrivateFieldGet11(this, _YargsInstance_command, "f").addDirectory(dir, req, __classPrivateFieldGet11(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, __classPrivateFieldGet11(this, _YargsInstance_shim, "f"));
      __classPrivateFieldGet11(this, _YargsInstance_options, "f").defaultDescription[key] = defaultDescription;
    }
    if (typeof value === "function") {
      assertSingleKey(key, __classPrivateFieldGet11(this, _YargsInstance_shim, "f"));
      if (!__classPrivateFieldGet11(this, _YargsInstance_options, "f").defaultDescription[key])
        __classPrivateFieldGet11(this, _YargsInstance_options, "f").defaultDescription[key] = __classPrivateFieldGet11(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);
    __classPrivateFieldGet11(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, __classPrivateFieldGet11(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, __classPrivateFieldGet11(this, _YargsInstance_shim, "f"));
      this.demandCommand(keys, max, msg, msg);
    } else if (Array.isArray(keys)) {
      keys.forEach((key) => {
        assertNotStrictEqual(msg, true, __classPrivateFieldGet11(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);
    __classPrivateFieldGet11(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);
    __classPrivateFieldGet11(this, _YargsInstance_usage, "f").describe(keys, description);
    return this;
  }
  detectLocale(detect) {
    argsert("<boolean>", [detect], arguments.length);
    __classPrivateFieldSet9(this, _YargsInstance_detectLocale, detect, "f");
    return this;
  }
  env(prefix) {
    argsert("[string|boolean]", [prefix], arguments.length);
    if (prefix === false)
      delete __classPrivateFieldGet11(this, _YargsInstance_options, "f").envPrefix;
    else
      __classPrivateFieldGet11(this, _YargsInstance_options, "f").envPrefix = prefix || "";
    return this;
  }
  epilogue(msg) {
    argsert("<string>", [msg], arguments.length);
    __classPrivateFieldGet11(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 {
      __classPrivateFieldGet11(this, _YargsInstance_usage, "f").example(cmd, description);
    }
    return this;
  }
  exit(code2, err) {
    __classPrivateFieldSet9(this, _YargsInstance_hasOutput, true, "f");
    __classPrivateFieldSet9(this, _YargsInstance_exitError, err, "f");
    if (__classPrivateFieldGet11(this, _YargsInstance_exitProcess, "f"))
      __classPrivateFieldGet11(this, _YargsInstance_shim, "f").process.exit(code2);
  }
  exitProcess(enabled = true) {
    argsert("[boolean]", [enabled], arguments.length);
    __classPrivateFieldSet9(this, _YargsInstance_exitProcess, enabled, "f");
    return this;
  }
  fail(f5) {
    argsert("<function|boolean>", [f5], arguments.length);
    if (typeof f5 === "boolean" && f5 !== false) {
      throw new YError("Invalid first argument. Expected function or boolean 'false'");
    }
    __classPrivateFieldGet11(this, _YargsInstance_usage, "f").failFn(f5);
    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((resolve30, reject) => {
        __classPrivateFieldGet11(this, _YargsInstance_completion, "f").getCompletion(args, (err, completions) => {
          if (err)
            reject(err);
          else
            resolve30(completions);
        });
      });
    } else {
      return __classPrivateFieldGet11(this, _YargsInstance_completion, "f").getCompletion(args, done);
    }
  }
  getDemandedOptions() {
    argsert([], 0);
    return __classPrivateFieldGet11(this, _YargsInstance_options, "f").demandedOptions;
  }
  getDemandedCommands() {
    argsert([], 0);
    return __classPrivateFieldGet11(this, _YargsInstance_options, "f").demandedCommands;
  }
  getDeprecatedOptions() {
    argsert([], 0);
    return __classPrivateFieldGet11(this, _YargsInstance_options, "f").deprecatedOptions;
  }
  getDetectLocale() {
    return __classPrivateFieldGet11(this, _YargsInstance_detectLocale, "f");
  }
  getExitProcess() {
    return __classPrivateFieldGet11(this, _YargsInstance_exitProcess, "f");
  }
  getGroups() {
    return Object.assign({}, __classPrivateFieldGet11(this, _YargsInstance_groups, "f"), __classPrivateFieldGet11(this, _YargsInstance_preservedGroups, "f"));
  }
  getHelp() {
    __classPrivateFieldSet9(this, _YargsInstance_hasOutput, true, "f");
    if (!__classPrivateFieldGet11(this, _YargsInstance_usage, "f").hasCachedHelpMessage()) {
      if (!this.parsed) {
        const parse14 = this[kRunYargsParserAndExecuteCommands](__classPrivateFieldGet11(this, _YargsInstance_processArgs, "f"), void 0, void 0, 0, true);
        if (isPromise(parse14)) {
          return parse14.then(() => {
            return __classPrivateFieldGet11(this, _YargsInstance_usage, "f").help();
          });
        }
      }
      const builderResponse = __classPrivateFieldGet11(this, _YargsInstance_command, "f").runDefaultBuilderOn(this);
      if (isPromise(builderResponse)) {
        return builderResponse.then(() => {
          return __classPrivateFieldGet11(this, _YargsInstance_usage, "f").help();
        });
      }
    }
    return Promise.resolve(__classPrivateFieldGet11(this, _YargsInstance_usage, "f").help());
  }
  getOptions() {
    return __classPrivateFieldGet11(this, _YargsInstance_options, "f");
  }
  getStrict() {
    return __classPrivateFieldGet11(this, _YargsInstance_strict, "f");
  }
  getStrictCommands() {
    return __classPrivateFieldGet11(this, _YargsInstance_strictCommands, "f");
  }
  getStrictOptions() {
    return __classPrivateFieldGet11(this, _YargsInstance_strictOptions, "f");
  }
  global(globals, global2) {
    argsert("<string|array> [boolean]", [globals, global2], arguments.length);
    globals = [].concat(globals);
    if (global2 !== false) {
      __classPrivateFieldGet11(this, _YargsInstance_options, "f").local = __classPrivateFieldGet11(this, _YargsInstance_options, "f").local.filter((l3) => globals.indexOf(l3) === -1);
    } else {
      globals.forEach((g2) => {
        if (!__classPrivateFieldGet11(this, _YargsInstance_options, "f").local.includes(g2))
          __classPrivateFieldGet11(this, _YargsInstance_options, "f").local.push(g2);
      });
    }
    return this;
  }
  group(opts, groupName) {
    argsert("<string|array> <string>", [opts, groupName], arguments.length);
    const existing = __classPrivateFieldGet11(this, _YargsInstance_preservedGroups, "f")[groupName] || __classPrivateFieldGet11(this, _YargsInstance_groups, "f")[groupName];
    if (__classPrivateFieldGet11(this, _YargsInstance_preservedGroups, "f")[groupName]) {
      delete __classPrivateFieldGet11(this, _YargsInstance_preservedGroups, "f")[groupName];
    }
    const seen = {};
    __classPrivateFieldGet11(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);
    __classPrivateFieldGet11(this, _YargsInstance_options, "f").hiddenOptions.push(key);
    return this;
  }
  implies(key, value) {
    argsert("<string|object> [number|string|array]", [key, value], arguments.length);
    __classPrivateFieldGet11(this, _YargsInstance_validation, "f").implies(key, value);
    return this;
  }
  locale(locale) {
    argsert("[string]", [locale], arguments.length);
    if (locale === void 0) {
      this[kGuessLocale]();
      return __classPrivateFieldGet11(this, _YargsInstance_shim, "f").y18n.getLocale();
    }
    __classPrivateFieldSet9(this, _YargsInstance_detectLocale, false, "f");
    __classPrivateFieldGet11(this, _YargsInstance_shim, "f").y18n.setLocale(locale);
    return this;
  }
  middleware(callback, applyBeforeValidation, global2) {
    return __classPrivateFieldGet11(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((k2) => {
        this.options(k2, key[k2]);
      });
    } else {
      if (typeof opt !== "object") {
        opt = {};
      }
      this[kTrackManuallySetKeys](key);
      if (__classPrivateFieldGet11(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");
      }
      __classPrivateFieldGet11(this, _YargsInstance_options, "f").key[key] = true;
      if (opt.alias)
        this.alias(key, opt.alias);
      const deprecate6 = opt.deprecate || opt.deprecated;
      if (deprecate6) {
        this.deprecateOption(key, deprecate6);
      }
      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) {
        __classPrivateFieldGet11(this, _YargsInstance_options, "f").defaultDescription[key] = opt.defaultDescription;
      }
      if (opt.skipValidation) {
        this.skipValidation(key);
      }
      const desc2 = opt.describe || opt.description || opt.desc;
      const descriptions = __classPrivateFieldGet11(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 = __classPrivateFieldGet11(this, _YargsInstance_processArgs, "f");
    }
    if (typeof shortCircuit === "object") {
      __classPrivateFieldSet9(this, _YargsInstance_parseContext, shortCircuit, "f");
      shortCircuit = _parseFn;
    }
    if (typeof shortCircuit === "function") {
      __classPrivateFieldSet9(this, _YargsInstance_parseFn, shortCircuit, "f");
      shortCircuit = false;
    }
    if (!shortCircuit)
      __classPrivateFieldSet9(this, _YargsInstance_processArgs, args, "f");
    if (__classPrivateFieldGet11(this, _YargsInstance_parseFn, "f"))
      __classPrivateFieldSet9(this, _YargsInstance_exitProcess, false, "f");
    const parsed = this[kRunYargsParserAndExecuteCommands](args, !!shortCircuit);
    const tmpParsed = this.parsed;
    __classPrivateFieldGet11(this, _YargsInstance_completion, "f").setParsed(this.parsed);
    if (isPromise(parsed)) {
      return parsed.then((argv) => {
        if (__classPrivateFieldGet11(this, _YargsInstance_parseFn, "f"))
          __classPrivateFieldGet11(this, _YargsInstance_parseFn, "f").call(this, __classPrivateFieldGet11(this, _YargsInstance_exitError, "f"), argv, __classPrivateFieldGet11(this, _YargsInstance_output, "f"));
        return argv;
      }).catch((err) => {
        if (__classPrivateFieldGet11(this, _YargsInstance_parseFn, "f")) {
          __classPrivateFieldGet11(this, _YargsInstance_parseFn, "f")(err, this.parsed.argv, __classPrivateFieldGet11(this, _YargsInstance_output, "f"));
        }
        throw err;
      }).finally(() => {
        this[kUnfreeze]();
        this.parsed = tmpParsed;
      });
    } else {
      if (__classPrivateFieldGet11(this, _YargsInstance_parseFn, "f"))
        __classPrivateFieldGet11(this, _YargsInstance_parseFn, "f").call(this, __classPrivateFieldGet11(this, _YargsInstance_exitError, "f"), parsed, __classPrivateFieldGet11(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(config2) {
    argsert("<object>", [config2], arguments.length);
    __classPrivateFieldSet9(this, _YargsInstance_parserConfig, config2, "f");
    return this;
  }
  pkgConf(key, rootPath) {
    argsert("<string> [string]", [key, rootPath], arguments.length);
    let conf = null;
    const obj = this[kPkgUp](rootPath || __classPrivateFieldGet11(this, _YargsInstance_cwd, "f"));
    if (obj[key] && typeof obj[key] === "object") {
      conf = applyExtends(obj[key], rootPath || __classPrivateFieldGet11(this, _YargsInstance_cwd, "f"), this[kGetParserConfiguration]()["deep-merge-config"] || false, __classPrivateFieldGet11(this, _YargsInstance_shim, "f"));
      __classPrivateFieldGet11(this, _YargsInstance_options, "f").configObjects = (__classPrivateFieldGet11(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, (k2, v2) => {
      if (k2 === "type" && !["string", "number", "boolean"].includes(v2))
        return false;
      return supportedOpts.includes(k2);
    });
    const fullCommand = __classPrivateFieldGet11(this, _YargsInstance_context, "f").fullCommands[__classPrivateFieldGet11(this, _YargsInstance_context, "f").fullCommands.length - 1];
    const parseOptions = fullCommand ? __classPrivateFieldGet11(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, __classPrivateFieldGet11(this, _YargsInstance_usage, "f").getPositionalGroupName());
    return this.option(key, opts);
  }
  recommendCommands(recommend = true) {
    argsert("[boolean]", [recommend], arguments.length);
    __classPrivateFieldSet9(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" && __classPrivateFieldGet11(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;
    __classPrivateFieldGet11(this, _YargsInstance_logger, "f").log(__classPrivateFieldGet11(this, _YargsInstance_completion, "f").generateCompletionScript($0, cmd || __classPrivateFieldGet11(this, _YargsInstance_completionCommand, "f") || "completion"));
    return this;
  }
  showHelp(level) {
    argsert("[string|function]", [level], arguments.length);
    __classPrivateFieldSet9(this, _YargsInstance_hasOutput, true, "f");
    if (!__classPrivateFieldGet11(this, _YargsInstance_usage, "f").hasCachedHelpMessage()) {
      if (!this.parsed) {
        const parse14 = this[kRunYargsParserAndExecuteCommands](__classPrivateFieldGet11(this, _YargsInstance_processArgs, "f"), void 0, void 0, 0, true);
        if (isPromise(parse14)) {
          parse14.then(() => {
            __classPrivateFieldGet11(this, _YargsInstance_usage, "f").showHelp(level);
          });
          return this;
        }
      }
      const builderResponse = __classPrivateFieldGet11(this, _YargsInstance_command, "f").runDefaultBuilderOn(this);
      if (isPromise(builderResponse)) {
        builderResponse.then(() => {
          __classPrivateFieldGet11(this, _YargsInstance_usage, "f").showHelp(level);
        });
        return this;
      }
    }
    __classPrivateFieldGet11(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);
    __classPrivateFieldGet11(this, _YargsInstance_usage, "f").showHelpOnFail(enabled, message);
    return this;
  }
  showVersion(level) {
    argsert("[string|function]", [level], arguments.length);
    __classPrivateFieldGet11(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);
    __classPrivateFieldSet9(this, _YargsInstance_strict, enabled !== false, "f");
    return this;
  }
  strictCommands(enabled) {
    argsert("[boolean]", [enabled], arguments.length);
    __classPrivateFieldSet9(this, _YargsInstance_strictCommands, enabled !== false, "f");
    return this;
  }
  strictOptions(enabled) {
    argsert("[boolean]", [enabled], arguments.length);
    __classPrivateFieldSet9(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 __classPrivateFieldGet11(this, _YargsInstance_shim, "f").process.stdColumns;
  }
  updateLocale(obj) {
    return this.updateStrings(obj);
  }
  updateStrings(obj) {
    argsert("<object>", [obj], arguments.length);
    __classPrivateFieldSet9(this, _YargsInstance_detectLocale, false, "f");
    __classPrivateFieldGet11(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, __classPrivateFieldGet11(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 {
      __classPrivateFieldGet11(this, _YargsInstance_usage, "f").usage(msg);
      return this;
    }
  }
  usageConfiguration(config2) {
    argsert("<object>", [config2], arguments.length);
    __classPrivateFieldSet9(this, _YargsInstance_usageConfig, config2, "f");
    return this;
  }
  version(opt, msg, ver) {
    const defaultVersionOpt = "version";
    argsert("[boolean|string] [string] [string]", [opt, msg, ver], arguments.length);
    if (__classPrivateFieldGet11(this, _YargsInstance_versionOpt, "f")) {
      this[kDeleteFromParserHintObject](__classPrivateFieldGet11(this, _YargsInstance_versionOpt, "f"));
      __classPrivateFieldGet11(this, _YargsInstance_usage, "f").version(void 0);
      __classPrivateFieldSet9(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;
    }
    __classPrivateFieldSet9(this, _YargsInstance_versionOpt, typeof opt === "string" ? opt : defaultVersionOpt, "f");
    msg = msg || __classPrivateFieldGet11(this, _YargsInstance_usage, "f").deferY18nLookup("Show version number");
    __classPrivateFieldGet11(this, _YargsInstance_usage, "f").version(ver || void 0);
    this.boolean(__classPrivateFieldGet11(this, _YargsInstance_versionOpt, "f"));
    this.describe(__classPrivateFieldGet11(this, _YargsInstance_versionOpt, "f"), msg);
    return this;
  }
  wrap(cols) {
    argsert("<number|null|undefined>", [cols], arguments.length);
    __classPrivateFieldGet11(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);
        __classPrivateFieldSet9(this, _YargsInstance_hasOutput, true, "f");
        if (__classPrivateFieldGet11(this, _YargsInstance_output, "f").length)
          __classPrivateFieldSet9(this, _YargsInstance_output, __classPrivateFieldGet11(this, _YargsInstance_output, "f") + "\n", "f");
        __classPrivateFieldSet9(this, _YargsInstance_output, __classPrivateFieldGet11(this, _YargsInstance_output, "f") + args.join(" "), "f");
      }, "log"),
      error: /* @__PURE__ */ __name((...args) => {
        if (!this[kHasParseCallback]())
          console.error(...args);
        __classPrivateFieldSet9(this, _YargsInstance_hasOutput, true, "f");
        if (__classPrivateFieldGet11(this, _YargsInstance_output, "f").length)
          __classPrivateFieldSet9(this, _YargsInstance_output, __classPrivateFieldGet11(this, _YargsInstance_output, "f") + "\n", "f");
        __classPrivateFieldSet9(this, _YargsInstance_output, __classPrivateFieldGet11(this, _YargsInstance_output, "f") + args.join(" "), "f");
      }, "error")
    };
  }
  [kDeleteFromParserHintObject](optionKey) {
    objectKeys(__classPrivateFieldGet11(this, _YargsInstance_options, "f")).forEach((hintKey) => {
      if (/* @__PURE__ */ ((key) => key === "configObjects")(hintKey))
        return;
      const hint = __classPrivateFieldGet11(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 __classPrivateFieldGet11(this, _YargsInstance_usage, "f").getDescriptions()[optionKey];
  }
  [kEmitWarning](warning, type, deduplicationId) {
    if (!__classPrivateFieldGet11(this, _YargsInstance_emittedWarnings, "f")[deduplicationId]) {
      __classPrivateFieldGet11(this, _YargsInstance_shim, "f").process.emitWarning(warning, type);
      __classPrivateFieldGet11(this, _YargsInstance_emittedWarnings, "f")[deduplicationId] = true;
    }
  }
  [kFreeze]() {
    __classPrivateFieldGet11(this, _YargsInstance_frozens, "f").push({
      options: __classPrivateFieldGet11(this, _YargsInstance_options, "f"),
      configObjects: __classPrivateFieldGet11(this, _YargsInstance_options, "f").configObjects.slice(0),
      exitProcess: __classPrivateFieldGet11(this, _YargsInstance_exitProcess, "f"),
      groups: __classPrivateFieldGet11(this, _YargsInstance_groups, "f"),
      strict: __classPrivateFieldGet11(this, _YargsInstance_strict, "f"),
      strictCommands: __classPrivateFieldGet11(this, _YargsInstance_strictCommands, "f"),
      strictOptions: __classPrivateFieldGet11(this, _YargsInstance_strictOptions, "f"),
      completionCommand: __classPrivateFieldGet11(this, _YargsInstance_completionCommand, "f"),
      output: __classPrivateFieldGet11(this, _YargsInstance_output, "f"),
      exitError: __classPrivateFieldGet11(this, _YargsInstance_exitError, "f"),
      hasOutput: __classPrivateFieldGet11(this, _YargsInstance_hasOutput, "f"),
      parsed: this.parsed,
      parseFn: __classPrivateFieldGet11(this, _YargsInstance_parseFn, "f"),
      parseContext: __classPrivateFieldGet11(this, _YargsInstance_parseContext, "f")
    });
    __classPrivateFieldGet11(this, _YargsInstance_usage, "f").freeze();
    __classPrivateFieldGet11(this, _YargsInstance_validation, "f").freeze();
    __classPrivateFieldGet11(this, _YargsInstance_command, "f").freeze();
    __classPrivateFieldGet11(this, _YargsInstance_globalMiddleware, "f").freeze();
  }
  [kGetDollarZero]() {
    let $0 = "";
    let default$0;
    if (/\b(node|iojs|electron)(\.exe)?$/.test(__classPrivateFieldGet11(this, _YargsInstance_shim, "f").process.argv()[0])) {
      default$0 = __classPrivateFieldGet11(this, _YargsInstance_shim, "f").process.argv().slice(1, 2);
    } else {
      default$0 = __classPrivateFieldGet11(this, _YargsInstance_shim, "f").process.argv().slice(0, 1);
    }
    $0 = default$0.map((x3) => {
      const b2 = this[kRebase](__classPrivateFieldGet11(this, _YargsInstance_cwd, "f"), x3);
      return x3.match(/^(\/|([a-zA-Z]:)?\\)/) && b2.length < x3.length ? b2 : x3;
    }).join(" ").trim();
    if (__classPrivateFieldGet11(this, _YargsInstance_shim, "f").getEnv("_") && __classPrivateFieldGet11(this, _YargsInstance_shim, "f").getProcessArgvBin() === __classPrivateFieldGet11(this, _YargsInstance_shim, "f").getEnv("_")) {
      $0 = __classPrivateFieldGet11(this, _YargsInstance_shim, "f").getEnv("_").replace(`${__classPrivateFieldGet11(this, _YargsInstance_shim, "f").path.dirname(__classPrivateFieldGet11(this, _YargsInstance_shim, "f").process.execPath())}/`, "");
    }
    return $0;
  }
  [kGetParserConfiguration]() {
    return __classPrivateFieldGet11(this, _YargsInstance_parserConfig, "f");
  }
  [kGetUsageConfiguration]() {
    return __classPrivateFieldGet11(this, _YargsInstance_usageConfig, "f");
  }
  [kGuessLocale]() {
    if (!__classPrivateFieldGet11(this, _YargsInstance_detectLocale, "f"))
      return;
    const locale = __classPrivateFieldGet11(this, _YargsInstance_shim, "f").getEnv("LC_ALL") || __classPrivateFieldGet11(this, _YargsInstance_shim, "f").getEnv("LC_MESSAGES") || __classPrivateFieldGet11(this, _YargsInstance_shim, "f").getEnv("LANG") || __classPrivateFieldGet11(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 i3 = 0, arg; (arg = args[i3]) !== void 0; i3++) {
      if (__classPrivateFieldGet11(this, _YargsInstance_shim, "f").Parser.looksLikeNumber(arg) && Number.isSafeInteger(Math.floor(parseFloat(`${arg}`)))) {
        args[i3] = Number(arg);
      }
    }
    return argv;
  }
  [kPkgUp](rootPath) {
    const npath = rootPath || "*";
    if (__classPrivateFieldGet11(this, _YargsInstance_pkgs, "f")[npath])
      return __classPrivateFieldGet11(this, _YargsInstance_pkgs, "f")[npath];
    let obj = {};
    try {
      let startDir = rootPath || __classPrivateFieldGet11(this, _YargsInstance_shim, "f").mainFilename;
      if (!rootPath && __classPrivateFieldGet11(this, _YargsInstance_shim, "f").path.extname(startDir)) {
        startDir = __classPrivateFieldGet11(this, _YargsInstance_shim, "f").path.dirname(startDir);
      }
      const pkgJsonPath = __classPrivateFieldGet11(this, _YargsInstance_shim, "f").findUp(startDir, (dir, names) => {
        if (names.includes("package.json")) {
          return "package.json";
        } else {
          return void 0;
        }
      });
      assertNotStrictEqual(pkgJsonPath, void 0, __classPrivateFieldGet11(this, _YargsInstance_shim, "f"));
      obj = JSON.parse(__classPrivateFieldGet11(this, _YargsInstance_shim, "f").readFileSync(pkgJsonPath, "utf8"));
    } catch (_noop) {
    }
    __classPrivateFieldGet11(this, _YargsInstance_pkgs, "f")[npath] = obj || {};
    return __classPrivateFieldGet11(this, _YargsInstance_pkgs, "f")[npath];
  }
  [kPopulateParserHintArray](type, keys) {
    keys = [].concat(keys);
    keys.forEach((key) => {
      key = this[kSanitizeKey](key);
      __classPrivateFieldGet11(this, _YargsInstance_options, "f")[type].push(key);
    });
  }
  [kPopulateParserHintSingleValueDictionary](builder, type, key, value) {
    this[kPopulateParserHintDictionary](builder, type, key, value, (type2, key2, value2) => {
      __classPrivateFieldGet11(this, _YargsInstance_options, "f")[type2][key2] = value2;
    });
  }
  [kPopulateParserHintArrayDictionary](builder, type, key, value) {
    this[kPopulateParserHintDictionary](builder, type, key, value, (type2, key2, value2) => {
      __classPrivateFieldGet11(this, _YargsInstance_options, "f")[type2][key2] = (__classPrivateFieldGet11(this, _YargsInstance_options, "f")[type2][key2] || []).concat(value2);
    });
  }
  [kPopulateParserHintDictionary](builder, type, key, value, singleKeyHandler) {
    if (Array.isArray(key)) {
      key.forEach((k2) => {
        builder(k2, value);
      });
    } else if (/* @__PURE__ */ ((key2) => typeof key2 === "object")(key)) {
      for (const k2 of objectKeys(key)) {
        builder(k2, key[k2]);
      }
    } 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 _a7, _b2, _c2, _d, _e2, _f, _g, _h, _j, _k, _l, _m;
    const frozen = __classPrivateFieldGet11(this, _YargsInstance_frozens, "f").pop();
    assertNotStrictEqual(frozen, void 0, __classPrivateFieldGet11(this, _YargsInstance_shim, "f"));
    let configObjects;
    _a7 = this, _b2 = this, _c2 = this, _d = this, _e2 = this, _f = this, _g = this, _h = this, _j = this, _k = this, _l = this, _m = this, {
      options: { set value(_o) {
        __classPrivateFieldSet9(_a7, _YargsInstance_options, _o, "f");
      } }.value,
      configObjects,
      exitProcess: { set value(_o) {
        __classPrivateFieldSet9(_b2, _YargsInstance_exitProcess, _o, "f");
      } }.value,
      groups: { set value(_o) {
        __classPrivateFieldSet9(_c2, _YargsInstance_groups, _o, "f");
      } }.value,
      output: { set value(_o) {
        __classPrivateFieldSet9(_d, _YargsInstance_output, _o, "f");
      } }.value,
      exitError: { set value(_o) {
        __classPrivateFieldSet9(_e2, _YargsInstance_exitError, _o, "f");
      } }.value,
      hasOutput: { set value(_o) {
        __classPrivateFieldSet9(_f, _YargsInstance_hasOutput, _o, "f");
      } }.value,
      parsed: this.parsed,
      strict: { set value(_o) {
        __classPrivateFieldSet9(_g, _YargsInstance_strict, _o, "f");
      } }.value,
      strictCommands: { set value(_o) {
        __classPrivateFieldSet9(_h, _YargsInstance_strictCommands, _o, "f");
      } }.value,
      strictOptions: { set value(_o) {
        __classPrivateFieldSet9(_j, _YargsInstance_strictOptions, _o, "f");
      } }.value,
      completionCommand: { set value(_o) {
        __classPrivateFieldSet9(_k, _YargsInstance_completionCommand, _o, "f");
      } }.value,
      parseFn: { set value(_o) {
        __classPrivateFieldSet9(_l, _YargsInstance_parseFn, _o, "f");
      } }.value,
      parseContext: { set value(_o) {
        __classPrivateFieldSet9(_m, _YargsInstance_parseContext, _o, "f");
      } }.value
    } = frozen;
    __classPrivateFieldGet11(this, _YargsInstance_options, "f").configObjects = configObjects;
    __classPrivateFieldGet11(this, _YargsInstance_usage, "f").unfreeze();
    __classPrivateFieldGet11(this, _YargsInstance_validation, "f").unfreeze();
    __classPrivateFieldGet11(this, _YargsInstance_command, "f").unfreeze();
    __classPrivateFieldGet11(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 __classPrivateFieldGet11(this, _YargsInstance_command, "f");
  }
  [kGetContext]() {
    return __classPrivateFieldGet11(this, _YargsInstance_context, "f");
  }
  [kGetHasOutput]() {
    return __classPrivateFieldGet11(this, _YargsInstance_hasOutput, "f");
  }
  [kGetLoggerInstance]() {
    return __classPrivateFieldGet11(this, _YargsInstance_logger, "f");
  }
  [kGetParseContext]() {
    return __classPrivateFieldGet11(this, _YargsInstance_parseContext, "f") || {};
  }
  [kGetUsageInstance]() {
    return __classPrivateFieldGet11(this, _YargsInstance_usage, "f");
  }
  [kGetValidationInstance]() {
    return __classPrivateFieldGet11(this, _YargsInstance_validation, "f");
  }
  [kHasParseCallback]() {
    return !!__classPrivateFieldGet11(this, _YargsInstance_parseFn, "f");
  }
  [kIsGlobalContext]() {
    return __classPrivateFieldGet11(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, __classPrivateFieldGet11(this, _YargsInstance_globalMiddleware, "f").getMiddleware(), false);
    }
    return argv;
  }
  [kReset](aliases = {}) {
    __classPrivateFieldSet9(this, _YargsInstance_options, __classPrivateFieldGet11(this, _YargsInstance_options, "f") || {}, "f");
    const tmpOptions = {};
    tmpOptions.local = __classPrivateFieldGet11(this, _YargsInstance_options, "f").local || [];
    tmpOptions.configObjects = __classPrivateFieldGet11(this, _YargsInstance_options, "f").configObjects || [];
    const localLookup = {};
    tmpOptions.local.forEach((l3) => {
      localLookup[l3] = true;
      (aliases[l3] || []).forEach((a2) => {
        localLookup[a2] = true;
      });
    });
    Object.assign(__classPrivateFieldGet11(this, _YargsInstance_preservedGroups, "f"), Object.keys(__classPrivateFieldGet11(this, _YargsInstance_groups, "f")).reduce((acc, groupName) => {
      const keys = __classPrivateFieldGet11(this, _YargsInstance_groups, "f")[groupName].filter((key) => !(key in localLookup));
      if (keys.length > 0) {
        acc[groupName] = keys;
      }
      return acc;
    }, {}));
    __classPrivateFieldSet9(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((k2) => {
      tmpOptions[k2] = (__classPrivateFieldGet11(this, _YargsInstance_options, "f")[k2] || []).filter((k3) => !localLookup[k3]);
    });
    objectOptions.forEach((k2) => {
      tmpOptions[k2] = objFilter(__classPrivateFieldGet11(this, _YargsInstance_options, "f")[k2], (k3) => !localLookup[k3]);
    });
    tmpOptions.envPrefix = __classPrivateFieldGet11(this, _YargsInstance_options, "f").envPrefix;
    __classPrivateFieldSet9(this, _YargsInstance_options, tmpOptions, "f");
    __classPrivateFieldSet9(this, _YargsInstance_usage, __classPrivateFieldGet11(this, _YargsInstance_usage, "f") ? __classPrivateFieldGet11(this, _YargsInstance_usage, "f").reset(localLookup) : usage(this, __classPrivateFieldGet11(this, _YargsInstance_shim, "f")), "f");
    __classPrivateFieldSet9(this, _YargsInstance_validation, __classPrivateFieldGet11(this, _YargsInstance_validation, "f") ? __classPrivateFieldGet11(this, _YargsInstance_validation, "f").reset(localLookup) : validation(this, __classPrivateFieldGet11(this, _YargsInstance_usage, "f"), __classPrivateFieldGet11(this, _YargsInstance_shim, "f")), "f");
    __classPrivateFieldSet9(this, _YargsInstance_command, __classPrivateFieldGet11(this, _YargsInstance_command, "f") ? __classPrivateFieldGet11(this, _YargsInstance_command, "f").reset() : command(__classPrivateFieldGet11(this, _YargsInstance_usage, "f"), __classPrivateFieldGet11(this, _YargsInstance_validation, "f"), __classPrivateFieldGet11(this, _YargsInstance_globalMiddleware, "f"), __classPrivateFieldGet11(this, _YargsInstance_shim, "f")), "f");
    if (!__classPrivateFieldGet11(this, _YargsInstance_completion, "f"))
      __classPrivateFieldSet9(this, _YargsInstance_completion, completion(this, __classPrivateFieldGet11(this, _YargsInstance_usage, "f"), __classPrivateFieldGet11(this, _YargsInstance_command, "f"), __classPrivateFieldGet11(this, _YargsInstance_shim, "f")), "f");
    __classPrivateFieldGet11(this, _YargsInstance_globalMiddleware, "f").reset();
    __classPrivateFieldSet9(this, _YargsInstance_completionCommand, null, "f");
    __classPrivateFieldSet9(this, _YargsInstance_output, "", "f");
    __classPrivateFieldSet9(this, _YargsInstance_exitError, null, "f");
    __classPrivateFieldSet9(this, _YargsInstance_hasOutput, false, "f");
    this.parsed = false;
    return this;
  }
  [kRebase](base, dir) {
    return __classPrivateFieldGet11(this, _YargsInstance_shim, "f").path.relative(base, dir);
  }
  [kRunYargsParserAndExecuteCommands](args, shortCircuit, calledFromCommand, commandIndex = 0, helpOnly = false) {
    let skipValidation = !!calledFromCommand || helpOnly;
    args = args || __classPrivateFieldGet11(this, _YargsInstance_processArgs, "f");
    __classPrivateFieldGet11(this, _YargsInstance_options, "f").__ = __classPrivateFieldGet11(this, _YargsInstance_shim, "f").y18n.__;
    __classPrivateFieldGet11(this, _YargsInstance_options, "f").configuration = this[kGetParserConfiguration]();
    const populateDoubleDash = !!__classPrivateFieldGet11(this, _YargsInstance_options, "f").configuration["populate--"];
    const config2 = Object.assign({}, __classPrivateFieldGet11(this, _YargsInstance_options, "f").configuration, {
      "populate--": true
    });
    const parsed = __classPrivateFieldGet11(this, _YargsInstance_shim, "f").Parser.detailed(args, Object.assign({}, __classPrivateFieldGet11(this, _YargsInstance_options, "f"), {
      configuration: { "parse-positional-numbers": false, ...config2 }
    }));
    const argv = Object.assign(parsed.argv, __classPrivateFieldGet11(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 === __classPrivateFieldGet11(this, _YargsInstance_helpOpt, "f") && argv[key]) {
        helpOptSet = true;
      } else if (key === __classPrivateFieldGet11(this, _YargsInstance_versionOpt, "f") && argv[key]) {
        versionOptSet = true;
      }
    });
    argv.$0 = this.$0;
    this.parsed = parsed;
    if (commandIndex === 0) {
      __classPrivateFieldGet11(this, _YargsInstance_usage, "f").clearCachedHelpMessage();
    }
    try {
      this[kGuessLocale]();
      if (shortCircuit) {
        return this[kPostProcess](argv, populateDoubleDash, !!calledFromCommand, false);
      }
      if (__classPrivateFieldGet11(this, _YargsInstance_helpOpt, "f")) {
        const helpCmds = [__classPrivateFieldGet11(this, _YargsInstance_helpOpt, "f")].concat(aliases[__classPrivateFieldGet11(this, _YargsInstance_helpOpt, "f")] || []).filter((k2) => k2.length > 1);
        if (helpCmds.includes("" + argv._[argv._.length - 1])) {
          argv._.pop();
          helpOptSet = true;
        }
      }
      __classPrivateFieldSet9(this, _YargsInstance_isGlobalContext, false, "f");
      const handlerKeys = __classPrivateFieldGet11(this, _YargsInstance_command, "f").getCommands();
      const requestCompletions = __classPrivateFieldGet11(this, _YargsInstance_completion, "f").completionKey in argv;
      const skipRecommendation = helpOptSet || requestCompletions || helpOnly;
      if (argv._.length) {
        if (handlerKeys.length) {
          let firstUnknownCommand;
          for (let i3 = commandIndex || 0, cmd; argv._[i3] !== void 0; i3++) {
            cmd = String(argv._[i3]);
            if (handlerKeys.includes(cmd) && cmd !== __classPrivateFieldGet11(this, _YargsInstance_completionCommand, "f")) {
              const innerArgv = __classPrivateFieldGet11(this, _YargsInstance_command, "f").runCommand(cmd, this, parsed, i3 + 1, helpOnly, helpOptSet || versionOptSet || helpOnly);
              return this[kPostProcess](innerArgv, populateDoubleDash, !!calledFromCommand, false);
            } else if (!firstUnknownCommand && cmd !== __classPrivateFieldGet11(this, _YargsInstance_completionCommand, "f")) {
              firstUnknownCommand = cmd;
              break;
            }
          }
          if (!__classPrivateFieldGet11(this, _YargsInstance_command, "f").hasDefaultCommand() && __classPrivateFieldGet11(this, _YargsInstance_recommendCommands, "f") && firstUnknownCommand && !skipRecommendation) {
            __classPrivateFieldGet11(this, _YargsInstance_validation, "f").recommendCommands(firstUnknownCommand, handlerKeys);
          }
        }
        if (__classPrivateFieldGet11(this, _YargsInstance_completionCommand, "f") && argv._.includes(__classPrivateFieldGet11(this, _YargsInstance_completionCommand, "f")) && !requestCompletions) {
          if (__classPrivateFieldGet11(this, _YargsInstance_exitProcess, "f"))
            setBlocking(true);
          this.showCompletionScript();
          this.exit(0);
        }
      }
      if (__classPrivateFieldGet11(this, _YargsInstance_command, "f").hasDefaultCommand() && !skipRecommendation) {
        const innerArgv = __classPrivateFieldGet11(this, _YargsInstance_command, "f").runCommand(null, this, parsed, 0, helpOnly, helpOptSet || versionOptSet || helpOnly);
        return this[kPostProcess](innerArgv, populateDoubleDash, !!calledFromCommand, false);
      }
      if (requestCompletions) {
        if (__classPrivateFieldGet11(this, _YargsInstance_exitProcess, "f"))
          setBlocking(true);
        args = [].concat(args);
        const completionArgs = args.slice(args.indexOf(`--${__classPrivateFieldGet11(this, _YargsInstance_completion, "f").completionKey}`) + 1);
        __classPrivateFieldGet11(this, _YargsInstance_completion, "f").getCompletion(completionArgs, (err, completions) => {
          if (err)
            throw new YError(err.message);
          (completions || []).forEach((completion3) => {
            __classPrivateFieldGet11(this, _YargsInstance_logger, "f").log(completion3);
          });
          this.exit(0);
        });
        return this[kPostProcess](argv, !populateDoubleDash, !!calledFromCommand, false);
      }
      if (!__classPrivateFieldGet11(this, _YargsInstance_hasOutput, "f")) {
        if (helpOptSet) {
          if (__classPrivateFieldGet11(this, _YargsInstance_exitProcess, "f"))
            setBlocking(true);
          skipValidation = true;
          this.showHelp("log");
          this.exit(0);
        } else if (versionOptSet) {
          if (__classPrivateFieldGet11(this, _YargsInstance_exitProcess, "f"))
            setBlocking(true);
          skipValidation = true;
          __classPrivateFieldGet11(this, _YargsInstance_usage, "f").showVersion("log");
          this.exit(0);
        }
      }
      if (!skipValidation && __classPrivateFieldGet11(this, _YargsInstance_options, "f").skipValidation.length > 0) {
        skipValidation = Object.keys(argv).some((key) => __classPrivateFieldGet11(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, __classPrivateFieldGet11(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, __classPrivateFieldGet11(this, _YargsInstance_globalMiddleware, "f").getMiddleware(), false);
            });
          }
        }
      }
    } catch (err) {
      if (err instanceof YError)
        __classPrivateFieldGet11(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);
      __classPrivateFieldGet11(this, _YargsInstance_validation, "f").nonOptionCount(argv);
      __classPrivateFieldGet11(this, _YargsInstance_validation, "f").requiredArguments(argv, demandedOptions);
      let failedStrictCommands = false;
      if (__classPrivateFieldGet11(this, _YargsInstance_strictCommands, "f")) {
        failedStrictCommands = __classPrivateFieldGet11(this, _YargsInstance_validation, "f").unknownCommands(argv);
      }
      if (__classPrivateFieldGet11(this, _YargsInstance_strict, "f") && !failedStrictCommands) {
        __classPrivateFieldGet11(this, _YargsInstance_validation, "f").unknownArguments(argv, aliases, positionalMap, !!isDefaultCommand);
      } else if (__classPrivateFieldGet11(this, _YargsInstance_strictOptions, "f")) {
        __classPrivateFieldGet11(this, _YargsInstance_validation, "f").unknownArguments(argv, aliases, {}, false, false);
      }
      __classPrivateFieldGet11(this, _YargsInstance_validation, "f").limitedChoices(argv);
      __classPrivateFieldGet11(this, _YargsInstance_validation, "f").implications(argv);
      __classPrivateFieldGet11(this, _YargsInstance_validation, "f").conflicting(argv);
    };
  }
  [kSetHasOutput]() {
    __classPrivateFieldSet9(this, _YargsInstance_hasOutput, true, "f");
  }
  [kTrackManuallySetKeys](keys) {
    if (typeof keys === "string") {
      __classPrivateFieldGet11(this, _YargsInstance_options, "f").key[keys] = true;
    } else {
      for (const k2 of keys) {
        __classPrivateFieldGet11(this, _YargsInstance_options, "f").key[k2] = true;
      }
    }
  }
};
function isYargsInstance(y2) {
  return !!y2 && typeof y2.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
async function handleDisable(args) {
  const extensionManager = await getExtensionManager();
  try {
    if (args.scope?.toLowerCase() === "workspace") {
      extensionManager.disableExtension(args.name, "Workspace" /* Workspace */);
    } else {
      extensionManager.disableExtension(args.name, "User" /* User */);
    }
    writeStdoutLine(
      t4('Extension "{{name}}" successfully disabled for scope "{{scope}}".', {
        name: args.name,
        scope: args.scope || "User" /* User */
      })
    );
  } catch (error2) {
    writeStderrLine(getErrorMessage3(error2));
    process.exit(1);
  }
}
__name(handleDisable, "handleDisable");
var disableCommand = {
  command: "disable [--scope] <name>",
  describe: t4("Disables an extension."),
  builder: /* @__PURE__ */ __name((yargs) => yargs.positional("name", {
    describe: t4("The name of the extension to disable."),
    type: "string"
  }).option("scope", {
    describe: t4("The scope to disable the extenison in."),
    type: "string",
    default: "User" /* User */
  }).check((argv) => {
    if (argv.scope && !Object.values(SettingScope2).map((s5) => s5.toLowerCase()).includes(argv.scope.toLowerCase())) {
      throw new Error(
        t4("Invalid scope: {{scope}}. Please use one of {{scopes}}.", {
          scope: argv.scope,
          scopes: Object.values(SettingScope2).map((s5) => s5.toLowerCase()).join(", ")
        })
      );
    }
    return true;
  }), "builder"),
  handler: /* @__PURE__ */ __name(async (argv) => {
    await handleDisable({
      name: argv["name"],
      scope: argv["scope"]
    });
  }, "handler")
};

// packages/cli/src/commands/extensions/enable.ts
init_esbuild_shims();
async function handleEnable(args) {
  const extensionManager = await getExtensionManager();
  try {
    if (args.scope?.toLowerCase() === "workspace") {
      extensionManager.enableExtension(args.name, "Workspace" /* Workspace */);
    } else {
      extensionManager.enableExtension(args.name, "User" /* User */);
    }
    if (args.scope) {
      writeStdoutLine(
        t4('Extension "{{name}}" successfully enabled for scope "{{scope}}".', {
          name: args.name,
          scope: args.scope
        })
      );
    } else {
      writeStdoutLine(
        t4('Extension "{{name}}" successfully enabled in all scopes.', {
          name: args.name
        })
      );
    }
  } catch (error2) {
    throw new FatalConfigError(getErrorMessage(error2));
  }
}
__name(handleEnable, "handleEnable");
var enableCommand = {
  command: "enable [--scope] <name>",
  describe: t4("Enables an extension."),
  builder: /* @__PURE__ */ __name((yargs) => yargs.positional("name", {
    describe: t4("The name of the extension to enable."),
    type: "string"
  }).option("scope", {
    describe: t4(
      "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(SettingScope2).map((s5) => s5.toLowerCase()).includes(argv.scope.toLowerCase())) {
      throw new Error(
        t4("Invalid scope: {{scope}}. Please use one of {{scopes}}.", {
          scope: argv.scope,
          scopes: Object.values(SettingScope2).map((s5) => s5.toLowerCase()).join(", ")
        })
      );
    }
    return true;
  }), "builder"),
  handler: /* @__PURE__ */ __name(async (argv) => {
    await 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 extensionManager = await getExtensionManager();
    const extension = await extensionManager.installExtension(
      installMetadata,
      requestConsentOrFail.bind(null, requestConsentNonInteractive)
    );
    if (!extension) {
      writeStdoutLine(t4("Link extension failed to install."));
      return;
    }
    writeStdoutLine(
      t4('Extension "{{name}}" linked successfully and enabled.', {
        name: extension.name
      })
    );
  } catch (error2) {
    writeStderrLine(getErrorMessage3(error2));
    process.exit(1);
  }
}
__name(handleLink, "handleLink");
var linkCommand = {
  command: "link <path>",
  describe: t4(
    "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: t4("The name of the extension to link."),
    type: "string"
  }).check((_2) => 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 access7, cp as cp2, mkdir as mkdir7, readdir as readdir9, writeFile as writeFile9 } from "node:fs/promises";
import { join as join36, dirname as dirname22, basename as basename19 } from "node:path";
import { fileURLToPath as fileURLToPath10 } from "node:url";
var __filename3 = fileURLToPath10(import.meta.url);
var __dirname5 = dirname22(__filename3);
var EXAMPLES_PATH = join36(__dirname5, "examples");
async function pathExists(path125) {
  try {
    await access7(path125);
    return true;
  } catch (_e2) {
    return false;
  }
}
__name(pathExists, "pathExists");
async function createDirectory(path125) {
  if (await pathExists(path125)) {
    throw new Error(`Path already exists: ${path125}`);
  }
  await mkdir7(path125, { recursive: true });
}
__name(createDirectory, "createDirectory");
async function copyDirectory2(template, path125) {
  await createDirectory(path125);
  const examplePath = join36(EXAMPLES_PATH, template);
  const entries = await readdir9(examplePath, { withFileTypes: true });
  for (const entry of entries) {
    const srcPath = join36(examplePath, entry.name);
    const destPath = join36(path125, entry.name);
    await cp2(srcPath, destPath, { recursive: true });
  }
}
__name(copyDirectory2, "copyDirectory");
async function handleNew(args) {
  try {
    if (args.template) {
      await copyDirectory2(args.template, args.path);
      writeStdoutLine(
        `Successfully created new extension from template "${args.template}" at ${args.path}.`
      );
    } else {
      await createDirectory(args.path);
      const extensionName = basename19(args.path);
      const manifest = {
        name: extensionName,
        version: "1.0.0"
      };
      await writeFile9(
        join36(args.path, "qwen-extension.json"),
        JSON.stringify(manifest, null, 2)
      );
      writeStdoutLine(`Successfully created new extension at ${args.path}.`);
    }
    writeStdoutLine(
      `You can install this using "qwen extensions link ${args.path}" to test it out.`
    );
  } catch (error2) {
    writeStderrLine(getErrorMessage3(error2));
    throw error2;
  }
}
__name(handleNew, "handleNew");
async function getBoilerplateChoices() {
  const entries = await readdir9(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/settings.ts
init_esbuild_shims();
var setCommand = {
  command: "set [--scope] <name> <setting>",
  describe: t4("Set a specific setting for an extension."),
  builder: /* @__PURE__ */ __name((yargs) => yargs.positional("name", {
    describe: t4("Name of the extension to configure."),
    type: "string",
    demandOption: true
  }).positional("setting", {
    describe: t4("The setting to configure (name or env var)."),
    type: "string",
    demandOption: true
  }).option("scope", {
    describe: t4("The scope to set the setting in."),
    type: "string",
    choices: ["user", "workspace"],
    default: "user"
  }), "builder"),
  handler: /* @__PURE__ */ __name(async (args) => {
    const { name: name3, setting, scope } = args;
    const extensionManager = await getExtensionManager();
    if (!extensionManager) return;
    const extensions = extensionManager.getLoadedExtensions();
    if (!extensions || extensions.length === 0) return;
    const extension = extensions.find((e4) => e4.name === name3);
    if (!extension) {
      writeStdoutLine(t4('Extension "{{name}}" not found.', { name: name3 }));
      return;
    }
    await updateSetting(
      extension.config,
      extension.id,
      setting,
      promptForSetting,
      scope
    );
  }, "handler")
};
var listCommand2 = {
  command: "list <name>",
  describe: t4("List all settings for an extension."),
  builder: /* @__PURE__ */ __name((yargs) => yargs.positional("name", {
    describe: t4("Name of the extension."),
    type: "string",
    demandOption: true
  }), "builder"),
  handler: /* @__PURE__ */ __name(async (args) => {
    const { name: name3 } = args;
    const extensionManager = await getExtensionManager();
    if (!extensionManager) return;
    const extensions = extensionManager.getLoadedExtensions();
    if (!extensions || extensions.length === 0) return;
    const extension = extensions.find((e4) => e4.name === name3);
    if (!extension) {
      writeStdoutLine(t4('Extension "{{name}}" not found.', { name: name3 }));
      return;
    }
    if (!extension || !extension.settings || extension.settings.length === 0) {
      writeStdoutLine(
        t4('Extension "{{name}}" has no settings to configure.', { name: name3 })
      );
      return;
    }
    const userSettings = await getScopedEnvContents(
      extension.config,
      extension.id,
      ExtensionSettingScope.USER
    );
    const workspaceSettings = await getScopedEnvContents(
      extension.config,
      extension.id,
      ExtensionSettingScope.WORKSPACE
    );
    const mergedSettings = { ...userSettings, ...workspaceSettings };
    writeStdoutLine(t4('Settings for "{{name}}":', { name: name3 }));
    for (const setting of extension.settings) {
      const value = mergedSettings[setting.envVar];
      let displayValue;
      let scopeInfo = "";
      if (workspaceSettings[setting.envVar] !== void 0) {
        scopeInfo = " " + t4("(workspace)");
      } else if (userSettings[setting.envVar] !== void 0) {
        scopeInfo = " " + t4("(user)");
      }
      if (value === void 0) {
        displayValue = t4("[not set]");
      } else if (setting.sensitive) {
        displayValue = t4("[value stored in keychain]");
      } else {
        displayValue = value;
      }
      writeStdoutLine(`
- ${setting.name} (${setting.envVar})`);
      writeStdoutLine(`  ${t4("Description:")} ${setting.description}`);
      writeStdoutLine(`  ${t4("Value:")} ${displayValue}${scopeInfo}`);
    }
  }, "handler")
};
var settingsCommand = {
  command: "settings <command>",
  describe: t4("Manage extension settings."),
  builder: /* @__PURE__ */ __name((yargs) => yargs.command(setCommand).command(listCommand2).demandCommand(1, t4("You need to specify a command (set or list).")).version(false), "builder"),
  handler: /* @__PURE__ */ __name(() => {
  }, "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).command(settingsCommand).demandCommand(1, "You need at least one command before continuing.").version(false), "builder"),
  handler: /* @__PURE__ */ __name(() => {
  }, "handler")
};

// packages/cli/src/utils/modelConfigUtils.ts
init_esbuild_shims();
function getAuthTypeFromEnv() {
  if (process.env["QWEN_OAUTH"]) {
    return AuthType2.QWEN_OAUTH;
  }
  if (process.env["OPENAI_API_KEY"] && process.env["OPENAI_MODEL"] && process.env["OPENAI_BASE_URL"]) {
    return AuthType2.USE_OPENAI;
  }
  if (process.env["GEMINI_API_KEY"] && process.env["GEMINI_MODEL"]) {
    return AuthType2.USE_GEMINI;
  }
  if (process.env["GOOGLE_API_KEY"] && process.env["GOOGLE_MODEL"]) {
    return AuthType2.USE_VERTEX_AI;
  }
  if (process.env["ANTHROPIC_API_KEY"] && process.env["ANTHROPIC_MODEL"] && process.env["ANTHROPIC_BASE_URL"]) {
    return AuthType2.USE_ANTHROPIC;
  }
  return void 0;
}
__name(getAuthTypeFromEnv, "getAuthTypeFromEnv");
function resolveCliGenerationConfig(inputs) {
  const { argv, settings, selectedAuthType } = inputs;
  const env7 = inputs.env ?? process.env;
  const authType = selectedAuthType;
  let modelProvider;
  if (authType && settings.modelProviders) {
    const providers = settings.modelProviders[authType];
    if (providers && Array.isArray(providers)) {
      const requestedModel = argv.model || settings.model?.name;
      if (requestedModel) {
        modelProvider = providers.find((p2) => p2.id === requestedModel);
      }
    }
  }
  const configSources = {
    authType,
    cli: {
      model: argv.model,
      apiKey: argv.openaiApiKey,
      baseUrl: argv.openaiBaseUrl
    },
    settings: {
      model: settings.model?.name,
      apiKey: settings.security?.auth?.apiKey,
      baseUrl: settings.security?.auth?.baseUrl,
      generationConfig: settings.model?.generationConfig
    },
    modelProvider,
    env: env7
  };
  const resolved = resolveModelConfig(configSources);
  const enableOpenAILogging = (typeof argv.openaiLogging === "undefined" ? settings.model?.enableOpenAILogging : argv.openaiLogging) ?? false;
  const openAILoggingDir = argv.openaiLoggingDir || settings.model?.openAILoggingDir;
  const generationConfig = {
    ...resolved.config,
    enableOpenAILogging,
    openAILoggingDir
  };
  return {
    model: resolved.config.model || "",
    apiKey: resolved.config.apiKey || "",
    baseUrl: resolved.config.baseUrl || "",
    generationConfig,
    sources: resolved.sources,
    warnings: resolved.warnings
  };
}
__name(resolveCliGenerationConfig, "resolveCliGenerationConfig");

// node_modules/yargs/helpers/helpers.mjs
init_esbuild_shims();

// packages/cli/src/config/config.ts
import * as fs81 from "node:fs";
import * as path88 from "node:path";
import { homedir as homedir19 } from "node:os";

// packages/cli/src/utils/resolvePath.ts
init_esbuild_shims();
import * as os26 from "node:os";
import * as path83 from "node:path";
function resolvePath2(p2) {
  if (!p2) {
    return "";
  }
  let expandedPath = p2;
  if (p2.toLowerCase().startsWith("%userprofile%")) {
    expandedPath = os26.homedir() + p2.substring("%userprofile%".length);
  } else if (p2 === "~" || p2.startsWith("~/")) {
    expandedPath = os26.homedir() + p2.substring(1);
  }
  return path83.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 path86 from "node:path";

// node_modules/find-up-simple/index.js
init_esbuild_shims();
import process28 from "node:process";
import fsPromises3 from "node:fs/promises";
import { fileURLToPath as fileURLToPath11 } from "node:url";
import path84 from "node:path";
var toPath = /* @__PURE__ */ __name((urlOrPath) => urlOrPath instanceof URL ? fileURLToPath11(urlOrPath) : urlOrPath, "toPath");
async function findUp(name3, {
  cwd: cwd7 = process28.cwd(),
  type = "file",
  stopAt
} = {}) {
  let directory = path84.resolve(toPath(cwd7) ?? "");
  const { root } = path84.parse(directory);
  stopAt = path84.resolve(directory, toPath(stopAt ?? root));
  const isAbsoluteName = path84.isAbsolute(name3);
  while (directory) {
    const filePath = isAbsoluteName ? name3 : path84.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 = path84.dirname(directory);
  }
}
__name(findUp, "findUp");

// node_modules/read-pkg/index.js
init_esbuild_shims();
import fsPromises4 from "node:fs/promises";
import path85 from "node:path";

// node_modules/parse-json/index.js
init_esbuild_shims();
var import_code_frame = __toESM(require_lib6(), 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((string4, 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(string4, 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>/,
  (_2, _quote, token2) => `"${token2}"(${getCodePoint2(token2)})`
), "addCodePointToUnexpectedToken");
function parseJson(string4, reviver, fileName) {
  if (typeof reviver === "string") {
    fileName = reviver;
    reviver = void 0;
  }
  try {
    return JSON.parse(string4, reviver);
  } catch (error2) {
    throw new JSONError({
      jsonParseError: error2,
      fileName,
      input: string4
    });
  }
}
__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 fileURLToPath12 } from "node:url";
function toPath2(urlOrPath) {
  return urlOrPath instanceof URL ? fileURLToPath12(urlOrPath) : urlOrPath;
}
__name(toPath2, "toPath");

// node_modules/read-pkg/index.js
var getPackagePath = /* @__PURE__ */ __name((cwd7) => path85.resolve(toPath2(cwd7) ?? ".", "package.json"), "getPackagePath");
var _readPackage = /* @__PURE__ */ __name((file, normalize12) => {
  const json2 = typeof file === "string" ? parseJson(file) : file;
  if (normalize12) {
    (0, import_normalize_package_data.default)(json2);
  }
  return json2;
}, "_readPackage");
async function readPackage({ cwd: cwd7, normalize: normalize12 = true } = {}) {
  const packageFile = await fsPromises4.readFile(getPackagePath(cwd7), "utf8");
  return _readPackage(packageFile, normalize12);
}
__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: path86.dirname(filePath) }),
    path: filePath
  };
}
__name(readPackageUp, "readPackageUp");

// packages/cli/src/utils/package.ts
import { fileURLToPath as fileURLToPath13 } from "node:url";
import path87 from "node:path";
var __filename4 = fileURLToPath13(import.meta.url);
var __dirname6 = path87.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.11.0";
}
__name(getCliVersion, "getCliVersion");

// packages/cli/src/config/sandboxConfig.ts
init_esbuild_shims();
var import_command_exists = __toESM(require_command_exists2(), 1);
import * as os27 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 (os27.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/utils/events.ts
init_esbuild_shims();
import { EventEmitter as EventEmitter9 } from "node:events";
var appEvents = new EventEmitter9();

// 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) {
    writeStderrLine(
      "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) {
    writeStdoutLine(
      `MCP server "${name3}" is already configured within ${scope} settings.`
    );
  }
  mcpServers[name3] = newServer;
  settings.setValue(settingsScope, "mcpServers", mcpServers);
  if (isExistingServer) {
    writeStdoutLine(`MCP server "${name3}" updated in ${scope} settings.`);
  } else {
    writeStdoutLine(
      `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: qwen 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: "user",
    choices: ["user", "project"]
  }).option("transport", {
    alias: "t",
    describe: "Transport type (stdio, sse, http). Auto-detected from URL if not specified.",
    type: "string",
    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["--"]];
    }
    if (!argv["transport"]) {
      const commandOrUrl = argv["commandOrUrl"];
      if (commandOrUrl && (commandOrUrl.startsWith("http://") || commandOrUrl.startsWith("https://"))) {
        argv["transport"] = "http";
      } else {
        argv["transport"] = "stdio";
      }
    }
  }), "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]) {
    writeStdoutLine(`Server "${name3}" not found in ${scope} settings.`);
    return;
  }
  delete mcpServers[name3];
  settings.setValue(settingsScope, "mcpServers", mcpServers);
  try {
    const tokenStorage = new MCPOAuthTokenStorage();
    await tokenStorage.deleteCredentials(name3);
  } catch {
  }
  writeStdoutLine(`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: qwen 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: "user",
    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();

// packages/cli/node_modules/@modelcontextprotocol/sdk/dist/esm/client/index.js
init_esbuild_shims();

// packages/cli/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/protocol.js
init_esbuild_shims();

// packages/cli/node_modules/@modelcontextprotocol/sdk/dist/esm/server/zod-compat.js
init_esbuild_shims();
init_v4_mini();
function isZ4Schema2(s5) {
  const schema = s5;
  return !!schema._zod;
}
__name(isZ4Schema2, "isZ4Schema");
function safeParse4(schema, data) {
  if (isZ4Schema2(schema)) {
    const result2 = safeParse(schema, data);
    return result2;
  }
  const v3Schema = schema;
  const result = v3Schema.safeParse(data);
  return result;
}
__name(safeParse4, "safeParse");
function getObjectShape2(schema) {
  if (!schema)
    return void 0;
  let rawShape;
  if (isZ4Schema2(schema)) {
    const v4Schema = schema;
    rawShape = v4Schema._zod?.def?.shape;
  } else {
    const v3Schema = schema;
    rawShape = v3Schema.shape;
  }
  if (!rawShape)
    return void 0;
  if (typeof rawShape === "function") {
    try {
      return rawShape();
    } catch {
      return void 0;
    }
  }
  return rawShape;
}
__name(getObjectShape2, "getObjectShape");
function getLiteralValue2(schema) {
  if (isZ4Schema2(schema)) {
    const v4Schema = schema;
    const def3 = v4Schema._zod?.def;
    if (def3) {
      if (def3.value !== void 0)
        return def3.value;
      if (Array.isArray(def3.values) && def3.values.length > 0) {
        return def3.values[0];
      }
    }
  }
  const v3Schema = schema;
  const def2 = v3Schema._def;
  if (def2) {
    if (def2.value !== void 0)
      return def2.value;
    if (Array.isArray(def2.values) && def2.values.length > 0) {
      return def2.values[0];
    }
  }
  const directValue = schema.value;
  if (directValue !== void 0)
    return directValue;
  return void 0;
}
__name(getLiteralValue2, "getLiteralValue");

// packages/cli/node_modules/@modelcontextprotocol/sdk/dist/esm/types.js
init_esbuild_shims();
init_v42();
var LATEST_PROTOCOL_VERSION2 = "2025-11-25";
var SUPPORTED_PROTOCOL_VERSIONS2 = [LATEST_PROTOCOL_VERSION2, "2025-06-18", "2025-03-26", "2024-11-05", "2024-10-07"];
var RELATED_TASK_META_KEY2 = "io.modelcontextprotocol/related-task";
var JSONRPC_VERSION2 = "2.0";
var AssertObjectSchema2 = custom2((v2) => v2 !== null && (typeof v2 === "object" || typeof v2 === "function"));
var ProgressTokenSchema2 = union([string2(), number2().int()]);
var CursorSchema2 = string2();
var TaskCreationParamsSchema2 = looseObject({
  /**
   * Time in milliseconds to keep task results available after completion.
   * If null, the task has unlimited lifetime until manually cleaned up.
   */
  ttl: union([number2(), _null3()]).optional(),
  /**
   * Time in milliseconds to wait between task status requests.
   */
  pollInterval: number2().optional()
});
var TaskMetadataSchema2 = object2({
  ttl: number2().optional()
});
var RelatedTaskMetadataSchema2 = object2({
  taskId: string2()
});
var RequestMetaSchema2 = looseObject({
  /**
   * If specified, the caller is requesting out-of-band progress notifications for this request (as represented by notifications/progress). The value of this parameter is an opaque token that will be attached to any subsequent notifications. The receiver is not obligated to provide these notifications.
   */
  progressToken: ProgressTokenSchema2.optional(),
  /**
   * If specified, this request is related to the provided task.
   */
  [RELATED_TASK_META_KEY2]: RelatedTaskMetadataSchema2.optional()
});
var BaseRequestParamsSchema2 = object2({
  /**
   * See [General fields: `_meta`](/specification/draft/basic/index#meta) for notes on `_meta` usage.
   */
  _meta: RequestMetaSchema2.optional()
});
var TaskAugmentedRequestParamsSchema2 = BaseRequestParamsSchema2.extend({
  /**
   * If specified, the caller is requesting task-augmented execution for this request.
   * The request will return a CreateTaskResult immediately, and the actual result can be
   * retrieved later via tasks/result.
   *
   * Task augmentation is subject to capability negotiation - receivers MUST declare support
   * for task augmentation of specific request types in their capabilities.
   */
  task: TaskMetadataSchema2.optional()
});
var isTaskAugmentedRequestParams2 = /* @__PURE__ */ __name((value) => TaskAugmentedRequestParamsSchema2.safeParse(value).success, "isTaskAugmentedRequestParams");
var RequestSchema2 = object2({
  method: string2(),
  params: BaseRequestParamsSchema2.loose().optional()
});
var NotificationsParamsSchema2 = object2({
  /**
   * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)
   * for notes on _meta usage.
   */
  _meta: RequestMetaSchema2.optional()
});
var NotificationSchema2 = object2({
  method: string2(),
  params: NotificationsParamsSchema2.loose().optional()
});
var ResultSchema2 = looseObject({
  /**
   * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)
   * for notes on _meta usage.
   */
  _meta: RequestMetaSchema2.optional()
});
var RequestIdSchema2 = union([string2(), number2().int()]);
var JSONRPCRequestSchema2 = object2({
  jsonrpc: literal(JSONRPC_VERSION2),
  id: RequestIdSchema2,
  ...RequestSchema2.shape
}).strict();
var isJSONRPCRequest2 = /* @__PURE__ */ __name((value) => JSONRPCRequestSchema2.safeParse(value).success, "isJSONRPCRequest");
var JSONRPCNotificationSchema2 = object2({
  jsonrpc: literal(JSONRPC_VERSION2),
  ...NotificationSchema2.shape
}).strict();
var isJSONRPCNotification2 = /* @__PURE__ */ __name((value) => JSONRPCNotificationSchema2.safeParse(value).success, "isJSONRPCNotification");
var JSONRPCResultResponseSchema2 = object2({
  jsonrpc: literal(JSONRPC_VERSION2),
  id: RequestIdSchema2,
  result: ResultSchema2
}).strict();
var isJSONRPCResultResponse2 = /* @__PURE__ */ __name((value) => JSONRPCResultResponseSchema2.safeParse(value).success, "isJSONRPCResultResponse");
var ErrorCode2;
(function(ErrorCode3) {
  ErrorCode3[ErrorCode3["ConnectionClosed"] = -32e3] = "ConnectionClosed";
  ErrorCode3[ErrorCode3["RequestTimeout"] = -32001] = "RequestTimeout";
  ErrorCode3[ErrorCode3["ParseError"] = -32700] = "ParseError";
  ErrorCode3[ErrorCode3["InvalidRequest"] = -32600] = "InvalidRequest";
  ErrorCode3[ErrorCode3["MethodNotFound"] = -32601] = "MethodNotFound";
  ErrorCode3[ErrorCode3["InvalidParams"] = -32602] = "InvalidParams";
  ErrorCode3[ErrorCode3["InternalError"] = -32603] = "InternalError";
  ErrorCode3[ErrorCode3["UrlElicitationRequired"] = -32042] = "UrlElicitationRequired";
})(ErrorCode2 || (ErrorCode2 = {}));
var JSONRPCErrorResponseSchema2 = object2({
  jsonrpc: literal(JSONRPC_VERSION2),
  id: RequestIdSchema2.optional(),
  error: object2({
    /**
     * The error type that occurred.
     */
    code: number2().int(),
    /**
     * A short description of the error. The message SHOULD be limited to a concise single sentence.
     */
    message: string2(),
    /**
     * Additional information about the error. The value of this member is defined by the sender (e.g. detailed error information, nested errors etc.).
     */
    data: unknown().optional()
  })
}).strict();
var isJSONRPCErrorResponse2 = /* @__PURE__ */ __name((value) => JSONRPCErrorResponseSchema2.safeParse(value).success, "isJSONRPCErrorResponse");
var JSONRPCMessageSchema2 = union([
  JSONRPCRequestSchema2,
  JSONRPCNotificationSchema2,
  JSONRPCResultResponseSchema2,
  JSONRPCErrorResponseSchema2
]);
var JSONRPCResponseSchema2 = union([JSONRPCResultResponseSchema2, JSONRPCErrorResponseSchema2]);
var EmptyResultSchema2 = ResultSchema2.strict();
var CancelledNotificationParamsSchema2 = NotificationsParamsSchema2.extend({
  /**
   * The ID of the request to cancel.
   *
   * This MUST correspond to the ID of a request previously issued in the same direction.
   */
  requestId: RequestIdSchema2.optional(),
  /**
   * An optional string describing the reason for the cancellation. This MAY be logged or presented to the user.
   */
  reason: string2().optional()
});
var CancelledNotificationSchema2 = NotificationSchema2.extend({
  method: literal("notifications/cancelled"),
  params: CancelledNotificationParamsSchema2
});
var IconSchema2 = object2({
  /**
   * URL or data URI for the icon.
   */
  src: string2(),
  /**
   * Optional MIME type for the icon.
   */
  mimeType: string2().optional(),
  /**
   * Optional array of strings that specify sizes at which the icon can be used.
   * Each string should be in WxH format (e.g., `"48x48"`, `"96x96"`) or `"any"` for scalable formats like SVG.
   *
   * If not provided, the client should assume that the icon can be used at any size.
   */
  sizes: array(string2()).optional(),
  /**
   * Optional specifier for the theme this icon is designed for. `light` indicates
   * the icon is designed to be used with a light background, and `dark` indicates
   * the icon is designed to be used with a dark background.
   *
   * If not provided, the client should assume the icon can be used with any theme.
   */
  theme: _enum(["light", "dark"]).optional()
});
var IconsSchema2 = object2({
  /**
   * Optional set of sized icons that the client can display in a user interface.
   *
   * Clients that support rendering icons MUST support at least the following MIME types:
   * - `image/png` - PNG images (safe, universal compatibility)
   * - `image/jpeg` (and `image/jpg`) - JPEG images (safe, universal compatibility)
   *
   * Clients that support rendering icons SHOULD also support:
   * - `image/svg+xml` - SVG images (scalable but requires security precautions)
   * - `image/webp` - WebP images (modern, efficient format)
   */
  icons: array(IconSchema2).optional()
});
var BaseMetadataSchema2 = object2({
  /** Intended for programmatic or logical use, but used as a display name in past specs or fallback */
  name: string2(),
  /**
   * 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: string2().optional()
});
var ImplementationSchema2 = BaseMetadataSchema2.extend({
  ...BaseMetadataSchema2.shape,
  ...IconsSchema2.shape,
  version: string2(),
  /**
   * An optional URL of the website for this implementation.
   */
  websiteUrl: string2().optional(),
  /**
   * An optional human-readable description of what this implementation does.
   *
   * This can be used by clients or servers to provide context about their purpose
   * and capabilities. For example, a server might describe the types of resources
   * or tools it provides, while a client might describe its intended use case.
   */
  description: string2().optional()
});
var FormElicitationCapabilitySchema2 = intersection(object2({
  applyDefaults: boolean2().optional()
}), record(string2(), unknown()));
var ElicitationCapabilitySchema2 = preprocess((value) => {
  if (value && typeof value === "object" && !Array.isArray(value)) {
    if (Object.keys(value).length === 0) {
      return { form: {} };
    }
  }
  return value;
}, intersection(object2({
  form: FormElicitationCapabilitySchema2.optional(),
  url: AssertObjectSchema2.optional()
}), record(string2(), unknown()).optional()));
var ClientTasksCapabilitySchema2 = looseObject({
  /**
   * Present if the client supports listing tasks.
   */
  list: AssertObjectSchema2.optional(),
  /**
   * Present if the client supports cancelling tasks.
   */
  cancel: AssertObjectSchema2.optional(),
  /**
   * Capabilities for task creation on specific request types.
   */
  requests: looseObject({
    /**
     * Task support for sampling requests.
     */
    sampling: looseObject({
      createMessage: AssertObjectSchema2.optional()
    }).optional(),
    /**
     * Task support for elicitation requests.
     */
    elicitation: looseObject({
      create: AssertObjectSchema2.optional()
    }).optional()
  }).optional()
});
var ServerTasksCapabilitySchema2 = looseObject({
  /**
   * Present if the server supports listing tasks.
   */
  list: AssertObjectSchema2.optional(),
  /**
   * Present if the server supports cancelling tasks.
   */
  cancel: AssertObjectSchema2.optional(),
  /**
   * Capabilities for task creation on specific request types.
   */
  requests: looseObject({
    /**
     * Task support for tool requests.
     */
    tools: looseObject({
      call: AssertObjectSchema2.optional()
    }).optional()
  }).optional()
});
var ClientCapabilitiesSchema2 = object2({
  /**
   * Experimental, non-standard capabilities that the client supports.
   */
  experimental: record(string2(), AssertObjectSchema2).optional(),
  /**
   * Present if the client supports sampling from an LLM.
   */
  sampling: object2({
    /**
     * Present if the client supports context inclusion via includeContext parameter.
     * If not declared, servers SHOULD only use `includeContext: "none"` (or omit it).
     */
    context: AssertObjectSchema2.optional(),
    /**
     * Present if the client supports tool use via tools and toolChoice parameters.
     */
    tools: AssertObjectSchema2.optional()
  }).optional(),
  /**
   * Present if the client supports eliciting user input.
   */
  elicitation: ElicitationCapabilitySchema2.optional(),
  /**
   * Present if the client supports listing roots.
   */
  roots: object2({
    /**
     * Whether the client supports issuing notifications for changes to the roots list.
     */
    listChanged: boolean2().optional()
  }).optional(),
  /**
   * Present if the client supports task creation.
   */
  tasks: ClientTasksCapabilitySchema2.optional()
});
var InitializeRequestParamsSchema2 = BaseRequestParamsSchema2.extend({
  /**
   * The latest version of the Model Context Protocol that the client supports. The client MAY decide to support older versions as well.
   */
  protocolVersion: string2(),
  capabilities: ClientCapabilitiesSchema2,
  clientInfo: ImplementationSchema2
});
var InitializeRequestSchema2 = RequestSchema2.extend({
  method: literal("initialize"),
  params: InitializeRequestParamsSchema2
});
var ServerCapabilitiesSchema2 = object2({
  /**
   * Experimental, non-standard capabilities that the server supports.
   */
  experimental: record(string2(), AssertObjectSchema2).optional(),
  /**
   * Present if the server supports sending log messages to the client.
   */
  logging: AssertObjectSchema2.optional(),
  /**
   * Present if the server supports sending completions to the client.
   */
  completions: AssertObjectSchema2.optional(),
  /**
   * Present if the server offers any prompt templates.
   */
  prompts: object2({
    /**
     * Whether this server supports issuing notifications for changes to the prompt list.
     */
    listChanged: boolean2().optional()
  }).optional(),
  /**
   * Present if the server offers any resources to read.
   */
  resources: object2({
    /**
     * Whether this server supports clients subscribing to resource updates.
     */
    subscribe: boolean2().optional(),
    /**
     * Whether this server supports issuing notifications for changes to the resource list.
     */
    listChanged: boolean2().optional()
  }).optional(),
  /**
   * Present if the server offers any tools to call.
   */
  tools: object2({
    /**
     * Whether this server supports issuing notifications for changes to the tool list.
     */
    listChanged: boolean2().optional()
  }).optional(),
  /**
   * Present if the server supports task creation.
   */
  tasks: ServerTasksCapabilitySchema2.optional()
});
var InitializeResultSchema2 = ResultSchema2.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: string2(),
  capabilities: ServerCapabilitiesSchema2,
  serverInfo: ImplementationSchema2,
  /**
   * 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: string2().optional()
});
var InitializedNotificationSchema2 = NotificationSchema2.extend({
  method: literal("notifications/initialized"),
  params: NotificationsParamsSchema2.optional()
});
var PingRequestSchema2 = RequestSchema2.extend({
  method: literal("ping"),
  params: BaseRequestParamsSchema2.optional()
});
var ProgressSchema2 = object2({
  /**
   * The progress thus far. This should increase every time progress is made, even if the total is unknown.
   */
  progress: number2(),
  /**
   * Total number of items to process (or total progress required), if known.
   */
  total: optional(number2()),
  /**
   * An optional message describing the current progress.
   */
  message: optional(string2())
});
var ProgressNotificationParamsSchema2 = object2({
  ...NotificationsParamsSchema2.shape,
  ...ProgressSchema2.shape,
  /**
   * The progress token which was given in the initial request, used to associate this notification with the request that is proceeding.
   */
  progressToken: ProgressTokenSchema2
});
var ProgressNotificationSchema2 = NotificationSchema2.extend({
  method: literal("notifications/progress"),
  params: ProgressNotificationParamsSchema2
});
var PaginatedRequestParamsSchema2 = BaseRequestParamsSchema2.extend({
  /**
   * An opaque token representing the current pagination position.
   * If provided, the server should return results starting after this cursor.
   */
  cursor: CursorSchema2.optional()
});
var PaginatedRequestSchema2 = RequestSchema2.extend({
  params: PaginatedRequestParamsSchema2.optional()
});
var PaginatedResultSchema2 = ResultSchema2.extend({
  /**
   * An opaque token representing the pagination position after the last returned result.
   * If present, there may be more results available.
   */
  nextCursor: CursorSchema2.optional()
});
var TaskStatusSchema2 = _enum(["working", "input_required", "completed", "failed", "cancelled"]);
var TaskSchema2 = object2({
  taskId: string2(),
  status: TaskStatusSchema2,
  /**
   * Time in milliseconds to keep task results available after completion.
   * If null, the task has unlimited lifetime until manually cleaned up.
   */
  ttl: union([number2(), _null3()]),
  /**
   * ISO 8601 timestamp when the task was created.
   */
  createdAt: string2(),
  /**
   * ISO 8601 timestamp when the task was last updated.
   */
  lastUpdatedAt: string2(),
  pollInterval: optional(number2()),
  /**
   * Optional diagnostic message for failed tasks or other status information.
   */
  statusMessage: optional(string2())
});
var CreateTaskResultSchema2 = ResultSchema2.extend({
  task: TaskSchema2
});
var TaskStatusNotificationParamsSchema2 = NotificationsParamsSchema2.merge(TaskSchema2);
var TaskStatusNotificationSchema2 = NotificationSchema2.extend({
  method: literal("notifications/tasks/status"),
  params: TaskStatusNotificationParamsSchema2
});
var GetTaskRequestSchema2 = RequestSchema2.extend({
  method: literal("tasks/get"),
  params: BaseRequestParamsSchema2.extend({
    taskId: string2()
  })
});
var GetTaskResultSchema2 = ResultSchema2.merge(TaskSchema2);
var GetTaskPayloadRequestSchema2 = RequestSchema2.extend({
  method: literal("tasks/result"),
  params: BaseRequestParamsSchema2.extend({
    taskId: string2()
  })
});
var GetTaskPayloadResultSchema2 = ResultSchema2.loose();
var ListTasksRequestSchema2 = PaginatedRequestSchema2.extend({
  method: literal("tasks/list")
});
var ListTasksResultSchema2 = PaginatedResultSchema2.extend({
  tasks: array(TaskSchema2)
});
var CancelTaskRequestSchema2 = RequestSchema2.extend({
  method: literal("tasks/cancel"),
  params: BaseRequestParamsSchema2.extend({
    taskId: string2()
  })
});
var CancelTaskResultSchema2 = ResultSchema2.merge(TaskSchema2);
var ResourceContentsSchema2 = object2({
  /**
   * The URI of this resource.
   */
  uri: string2(),
  /**
   * The MIME type of this resource, if known.
   */
  mimeType: optional(string2()),
  /**
   * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)
   * for notes on _meta usage.
   */
  _meta: record(string2(), unknown()).optional()
});
var TextResourceContentsSchema2 = ResourceContentsSchema2.extend({
  /**
   * The text of the item. This must only be set if the item can actually be represented as text (not binary data).
   */
  text: string2()
});
var Base64Schema2 = string2().refine((val) => {
  try {
    atob(val);
    return true;
  } catch {
    return false;
  }
}, { message: "Invalid Base64 string" });
var BlobResourceContentsSchema2 = ResourceContentsSchema2.extend({
  /**
   * A base64-encoded string representing the binary data of the item.
   */
  blob: Base64Schema2
});
var RoleSchema2 = _enum(["user", "assistant"]);
var AnnotationsSchema2 = object2({
  /**
   * Intended audience(s) for the resource.
   */
  audience: array(RoleSchema2).optional(),
  /**
   * Importance hint for the resource, from 0 (least) to 1 (most).
   */
  priority: number2().min(0).max(1).optional(),
  /**
   * ISO 8601 timestamp for the most recent modification.
   */
  lastModified: iso_exports2.datetime({ offset: true }).optional()
});
var ResourceSchema2 = object2({
  ...BaseMetadataSchema2.shape,
  ...IconsSchema2.shape,
  /**
   * The URI of this resource.
   */
  uri: string2(),
  /**
   * A description of what this resource represents.
   *
   * This can be used by clients to improve the LLM's understanding of available resources. It can be thought of like a "hint" to the model.
   */
  description: optional(string2()),
  /**
   * The MIME type of this resource, if known.
   */
  mimeType: optional(string2()),
  /**
   * Optional annotations for the client.
   */
  annotations: AnnotationsSchema2.optional(),
  /**
   * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)
   * for notes on _meta usage.
   */
  _meta: optional(looseObject({}))
});
var ResourceTemplateSchema2 = object2({
  ...BaseMetadataSchema2.shape,
  ...IconsSchema2.shape,
  /**
   * A URI template (according to RFC 6570) that can be used to construct resource URIs.
   */
  uriTemplate: string2(),
  /**
   * A description of what this template is for.
   *
   * This can be used by clients to improve the LLM's understanding of available resources. It can be thought of like a "hint" to the model.
   */
  description: optional(string2()),
  /**
   * The MIME type for all resources that match this template. This should only be included if all resources matching this template have the same type.
   */
  mimeType: optional(string2()),
  /**
   * Optional annotations for the client.
   */
  annotations: AnnotationsSchema2.optional(),
  /**
   * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)
   * for notes on _meta usage.
   */
  _meta: optional(looseObject({}))
});
var ListResourcesRequestSchema2 = PaginatedRequestSchema2.extend({
  method: literal("resources/list")
});
var ListResourcesResultSchema2 = PaginatedResultSchema2.extend({
  resources: array(ResourceSchema2)
});
var ListResourceTemplatesRequestSchema2 = PaginatedRequestSchema2.extend({
  method: literal("resources/templates/list")
});
var ListResourceTemplatesResultSchema2 = PaginatedResultSchema2.extend({
  resourceTemplates: array(ResourceTemplateSchema2)
});
var ResourceRequestParamsSchema2 = BaseRequestParamsSchema2.extend({
  /**
   * The URI of the resource to read. The URI can use any protocol; it is up to the server how to interpret it.
   *
   * @format uri
   */
  uri: string2()
});
var ReadResourceRequestParamsSchema2 = ResourceRequestParamsSchema2;
var ReadResourceRequestSchema2 = RequestSchema2.extend({
  method: literal("resources/read"),
  params: ReadResourceRequestParamsSchema2
});
var ReadResourceResultSchema2 = ResultSchema2.extend({
  contents: array(union([TextResourceContentsSchema2, BlobResourceContentsSchema2]))
});
var ResourceListChangedNotificationSchema2 = NotificationSchema2.extend({
  method: literal("notifications/resources/list_changed"),
  params: NotificationsParamsSchema2.optional()
});
var SubscribeRequestParamsSchema2 = ResourceRequestParamsSchema2;
var SubscribeRequestSchema2 = RequestSchema2.extend({
  method: literal("resources/subscribe"),
  params: SubscribeRequestParamsSchema2
});
var UnsubscribeRequestParamsSchema2 = ResourceRequestParamsSchema2;
var UnsubscribeRequestSchema2 = RequestSchema2.extend({
  method: literal("resources/unsubscribe"),
  params: UnsubscribeRequestParamsSchema2
});
var ResourceUpdatedNotificationParamsSchema2 = NotificationsParamsSchema2.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: string2()
});
var ResourceUpdatedNotificationSchema2 = NotificationSchema2.extend({
  method: literal("notifications/resources/updated"),
  params: ResourceUpdatedNotificationParamsSchema2
});
var PromptArgumentSchema2 = object2({
  /**
   * The name of the argument.
   */
  name: string2(),
  /**
   * A human-readable description of the argument.
   */
  description: optional(string2()),
  /**
   * Whether this argument must be provided.
   */
  required: optional(boolean2())
});
var PromptSchema2 = object2({
  ...BaseMetadataSchema2.shape,
  ...IconsSchema2.shape,
  /**
   * An optional description of what this prompt provides
   */
  description: optional(string2()),
  /**
   * A list of arguments to use for templating the prompt.
   */
  arguments: optional(array(PromptArgumentSchema2)),
  /**
   * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)
   * for notes on _meta usage.
   */
  _meta: optional(looseObject({}))
});
var ListPromptsRequestSchema2 = PaginatedRequestSchema2.extend({
  method: literal("prompts/list")
});
var ListPromptsResultSchema2 = PaginatedResultSchema2.extend({
  prompts: array(PromptSchema2)
});
var GetPromptRequestParamsSchema2 = BaseRequestParamsSchema2.extend({
  /**
   * The name of the prompt or prompt template.
   */
  name: string2(),
  /**
   * Arguments to use for templating the prompt.
   */
  arguments: record(string2(), string2()).optional()
});
var GetPromptRequestSchema2 = RequestSchema2.extend({
  method: literal("prompts/get"),
  params: GetPromptRequestParamsSchema2
});
var TextContentSchema2 = object2({
  type: literal("text"),
  /**
   * The text content of the message.
   */
  text: string2(),
  /**
   * Optional annotations for the client.
   */
  annotations: AnnotationsSchema2.optional(),
  /**
   * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)
   * for notes on _meta usage.
   */
  _meta: record(string2(), unknown()).optional()
});
var ImageContentSchema2 = object2({
  type: literal("image"),
  /**
   * The base64-encoded image data.
   */
  data: Base64Schema2,
  /**
   * The MIME type of the image. Different providers may support different image types.
   */
  mimeType: string2(),
  /**
   * Optional annotations for the client.
   */
  annotations: AnnotationsSchema2.optional(),
  /**
   * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)
   * for notes on _meta usage.
   */
  _meta: record(string2(), unknown()).optional()
});
var AudioContentSchema2 = object2({
  type: literal("audio"),
  /**
   * The base64-encoded audio data.
   */
  data: Base64Schema2,
  /**
   * The MIME type of the audio. Different providers may support different audio types.
   */
  mimeType: string2(),
  /**
   * Optional annotations for the client.
   */
  annotations: AnnotationsSchema2.optional(),
  /**
   * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)
   * for notes on _meta usage.
   */
  _meta: record(string2(), unknown()).optional()
});
var ToolUseContentSchema2 = object2({
  type: literal("tool_use"),
  /**
   * The name of the tool to invoke.
   * Must match a tool name from the request's tools array.
   */
  name: string2(),
  /**
   * Unique identifier for this tool call.
   * Used to correlate with ToolResultContent in subsequent messages.
   */
  id: string2(),
  /**
   * Arguments to pass to the tool.
   * Must conform to the tool's inputSchema.
   */
  input: record(string2(), unknown()),
  /**
   * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)
   * for notes on _meta usage.
   */
  _meta: record(string2(), unknown()).optional()
});
var EmbeddedResourceSchema2 = object2({
  type: literal("resource"),
  resource: union([TextResourceContentsSchema2, BlobResourceContentsSchema2]),
  /**
   * Optional annotations for the client.
   */
  annotations: AnnotationsSchema2.optional(),
  /**
   * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)
   * for notes on _meta usage.
   */
  _meta: record(string2(), unknown()).optional()
});
var ResourceLinkSchema2 = ResourceSchema2.extend({
  type: literal("resource_link")
});
var ContentBlockSchema2 = union([
  TextContentSchema2,
  ImageContentSchema2,
  AudioContentSchema2,
  ResourceLinkSchema2,
  EmbeddedResourceSchema2
]);
var PromptMessageSchema2 = object2({
  role: RoleSchema2,
  content: ContentBlockSchema2
});
var GetPromptResultSchema2 = ResultSchema2.extend({
  /**
   * An optional description for the prompt.
   */
  description: string2().optional(),
  messages: array(PromptMessageSchema2)
});
var PromptListChangedNotificationSchema2 = NotificationSchema2.extend({
  method: literal("notifications/prompts/list_changed"),
  params: NotificationsParamsSchema2.optional()
});
var ToolAnnotationsSchema2 = object2({
  /**
   * A human-readable title for the tool.
   */
  title: string2().optional(),
  /**
   * If true, the tool does not modify its environment.
   *
   * Default: false
   */
  readOnlyHint: boolean2().optional(),
  /**
   * If true, the tool may perform destructive updates to its environment.
   * If false, the tool performs only additive updates.
   *
   * (This property is meaningful only when `readOnlyHint == false`)
   *
   * Default: true
   */
  destructiveHint: boolean2().optional(),
  /**
   * If true, calling the tool repeatedly with the same arguments
   * will have no additional effect on the its environment.
   *
   * (This property is meaningful only when `readOnlyHint == false`)
   *
   * Default: false
   */
  idempotentHint: boolean2().optional(),
  /**
   * If true, this tool may interact with an "open world" of external
   * entities. If false, the tool's domain of interaction is closed.
   * For example, the world of a web search tool is open, whereas that
   * of a memory tool is not.
   *
   * Default: true
   */
  openWorldHint: boolean2().optional()
});
var ToolExecutionSchema2 = object2({
  /**
   * Indicates the tool's preference for task-augmented execution.
   * - "required": Clients MUST invoke the tool as a task
   * - "optional": Clients MAY invoke the tool as a task or normal request
   * - "forbidden": Clients MUST NOT attempt to invoke the tool as a task
   *
   * If not present, defaults to "forbidden".
   */
  taskSupport: _enum(["required", "optional", "forbidden"]).optional()
});
var ToolSchema2 = object2({
  ...BaseMetadataSchema2.shape,
  ...IconsSchema2.shape,
  /**
   * A human-readable description of the tool.
   */
  description: string2().optional(),
  /**
   * A JSON Schema 2020-12 object defining the expected parameters for the tool.
   * Must have type: 'object' at the root level per MCP spec.
   */
  inputSchema: object2({
    type: literal("object"),
    properties: record(string2(), AssertObjectSchema2).optional(),
    required: array(string2()).optional()
  }).catchall(unknown()),
  /**
   * An optional JSON Schema 2020-12 object defining the structure of the tool's output
   * returned in the structuredContent field of a CallToolResult.
   * Must have type: 'object' at the root level per MCP spec.
   */
  outputSchema: object2({
    type: literal("object"),
    properties: record(string2(), AssertObjectSchema2).optional(),
    required: array(string2()).optional()
  }).catchall(unknown()).optional(),
  /**
   * Optional additional tool information.
   */
  annotations: ToolAnnotationsSchema2.optional(),
  /**
   * Execution-related properties for this tool.
   */
  execution: ToolExecutionSchema2.optional(),
  /**
   * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)
   * for notes on _meta usage.
   */
  _meta: record(string2(), unknown()).optional()
});
var ListToolsRequestSchema2 = PaginatedRequestSchema2.extend({
  method: literal("tools/list")
});
var ListToolsResultSchema2 = PaginatedResultSchema2.extend({
  tools: array(ToolSchema2)
});
var CallToolResultSchema2 = ResultSchema2.extend({
  /**
   * A list of content objects that represent the result of the tool call.
   *
   * If the Tool does not define an outputSchema, this field MUST be present in the result.
   * For backwards compatibility, this field is always present, but it may be empty.
   */
  content: array(ContentBlockSchema2).default([]),
  /**
   * An object containing structured tool output.
   *
   * If the Tool defines an outputSchema, this field MUST be present in the result, and contain a JSON object that matches the schema.
   */
  structuredContent: record(string2(), unknown()).optional(),
  /**
   * Whether the tool call ended in an error.
   *
   * If not set, this is assumed to be false (the call was successful).
   *
   * Any errors that originate from the tool SHOULD be reported inside the result
   * object, with `isError` set to true, _not_ as an MCP protocol-level error
   * response. Otherwise, the LLM would not be able to see that an error occurred
   * and self-correct.
   *
   * However, any errors in _finding_ the tool, an error indicating that the
   * server does not support tool calls, or any other exceptional conditions,
   * should be reported as an MCP error response.
   */
  isError: boolean2().optional()
});
var CompatibilityCallToolResultSchema2 = CallToolResultSchema2.or(ResultSchema2.extend({
  toolResult: unknown()
}));
var CallToolRequestParamsSchema2 = TaskAugmentedRequestParamsSchema2.extend({
  /**
   * The name of the tool to call.
   */
  name: string2(),
  /**
   * Arguments to pass to the tool.
   */
  arguments: record(string2(), unknown()).optional()
});
var CallToolRequestSchema2 = RequestSchema2.extend({
  method: literal("tools/call"),
  params: CallToolRequestParamsSchema2
});
var ToolListChangedNotificationSchema2 = NotificationSchema2.extend({
  method: literal("notifications/tools/list_changed"),
  params: NotificationsParamsSchema2.optional()
});
var ListChangedOptionsBaseSchema2 = object2({
  /**
   * If true, the list will be refreshed automatically when a list changed notification is received.
   * The callback will be called with the updated list.
   *
   * If false, the callback will be called with null items, allowing manual refresh.
   *
   * @default true
   */
  autoRefresh: boolean2().default(true),
  /**
   * Debounce time in milliseconds for list changed notification processing.
   *
   * Multiple notifications received within this timeframe will only trigger one refresh.
   * Set to 0 to disable debouncing.
   *
   * @default 300
   */
  debounceMs: number2().int().nonnegative().default(300)
});
var LoggingLevelSchema2 = _enum(["debug", "info", "notice", "warning", "error", "critical", "alert", "emergency"]);
var SetLevelRequestParamsSchema2 = BaseRequestParamsSchema2.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: LoggingLevelSchema2
});
var SetLevelRequestSchema2 = RequestSchema2.extend({
  method: literal("logging/setLevel"),
  params: SetLevelRequestParamsSchema2
});
var LoggingMessageNotificationParamsSchema2 = NotificationsParamsSchema2.extend({
  /**
   * The severity of this log message.
   */
  level: LoggingLevelSchema2,
  /**
   * An optional name of the logger issuing this message.
   */
  logger: string2().optional(),
  /**
   * The data to be logged, such as a string message or an object. Any JSON serializable type is allowed here.
   */
  data: unknown()
});
var LoggingMessageNotificationSchema2 = NotificationSchema2.extend({
  method: literal("notifications/message"),
  params: LoggingMessageNotificationParamsSchema2
});
var ModelHintSchema2 = object2({
  /**
   * A hint for a model name.
   */
  name: string2().optional()
});
var ModelPreferencesSchema2 = object2({
  /**
   * Optional hints to use for model selection.
   */
  hints: array(ModelHintSchema2).optional(),
  /**
   * How much to prioritize cost when selecting a model.
   */
  costPriority: number2().min(0).max(1).optional(),
  /**
   * How much to prioritize sampling speed (latency) when selecting a model.
   */
  speedPriority: number2().min(0).max(1).optional(),
  /**
   * How much to prioritize intelligence and capabilities when selecting a model.
   */
  intelligencePriority: number2().min(0).max(1).optional()
});
var ToolChoiceSchema2 = object2({
  /**
   * Controls when tools are used:
   * - "auto": Model decides whether to use tools (default)
   * - "required": Model MUST use at least one tool before completing
   * - "none": Model MUST NOT use any tools
   */
  mode: _enum(["auto", "required", "none"]).optional()
});
var ToolResultContentSchema2 = object2({
  type: literal("tool_result"),
  toolUseId: string2().describe("The unique identifier for the corresponding tool call."),
  content: array(ContentBlockSchema2).default([]),
  structuredContent: object2({}).loose().optional(),
  isError: boolean2().optional(),
  /**
   * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)
   * for notes on _meta usage.
   */
  _meta: record(string2(), unknown()).optional()
});
var SamplingContentSchema2 = discriminatedUnion("type", [TextContentSchema2, ImageContentSchema2, AudioContentSchema2]);
var SamplingMessageContentBlockSchema2 = discriminatedUnion("type", [
  TextContentSchema2,
  ImageContentSchema2,
  AudioContentSchema2,
  ToolUseContentSchema2,
  ToolResultContentSchema2
]);
var SamplingMessageSchema2 = object2({
  role: RoleSchema2,
  content: union([SamplingMessageContentBlockSchema2, array(SamplingMessageContentBlockSchema2)]),
  /**
   * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)
   * for notes on _meta usage.
   */
  _meta: record(string2(), unknown()).optional()
});
var CreateMessageRequestParamsSchema2 = TaskAugmentedRequestParamsSchema2.extend({
  messages: array(SamplingMessageSchema2),
  /**
   * The server's preferences for which model to select. The client MAY modify or omit this request.
   */
  modelPreferences: ModelPreferencesSchema2.optional(),
  /**
   * An optional system prompt the server wants to use for sampling. The client MAY modify or omit this prompt.
   */
  systemPrompt: string2().optional(),
  /**
   * A request to include context from one or more MCP servers (including the caller), to be attached to the prompt.
   * The client MAY ignore this request.
   *
   * Default is "none". Values "thisServer" and "allServers" are soft-deprecated. Servers SHOULD only use these values if the client
   * declares ClientCapabilities.sampling.context. These values may be removed in future spec releases.
   */
  includeContext: _enum(["none", "thisServer", "allServers"]).optional(),
  temperature: number2().optional(),
  /**
   * The requested maximum number of tokens to sample (to prevent runaway completions).
   *
   * The client MAY choose to sample fewer tokens than the requested maximum.
   */
  maxTokens: number2().int(),
  stopSequences: array(string2()).optional(),
  /**
   * Optional metadata to pass through to the LLM provider. The format of this metadata is provider-specific.
   */
  metadata: AssertObjectSchema2.optional(),
  /**
   * Tools that the model may use during generation.
   * The client MUST return an error if this field is provided but ClientCapabilities.sampling.tools is not declared.
   */
  tools: array(ToolSchema2).optional(),
  /**
   * Controls how the model uses tools.
   * The client MUST return an error if this field is provided but ClientCapabilities.sampling.tools is not declared.
   * Default is `{ mode: "auto" }`.
   */
  toolChoice: ToolChoiceSchema2.optional()
});
var CreateMessageRequestSchema2 = RequestSchema2.extend({
  method: literal("sampling/createMessage"),
  params: CreateMessageRequestParamsSchema2
});
var CreateMessageResultSchema2 = ResultSchema2.extend({
  /**
   * The name of the model that generated the message.
   */
  model: string2(),
  /**
   * The reason why sampling stopped, if known.
   *
   * Standard values:
   * - "endTurn": Natural end of the assistant's turn
   * - "stopSequence": A stop sequence was encountered
   * - "maxTokens": Maximum token limit was reached
   *
   * This field is an open string to allow for provider-specific stop reasons.
   */
  stopReason: optional(_enum(["endTurn", "stopSequence", "maxTokens"]).or(string2())),
  role: RoleSchema2,
  /**
   * Response content. Single content block (text, image, or audio).
   */
  content: SamplingContentSchema2
});
var CreateMessageResultWithToolsSchema2 = ResultSchema2.extend({
  /**
   * The name of the model that generated the message.
   */
  model: string2(),
  /**
   * The reason why sampling stopped, if known.
   *
   * Standard values:
   * - "endTurn": Natural end of the assistant's turn
   * - "stopSequence": A stop sequence was encountered
   * - "maxTokens": Maximum token limit was reached
   * - "toolUse": The model wants to use one or more tools
   *
   * This field is an open string to allow for provider-specific stop reasons.
   */
  stopReason: optional(_enum(["endTurn", "stopSequence", "maxTokens", "toolUse"]).or(string2())),
  role: RoleSchema2,
  /**
   * Response content. May be a single block or array. May include ToolUseContent if stopReason is "toolUse".
   */
  content: union([SamplingMessageContentBlockSchema2, array(SamplingMessageContentBlockSchema2)])
});
var BooleanSchemaSchema2 = object2({
  type: literal("boolean"),
  title: string2().optional(),
  description: string2().optional(),
  default: boolean2().optional()
});
var StringSchemaSchema2 = object2({
  type: literal("string"),
  title: string2().optional(),
  description: string2().optional(),
  minLength: number2().optional(),
  maxLength: number2().optional(),
  format: _enum(["email", "uri", "date", "date-time"]).optional(),
  default: string2().optional()
});
var NumberSchemaSchema2 = object2({
  type: _enum(["number", "integer"]),
  title: string2().optional(),
  description: string2().optional(),
  minimum: number2().optional(),
  maximum: number2().optional(),
  default: number2().optional()
});
var UntitledSingleSelectEnumSchemaSchema2 = object2({
  type: literal("string"),
  title: string2().optional(),
  description: string2().optional(),
  enum: array(string2()),
  default: string2().optional()
});
var TitledSingleSelectEnumSchemaSchema2 = object2({
  type: literal("string"),
  title: string2().optional(),
  description: string2().optional(),
  oneOf: array(object2({
    const: string2(),
    title: string2()
  })),
  default: string2().optional()
});
var LegacyTitledEnumSchemaSchema2 = object2({
  type: literal("string"),
  title: string2().optional(),
  description: string2().optional(),
  enum: array(string2()),
  enumNames: array(string2()).optional(),
  default: string2().optional()
});
var SingleSelectEnumSchemaSchema2 = union([UntitledSingleSelectEnumSchemaSchema2, TitledSingleSelectEnumSchemaSchema2]);
var UntitledMultiSelectEnumSchemaSchema2 = object2({
  type: literal("array"),
  title: string2().optional(),
  description: string2().optional(),
  minItems: number2().optional(),
  maxItems: number2().optional(),
  items: object2({
    type: literal("string"),
    enum: array(string2())
  }),
  default: array(string2()).optional()
});
var TitledMultiSelectEnumSchemaSchema2 = object2({
  type: literal("array"),
  title: string2().optional(),
  description: string2().optional(),
  minItems: number2().optional(),
  maxItems: number2().optional(),
  items: object2({
    anyOf: array(object2({
      const: string2(),
      title: string2()
    }))
  }),
  default: array(string2()).optional()
});
var MultiSelectEnumSchemaSchema2 = union([UntitledMultiSelectEnumSchemaSchema2, TitledMultiSelectEnumSchemaSchema2]);
var EnumSchemaSchema2 = union([LegacyTitledEnumSchemaSchema2, SingleSelectEnumSchemaSchema2, MultiSelectEnumSchemaSchema2]);
var PrimitiveSchemaDefinitionSchema2 = union([EnumSchemaSchema2, BooleanSchemaSchema2, StringSchemaSchema2, NumberSchemaSchema2]);
var ElicitRequestFormParamsSchema2 = TaskAugmentedRequestParamsSchema2.extend({
  /**
   * The elicitation mode.
   *
   * Optional for backward compatibility. Clients MUST treat missing mode as "form".
   */
  mode: literal("form").optional(),
  /**
   * The message to present to the user describing what information is being requested.
   */
  message: string2(),
  /**
   * A restricted subset of JSON Schema.
   * Only top-level properties are allowed, without nesting.
   */
  requestedSchema: object2({
    type: literal("object"),
    properties: record(string2(), PrimitiveSchemaDefinitionSchema2),
    required: array(string2()).optional()
  })
});
var ElicitRequestURLParamsSchema2 = TaskAugmentedRequestParamsSchema2.extend({
  /**
   * The elicitation mode.
   */
  mode: literal("url"),
  /**
   * The message to present to the user explaining why the interaction is needed.
   */
  message: string2(),
  /**
   * The ID of the elicitation, which must be unique within the context of the server.
   * The client MUST treat this ID as an opaque value.
   */
  elicitationId: string2(),
  /**
   * The URL that the user should navigate to.
   */
  url: string2().url()
});
var ElicitRequestParamsSchema2 = union([ElicitRequestFormParamsSchema2, ElicitRequestURLParamsSchema2]);
var ElicitRequestSchema2 = RequestSchema2.extend({
  method: literal("elicitation/create"),
  params: ElicitRequestParamsSchema2
});
var ElicitationCompleteNotificationParamsSchema2 = NotificationsParamsSchema2.extend({
  /**
   * The ID of the elicitation that completed.
   */
  elicitationId: string2()
});
var ElicitationCompleteNotificationSchema2 = NotificationSchema2.extend({
  method: literal("notifications/elicitation/complete"),
  params: ElicitationCompleteNotificationParamsSchema2
});
var ElicitResultSchema2 = ResultSchema2.extend({
  /**
   * The user action in response to the elicitation.
   * - "accept": User submitted the form/confirmed the action
   * - "decline": User explicitly decline the action
   * - "cancel": User dismissed without making an explicit choice
   */
  action: _enum(["accept", "decline", "cancel"]),
  /**
   * The submitted form data, only present when action is "accept".
   * Contains values matching the requested schema.
   * Per MCP spec, content is "typically omitted" for decline/cancel actions.
   * We normalize null to undefined for leniency while maintaining type compatibility.
   */
  content: preprocess((val) => val === null ? void 0 : val, record(string2(), union([string2(), number2(), boolean2(), array(string2())])).optional())
});
var ResourceTemplateReferenceSchema2 = object2({
  type: literal("ref/resource"),
  /**
   * The URI or URI template of the resource.
   */
  uri: string2()
});
var PromptReferenceSchema2 = object2({
  type: literal("ref/prompt"),
  /**
   * The name of the prompt or prompt template
   */
  name: string2()
});
var CompleteRequestParamsSchema2 = BaseRequestParamsSchema2.extend({
  ref: union([PromptReferenceSchema2, ResourceTemplateReferenceSchema2]),
  /**
   * The argument's information
   */
  argument: object2({
    /**
     * The name of the argument
     */
    name: string2(),
    /**
     * The value of the argument to use for completion matching.
     */
    value: string2()
  }),
  context: object2({
    /**
     * Previously-resolved variables in a URI template or prompt.
     */
    arguments: record(string2(), string2()).optional()
  }).optional()
});
var CompleteRequestSchema2 = RequestSchema2.extend({
  method: literal("completion/complete"),
  params: CompleteRequestParamsSchema2
});
var CompleteResultSchema2 = ResultSchema2.extend({
  completion: looseObject({
    /**
     * An array of completion values. Must not exceed 100 items.
     */
    values: array(string2()).max(100),
    /**
     * The total number of completion options available. This can exceed the number of values actually sent in the response.
     */
    total: optional(number2().int()),
    /**
     * Indicates whether there are additional completion options beyond those provided in the current response, even if the exact total is unknown.
     */
    hasMore: optional(boolean2())
  })
});
var RootSchema2 = object2({
  /**
   * The URI identifying the root. This *must* start with file:// for now.
   */
  uri: string2().startsWith("file://"),
  /**
   * An optional name for the root.
   */
  name: string2().optional(),
  /**
   * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)
   * for notes on _meta usage.
   */
  _meta: record(string2(), unknown()).optional()
});
var ListRootsRequestSchema2 = RequestSchema2.extend({
  method: literal("roots/list"),
  params: BaseRequestParamsSchema2.optional()
});
var ListRootsResultSchema2 = ResultSchema2.extend({
  roots: array(RootSchema2)
});
var RootsListChangedNotificationSchema2 = NotificationSchema2.extend({
  method: literal("notifications/roots/list_changed"),
  params: NotificationsParamsSchema2.optional()
});
var ClientRequestSchema2 = union([
  PingRequestSchema2,
  InitializeRequestSchema2,
  CompleteRequestSchema2,
  SetLevelRequestSchema2,
  GetPromptRequestSchema2,
  ListPromptsRequestSchema2,
  ListResourcesRequestSchema2,
  ListResourceTemplatesRequestSchema2,
  ReadResourceRequestSchema2,
  SubscribeRequestSchema2,
  UnsubscribeRequestSchema2,
  CallToolRequestSchema2,
  ListToolsRequestSchema2,
  GetTaskRequestSchema2,
  GetTaskPayloadRequestSchema2,
  ListTasksRequestSchema2,
  CancelTaskRequestSchema2
]);
var ClientNotificationSchema2 = union([
  CancelledNotificationSchema2,
  ProgressNotificationSchema2,
  InitializedNotificationSchema2,
  RootsListChangedNotificationSchema2,
  TaskStatusNotificationSchema2
]);
var ClientResultSchema2 = union([
  EmptyResultSchema2,
  CreateMessageResultSchema2,
  CreateMessageResultWithToolsSchema2,
  ElicitResultSchema2,
  ListRootsResultSchema2,
  GetTaskResultSchema2,
  ListTasksResultSchema2,
  CreateTaskResultSchema2
]);
var ServerRequestSchema2 = union([
  PingRequestSchema2,
  CreateMessageRequestSchema2,
  ElicitRequestSchema2,
  ListRootsRequestSchema2,
  GetTaskRequestSchema2,
  GetTaskPayloadRequestSchema2,
  ListTasksRequestSchema2,
  CancelTaskRequestSchema2
]);
var ServerNotificationSchema2 = union([
  CancelledNotificationSchema2,
  ProgressNotificationSchema2,
  LoggingMessageNotificationSchema2,
  ResourceUpdatedNotificationSchema2,
  ResourceListChangedNotificationSchema2,
  ToolListChangedNotificationSchema2,
  PromptListChangedNotificationSchema2,
  TaskStatusNotificationSchema2,
  ElicitationCompleteNotificationSchema2
]);
var ServerResultSchema2 = union([
  EmptyResultSchema2,
  InitializeResultSchema2,
  CompleteResultSchema2,
  GetPromptResultSchema2,
  ListPromptsResultSchema2,
  ListResourcesResultSchema2,
  ListResourceTemplatesResultSchema2,
  ReadResourceResultSchema2,
  CallToolResultSchema2,
  ListToolsResultSchema2,
  GetTaskResultSchema2,
  ListTasksResultSchema2,
  CreateTaskResultSchema2
]);
var McpError2 = class _McpError extends Error {
  static {
    __name(this, "McpError");
  }
  constructor(code2, message, data) {
    super(`MCP error ${code2}: ${message}`);
    this.code = code2;
    this.data = data;
    this.name = "McpError";
  }
  /**
   * Factory method to create the appropriate error type based on the error code and data
   */
  static fromError(code2, message, data) {
    if (code2 === ErrorCode2.UrlElicitationRequired && data) {
      const errorData = data;
      if (errorData.elicitations) {
        return new UrlElicitationRequiredError2(errorData.elicitations, message);
      }
    }
    return new _McpError(code2, message, data);
  }
};
var UrlElicitationRequiredError2 = class extends McpError2 {
  static {
    __name(this, "UrlElicitationRequiredError");
  }
  constructor(elicitations, message = `URL elicitation${elicitations.length > 1 ? "s" : ""} required`) {
    super(ErrorCode2.UrlElicitationRequired, message, {
      elicitations
    });
  }
  get elicitations() {
    return this.data?.elicitations ?? [];
  }
};

// packages/cli/node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/interfaces.js
init_esbuild_shims();
function isTerminal2(status) {
  return status === "completed" || status === "failed" || status === "cancelled";
}
__name(isTerminal2, "isTerminal");

// packages/cli/node_modules/@modelcontextprotocol/sdk/dist/esm/server/zod-json-schema-compat.js
init_esbuild_shims();

// packages/cli/node_modules/@modelcontextprotocol/sdk/node_modules/zod-to-json-schema/dist/esm/index.js
init_esbuild_shims();

// packages/cli/node_modules/@modelcontextprotocol/sdk/node_modules/zod-to-json-schema/dist/esm/Options.js
init_esbuild_shims();
var ignoreOverride2 = Symbol("Let zodToJsonSchema decide on which parser to use");

// packages/cli/node_modules/@modelcontextprotocol/sdk/node_modules/zod-to-json-schema/dist/esm/Refs.js
init_esbuild_shims();

// packages/cli/node_modules/@modelcontextprotocol/sdk/node_modules/zod-to-json-schema/dist/esm/errorMessages.js
init_esbuild_shims();

// packages/cli/node_modules/@modelcontextprotocol/sdk/node_modules/zod-to-json-schema/dist/esm/getRelativePath.js
init_esbuild_shims();

// packages/cli/node_modules/@modelcontextprotocol/sdk/node_modules/zod-to-json-schema/dist/esm/parseDef.js
init_esbuild_shims();

// packages/cli/node_modules/@modelcontextprotocol/sdk/node_modules/zod-to-json-schema/dist/esm/selectParser.js
init_esbuild_shims();

// packages/cli/node_modules/@modelcontextprotocol/sdk/node_modules/zod-to-json-schema/dist/esm/parsers/any.js
init_esbuild_shims();

// packages/cli/node_modules/@modelcontextprotocol/sdk/node_modules/zod-to-json-schema/dist/esm/parsers/array.js
init_esbuild_shims();

// packages/cli/node_modules/@modelcontextprotocol/sdk/node_modules/zod-to-json-schema/dist/esm/parsers/bigint.js
init_esbuild_shims();

// packages/cli/node_modules/@modelcontextprotocol/sdk/node_modules/zod-to-json-schema/dist/esm/parsers/boolean.js
init_esbuild_shims();

// packages/cli/node_modules/@modelcontextprotocol/sdk/node_modules/zod-to-json-schema/dist/esm/parsers/branded.js
init_esbuild_shims();

// packages/cli/node_modules/@modelcontextprotocol/sdk/node_modules/zod-to-json-schema/dist/esm/parsers/catch.js
init_esbuild_shims();

// packages/cli/node_modules/@modelcontextprotocol/sdk/node_modules/zod-to-json-schema/dist/esm/parsers/date.js
init_esbuild_shims();

// packages/cli/node_modules/@modelcontextprotocol/sdk/node_modules/zod-to-json-schema/dist/esm/parsers/default.js
init_esbuild_shims();

// packages/cli/node_modules/@modelcontextprotocol/sdk/node_modules/zod-to-json-schema/dist/esm/parsers/effects.js
init_esbuild_shims();

// packages/cli/node_modules/@modelcontextprotocol/sdk/node_modules/zod-to-json-schema/dist/esm/parsers/enum.js
init_esbuild_shims();

// packages/cli/node_modules/@modelcontextprotocol/sdk/node_modules/zod-to-json-schema/dist/esm/parsers/intersection.js
init_esbuild_shims();

// packages/cli/node_modules/@modelcontextprotocol/sdk/node_modules/zod-to-json-schema/dist/esm/parsers/literal.js
init_esbuild_shims();

// packages/cli/node_modules/@modelcontextprotocol/sdk/node_modules/zod-to-json-schema/dist/esm/parsers/map.js
init_esbuild_shims();

// packages/cli/node_modules/@modelcontextprotocol/sdk/node_modules/zod-to-json-schema/dist/esm/parsers/record.js
init_esbuild_shims();

// packages/cli/node_modules/@modelcontextprotocol/sdk/node_modules/zod-to-json-schema/dist/esm/parsers/string.js
init_esbuild_shims();
var ALPHA_NUMERIC2 = new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");

// packages/cli/node_modules/@modelcontextprotocol/sdk/node_modules/zod-to-json-schema/dist/esm/parsers/nativeEnum.js
init_esbuild_shims();

// packages/cli/node_modules/@modelcontextprotocol/sdk/node_modules/zod-to-json-schema/dist/esm/parsers/never.js
init_esbuild_shims();

// packages/cli/node_modules/@modelcontextprotocol/sdk/node_modules/zod-to-json-schema/dist/esm/parsers/null.js
init_esbuild_shims();

// packages/cli/node_modules/@modelcontextprotocol/sdk/node_modules/zod-to-json-schema/dist/esm/parsers/nullable.js
init_esbuild_shims();

// packages/cli/node_modules/@modelcontextprotocol/sdk/node_modules/zod-to-json-schema/dist/esm/parsers/union.js
init_esbuild_shims();

// packages/cli/node_modules/@modelcontextprotocol/sdk/node_modules/zod-to-json-schema/dist/esm/parsers/number.js
init_esbuild_shims();

// packages/cli/node_modules/@modelcontextprotocol/sdk/node_modules/zod-to-json-schema/dist/esm/parsers/object.js
init_esbuild_shims();

// packages/cli/node_modules/@modelcontextprotocol/sdk/node_modules/zod-to-json-schema/dist/esm/parsers/optional.js
init_esbuild_shims();

// packages/cli/node_modules/@modelcontextprotocol/sdk/node_modules/zod-to-json-schema/dist/esm/parsers/pipeline.js
init_esbuild_shims();

// packages/cli/node_modules/@modelcontextprotocol/sdk/node_modules/zod-to-json-schema/dist/esm/parsers/promise.js
init_esbuild_shims();

// packages/cli/node_modules/@modelcontextprotocol/sdk/node_modules/zod-to-json-schema/dist/esm/parsers/set.js
init_esbuild_shims();

// packages/cli/node_modules/@modelcontextprotocol/sdk/node_modules/zod-to-json-schema/dist/esm/parsers/tuple.js
init_esbuild_shims();

// packages/cli/node_modules/@modelcontextprotocol/sdk/node_modules/zod-to-json-schema/dist/esm/parsers/undefined.js
init_esbuild_shims();

// packages/cli/node_modules/@modelcontextprotocol/sdk/node_modules/zod-to-json-schema/dist/esm/parsers/unknown.js
init_esbuild_shims();

// packages/cli/node_modules/@modelcontextprotocol/sdk/node_modules/zod-to-json-schema/dist/esm/parsers/readonly.js
init_esbuild_shims();

// packages/cli/node_modules/@modelcontextprotocol/sdk/node_modules/zod-to-json-schema/dist/esm/parseTypes.js
init_esbuild_shims();

// packages/cli/node_modules/@modelcontextprotocol/sdk/node_modules/zod-to-json-schema/dist/esm/zodToJsonSchema.js
init_esbuild_shims();

// packages/cli/node_modules/@modelcontextprotocol/sdk/dist/esm/server/zod-json-schema-compat.js
function getMethodLiteral2(schema) {
  const shape = getObjectShape2(schema);
  const methodSchema = shape?.method;
  if (!methodSchema) {
    throw new Error("Schema is missing a method literal");
  }
  const value = getLiteralValue2(methodSchema);
  if (typeof value !== "string") {
    throw new Error("Schema method literal must be a string");
  }
  return value;
}
__name(getMethodLiteral2, "getMethodLiteral");
function parseWithCompat2(schema, data) {
  const result = safeParse4(schema, data);
  if (!result.success) {
    throw result.error;
  }
  return result.data;
}
__name(parseWithCompat2, "parseWithCompat");

// packages/cli/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/protocol.js
var DEFAULT_REQUEST_TIMEOUT_MSEC2 = 6e4;
var Protocol2 = 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._pendingDebouncedNotifications = /* @__PURE__ */ new Set();
    this._taskProgressTokens = /* @__PURE__ */ new Map();
    this._requestResolvers = /* @__PURE__ */ new Map();
    this.setNotificationHandler(CancelledNotificationSchema2, (notification) => {
      this._oncancel(notification);
    });
    this.setNotificationHandler(ProgressNotificationSchema2, (notification) => {
      this._onprogress(notification);
    });
    this.setRequestHandler(
      PingRequestSchema2,
      // Automatic pong by default.
      (_request) => ({})
    );
    this._taskStore = _options?.taskStore;
    this._taskMessageQueue = _options?.taskMessageQueue;
    if (this._taskStore) {
      this.setRequestHandler(GetTaskRequestSchema2, async (request4, extra) => {
        const task = await this._taskStore.getTask(request4.params.taskId, extra.sessionId);
        if (!task) {
          throw new McpError2(ErrorCode2.InvalidParams, "Failed to retrieve task: Task not found");
        }
        return {
          ...task
        };
      });
      this.setRequestHandler(GetTaskPayloadRequestSchema2, async (request4, extra) => {
        const handleTaskResult = /* @__PURE__ */ __name(async () => {
          const taskId = request4.params.taskId;
          if (this._taskMessageQueue) {
            let queuedMessage;
            while (queuedMessage = await this._taskMessageQueue.dequeue(taskId, extra.sessionId)) {
              if (queuedMessage.type === "response" || queuedMessage.type === "error") {
                const message = queuedMessage.message;
                const requestId = message.id;
                const resolver = this._requestResolvers.get(requestId);
                if (resolver) {
                  this._requestResolvers.delete(requestId);
                  if (queuedMessage.type === "response") {
                    resolver(message);
                  } else {
                    const errorMessage = message;
                    const error2 = new McpError2(errorMessage.error.code, errorMessage.error.message, errorMessage.error.data);
                    resolver(error2);
                  }
                } else {
                  const messageType = queuedMessage.type === "response" ? "Response" : "Error";
                  this._onerror(new Error(`${messageType} handler missing for request ${requestId}`));
                }
                continue;
              }
              await this._transport?.send(queuedMessage.message, { relatedRequestId: extra.requestId });
            }
          }
          const task = await this._taskStore.getTask(taskId, extra.sessionId);
          if (!task) {
            throw new McpError2(ErrorCode2.InvalidParams, `Task not found: ${taskId}`);
          }
          if (!isTerminal2(task.status)) {
            await this._waitForTaskUpdate(taskId, extra.signal);
            return await handleTaskResult();
          }
          if (isTerminal2(task.status)) {
            const result = await this._taskStore.getTaskResult(taskId, extra.sessionId);
            this._clearTaskQueue(taskId);
            return {
              ...result,
              _meta: {
                ...result._meta,
                [RELATED_TASK_META_KEY2]: {
                  taskId
                }
              }
            };
          }
          return await handleTaskResult();
        }, "handleTaskResult");
        return await handleTaskResult();
      });
      this.setRequestHandler(ListTasksRequestSchema2, async (request4, extra) => {
        try {
          const { tasks, nextCursor } = await this._taskStore.listTasks(request4.params?.cursor, extra.sessionId);
          return {
            tasks,
            nextCursor,
            _meta: {}
          };
        } catch (error2) {
          throw new McpError2(ErrorCode2.InvalidParams, `Failed to list tasks: ${error2 instanceof Error ? error2.message : String(error2)}`);
        }
      });
      this.setRequestHandler(CancelTaskRequestSchema2, async (request4, extra) => {
        try {
          const task = await this._taskStore.getTask(request4.params.taskId, extra.sessionId);
          if (!task) {
            throw new McpError2(ErrorCode2.InvalidParams, `Task not found: ${request4.params.taskId}`);
          }
          if (isTerminal2(task.status)) {
            throw new McpError2(ErrorCode2.InvalidParams, `Cannot cancel task in terminal status: ${task.status}`);
          }
          await this._taskStore.updateTaskStatus(request4.params.taskId, "cancelled", "Client cancelled task execution.", extra.sessionId);
          this._clearTaskQueue(request4.params.taskId);
          const cancelledTask = await this._taskStore.getTask(request4.params.taskId, extra.sessionId);
          if (!cancelledTask) {
            throw new McpError2(ErrorCode2.InvalidParams, `Task not found after cancellation: ${request4.params.taskId}`);
          }
          return {
            _meta: {},
            ...cancelledTask
          };
        } catch (error2) {
          if (error2 instanceof McpError2) {
            throw error2;
          }
          throw new McpError2(ErrorCode2.InvalidRequest, `Failed to cancel task: ${error2 instanceof Error ? error2.message : String(error2)}`);
        }
      });
    }
  }
  async _oncancel(notification) {
    if (!notification.params.requestId) {
      return;
    }
    const controller = this._requestHandlerAbortControllers.get(notification.params.requestId);
    controller?.abort(notification.params.reason);
  }
  _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 McpError2.fromError(ErrorCode2.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) {
    this._transport = transport;
    const _onclose = this.transport?.onclose;
    this._transport.onclose = () => {
      _onclose?.();
      this._onclose();
    };
    const _onerror2 = this.transport?.onerror;
    this._transport.onerror = (error2) => {
      _onerror2?.(error2);
      this._onerror(error2);
    };
    const _onmessage = this._transport?.onmessage;
    this._transport.onmessage = (message, extra) => {
      _onmessage?.(message, extra);
      if (isJSONRPCResultResponse2(message) || isJSONRPCErrorResponse2(message)) {
        this._onresponse(message);
      } else if (isJSONRPCRequest2(message)) {
        this._onrequest(message, extra);
      } else if (isJSONRPCNotification2(message)) {
        this._onnotification(message);
      } else {
        this._onerror(new Error(`Unknown message type: ${JSON.stringify(message)}`));
      }
    };
    await this._transport.start();
  }
  _onclose() {
    const responseHandlers = this._responseHandlers;
    this._responseHandlers = /* @__PURE__ */ new Map();
    this._progressHandlers.clear();
    this._taskProgressTokens.clear();
    this._pendingDebouncedNotifications.clear();
    const error2 = McpError2.fromError(ErrorCode2.ConnectionClosed, "Connection closed");
    this._transport = void 0;
    this.onclose?.();
    for (const handler of responseHandlers.values()) {
      handler(error2);
    }
  }
  _onerror(error2) {
    this.onerror?.(error2);
  }
  _onnotification(notification) {
    const handler = this._notificationHandlers.get(notification.method) ?? this.fallbackNotificationHandler;
    if (handler === void 0) {
      return;
    }
    Promise.resolve().then(() => handler(notification)).catch((error2) => this._onerror(new Error(`Uncaught error in notification handler: ${error2}`)));
  }
  _onrequest(request4, extra) {
    const handler = this._requestHandlers.get(request4.method) ?? this.fallbackRequestHandler;
    const capturedTransport = this._transport;
    const relatedTaskId = request4.params?._meta?.[RELATED_TASK_META_KEY2]?.taskId;
    if (handler === void 0) {
      const errorResponse = {
        jsonrpc: "2.0",
        id: request4.id,
        error: {
          code: ErrorCode2.MethodNotFound,
          message: "Method not found"
        }
      };
      if (relatedTaskId && this._taskMessageQueue) {
        this._enqueueTaskMessage(relatedTaskId, {
          type: "error",
          message: errorResponse,
          timestamp: Date.now()
        }, capturedTransport?.sessionId).catch((error2) => this._onerror(new Error(`Failed to enqueue error response: ${error2}`)));
      } else {
        capturedTransport?.send(errorResponse).catch((error2) => this._onerror(new Error(`Failed to send an error response: ${error2}`)));
      }
      return;
    }
    const abortController = new AbortController();
    this._requestHandlerAbortControllers.set(request4.id, abortController);
    const taskCreationParams = isTaskAugmentedRequestParams2(request4.params) ? request4.params.task : void 0;
    const taskStore = this._taskStore ? this.requestTaskStore(request4, capturedTransport?.sessionId) : void 0;
    const fullExtra = {
      signal: abortController.signal,
      sessionId: capturedTransport?.sessionId,
      _meta: request4.params?._meta,
      sendNotification: /* @__PURE__ */ __name(async (notification) => {
        const notificationOptions = { relatedRequestId: request4.id };
        if (relatedTaskId) {
          notificationOptions.relatedTask = { taskId: relatedTaskId };
        }
        await this.notification(notification, notificationOptions);
      }, "sendNotification"),
      sendRequest: /* @__PURE__ */ __name(async (r5, resultSchema, options2) => {
        const requestOptions = { ...options2, relatedRequestId: request4.id };
        if (relatedTaskId && !requestOptions.relatedTask) {
          requestOptions.relatedTask = { taskId: relatedTaskId };
        }
        const effectiveTaskId = requestOptions.relatedTask?.taskId ?? relatedTaskId;
        if (effectiveTaskId && taskStore) {
          await taskStore.updateTaskStatus(effectiveTaskId, "input_required");
        }
        return await this.request(r5, resultSchema, requestOptions);
      }, "sendRequest"),
      authInfo: extra?.authInfo,
      requestId: request4.id,
      requestInfo: extra?.requestInfo,
      taskId: relatedTaskId,
      taskStore,
      taskRequestedTtl: taskCreationParams?.ttl,
      closeSSEStream: extra?.closeSSEStream,
      closeStandaloneSSEStream: extra?.closeStandaloneSSEStream
    };
    Promise.resolve().then(() => {
      if (taskCreationParams) {
        this.assertTaskHandlerCapability(request4.method);
      }
    }).then(() => handler(request4, fullExtra)).then(async (result) => {
      if (abortController.signal.aborted) {
        return;
      }
      const response = {
        result,
        jsonrpc: "2.0",
        id: request4.id
      };
      if (relatedTaskId && this._taskMessageQueue) {
        await this._enqueueTaskMessage(relatedTaskId, {
          type: "response",
          message: response,
          timestamp: Date.now()
        }, capturedTransport?.sessionId);
      } else {
        await capturedTransport?.send(response);
      }
    }, async (error2) => {
      if (abortController.signal.aborted) {
        return;
      }
      const errorResponse = {
        jsonrpc: "2.0",
        id: request4.id,
        error: {
          code: Number.isSafeInteger(error2["code"]) ? error2["code"] : ErrorCode2.InternalError,
          message: error2.message ?? "Internal error",
          ...error2["data"] !== void 0 && { data: error2["data"] }
        }
      };
      if (relatedTaskId && this._taskMessageQueue) {
        await this._enqueueTaskMessage(relatedTaskId, {
          type: "error",
          message: errorResponse,
          timestamp: Date.now()
        }, capturedTransport?.sessionId);
      } else {
        await capturedTransport?.send(errorResponse);
      }
    }).catch((error2) => this._onerror(new Error(`Failed to send response: ${error2}`))).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 (error2) {
        this._responseHandlers.delete(messageId);
        this._progressHandlers.delete(messageId);
        this._cleanupTimeout(messageId);
        responseHandler(error2);
        return;
      }
    }
    handler(params);
  }
  _onresponse(response) {
    const messageId = Number(response.id);
    const resolver = this._requestResolvers.get(messageId);
    if (resolver) {
      this._requestResolvers.delete(messageId);
      if (isJSONRPCResultResponse2(response)) {
        resolver(response);
      } else {
        const error2 = new McpError2(response.error.code, response.error.message, response.error.data);
        resolver(error2);
      }
      return;
    }
    const handler = this._responseHandlers.get(messageId);
    if (handler === void 0) {
      this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(response)}`));
      return;
    }
    this._responseHandlers.delete(messageId);
    this._cleanupTimeout(messageId);
    let isTaskResponse = false;
    if (isJSONRPCResultResponse2(response) && response.result && typeof response.result === "object") {
      const result = response.result;
      if (result.task && typeof result.task === "object") {
        const task = result.task;
        if (typeof task.taskId === "string") {
          isTaskResponse = true;
          this._taskProgressTokens.set(task.taskId, messageId);
        }
      }
    }
    if (!isTaskResponse) {
      this._progressHandlers.delete(messageId);
    }
    if (isJSONRPCResultResponse2(response)) {
      handler(response);
    } else {
      const error2 = McpError2.fromError(response.error.code, response.error.message, response.error.data);
      handler(error2);
    }
  }
  get transport() {
    return this._transport;
  }
  /**
   * Closes the connection.
   */
  async close() {
    await this._transport?.close();
  }
  /**
   * Sends a request and returns an AsyncGenerator that yields response messages.
   * The generator is guaranteed to end with either a 'result' or 'error' message.
   *
   * @example
   * ```typescript
   * const stream = protocol.requestStream(request, resultSchema, options);
   * for await (const message of stream) {
   *   switch (message.type) {
   *     case 'taskCreated':
   *       console.log('Task created:', message.task.taskId);
   *       break;
   *     case 'taskStatus':
   *       console.log('Task status:', message.task.status);
   *       break;
   *     case 'result':
   *       console.log('Final result:', message.result);
   *       break;
   *     case 'error':
   *       console.error('Error:', message.error);
   *       break;
   *   }
   * }
   * ```
   *
   * @experimental Use `client.experimental.tasks.requestStream()` to access this method.
   */
  async *requestStream(request4, resultSchema, options2) {
    const { task } = options2 ?? {};
    if (!task) {
      try {
        const result = await this.request(request4, resultSchema, options2);
        yield { type: "result", result };
      } catch (error2) {
        yield {
          type: "error",
          error: error2 instanceof McpError2 ? error2 : new McpError2(ErrorCode2.InternalError, String(error2))
        };
      }
      return;
    }
    let taskId;
    try {
      const createResult = await this.request(request4, CreateTaskResultSchema2, options2);
      if (createResult.task) {
        taskId = createResult.task.taskId;
        yield { type: "taskCreated", task: createResult.task };
      } else {
        throw new McpError2(ErrorCode2.InternalError, "Task creation did not return a task");
      }
      while (true) {
        const task2 = await this.getTask({ taskId }, options2);
        yield { type: "taskStatus", task: task2 };
        if (isTerminal2(task2.status)) {
          if (task2.status === "completed") {
            const result = await this.getTaskResult({ taskId }, resultSchema, options2);
            yield { type: "result", result };
          } else if (task2.status === "failed") {
            yield {
              type: "error",
              error: new McpError2(ErrorCode2.InternalError, `Task ${taskId} failed`)
            };
          } else if (task2.status === "cancelled") {
            yield {
              type: "error",
              error: new McpError2(ErrorCode2.InternalError, `Task ${taskId} was cancelled`)
            };
          }
          return;
        }
        if (task2.status === "input_required") {
          const result = await this.getTaskResult({ taskId }, resultSchema, options2);
          yield { type: "result", result };
          return;
        }
        const pollInterval = task2.pollInterval ?? this._options?.defaultTaskPollInterval ?? 1e3;
        await new Promise((resolve30) => setTimeout(resolve30, pollInterval));
        options2?.signal?.throwIfAborted();
      }
    } catch (error2) {
      yield {
        type: "error",
        error: error2 instanceof McpError2 ? error2 : new McpError2(ErrorCode2.InternalError, String(error2))
      };
    }
  }
  /**
   * Sends a request and waits for a response.
   *
   * Do not use this method to emit notifications! Use notification() instead.
   */
  request(request4, resultSchema, options2) {
    const { relatedRequestId, resumptionToken, onresumptiontoken, task, relatedTask } = options2 ?? {};
    return new Promise((resolve30, reject) => {
      const earlyReject = /* @__PURE__ */ __name((error2) => {
        reject(error2);
      }, "earlyReject");
      if (!this._transport) {
        earlyReject(new Error("Not connected"));
        return;
      }
      if (this._options?.enforceStrictCapabilities === true) {
        try {
          this.assertCapabilityForMethod(request4.method);
          if (task) {
            this.assertTaskCapability(request4.method);
          }
        } catch (e4) {
          earlyReject(e4);
          return;
        }
      }
      options2?.signal?.throwIfAborted();
      const messageId = this._requestMessageId++;
      const jsonrpcRequest = {
        ...request4,
        jsonrpc: "2.0",
        id: messageId
      };
      if (options2?.onprogress) {
        this._progressHandlers.set(messageId, options2.onprogress);
        jsonrpcRequest.params = {
          ...request4.params,
          _meta: {
            ...request4.params?._meta || {},
            progressToken: messageId
          }
        };
      }
      if (task) {
        jsonrpcRequest.params = {
          ...jsonrpcRequest.params,
          task
        };
      }
      if (relatedTask) {
        jsonrpcRequest.params = {
          ...jsonrpcRequest.params,
          _meta: {
            ...jsonrpcRequest.params?._meta || {},
            [RELATED_TASK_META_KEY2]: relatedTask
          }
        };
      }
      const cancel = /* @__PURE__ */ __name((reason) => {
        this._responseHandlers.delete(messageId);
        this._progressHandlers.delete(messageId);
        this._cleanupTimeout(messageId);
        this._transport?.send({
          jsonrpc: "2.0",
          method: "notifications/cancelled",
          params: {
            requestId: messageId,
            reason: String(reason)
          }
        }, { relatedRequestId, resumptionToken, onresumptiontoken }).catch((error3) => this._onerror(new Error(`Failed to send cancellation: ${error3}`)));
        const error2 = reason instanceof McpError2 ? reason : new McpError2(ErrorCode2.RequestTimeout, String(reason));
        reject(error2);
      }, "cancel");
      this._responseHandlers.set(messageId, (response) => {
        if (options2?.signal?.aborted) {
          return;
        }
        if (response instanceof Error) {
          return reject(response);
        }
        try {
          const parseResult = safeParse4(resultSchema, response.result);
          if (!parseResult.success) {
            reject(parseResult.error);
          } else {
            resolve30(parseResult.data);
          }
        } catch (error2) {
          reject(error2);
        }
      });
      options2?.signal?.addEventListener("abort", () => {
        cancel(options2?.signal?.reason);
      });
      const timeout2 = options2?.timeout ?? DEFAULT_REQUEST_TIMEOUT_MSEC2;
      const timeoutHandler = /* @__PURE__ */ __name(() => cancel(McpError2.fromError(ErrorCode2.RequestTimeout, "Request timed out", { timeout: timeout2 })), "timeoutHandler");
      this._setupTimeout(messageId, timeout2, options2?.maxTotalTimeout, timeoutHandler, options2?.resetTimeoutOnProgress ?? false);
      const relatedTaskId = relatedTask?.taskId;
      if (relatedTaskId) {
        const responseResolver = /* @__PURE__ */ __name((response) => {
          const handler = this._responseHandlers.get(messageId);
          if (handler) {
            handler(response);
          } else {
            this._onerror(new Error(`Response handler missing for side-channeled request ${messageId}`));
          }
        }, "responseResolver");
        this._requestResolvers.set(messageId, responseResolver);
        this._enqueueTaskMessage(relatedTaskId, {
          type: "request",
          message: jsonrpcRequest,
          timestamp: Date.now()
        }).catch((error2) => {
          this._cleanupTimeout(messageId);
          reject(error2);
        });
      } else {
        this._transport.send(jsonrpcRequest, { relatedRequestId, resumptionToken, onresumptiontoken }).catch((error2) => {
          this._cleanupTimeout(messageId);
          reject(error2);
        });
      }
    });
  }
  /**
   * Gets the current status of a task.
   *
   * @experimental Use `client.experimental.tasks.getTask()` to access this method.
   */
  async getTask(params, options2) {
    return this.request({ method: "tasks/get", params }, GetTaskResultSchema2, options2);
  }
  /**
   * Retrieves the result of a completed task.
   *
   * @experimental Use `client.experimental.tasks.getTaskResult()` to access this method.
   */
  async getTaskResult(params, resultSchema, options2) {
    return this.request({ method: "tasks/result", params }, resultSchema, options2);
  }
  /**
   * Lists tasks, optionally starting from a pagination cursor.
   *
   * @experimental Use `client.experimental.tasks.listTasks()` to access this method.
   */
  async listTasks(params, options2) {
    return this.request({ method: "tasks/list", params }, ListTasksResultSchema2, options2);
  }
  /**
   * Cancels a specific task.
   *
   * @experimental Use `client.experimental.tasks.cancelTask()` to access this method.
   */
  async cancelTask(params, options2) {
    return this.request({ method: "tasks/cancel", params }, CancelTaskResultSchema2, options2);
  }
  /**
   * 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 relatedTaskId = options2?.relatedTask?.taskId;
    if (relatedTaskId) {
      const jsonrpcNotification2 = {
        ...notification,
        jsonrpc: "2.0",
        params: {
          ...notification.params,
          _meta: {
            ...notification.params?._meta || {},
            [RELATED_TASK_META_KEY2]: options2.relatedTask
          }
        }
      };
      await this._enqueueTaskMessage(relatedTaskId, {
        type: "notification",
        message: jsonrpcNotification2,
        timestamp: Date.now()
      });
      return;
    }
    const debouncedMethods = this._options?.debouncedNotificationMethods ?? [];
    const canDebounce = debouncedMethods.includes(notification.method) && !notification.params && !options2?.relatedRequestId && !options2?.relatedTask;
    if (canDebounce) {
      if (this._pendingDebouncedNotifications.has(notification.method)) {
        return;
      }
      this._pendingDebouncedNotifications.add(notification.method);
      Promise.resolve().then(() => {
        this._pendingDebouncedNotifications.delete(notification.method);
        if (!this._transport) {
          return;
        }
        let jsonrpcNotification2 = {
          ...notification,
          jsonrpc: "2.0"
        };
        if (options2?.relatedTask) {
          jsonrpcNotification2 = {
            ...jsonrpcNotification2,
            params: {
              ...jsonrpcNotification2.params,
              _meta: {
                ...jsonrpcNotification2.params?._meta || {},
                [RELATED_TASK_META_KEY2]: options2.relatedTask
              }
            }
          };
        }
        this._transport?.send(jsonrpcNotification2, options2).catch((error2) => this._onerror(error2));
      });
      return;
    }
    let jsonrpcNotification = {
      ...notification,
      jsonrpc: "2.0"
    };
    if (options2?.relatedTask) {
      jsonrpcNotification = {
        ...jsonrpcNotification,
        params: {
          ...jsonrpcNotification.params,
          _meta: {
            ...jsonrpcNotification.params?._meta || {},
            [RELATED_TASK_META_KEY2]: options2.relatedTask
          }
        }
      };
    }
    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 = getMethodLiteral2(requestSchema);
    this.assertRequestHandlerCapability(method);
    this._requestHandlers.set(method, (request4, extra) => {
      const parsed = parseWithCompat2(requestSchema, request4);
      return Promise.resolve(handler(parsed, extra));
    });
  }
  /**
   * Removes the request handler for the given method.
   */
  removeRequestHandler(method) {
    this._requestHandlers.delete(method);
  }
  /**
   * Asserts that a request handler has not already been set for the given method, in preparation for a new one being automatically installed.
   */
  assertCanSetRequestHandler(method) {
    if (this._requestHandlers.has(method)) {
      throw new Error(`A request handler for ${method} already exists, which would be overridden`);
    }
  }
  /**
   * Registers a handler to invoke when this protocol object receives a notification with the given method.
   *
   * Note that this will replace any previous notification handler for the same method.
   */
  setNotificationHandler(notificationSchema, handler) {
    const method = getMethodLiteral2(notificationSchema);
    this._notificationHandlers.set(method, (notification) => {
      const parsed = parseWithCompat2(notificationSchema, notification);
      return Promise.resolve(handler(parsed));
    });
  }
  /**
   * Removes the notification handler for the given method.
   */
  removeNotificationHandler(method) {
    this._notificationHandlers.delete(method);
  }
  /**
   * Cleans up the progress handler associated with a task.
   * This should be called when a task reaches a terminal status.
   */
  _cleanupTaskProgressHandler(taskId) {
    const progressToken = this._taskProgressTokens.get(taskId);
    if (progressToken !== void 0) {
      this._progressHandlers.delete(progressToken);
      this._taskProgressTokens.delete(taskId);
    }
  }
  /**
   * Enqueues a task-related message for side-channel delivery via tasks/result.
   * @param taskId The task ID to associate the message with
   * @param message The message to enqueue
   * @param sessionId Optional session ID for binding the operation to a specific session
   * @throws Error if taskStore is not configured or if enqueue fails (e.g., queue overflow)
   *
   * Note: If enqueue fails, it's the TaskMessageQueue implementation's responsibility to handle
   * the error appropriately (e.g., by failing the task, logging, etc.). The Protocol layer
   * simply propagates the error.
   */
  async _enqueueTaskMessage(taskId, message, sessionId) {
    if (!this._taskStore || !this._taskMessageQueue) {
      throw new Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");
    }
    const maxQueueSize = this._options?.maxTaskQueueSize;
    await this._taskMessageQueue.enqueue(taskId, message, sessionId, maxQueueSize);
  }
  /**
   * Clears the message queue for a task and rejects any pending request resolvers.
   * @param taskId The task ID whose queue should be cleared
   * @param sessionId Optional session ID for binding the operation to a specific session
   */
  async _clearTaskQueue(taskId, sessionId) {
    if (this._taskMessageQueue) {
      const messages = await this._taskMessageQueue.dequeueAll(taskId, sessionId);
      for (const message of messages) {
        if (message.type === "request" && isJSONRPCRequest2(message.message)) {
          const requestId = message.message.id;
          const resolver = this._requestResolvers.get(requestId);
          if (resolver) {
            resolver(new McpError2(ErrorCode2.InternalError, "Task cancelled or completed"));
            this._requestResolvers.delete(requestId);
          } else {
            this._onerror(new Error(`Resolver missing for request ${requestId} during task ${taskId} cleanup`));
          }
        }
      }
    }
  }
  /**
   * Waits for a task update (new messages or status change) with abort signal support.
   * Uses polling to check for updates at the task's configured poll interval.
   * @param taskId The task ID to wait for
   * @param signal Abort signal to cancel the wait
   * @returns Promise that resolves when an update occurs or rejects if aborted
   */
  async _waitForTaskUpdate(taskId, signal) {
    let interval = this._options?.defaultTaskPollInterval ?? 1e3;
    try {
      const task = await this._taskStore?.getTask(taskId);
      if (task?.pollInterval) {
        interval = task.pollInterval;
      }
    } catch {
    }
    return new Promise((resolve30, reject) => {
      if (signal.aborted) {
        reject(new McpError2(ErrorCode2.InvalidRequest, "Request cancelled"));
        return;
      }
      const timeoutId = setTimeout(resolve30, interval);
      signal.addEventListener("abort", () => {
        clearTimeout(timeoutId);
        reject(new McpError2(ErrorCode2.InvalidRequest, "Request cancelled"));
      }, { once: true });
    });
  }
  requestTaskStore(request4, sessionId) {
    const taskStore = this._taskStore;
    if (!taskStore) {
      throw new Error("No task store configured");
    }
    return {
      createTask: /* @__PURE__ */ __name(async (taskParams) => {
        if (!request4) {
          throw new Error("No request provided");
        }
        return await taskStore.createTask(taskParams, request4.id, {
          method: request4.method,
          params: request4.params
        }, sessionId);
      }, "createTask"),
      getTask: /* @__PURE__ */ __name(async (taskId) => {
        const task = await taskStore.getTask(taskId, sessionId);
        if (!task) {
          throw new McpError2(ErrorCode2.InvalidParams, "Failed to retrieve task: Task not found");
        }
        return task;
      }, "getTask"),
      storeTaskResult: /* @__PURE__ */ __name(async (taskId, status, result) => {
        await taskStore.storeTaskResult(taskId, status, result, sessionId);
        const task = await taskStore.getTask(taskId, sessionId);
        if (task) {
          const notification = TaskStatusNotificationSchema2.parse({
            method: "notifications/tasks/status",
            params: task
          });
          await this.notification(notification);
          if (isTerminal2(task.status)) {
            this._cleanupTaskProgressHandler(taskId);
          }
        }
      }, "storeTaskResult"),
      getTaskResult: /* @__PURE__ */ __name((taskId) => {
        return taskStore.getTaskResult(taskId, sessionId);
      }, "getTaskResult"),
      updateTaskStatus: /* @__PURE__ */ __name(async (taskId, status, statusMessage) => {
        const task = await taskStore.getTask(taskId, sessionId);
        if (!task) {
          throw new McpError2(ErrorCode2.InvalidParams, `Task "${taskId}" not found - it may have been cleaned up`);
        }
        if (isTerminal2(task.status)) {
          throw new McpError2(ErrorCode2.InvalidParams, `Cannot update task "${taskId}" from terminal status "${task.status}" to "${status}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);
        }
        await taskStore.updateTaskStatus(taskId, status, statusMessage, sessionId);
        const updatedTask = await taskStore.getTask(taskId, sessionId);
        if (updatedTask) {
          const notification = TaskStatusNotificationSchema2.parse({
            method: "notifications/tasks/status",
            params: updatedTask
          });
          await this.notification(notification);
          if (isTerminal2(updatedTask.status)) {
            this._cleanupTaskProgressHandler(taskId);
          }
        }
      }, "updateTaskStatus"),
      listTasks: /* @__PURE__ */ __name((cursor) => {
        return taskStore.listTasks(cursor, sessionId);
      }, "listTasks")
    };
  }
};
function isPlainObject6(value) {
  return value !== null && typeof value === "object" && !Array.isArray(value);
}
__name(isPlainObject6, "isPlainObject");
function mergeCapabilities2(base, additional) {
  const result = { ...base };
  for (const key in additional) {
    const k2 = key;
    const addValue = additional[k2];
    if (addValue === void 0)
      continue;
    const baseValue = result[k2];
    if (isPlainObject6(baseValue) && isPlainObject6(addValue)) {
      result[k2] = { ...baseValue, ...addValue };
    } else {
      result[k2] = addValue;
    }
  }
  return result;
}
__name(mergeCapabilities2, "mergeCapabilities");

// packages/cli/node_modules/@modelcontextprotocol/sdk/dist/esm/validation/ajv-provider.js
init_esbuild_shims();
var import_ajv3 = __toESM(require_ajv3(), 1);
var import_ajv_formats2 = __toESM(require_dist3(), 1);
function createDefaultAjvInstance2() {
  const ajv = new import_ajv3.default({
    strict: false,
    validateFormats: true,
    validateSchema: false,
    allErrors: true
  });
  const addFormats2 = import_ajv_formats2.default;
  addFormats2(ajv);
  return ajv;
}
__name(createDefaultAjvInstance2, "createDefaultAjvInstance");
var AjvJsonSchemaValidator2 = class {
  static {
    __name(this, "AjvJsonSchemaValidator");
  }
  /**
   * Create an AJV validator
   *
   * @param ajv - Optional pre-configured AJV instance. If not provided, a default instance will be created.
   *
   * @example
   * ```typescript
   * // Use default configuration (recommended for most cases)
   * import { AjvJsonSchemaValidator } from '@modelcontextprotocol/sdk/validation/ajv';
   * const validator = new AjvJsonSchemaValidator();
   *
   * // Or provide custom AJV instance for advanced configuration
   * import { Ajv } from 'ajv';
   * import addFormats from 'ajv-formats';
   *
   * const ajv = new Ajv({ validateFormats: true });
   * addFormats(ajv);
   * const validator = new AjvJsonSchemaValidator(ajv);
   * ```
   */
  constructor(ajv) {
    this._ajv = ajv ?? createDefaultAjvInstance2();
  }
  /**
   * Create a validator for the given JSON Schema
   *
   * The validator is compiled once and can be reused multiple times.
   * If the schema has an $id, it will be cached by AJV automatically.
   *
   * @param schema - Standard JSON Schema object
   * @returns A validator function that validates input data
   */
  getValidator(schema) {
    const ajvValidator = "$id" in schema && typeof schema.$id === "string" ? this._ajv.getSchema(schema.$id) ?? this._ajv.compile(schema) : this._ajv.compile(schema);
    return (input) => {
      const valid = ajvValidator(input);
      if (valid) {
        return {
          valid: true,
          data: input,
          errorMessage: void 0
        };
      } else {
        return {
          valid: false,
          data: void 0,
          errorMessage: this._ajv.errorsText(ajvValidator.errors)
        };
      }
    };
  }
};

// packages/cli/node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/client.js
init_esbuild_shims();
var ExperimentalClientTasks2 = class {
  static {
    __name(this, "ExperimentalClientTasks");
  }
  constructor(_client) {
    this._client = _client;
  }
  /**
   * Calls a tool and returns an AsyncGenerator that yields response messages.
   * The generator is guaranteed to end with either a 'result' or 'error' message.
   *
   * This method provides streaming access to tool execution, allowing you to
   * observe intermediate task status updates for long-running tool calls.
   * Automatically validates structured output if the tool has an outputSchema.
   *
   * @example
   * ```typescript
   * const stream = client.experimental.tasks.callToolStream({ name: 'myTool', arguments: {} });
   * for await (const message of stream) {
   *   switch (message.type) {
   *     case 'taskCreated':
   *       console.log('Tool execution started:', message.task.taskId);
   *       break;
   *     case 'taskStatus':
   *       console.log('Tool status:', message.task.status);
   *       break;
   *     case 'result':
   *       console.log('Tool result:', message.result);
   *       break;
   *     case 'error':
   *       console.error('Tool error:', message.error);
   *       break;
   *   }
   * }
   * ```
   *
   * @param params - Tool call parameters (name and arguments)
   * @param resultSchema - Zod schema for validating the result (defaults to CallToolResultSchema)
   * @param options - Optional request options (timeout, signal, task creation params, etc.)
   * @returns AsyncGenerator that yields ResponseMessage objects
   *
   * @experimental
   */
  async *callToolStream(params, resultSchema = CallToolResultSchema2, options2) {
    const clientInternal = this._client;
    const optionsWithTask = {
      ...options2,
      // We check if the tool is known to be a task during auto-configuration, but assume
      // the caller knows what they're doing if they pass this explicitly
      task: options2?.task ?? (clientInternal.isToolTask(params.name) ? {} : void 0)
    };
    const stream2 = clientInternal.requestStream({ method: "tools/call", params }, resultSchema, optionsWithTask);
    const validator = clientInternal.getToolOutputValidator(params.name);
    for await (const message of stream2) {
      if (message.type === "result" && validator) {
        const result = message.result;
        if (!result.structuredContent && !result.isError) {
          yield {
            type: "error",
            error: new McpError2(ErrorCode2.InvalidRequest, `Tool ${params.name} has an output schema but did not return structured content`)
          };
          return;
        }
        if (result.structuredContent) {
          try {
            const validationResult = validator(result.structuredContent);
            if (!validationResult.valid) {
              yield {
                type: "error",
                error: new McpError2(ErrorCode2.InvalidParams, `Structured content does not match the tool's output schema: ${validationResult.errorMessage}`)
              };
              return;
            }
          } catch (error2) {
            if (error2 instanceof McpError2) {
              yield { type: "error", error: error2 };
              return;
            }
            yield {
              type: "error",
              error: new McpError2(ErrorCode2.InvalidParams, `Failed to validate structured content: ${error2 instanceof Error ? error2.message : String(error2)}`)
            };
            return;
          }
        }
      }
      yield message;
    }
  }
  /**
   * Gets the current status of a task.
   *
   * @param taskId - The task identifier
   * @param options - Optional request options
   * @returns The task status
   *
   * @experimental
   */
  async getTask(taskId, options2) {
    return this._client.getTask({ taskId }, options2);
  }
  /**
   * Retrieves the result of a completed task.
   *
   * @param taskId - The task identifier
   * @param resultSchema - Zod schema for validating the result
   * @param options - Optional request options
   * @returns The task result
   *
   * @experimental
   */
  async getTaskResult(taskId, resultSchema, options2) {
    return this._client.getTaskResult({ taskId }, resultSchema, options2);
  }
  /**
   * Lists tasks with optional pagination.
   *
   * @param cursor - Optional pagination cursor
   * @param options - Optional request options
   * @returns List of tasks with optional next cursor
   *
   * @experimental
   */
  async listTasks(cursor, options2) {
    return this._client.listTasks(cursor ? { cursor } : void 0, options2);
  }
  /**
   * Cancels a running task.
   *
   * @param taskId - The task identifier
   * @param options - Optional request options
   *
   * @experimental
   */
  async cancelTask(taskId, options2) {
    return this._client.cancelTask({ taskId }, options2);
  }
  /**
   * Sends a request and returns an AsyncGenerator that yields response messages.
   * The generator is guaranteed to end with either a 'result' or 'error' message.
   *
   * This method provides streaming access to request processing, allowing you to
   * observe intermediate task status updates for task-augmented requests.
   *
   * @param request - The request to send
   * @param resultSchema - Zod schema for validating the result
   * @param options - Optional request options (timeout, signal, task creation params, etc.)
   * @returns AsyncGenerator that yields ResponseMessage objects
   *
   * @experimental
   */
  requestStream(request4, resultSchema, options2) {
    return this._client.requestStream(request4, resultSchema, options2);
  }
};

// packages/cli/node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/helpers.js
init_esbuild_shims();
function assertToolsCallTaskCapability2(requests, method, entityName) {
  if (!requests) {
    throw new Error(`${entityName} does not support task creation (required for ${method})`);
  }
  switch (method) {
    case "tools/call":
      if (!requests.tools?.call) {
        throw new Error(`${entityName} does not support task creation for tools/call (required for ${method})`);
      }
      break;
    default:
      break;
  }
}
__name(assertToolsCallTaskCapability2, "assertToolsCallTaskCapability");
function assertClientRequestTaskCapability2(requests, method, entityName) {
  if (!requests) {
    throw new Error(`${entityName} does not support task creation (required for ${method})`);
  }
  switch (method) {
    case "sampling/createMessage":
      if (!requests.sampling?.createMessage) {
        throw new Error(`${entityName} does not support task creation for sampling/createMessage (required for ${method})`);
      }
      break;
    case "elicitation/create":
      if (!requests.elicitation?.create) {
        throw new Error(`${entityName} does not support task creation for elicitation/create (required for ${method})`);
      }
      break;
    default:
      break;
  }
}
__name(assertClientRequestTaskCapability2, "assertClientRequestTaskCapability");

// packages/cli/node_modules/@modelcontextprotocol/sdk/dist/esm/client/index.js
function applyElicitationDefaults2(schema, data) {
  if (!schema || data === null || typeof data !== "object")
    return;
  if (schema.type === "object" && schema.properties && typeof schema.properties === "object") {
    const obj = data;
    const props = schema.properties;
    for (const key of Object.keys(props)) {
      const propSchema = props[key];
      if (obj[key] === void 0 && Object.prototype.hasOwnProperty.call(propSchema, "default")) {
        obj[key] = propSchema.default;
      }
      if (obj[key] !== void 0) {
        applyElicitationDefaults2(propSchema, obj[key]);
      }
    }
  }
  if (Array.isArray(schema.anyOf)) {
    for (const sub of schema.anyOf) {
      if (typeof sub !== "boolean") {
        applyElicitationDefaults2(sub, data);
      }
    }
  }
  if (Array.isArray(schema.oneOf)) {
    for (const sub of schema.oneOf) {
      if (typeof sub !== "boolean") {
        applyElicitationDefaults2(sub, data);
      }
    }
  }
}
__name(applyElicitationDefaults2, "applyElicitationDefaults");
function getSupportedElicitationModes2(capabilities) {
  if (!capabilities) {
    return { supportsFormMode: false, supportsUrlMode: false };
  }
  const hasFormCapability = capabilities.form !== void 0;
  const hasUrlCapability = capabilities.url !== void 0;
  const supportsFormMode = hasFormCapability || !hasFormCapability && !hasUrlCapability;
  const supportsUrlMode = hasUrlCapability;
  return { supportsFormMode, supportsUrlMode };
}
__name(getSupportedElicitationModes2, "getSupportedElicitationModes");
var Client2 = class extends Protocol2 {
  static {
    __name(this, "Client");
  }
  /**
   * Initializes this client with the given name and version information.
   */
  constructor(_clientInfo, options2) {
    super(options2);
    this._clientInfo = _clientInfo;
    this._cachedToolOutputValidators = /* @__PURE__ */ new Map();
    this._cachedKnownTaskTools = /* @__PURE__ */ new Set();
    this._cachedRequiredTaskTools = /* @__PURE__ */ new Set();
    this._listChangedDebounceTimers = /* @__PURE__ */ new Map();
    this._capabilities = options2?.capabilities ?? {};
    this._jsonSchemaValidator = options2?.jsonSchemaValidator ?? new AjvJsonSchemaValidator2();
    if (options2?.listChanged) {
      this._pendingListChangedConfig = options2.listChanged;
    }
  }
  /**
   * Set up handlers for list changed notifications based on config and server capabilities.
   * This should only be called after initialization when server capabilities are known.
   * Handlers are silently skipped if the server doesn't advertise the corresponding listChanged capability.
   * @internal
   */
  _setupListChangedHandlers(config2) {
    if (config2.tools && this._serverCapabilities?.tools?.listChanged) {
      this._setupListChangedHandler("tools", ToolListChangedNotificationSchema2, config2.tools, async () => {
        const result = await this.listTools();
        return result.tools;
      });
    }
    if (config2.prompts && this._serverCapabilities?.prompts?.listChanged) {
      this._setupListChangedHandler("prompts", PromptListChangedNotificationSchema2, config2.prompts, async () => {
        const result = await this.listPrompts();
        return result.prompts;
      });
    }
    if (config2.resources && this._serverCapabilities?.resources?.listChanged) {
      this._setupListChangedHandler("resources", ResourceListChangedNotificationSchema2, config2.resources, async () => {
        const result = await this.listResources();
        return result.resources;
      });
    }
  }
  /**
   * Access experimental features.
   *
   * WARNING: These APIs are experimental and may change without notice.
   *
   * @experimental
   */
  get experimental() {
    if (!this._experimental) {
      this._experimental = {
        tasks: new ExperimentalClientTasks2(this)
      };
    }
    return this._experimental;
  }
  /**
   * Registers new capabilities. This can only be called before connecting to a transport.
   *
   * The new capabilities will be merged with any existing capabilities previously given (e.g., at initialization).
   */
  registerCapabilities(capabilities) {
    if (this.transport) {
      throw new Error("Cannot register capabilities after connecting to transport");
    }
    this._capabilities = mergeCapabilities2(this._capabilities, capabilities);
  }
  /**
   * Override request handler registration to enforce client-side validation for elicitation.
   */
  setRequestHandler(requestSchema, handler) {
    const shape = getObjectShape2(requestSchema);
    const methodSchema = shape?.method;
    if (!methodSchema) {
      throw new Error("Schema is missing a method literal");
    }
    let methodValue;
    if (isZ4Schema2(methodSchema)) {
      const v4Schema = methodSchema;
      const v4Def = v4Schema._zod?.def;
      methodValue = v4Def?.value ?? v4Schema.value;
    } else {
      const v3Schema = methodSchema;
      const legacyDef = v3Schema._def;
      methodValue = legacyDef?.value ?? v3Schema.value;
    }
    if (typeof methodValue !== "string") {
      throw new Error("Schema method literal must be a string");
    }
    const method = methodValue;
    if (method === "elicitation/create") {
      const wrappedHandler = /* @__PURE__ */ __name(async (request4, extra) => {
        const validatedRequest = safeParse4(ElicitRequestSchema2, request4);
        if (!validatedRequest.success) {
          const errorMessage = validatedRequest.error instanceof Error ? validatedRequest.error.message : String(validatedRequest.error);
          throw new McpError2(ErrorCode2.InvalidParams, `Invalid elicitation request: ${errorMessage}`);
        }
        const { params } = validatedRequest.data;
        params.mode = params.mode ?? "form";
        const { supportsFormMode, supportsUrlMode } = getSupportedElicitationModes2(this._capabilities.elicitation);
        if (params.mode === "form" && !supportsFormMode) {
          throw new McpError2(ErrorCode2.InvalidParams, "Client does not support form-mode elicitation requests");
        }
        if (params.mode === "url" && !supportsUrlMode) {
          throw new McpError2(ErrorCode2.InvalidParams, "Client does not support URL-mode elicitation requests");
        }
        const result = await Promise.resolve(handler(request4, extra));
        if (params.task) {
          const taskValidationResult = safeParse4(CreateTaskResultSchema2, result);
          if (!taskValidationResult.success) {
            const errorMessage = taskValidationResult.error instanceof Error ? taskValidationResult.error.message : String(taskValidationResult.error);
            throw new McpError2(ErrorCode2.InvalidParams, `Invalid task creation result: ${errorMessage}`);
          }
          return taskValidationResult.data;
        }
        const validationResult = safeParse4(ElicitResultSchema2, result);
        if (!validationResult.success) {
          const errorMessage = validationResult.error instanceof Error ? validationResult.error.message : String(validationResult.error);
          throw new McpError2(ErrorCode2.InvalidParams, `Invalid elicitation result: ${errorMessage}`);
        }
        const validatedResult = validationResult.data;
        const requestedSchema = params.mode === "form" ? params.requestedSchema : void 0;
        if (params.mode === "form" && validatedResult.action === "accept" && validatedResult.content && requestedSchema) {
          if (this._capabilities.elicitation?.form?.applyDefaults) {
            try {
              applyElicitationDefaults2(requestedSchema, validatedResult.content);
            } catch {
            }
          }
        }
        return validatedResult;
      }, "wrappedHandler");
      return super.setRequestHandler(requestSchema, wrappedHandler);
    }
    if (method === "sampling/createMessage") {
      const wrappedHandler = /* @__PURE__ */ __name(async (request4, extra) => {
        const validatedRequest = safeParse4(CreateMessageRequestSchema2, request4);
        if (!validatedRequest.success) {
          const errorMessage = validatedRequest.error instanceof Error ? validatedRequest.error.message : String(validatedRequest.error);
          throw new McpError2(ErrorCode2.InvalidParams, `Invalid sampling request: ${errorMessage}`);
        }
        const { params } = validatedRequest.data;
        const result = await Promise.resolve(handler(request4, extra));
        if (params.task) {
          const taskValidationResult = safeParse4(CreateTaskResultSchema2, result);
          if (!taskValidationResult.success) {
            const errorMessage = taskValidationResult.error instanceof Error ? taskValidationResult.error.message : String(taskValidationResult.error);
            throw new McpError2(ErrorCode2.InvalidParams, `Invalid task creation result: ${errorMessage}`);
          }
          return taskValidationResult.data;
        }
        const validationResult = safeParse4(CreateMessageResultSchema2, result);
        if (!validationResult.success) {
          const errorMessage = validationResult.error instanceof Error ? validationResult.error.message : String(validationResult.error);
          throw new McpError2(ErrorCode2.InvalidParams, `Invalid sampling result: ${errorMessage}`);
        }
        return validationResult.data;
      }, "wrappedHandler");
      return super.setRequestHandler(requestSchema, wrappedHandler);
    }
    return super.setRequestHandler(requestSchema, handler);
  }
  assertCapability(capability, method) {
    if (!this._serverCapabilities?.[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_VERSION2,
          capabilities: this._capabilities,
          clientInfo: this._clientInfo
        }
      }, InitializeResultSchema2, options2);
      if (result === void 0) {
        throw new Error(`Server sent invalid initialize result: ${result}`);
      }
      if (!SUPPORTED_PROTOCOL_VERSIONS2.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"
      });
      if (this._pendingListChangedConfig) {
        this._setupListChangedHandlers(this._pendingListChangedConfig);
        this._pendingListChangedConfig = void 0;
      }
    } catch (error2) {
      void this.close();
      throw error2;
    }
  }
  /**
   * 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) {
    switch (method) {
      case "logging/setLevel":
        if (!this._serverCapabilities?.logging) {
          throw new Error(`Server does not support logging (required for ${method})`);
        }
        break;
      case "prompts/get":
      case "prompts/list":
        if (!this._serverCapabilities?.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 (!this._serverCapabilities?.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 (!this._serverCapabilities?.tools) {
          throw new Error(`Server does not support tools (required for ${method})`);
        }
        break;
      case "completion/complete":
        if (!this._serverCapabilities?.completions) {
          throw new Error(`Server does not support completions (required for ${method})`);
        }
        break;
      case "initialize":
        break;
      case "ping":
        break;
    }
  }
  assertNotificationCapability(method) {
    switch (method) {
      case "notifications/roots/list_changed":
        if (!this._capabilities.roots?.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) {
    if (!this._capabilities) {
      return;
    }
    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 "tasks/get":
      case "tasks/list":
      case "tasks/result":
      case "tasks/cancel":
        if (!this._capabilities.tasks) {
          throw new Error(`Client does not support tasks capability (required for ${method})`);
        }
        break;
      case "ping":
        break;
    }
  }
  assertTaskCapability(method) {
    assertToolsCallTaskCapability2(this._serverCapabilities?.tasks?.requests, method, "Server");
  }
  assertTaskHandlerCapability(method) {
    if (!this._capabilities) {
      return;
    }
    assertClientRequestTaskCapability2(this._capabilities.tasks?.requests, method, "Client");
  }
  async ping(options2) {
    return this.request({ method: "ping" }, EmptyResultSchema2, options2);
  }
  async complete(params, options2) {
    return this.request({ method: "completion/complete", params }, CompleteResultSchema2, options2);
  }
  async setLoggingLevel(level, options2) {
    return this.request({ method: "logging/setLevel", params: { level } }, EmptyResultSchema2, options2);
  }
  async getPrompt(params, options2) {
    return this.request({ method: "prompts/get", params }, GetPromptResultSchema2, options2);
  }
  async listPrompts(params, options2) {
    return this.request({ method: "prompts/list", params }, ListPromptsResultSchema2, options2);
  }
  async listResources(params, options2) {
    return this.request({ method: "resources/list", params }, ListResourcesResultSchema2, options2);
  }
  async listResourceTemplates(params, options2) {
    return this.request({ method: "resources/templates/list", params }, ListResourceTemplatesResultSchema2, options2);
  }
  async readResource(params, options2) {
    return this.request({ method: "resources/read", params }, ReadResourceResultSchema2, options2);
  }
  async subscribeResource(params, options2) {
    return this.request({ method: "resources/subscribe", params }, EmptyResultSchema2, options2);
  }
  async unsubscribeResource(params, options2) {
    return this.request({ method: "resources/unsubscribe", params }, EmptyResultSchema2, options2);
  }
  /**
   * Calls a tool and waits for the result. Automatically validates structured output if the tool has an outputSchema.
   *
   * For task-based execution with streaming behavior, use client.experimental.tasks.callToolStream() instead.
   */
  async callTool(params, resultSchema = CallToolResultSchema2, options2) {
    if (this.isToolTaskRequired(params.name)) {
      throw new McpError2(ErrorCode2.InvalidRequest, `Tool "${params.name}" requires task-based execution. Use client.experimental.tasks.callToolStream() instead.`);
    }
    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 McpError2(ErrorCode2.InvalidRequest, `Tool ${params.name} has an output schema but did not return structured content`);
      }
      if (result.structuredContent) {
        try {
          const validationResult = validator(result.structuredContent);
          if (!validationResult.valid) {
            throw new McpError2(ErrorCode2.InvalidParams, `Structured content does not match the tool's output schema: ${validationResult.errorMessage}`);
          }
        } catch (error2) {
          if (error2 instanceof McpError2) {
            throw error2;
          }
          throw new McpError2(ErrorCode2.InvalidParams, `Failed to validate structured content: ${error2 instanceof Error ? error2.message : String(error2)}`);
        }
      }
    }
    return result;
  }
  isToolTask(toolName) {
    if (!this._serverCapabilities?.tasks?.requests?.tools?.call) {
      return false;
    }
    return this._cachedKnownTaskTools.has(toolName);
  }
  /**
   * Check if a tool requires task-based execution.
   * Unlike isToolTask which includes 'optional' tools, this only checks for 'required'.
   */
  isToolTaskRequired(toolName) {
    return this._cachedRequiredTaskTools.has(toolName);
  }
  /**
   * Cache validators for tool output schemas.
   * Called after listTools() to pre-compile validators for better performance.
   */
  cacheToolMetadata(tools) {
    this._cachedToolOutputValidators.clear();
    this._cachedKnownTaskTools.clear();
    this._cachedRequiredTaskTools.clear();
    for (const tool of tools) {
      if (tool.outputSchema) {
        const toolValidator = this._jsonSchemaValidator.getValidator(tool.outputSchema);
        this._cachedToolOutputValidators.set(tool.name, toolValidator);
      }
      const taskSupport = tool.execution?.taskSupport;
      if (taskSupport === "required" || taskSupport === "optional") {
        this._cachedKnownTaskTools.add(tool.name);
      }
      if (taskSupport === "required") {
        this._cachedRequiredTaskTools.add(tool.name);
      }
    }
  }
  /**
   * Get cached validator for a tool
   */
  getToolOutputValidator(toolName) {
    return this._cachedToolOutputValidators.get(toolName);
  }
  async listTools(params, options2) {
    const result = await this.request({ method: "tools/list", params }, ListToolsResultSchema2, options2);
    this.cacheToolMetadata(result.tools);
    return result;
  }
  /**
   * Set up a single list changed handler.
   * @internal
   */
  _setupListChangedHandler(listType, notificationSchema, options2, fetcher) {
    const parseResult = ListChangedOptionsBaseSchema2.safeParse(options2);
    if (!parseResult.success) {
      throw new Error(`Invalid ${listType} listChanged options: ${parseResult.error.message}`);
    }
    if (typeof options2.onChanged !== "function") {
      throw new Error(`Invalid ${listType} listChanged options: onChanged must be a function`);
    }
    const { autoRefresh, debounceMs } = parseResult.data;
    const { onChanged } = options2;
    const refresh = /* @__PURE__ */ __name(async () => {
      if (!autoRefresh) {
        onChanged(null, null);
        return;
      }
      try {
        const items = await fetcher();
        onChanged(null, items);
      } catch (e4) {
        const error2 = e4 instanceof Error ? e4 : new Error(String(e4));
        onChanged(error2, null);
      }
    }, "refresh");
    const handler = /* @__PURE__ */ __name(() => {
      if (debounceMs) {
        const existingTimer = this._listChangedDebounceTimers.get(listType);
        if (existingTimer) {
          clearTimeout(existingTimer);
        }
        const timer = setTimeout(refresh, debounceMs);
        this._listChangedDebounceTimers.set(listType, timer);
      } else {
        refresh();
      }
    }, "handler");
    this.setNotificationHandler(notificationSchema, handler);
  }
  async sendRootsListChanged() {
    return this.notification({ method: "notifications/roots/list_changed" });
  }
};

// packages/cli/src/commands/mcp/list.ts
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 extensionManager = new ExtensionManager({
    isWorkspaceTrusted: !!isWorkspaceTrusted(settings.merged),
    telemetrySettings: settings.merged.telemetry
  });
  await extensionManager.refreshCache();
  const extensions = extensionManager.getLoadedExtensions();
  const mcpServers = { ...settings.merged.mcpServers || {} };
  for (const extension of extensions) {
    if (extension.isActive) {
      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, config2) {
  const client = new Client2({
    name: "mcp-test-client",
    version: "0.0.1"
  });
  let transport;
  try {
    transport = await createTransport(serverName, config2, 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) {
    writeStdoutLine("No MCP servers configured.");
    return;
  }
  writeStdoutLine("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)`;
    }
    writeStdoutLine(`${statusIndicator} ${serverInfo} - ${statusText}`);
  }
}
__name(listMcpServers, "listMcpServers");
var listCommand3 = {
  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(listCommand3).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((p2) => p2.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((p2) => p2.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 UUID_REGEX = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
function isValidUUID(value) {
  return UUID_REGEX.test(value);
}
__name(isValidUUID, "isValidUUID");
var debugLogger72 = createDebugLogger("CONFIG");
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");
function normalizeOutputFormat(format4) {
  if (!format4) {
    return void 0;
  }
  if (format4 === OutputFormat.STREAM_JSON) {
    return OutputFormat.STREAM_JSON;
  }
  if (format4 === "json" || format4 === OutputFormat.JSON) {
    return OutputFormat.JSON;
  }
  return OutputFormat.TEXT;
}
__name(normalizeOutputFormat, "normalizeOutputFormat");
async function parseArguments() {
  let rawArgv = hideBin(process.argv);
  if (rawArgv.length > 0 && (rawArgv[0].endsWith("/dist/qwen-cli/cli.js") || rawArgv[0].endsWith("/dist/cli.js") || rawArgv[0].endsWith("/dist/cli/cli.js"))) {
    rawArgv = rawArgv.slice(1);
  }
  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.'
  ).option("chat-recording", {
    type: "boolean",
    description: "Enable chat recording to disk. If false, chat history is not saved and --continue/--resume will not work."
  }).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("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", {
      type: "boolean",
      description: "Enables checkpointing of file edits",
      default: false
    }).option("acp", {
      type: "boolean",
      description: "Starts the agent in ACP mode"
    }).option("experimental-acp", {
      type: "boolean",
      description: "Starts the agent in ACP mode (deprecated, use --acp instead)",
      hidden: true
    }).option("experimental-skills", {
      type: "boolean",
      description: "Deprecated: Skills are now enabled by default. This flag is ignored.",
      hidden: true
    }).option("experimental-lsp", {
      type: "boolean",
      description: "Enable experimental LSP (Language Server Protocol) feature for code intelligence",
      default: false
    }).option("channel", {
      type: "string",
      choices: ["VSCode", "ACP", "SDK", "CI"],
      description: "Channel identifier (VSCode, ACP, SDK, CI)"
    }).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((m3) => m3.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((t5) => t5.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((e4) => e4.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((d2) => d2.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("input-format", {
      type: "string",
      choices: ["text", "stream-json"],
      description: "The format consumed from standard input.",
      default: "text"
    }).option("output-format", {
      alias: "o",
      type: "string",
      description: "The format of the CLI output.",
      choices: ["text", "json", "stream-json"]
    }).option("include-partial-messages", {
      type: "boolean",
      description: "Include partial assistant messages when using stream-json output.",
      default: false
    }).option("continue", {
      alias: "c",
      type: "boolean",
      description: "Resume the most recent session for the current project.",
      default: false
    }).option("resume", {
      alias: "r",
      type: "string",
      description: "Resume a specific session by its ID. Use without an ID to show session picker."
    }).option("session-id", {
      type: "string",
      description: "Specify a session ID for this run."
    }).option("max-session-turns", {
      type: "number",
      description: "Maximum number of session turns"
    }).option("core-tools", {
      type: "array",
      string: true,
      description: "Core tool paths",
      coerce: /* @__PURE__ */ __name((tools) => tools.flatMap((tool) => tool.split(",").map((t5) => t5.trim())), "coerce")
    }).option("exclude-tools", {
      type: "array",
      string: true,
      description: "Tools to exclude",
      coerce: /* @__PURE__ */ __name((tools) => tools.flatMap((tool) => tool.split(",").map((t5) => t5.trim())), "coerce")
    }).option("allowed-tools", {
      type: "array",
      string: true,
      description: "Tools to allow, will bypass confirmation",
      coerce: /* @__PURE__ */ __name((tools) => tools.flatMap((tool) => tool.split(",").map((t5) => t5.trim())), "coerce")
    }).option("auth-type", {
      type: "string",
      choices: [
        AuthType2.USE_OPENAI,
        AuthType2.USE_ANTHROPIC,
        AuthType2.QWEN_OAUTH,
        AuthType2.USE_GEMINI,
        AuthType2.USE_VERTEX_AI
      ],
      description: "Authentication type"
    }).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(
      "prompt",
      "Use the positional prompt instead. This flag will be removed in a future version."
    ).fail((msg, err, yargs) => {
      writeStderrLine(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.";
      }
      if (argv["includePartialMessages"] && argv["outputFormat"] !== OutputFormat.STREAM_JSON) {
        return "--include-partial-messages requires --output-format stream-json";
      }
      if (argv["inputFormat"] === "stream-json" && argv["outputFormat"] !== OutputFormat.STREAM_JSON) {
        return "--input-format stream-json requires --output-format stream-json";
      }
      if (argv["continue"] && argv["resume"]) {
        return "Cannot use both --continue and --resume together. Use --continue to resume the latest session, or --resume <sessionId> to resume a specific session.";
      }
      if (argv["sessionId"] && (argv["continue"] || argv["resume"])) {
        return "Cannot use --session-id with --continue or --resume. Use --session-id to start a new session with a specific ID, or use --continue/--resume to resume an existing session.";
      }
      if (argv["sessionId"] && !isValidUUID(argv["sessionId"])) {
        return `Invalid --session-id: "${argv["sessionId"]}". Must be a valid UUID (e.g., "123e4567-e89b-12d3-a456-426614174000").`;
      }
      if (argv["resume"] && !isValidUUID(argv["resume"])) {
        return `Invalid --resume: "${argv["resume"]}". Must be a valid UUID (e.g., "123e4567-e89b-12d3-a456-426614174000").`;
      }
      return true;
    })
  ).command(mcpCommand).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 q2 = Array.isArray(queryArg) ? queryArg.join(" ") : queryArg;
  if (q2 && !result["prompt"]) {
    const hasExplicitInteractive = result["promptInteractive"] === "" || !!result["promptInteractive"];
    if (hasExplicitInteractive) {
      result["promptInteractive"] = q2;
    } else {
      result["prompt"] = q2;
    }
  }
  result["query"] = q2 || void 0;
  if (result["experimentalAcp"]) {
    writeStderrLine(
      "\x1B[33m\u26A0 Warning: --experimental-acp is deprecated and will be removed in a future release. Please use --acp instead.\x1B[0m"
    );
    if (!result["acp"]) {
      result["acp"] = true;
    }
  }
  if ((result["acp"] || result["experimentalAcp"]) && !result["channel"]) {
    result["channel"] = "ACP";
  }
  return result;
}
__name(parseArguments, "parseArguments");
async function loadHierarchicalGeminiMemory(currentWorkingDirectory, includeDirectoriesToReadGemini = [], fileService, extensionContextFilePaths = [], folderTrust, memoryImportFormat = "tree") {
  const realCwd = fs81.realpathSync(path88.resolve(currentWorkingDirectory));
  const realHome = fs81.realpathSync(path88.resolve(homedir19()));
  const isHomeDirectory = realCwd === realHome;
  const effectiveCwd = isHomeDirectory ? "" : currentWorkingDirectory;
  return loadServerHierarchicalMemory(
    effectiveCwd,
    includeDirectoriesToReadGemini,
    fileService,
    extensionContextFilePaths,
    folderTrust,
    memoryImportFormat
  );
}
__name(loadHierarchicalGeminiMemory, "loadHierarchicalGeminiMemory");
function isDebugMode(argv) {
  return argv.debug || [process.env["DEBUG"], process.env["DEBUG_MODE"]].some(
    (v2) => v2 === "true" || v2 === "1"
  );
}
__name(isDebugMode, "isDebugMode");
async function loadCliConfig(settings, argv, cwd7 = process.cwd(), overrideExtensions) {
  const debugMode = isDebugMode(argv);
  const ideMode = settings.ide?.enabled ?? false;
  const folderTrust = settings.security?.folderTrust?.enabled ?? false;
  const trustedFolder = isWorkspaceTrusted(settings)?.isTrusted ?? true;
  if (settings.context?.fileName) {
    setGeminiMdFilename(settings.context.fileName);
  } else {
    setGeminiMdFilename(getCurrentGeminiMdFilename());
  }
  let outputLanguageFilePath = path88.join(
    Storage.getGlobalQwenDir(),
    "output-language.md"
  );
  if (fs81.existsSync(outputLanguageFilePath)) {
  } else {
    outputLanguageFilePath = void 0;
  }
  const fileService = new FileDiscoveryService(cwd7);
  const includeDirectories = (settings.context?.includeDirectories || []).map(resolvePath2).concat((argv.includeDirectories || []).map(resolvePath2));
  const lspEnabled = argv.experimentalLsp === true;
  let lspClient;
  const question = argv.promptInteractive || argv.prompt || "";
  const inputFormat = argv.inputFormat ?? InputFormat.TEXT;
  const argvOutputFormat = normalizeOutputFormat(
    argv.outputFormat
  );
  const settingsOutputFormat = normalizeOutputFormat(settings.output?.format);
  const outputFormat = argvOutputFormat ?? settingsOutputFormat ?? OutputFormat.TEXT;
  const outputSettingsFormat = outputFormat === OutputFormat.STREAM_JSON ? settingsOutputFormat && settingsOutputFormat !== OutputFormat.STREAM_JSON ? settingsOutputFormat : OutputFormat.TEXT : outputFormat;
  const includePartialMessages = Boolean(argv.includePartialMessages);
  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) {
    writeStderrLine(
      `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 hasPrompt = !!argv.prompt;
  let interactive;
  if (argv.promptInteractive) {
    interactive = true;
  } else if ((outputFormat === OutputFormat.STREAM_JSON || outputFormat === OutputFormat.JSON) && (hasQuery || hasPrompt)) {
    interactive = false;
  } else if (!hasQuery && !hasPrompt) {
    interactive = process.stdin.isTTY ?? false;
  } else {
    interactive = false;
  }
  const extraExcludes = [];
  const resolvedCoreTools = argv.coreTools || settings.tools?.core || [];
  const resolvedAllowedTools = argv.allowedTools || settings.tools?.allowed || [];
  const isExplicitlyEnabled = /* @__PURE__ */ __name((toolName) => {
    if (resolvedCoreTools.length > 0) {
      if (isToolEnabled(toolName, resolvedCoreTools, [])) {
        return true;
      }
    }
    if (resolvedAllowedTools.length > 0) {
      if (isToolEnabled(toolName, resolvedAllowedTools, [])) {
        return true;
      }
    }
    return false;
  }, "isExplicitlyEnabled");
  const excludeUnlessExplicit = /* @__PURE__ */ __name((toolName) => {
    if (!isExplicitlyEnabled(toolName)) {
      extraExcludes.push(toolName);
    }
  }, "excludeUnlessExplicit");
  const isAcpMode = argv.acp || argv.experimentalAcp;
  if (!interactive && !isAcpMode && inputFormat !== InputFormat.STREAM_JSON) {
    switch (approvalMode) {
      case ApprovalMode.PLAN:
      case ApprovalMode.DEFAULT:
        excludeUnlessExplicit(ShellTool.Name);
        excludeUnlessExplicit(EditTool.Name);
        excludeUnlessExplicit(WriteFileTool.Name);
        break;
      case ApprovalMode.AUTO_EDIT:
        excludeUnlessExplicit(ShellTool.Name);
        break;
      case ApprovalMode.YOLO:
        break;
      default:
        break;
    }
  }
  const excludeTools = mergeExcludeTools(
    settings,
    extraExcludes.length > 0 ? extraExcludes : void 0,
    argv.excludeTools
  );
  let allowedMcpServers;
  let excludedMcpServers;
  if (argv.allowedMcpServerNames) {
    allowedMcpServers = new Set(argv.allowedMcpServerNames.filter(Boolean));
    excludedMcpServers = void 0;
  } else {
    allowedMcpServers = settings.mcp?.allowed ? new Set(settings.mcp.allowed.filter(Boolean)) : void 0;
    excludedMcpServers = settings.mcp?.excluded ? new Set(settings.mcp.excluded.filter(Boolean)) : void 0;
  }
  const selectedAuthType = argv.authType || settings.security?.auth?.selectedType || /* getAuthTypeFromEnv means no authType was explicitly provided, we infer the authType from env vars */
  getAuthTypeFromEnv();
  const resolvedCliConfig = resolveCliGenerationConfig({
    argv: {
      model: argv.model,
      openaiApiKey: argv.openaiApiKey,
      openaiBaseUrl: argv.openaiBaseUrl,
      openaiLogging: argv.openaiLogging,
      openaiLoggingDir: argv.openaiLoggingDir
    },
    settings,
    selectedAuthType,
    env: process.env
  });
  const { model: resolvedModel } = resolvedCliConfig;
  const sandboxConfig = await loadSandboxConfig(settings, argv);
  const screenReader = argv.screenReader !== void 0 ? argv.screenReader : settings.ui?.accessibility?.screenReader ?? false;
  let sessionId;
  let sessionData;
  if (argv.continue || argv.resume) {
    const sessionService = new SessionService(cwd7);
    if (argv.continue) {
      sessionData = await sessionService.loadLastSession();
      if (sessionData) {
        sessionId = sessionData.conversation.sessionId;
      }
    }
    if (argv.resume) {
      sessionId = argv.resume;
      sessionData = await sessionService.loadSession(argv.resume);
      if (!sessionData) {
        const message = `No saved session found with ID ${argv.resume}. Run \`qwen --resume\` without an ID to choose from existing sessions.`;
        writeStderrLine(message);
        process.exit(1);
      }
    }
  } else if (argv["sessionId"]) {
    const sessionService = new SessionService(cwd7);
    const exists2 = await sessionService.sessionExists(argv["sessionId"]);
    if (exists2) {
      const message = `Error: Session Id ${argv["sessionId"]} is already in use.`;
      writeStderrLine(message);
      process.exit(1);
    }
    sessionId = argv["sessionId"];
  }
  const modelProvidersConfig = settings.modelProviders;
  const config2 = new Config({
    sessionId,
    sessionData,
    embeddingModel: DEFAULT_QWEN_EMBEDDING_MODEL,
    sandbox: sandboxConfig,
    targetDir: cwd7,
    includeDirectories,
    loadMemoryFromIncludeDirectories: settings.context?.loadFromIncludeDirectories || false,
    importFormat: settings.context?.importFormat || "tree",
    debugMode,
    question,
    coreTools: argv.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: settings.mcpServers || {},
    allowedMcpServers: allowedMcpServers ? Array.from(allowedMcpServers) : void 0,
    excludedMcpServers: excludedMcpServers ? Array.from(excludedMcpServers) : void 0,
    approvalMode,
    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,
    outputLanguageFilePath,
    sessionTokenLimit: settings.model?.sessionTokenLimit ?? -1,
    maxSessionTurns: argv.maxSessionTurns ?? settings.model?.maxSessionTurns ?? -1,
    experimentalZedIntegration: argv.acp || argv.experimentalAcp || false,
    listExtensions: argv.listExtensions || false,
    overrideExtensions: overrideExtensions || argv.extensions,
    noBrowser: !!process.env["NO_BROWSER"],
    authType: selectedAuthType,
    inputFormat,
    outputFormat,
    includePartialMessages,
    modelProvidersConfig,
    generationConfigSources: resolvedCliConfig.sources,
    generationConfig: resolvedCliConfig.generationConfig,
    warnings: resolvedCliConfig.warnings,
    cliVersion: await getCliVersion(),
    webSearch: buildWebSearchConfig(argv, settings, selectedAuthType),
    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,
    truncateToolOutputThreshold: settings.tools?.truncateToolOutputThreshold,
    truncateToolOutputLines: settings.tools?.truncateToolOutputLines,
    enableToolOutputTruncation: settings.tools?.enableToolOutputTruncation,
    eventEmitter: appEvents,
    gitCoAuthor: settings.general?.gitCoAuthor,
    output: {
      format: outputSettingsFormat
    },
    channel: argv.channel,
    // Precedence: explicit CLI flag > settings file > default(true).
    // NOTE: do NOT set a yargs default for `chat-recording`, otherwise argv will
    // always be true and the settings file can never disable recording.
    chatRecording: argv.chatRecording ?? settings.general?.chatRecording ?? true,
    defaultFileEncoding: settings.general?.defaultFileEncoding ?? FileEncoding.UTF8,
    lsp: {
      enabled: lspEnabled
    }
  });
  if (lspEnabled) {
    try {
      const lspService = new NativeLspService(
        config2,
        config2.getWorkspaceContext(),
        appEvents,
        fileService,
        ideContextStore,
        {
          requireTrustedWorkspace: folderTrust
        }
      );
      await lspService.discoverAndPrepare();
      await lspService.start();
      lspClient = new NativeLspClient(lspService);
      config2.setLspClient(lspClient);
    } catch (err) {
      debugLogger72.warn("Failed to initialize native LSP service:", err);
    }
  }
  return config2;
}
__name(loadCliConfig, "loadCliConfig");
function mergeExcludeTools(settings, extraExcludes, cliExcludeTools) {
  const allExcludeTools = /* @__PURE__ */ new Set([
    ...cliExcludeTools || [],
    ...settings.tools?.exclude || [],
    ...extraExcludes || []
  ]);
  return [...allExcludeTools];
}
__name(mergeExcludeTools, "mergeExcludeTools");

// packages/cli/src/core/initializer.ts
init_esbuild_shims();

// packages/cli/src/core/auth.ts
init_esbuild_shims();
async function performInitialAuth(config2, authType) {
  if (!authType) {
    return null;
  }
  try {
    await config2.refreshAuth(authType, true);
    const authEvent = new AuthEvent(authType, "auto", "success");
    logAuth(config2, authEvent);
  } catch (e4) {
    const errorMessage = `Failed to login. Message: ${getErrorMessage(e4)}`;
    const authEvent = new AuthEvent(authType, "auto", "error", errorMessage);
    logAuth(config2, authEvent);
    return errorMessage;
  }
  return null;
}
__name(performInitialAuth, "performInitialAuth");

// packages/cli/src/core/theme.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();
var ayuDarkColors = {
  type: "dark",
  Background: "#0b0e14",
  Foreground: "#aeaca6",
  LightBlue: "#59C2FF",
  AccentBlue: "#39BAE6",
  AccentPurple: "#D2A6FF",
  AccentCyan: "#95E6CB",
  AccentGreen: "#AAD94C",
  AccentYellow: "#FFB454",
  AccentRed: "#F26D78",
  AccentYellowDim: "#8B7530",
  AccentRedDim: "#8B3A4A",
  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",
  AccentYellowDim: "#8B7000",
  AccentRedDim: "#993333",
  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",
  AccentYellowDim: "#8B7530",
  AccentRedDim: "#8B3A4A",
  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",
  AccentYellowDim: "#8B7530",
  AccentRedDim: "#8B3A4A",
  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",
  AccentYellowDim: "#8B7530",
  AccentRedDim: "#8B3A4A",
  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",
  AccentYellowDim: "#8B7000",
  AccentRedDim: "#993333",
  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",
  AccentYellowDim: "#8B7000",
  AccentRedDim: "#993333",
  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/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
  AccentYellowDim: "#8B7530",
  AccentRedDim: "#8B3A4A",
  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",
  AccentYellowDim: "#8B7000",
  AccentRedDim: "#993333",
  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,
    errorDim: lightTheme.AccentRedDim,
    warningDim: lightTheme.AccentYellowDim
  }
};
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,
    errorDim: darkTheme.AccentRedDim,
    warningDim: darkTheme.AccentYellowDim
  }
};
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,
    errorDim: ansiTheme.AccentRedDim,
    warningDim: ansiTheme.AccentYellowDim
  }
};

// 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",
  AccentYellowDim: "#8B7000",
  AccentRedDim: "#993333",
  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",
  AccentYellowDim: "#8B7530",
  AccentRedDim: "#8B3A4A",
  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 fs82 from "node:fs";
import * as path89 from "node:path";
import * as os28 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",
  AccentYellowDim: "yellow",
  AccentRedDim: "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",
  AccentYellowDim: "orange",
  AccentRedDim: "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: "",
  AccentYellowDim: "",
  AccentRedDim: "",
  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: "",
    errorDim: "",
    warningDim: ""
  }
};
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 process29 from "node:process";
var debugLogger73 = createDebugLogger("THEME_MANAGER");
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) {
          debugLogger73.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 (error2) {
          debugLogger73.warn(`Failed to load custom theme "${name3}":`, error2);
        }
      } else {
        debugLogger73.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 (process29.env["NO_COLOR"]) {
      return NoColorTheme;
    }
    if (this.activeTheme) {
      const isBuiltIn = this.availableThemes.some(
        (t5) => t5.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(
      (a2, b2) => {
        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(a2.type) - typeOrder(b2.type);
        if (typeComparison !== 0) {
          return typeComparison;
        }
        return a2.name.localeCompare(b2.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(".") || path89.isAbsolute(themeName);
  }
  loadThemeFromFile(themePath) {
    try {
      const canonicalPath = fs82.realpathSync(path89.resolve(themePath));
      if (this.customThemes.has(canonicalPath)) {
        return this.customThemes.get(canonicalPath);
      }
      const homeDir = path89.resolve(os28.homedir());
      if (!canonicalPath.startsWith(homeDir)) {
        debugLogger73.warn(
          `Theme file at "${themePath}" is outside your home directory. Only load themes from trusted sources.`
        );
        return void 0;
      }
      const themeContent = fs82.readFileSync(canonicalPath, "utf-8");
      const customThemeConfig = JSON.parse(themeContent);
      const validation2 = validateCustomTheme(customThemeConfig);
      if (!validation2.isValid) {
        debugLogger73.warn(
          `Invalid custom theme from file "${themePath}": ${validation2.error}`
        );
        return void 0;
      }
      if (validation2.warning) {
        debugLogger73.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 (error2) {
      if (!(error2 instanceof Error && "code" in error2 && error2.code === "ENOENT")) {
        debugLogger73.warn(
          `Could not load theme from file "${themePath}":`,
          error2
        );
      }
      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/core/theme.ts
function validateTheme(settings) {
  const effectiveTheme = settings.merged.ui?.theme;
  if (effectiveTheme && !themeManager.findThemeByName(effectiveTheme)) {
    return t4('Theme "{{themeName}}" not found.', {
      themeName: effectiveTheme
    });
  }
  return null;
}
__name(validateTheme, "validateTheme");

// packages/cli/src/core/initializer.ts
async function initializeApp(config2, settings) {
  const languageSetting = process.env["QWEN_CODE_LANG"] || settings.merged.general?.language || "auto";
  await initializeI18n(languageSetting);
  const authType = config2.getModelsConfig().getCurrentAuthType();
  const authError = await performInitialAuth(config2, authType);
  if (authError) {
    settings.setValue(
      "User" /* User */,
      "security.auth.selectedType",
      void 0
    );
  }
  const themeError = validateTheme(settings);
  const shouldOpenAuthDialog = !config2.getModelsConfig().wasAuthTypeExplicitlyProvided() || !!authError;
  if (config2.getIdeMode()) {
    const ideClient = await IdeClient.getInstance();
    await ideClient.connect();
    logIdeConnection(config2, new IdeConnectionEvent(IdeConnectionType.START));
  }
  return {
    authError,
    themeError,
    shouldOpenAuthDialog,
    geminiMdFileCount: config2.getGeminiMdFileCount()
  };
}
__name(initializeApp, "initializeApp");

// packages/cli/src/nonInteractiveCli.ts
init_esbuild_shims();

// packages/cli/src/ui/utils/commandUtils.ts
init_esbuild_shims();
import { spawn as spawn8 } 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 debugLogger74 = createDebugLogger("COMMAND_UTILS");
var copyToClipboard = /* @__PURE__ */ __name(async (text) => {
  const run = /* @__PURE__ */ __name((cmd, args, options2) => new Promise((resolve30, reject) => {
    const child = options2 ? spawn8(cmd, args, options2) : spawn8(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 resolve30();
      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";
      debugLogger74.warn(
        `Unknown platform: ${process.platform}. Attempting to open URLs with: ${openCmd}.`
      );
      break;
  }
  return openCmd;
}, "getUrlOpenCommand");

// packages/cli/src/nonInteractive/io/JsonOutputAdapter.ts
init_esbuild_shims();

// packages/cli/src/nonInteractive/io/BaseJsonOutputAdapter.ts
init_esbuild_shims();
import { randomUUID as randomUUID7 } from "node:crypto";

// packages/cli/src/utils/nonInteractiveHelpers.ts
init_esbuild_shims();

// 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/nonInteractiveCliCommands.ts
init_esbuild_shims();

// packages/cli/src/utils/commands.ts
init_esbuild_shims();

// packages/cli/src/ui/commands/types.ts
init_esbuild_shims();

// packages/cli/src/utils/commands.ts
var parseSlashCommand = /* @__PURE__ */ __name((query, commands) => {
  const trimmed2 = query.trim();
  const parts = trimmed2.substring(1).trim().split(/\s+/);
  const commandPath = parts.filter((p2) => p2);
  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/services/CommandService.ts
init_esbuild_shims();
var debugLogger75 = createDebugLogger("CLI_COMMANDS");
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 {
        debugLogger75.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/ui/types.ts
init_esbuild_shims();
var import_react26 = __toESM(require_react(), 1);

// packages/cli/src/utils/systemInfo.ts
init_esbuild_shims();
import process30 from "node:process";
import os29 from "node:os";
import { execSync as execSync5 } from "node:child_process";

// 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 formatRelativeTime = /* @__PURE__ */ __name((timestamp) => {
  const now = Date.now();
  const diffMs = now - timestamp;
  const seconds = Math.floor(diffMs / 1e3);
  const minutes = Math.floor(seconds / 60);
  const hours = Math.floor(minutes / 60);
  const days = Math.floor(hours / 24);
  const weeks = Math.floor(days / 7);
  const months = Math.floor(days / 30);
  if (months > 0) {
    return months === 1 ? "1 month ago" : `${months} months ago`;
  }
  if (weeks > 0) {
    return weeks === 1 ? "1 week ago" : `${weeks} weeks ago`;
  }
  if (days > 0) {
    return days === 1 ? "1 day ago" : `${days} days ago`;
  }
  if (hours > 0) {
    return hours === 1 ? "1 hour ago" : `${hours} hours ago`;
  }
  if (minutes > 0) {
    return minutes === 1 ? "1 minute ago" : `${minutes} minutes ago`;
  }
  return "just now";
}, "formatRelativeTime");
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/generated/git-commit.ts
init_esbuild_shims();
var GIT_COMMIT_INFO = "a31cf757";

// packages/cli/src/utils/systemInfo.ts
async function getNpmVersion() {
  try {
    return execSync5("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 = process30.env["SANDBOX"];
  if (!sandbox || sandbox === "sandbox-exec") {
    if (sandbox === "sandbox-exec") {
      const profile = process30.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 = process30.platform;
  const osArch = process30.arch;
  const osRelease = os29.release();
  const nodeVersion2 = process30.version;
  const npmVersion = await getNpmVersion();
  const sandboxEnv = getSandboxEnv();
  const modelVersion = context2.services.config?.getModel() || "Unknown";
  const cliVersion = await getCliVersion();
  const selectedAuthType = context2.services.config?.getAuthType() || "";
  const ideClient = await getIdeClientName(context2);
  const sessionId = context2.services.config?.getSessionId() || "unknown";
  const proxy = context2.services.config?.getProxy();
  return {
    cliVersion,
    osPlatform,
    osArch,
    osRelease,
    nodeVersion: nodeVersion2,
    npmVersion,
    sandboxEnv,
    modelVersion,
    selectedAuthType,
    ideClient,
    sessionId,
    proxy
  };
}
__name(getSystemInfo, "getSystemInfo");
async function getExtendedSystemInfo(context2) {
  const baseInfo = await getSystemInfo(context2);
  const memoryUsage = formatMemoryUsage2(process30.memoryUsage().rss);
  const sandboxEnv = getSandboxEnv(true);
  const baseUrl = baseInfo.selectedAuthType === AuthType2.USE_OPENAI || baseInfo.selectedAuthType === AuthType2.USE_ANTHROPIC ? context2.services.config?.getContentGeneratorConfig()?.baseUrl : void 0;
  const gitCommit = GIT_COMMIT_INFO && !["N/A"].includes(GIT_COMMIT_INFO) ? GIT_COMMIT_INFO : void 0;
  return {
    ...baseInfo,
    sandboxEnv,
    memoryUsage,
    baseUrl,
    gitCommit
  };
}
__name(getExtendedSystemInfo, "getExtendedSystemInfo");

// packages/cli/src/ui/commands/aboutCommand.ts
var aboutCommand = {
  name: "status",
  altNames: ["about"],
  get description() {
    return t4("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",
  get description() {
    return t4("Manage subagents for specialized task delegation.");
  },
  kind: "built-in" /* BUILT_IN */,
  subCommands: [
    {
      name: "manage",
      get description() {
        return t4("Manage existing subagents (view, edit, delete).");
      },
      kind: "built-in" /* BUILT_IN */,
      action: /* @__PURE__ */ __name(() => ({
        type: "dialog",
        dialog: "subagent_list"
      }), "action")
    },
    {
      name: "create",
      get description() {
        return t4("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();
function parseApprovalModeArg(arg) {
  const trimmed2 = arg.trim().toLowerCase();
  if (!trimmed2) {
    return void 0;
  }
  return APPROVAL_MODES.find((mode) => mode.toLowerCase() === trimmed2);
}
__name(parseApprovalModeArg, "parseApprovalModeArg");
var approvalModeCommand = {
  name: "approval-mode",
  get description() {
    return t4("View or change the approval mode for tool usage");
  },
  kind: "built-in" /* BUILT_IN */,
  action: /* @__PURE__ */ __name(async (context2, args) => {
    const mode = parseApprovalModeArg(args);
    if (!args.trim()) {
      return {
        type: "dialog",
        dialog: "approval-mode"
      };
    }
    if (!mode) {
      return {
        type: "message",
        messageType: "error",
        content: t4('Invalid approval mode "{{arg}}". Valid modes: {{modes}}', {
          arg: args.trim(),
          modes: APPROVAL_MODES.join(", ")
        })
      };
    }
    const { config: config2 } = context2.services;
    if (config2) {
      try {
        config2.setApprovalMode(mode);
      } catch (e4) {
        return {
          type: "message",
          messageType: "error",
          content: e4.message
        };
      }
    }
    return {
      type: "message",
      messageType: "info",
      content: t4('Approval mode set to "{{mode}}"', { mode })
    };
  }, "action")
};

// packages/cli/src/ui/commands/authCommand.ts
init_esbuild_shims();
var authCommand = {
  name: "auth",
  altNames: ["login"],
  get description() {
    return t4("Configure authentication information for login");
  },
  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();

// packages/cli/src/utils/systemInfoFields.ts
init_esbuild_shims();
function getSystemInfoFields(info) {
  const fields = [];
  addField(fields, t4("Qwen Code"), formatCliVersion(info));
  addField(fields, t4("Runtime"), formatRuntime(info));
  addField(fields, t4("IDE Client"), info.ideClient);
  addField(fields, t4("OS"), formatOs(info));
  addField(fields, t4("Auth"), formatAuth(info));
  addField(fields, t4("Model"), info.modelVersion);
  addField(fields, t4("Session ID"), info.sessionId);
  addField(fields, t4("Sandbox"), info.sandboxEnv);
  addField(fields, t4("Proxy"), formatProxy(info.proxy));
  addField(fields, t4("Memory Usage"), info.memoryUsage);
  return fields;
}
__name(getSystemInfoFields, "getSystemInfoFields");
function addField(fields, label, value) {
  if (value) {
    fields.push({ label, value });
  }
}
__name(addField, "addField");
function formatCliVersion(info) {
  if (!info.cliVersion) {
    return "";
  }
  if (!info.gitCommit) {
    return info.cliVersion;
  }
  return `${info.cliVersion} (${info.gitCommit})`;
}
__name(formatCliVersion, "formatCliVersion");
function formatRuntime(info) {
  if (!info.nodeVersion && !info.npmVersion) {
    return "";
  }
  const node = info.nodeVersion ? `Node.js ${info.nodeVersion}` : "";
  const npm = info.npmVersion ? `npm ${info.npmVersion}` : "";
  return joinParts([node, npm], " / ");
}
__name(formatRuntime, "formatRuntime");
function formatOs(info) {
  return joinParts(
    [info.osPlatform, info.osArch, formatOsRelease(info.osRelease)],
    " "
  ).trim();
}
__name(formatOs, "formatOs");
function formatOsRelease(release3) {
  if (!release3) {
    return "";
  }
  return `(${release3})`;
}
__name(formatOsRelease, "formatOsRelease");
function formatAuth(info) {
  if (!info.selectedAuthType) {
    return "";
  }
  const authType = formatAuthType(info.selectedAuthType);
  if (!info.baseUrl) {
    return authType;
  }
  return `${authType} (${info.baseUrl})`;
}
__name(formatAuth, "formatAuth");
function formatAuthType(authType) {
  return authType.startsWith("oauth") ? "OAuth" : authType;
}
__name(formatAuthType, "formatAuthType");
function formatProxy(proxy) {
  if (!proxy) {
    return "no proxy";
  }
  return redactProxy(proxy);
}
__name(formatProxy, "formatProxy");
function redactProxy(proxy) {
  try {
    const url2 = new URL(proxy);
    if (url2.username || url2.password) {
      url2.username = url2.username ? "***" : "";
      url2.password = url2.password ? "***" : "";
    }
    return url2.toString();
  } catch {
    return proxy.replace(/\/\/[^/]*@/, "//***@");
  }
}
__name(redactProxy, "redactProxy");
function joinParts(parts, separator) {
  return parts.filter((part) => part).join(separator);
}
__name(joinParts, "joinParts");

// packages/cli/src/ui/commands/bugCommand.ts
var bugCommand = {
  name: "bug",
  get description() {
    return t4("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);
    const info = fields.map((field) => `${field.label}: ${field.value}`).join("\n");
    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 (error2) {
      const errorMessage = error2 instanceof Error ? error2.message : String(error2);
      context2.ui.addItem(
        {
          type: "error" /* ERROR */,
          text: `Could not open URL in browser: ${errorMessage}`
        },
        Date.now()
      );
    }
  }, "action")
};

// packages/cli/src/ui/commands/clearCommand.ts
init_esbuild_shims();
var clearCommand = {
  name: "clear",
  altNames: ["reset", "new"],
  get description() {
    return t4("Clear conversation history and free up context");
  },
  kind: "built-in" /* BUILT_IN */,
  action: /* @__PURE__ */ __name(async (context2, _args) => {
    const { config: config2 } = context2.services;
    if (config2) {
      const newSessionId = config2.startNewSession();
      uiTelemetryService.reset();
      if (newSessionId && context2.session.startNewSession) {
        context2.session.startNewSession(newSessionId);
      }
      const geminiClient = config2.getGeminiClient();
      if (geminiClient) {
        context2.ui.setDebugMessage(
          t4("Starting a new session, resetting chat, and clearing terminal.")
        );
        await geminiClient.resetChat();
      } else {
        context2.ui.setDebugMessage(t4("Starting a new session and clearing."));
      }
    } else {
      context2.ui.setDebugMessage(t4("Starting a new session and clearing."));
    }
    context2.ui.clear();
  }, "action")
};

// packages/cli/src/ui/commands/compressCommand.ts
init_esbuild_shims();
var compressCommand = {
  name: "compress",
  altNames: ["summarize"],
  get description() {
    return t4("Compresses the context by replacing it with a summary.");
  },
  kind: "built-in" /* BUILT_IN */,
  action: /* @__PURE__ */ __name(async (context2) => {
    const { ui: ui2 } = context2;
    const executionMode = context2.executionMode ?? "interactive";
    const abortSignal = context2.abortSignal;
    if (executionMode === "interactive" && ui2.pendingItem) {
      ui2.addItem(
        {
          type: "error" /* ERROR */,
          text: t4("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
      }
    };
    const config2 = context2.services.config;
    const geminiClient = config2?.getGeminiClient();
    if (!config2 || !geminiClient) {
      return {
        type: "message",
        messageType: "error",
        content: t4("Config not loaded.")
      };
    }
    const doCompress = /* @__PURE__ */ __name(async () => {
      const promptId = `compress-${Date.now()}`;
      return await geminiClient.tryCompressChat(promptId, true);
    }, "doCompress");
    if (executionMode === "acp") {
      const messages = /* @__PURE__ */ __name(async function* () {
        try {
          yield {
            messageType: "info",
            content: "Compressing context..."
          };
          const compressed = await doCompress();
          if (!compressed) {
            yield {
              messageType: "error",
              content: t4("Failed to compress chat history.")
            };
            return;
          }
          yield {
            messageType: "info",
            content: `Context compressed (${compressed.originalTokenCount} -> ${compressed.newTokenCount}).`
          };
        } catch (e4) {
          yield {
            messageType: "error",
            content: t4("Failed to compress chat history: {{error}}", {
              error: e4 instanceof Error ? e4.message : String(e4)
            })
          };
        }
      }, "messages");
      return { type: "stream_messages", messages: messages() };
    }
    try {
      if (executionMode === "interactive") {
        ui2.setPendingItem(pendingMessage);
      }
      const compressed = await doCompress();
      if (abortSignal?.aborted) {
        return;
      }
      if (!compressed) {
        if (executionMode === "interactive") {
          ui2.addItem(
            {
              type: "error" /* ERROR */,
              text: t4("Failed to compress chat history.")
            },
            Date.now()
          );
          return;
        }
        return {
          type: "message",
          messageType: "error",
          content: t4("Failed to compress chat history.")
        };
      }
      if (executionMode === "interactive") {
        ui2.addItem(
          {
            type: "compression" /* COMPRESSION */,
            compression: {
              isPending: false,
              originalTokenCount: compressed.originalTokenCount,
              newTokenCount: compressed.newTokenCount,
              compressionStatus: compressed.compressionStatus
            }
          },
          Date.now()
        );
        return;
      }
      return {
        type: "message",
        messageType: "info",
        content: `Context compressed (${compressed.originalTokenCount} -> ${compressed.newTokenCount}).`
      };
    } catch (e4) {
      if (abortSignal?.aborted) {
        return;
      }
      if (executionMode === "interactive") {
        ui2.addItem(
          {
            type: "error" /* ERROR */,
            text: t4("Failed to compress chat history: {{error}}", {
              error: e4 instanceof Error ? e4.message : String(e4)
            })
          },
          Date.now()
        );
        return;
      }
      return {
        type: "message",
        messageType: "error",
        content: t4("Failed to compress chat history: {{error}}", {
          error: e4 instanceof Error ? e4.message : String(e4)
        })
      };
    } finally {
      if (executionMode === "interactive") {
        ui2.setPendingItem(null);
      }
    }
  }, "action")
};

// packages/cli/src/ui/commands/copyCommand.ts
init_esbuild_shims();
var copyCommand = {
  name: "copy",
  get description() {
    return t4("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 (error2) {
        const message = error2 instanceof Error ? error2.message : String(error2);
        context2.services.config?.getDebugLogger().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/docsCommand.ts
init_esbuild_shims();
init_open();
import process31 from "node:process";
var docsCommand = {
  name: "docs",
  get description() {
    return t4("open full Qwen Code documentation in your browser");
  },
  kind: "built-in" /* BUILT_IN */,
  action: /* @__PURE__ */ __name(async (context2) => {
    const langPath = getCurrentLanguage()?.startsWith("zh") ? "zh" : "en";
    const docsUrl = `https://qwenlm.github.io/qwen-code-docs/${langPath}`;
    if (process31.env["SANDBOX"] && process31.env["SANDBOX"] !== "sandbox-exec") {
      context2.ui.addItem(
        {
          type: "info" /* INFO */,
          text: t4(
            "Please open the following URL in your browser to view the documentation:\n{{url}}",
            {
              url: docsUrl
            }
          )
        },
        Date.now()
      );
    } else {
      context2.ui.addItem(
        {
          type: "info" /* INFO */,
          text: t4("Opening documentation in your browser: {{url}}", {
            url: 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 path90 from "node:path";
function expandHomeDir(p2) {
  if (!p2) {
    return "";
  }
  let expandedPath = p2;
  if (p2.toLowerCase().startsWith("%userprofile%")) {
    expandedPath = os30.homedir() + p2.substring("%userprofile%".length);
  } else if (p2 === "~" || p2.startsWith("~/")) {
    expandedPath = os30.homedir() + p2.substring(1);
  }
  return path90.normalize(expandedPath);
}
__name(expandHomeDir, "expandHomeDir");
var directoryCommand = {
  name: "directory",
  altNames: ["dir"],
  get description() {
    return t4("Manage workspace directories");
  },
  kind: "built-in" /* BUILT_IN */,
  subCommands: [
    {
      name: "add",
      get description() {
        return t4(
          "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: config2 }
        } = context2;
        const [...rest] = args.split(" ");
        if (!config2) {
          addItem(
            {
              type: "error" /* ERROR */,
              text: t4("Configuration is not available.")
            },
            Date.now()
          );
          return;
        }
        const workspaceContext = config2.getWorkspaceContext();
        const pathsToAdd = rest.join(" ").split(",").filter((p2) => p2);
        if (pathsToAdd.length === 0) {
          addItem(
            {
              type: "error" /* ERROR */,
              text: t4("Please provide at least one path to add.")
            },
            Date.now()
          );
          return;
        }
        if (config2.isRestrictiveSandbox()) {
          return {
            type: "message",
            messageType: "error",
            content: t4(
              "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 (e4) {
            const error2 = e4;
            errors.push(
              t4("Error adding '{{path}}': {{error}}", {
                path: pathToAdd.trim(),
                error: error2.message
              })
            );
          }
        }
        try {
          if (config2.shouldLoadMemoryFromIncludeDirectories()) {
            const { memoryContent, fileCount } = await loadServerHierarchicalMemory(
              config2.getWorkingDir(),
              [
                ...config2.getWorkspaceContext().getDirectories(),
                ...pathsToAdd
              ],
              config2.getFileService(),
              config2.getExtensionContextFilePaths(),
              config2.getFolderTrust(),
              context2.services.settings.merged.context?.importFormat || "tree"
              // Use setting or default to 'tree'
            );
            config2.setUserMemory(memoryContent);
            config2.setGeminiMdFileCount(fileCount);
            context2.ui.setGeminiMdFileCount(fileCount);
          }
          addItem(
            {
              type: "info" /* INFO */,
              text: t4(
                "Successfully added QWEN.md files from the following directories if there are:\n- {{directories}}",
                {
                  directories: added.join("\n- ")
                }
              )
            },
            Date.now()
          );
        } catch (error2) {
          errors.push(
            t4("Error refreshing memory: {{error}}", {
              error: error2.message
            })
          );
        }
        if (added.length > 0) {
          const gemini = config2.getGeminiClient();
          if (gemini) {
            await gemini.addDirectoryContext();
          }
          addItem(
            {
              type: "info" /* INFO */,
              text: t4("Successfully added directories:\n- {{directories}}", {
                directories: added.join("\n- ")
              })
            },
            Date.now()
          );
        }
        if (errors.length > 0) {
          addItem(
            { type: "error" /* ERROR */, text: errors.join("\n") },
            Date.now()
          );
        }
        return;
      }, "action")
    },
    {
      name: "show",
      get description() {
        return t4("Show all directories in the workspace");
      },
      kind: "built-in" /* BUILT_IN */,
      action: /* @__PURE__ */ __name(async (context2) => {
        const {
          ui: { addItem },
          services: { config: config2 }
        } = context2;
        if (!config2) {
          addItem(
            {
              type: "error" /* ERROR */,
              text: t4("Configuration is not available.")
            },
            Date.now()
          );
          return;
        }
        const workspaceContext = config2.getWorkspaceContext();
        const directories = workspaceContext.getDirectories();
        const directoryList = directories.map((dir) => `- ${dir}`).join("\n");
        addItem(
          {
            type: "info" /* INFO */,
            text: t4("Current workspace directories:\n{{directories}}", {
              directories: directoryList
            })
          },
          Date.now()
        );
      }, "action")
    }
  ]
};

// packages/cli/src/ui/commands/editorCommand.ts
init_esbuild_shims();
var editorCommand = {
  name: "editor",
  get description() {
    return t4("set external editor preference");
  },
  kind: "built-in" /* BUILT_IN */,
  action: /* @__PURE__ */ __name(() => ({
    type: "dialog",
    dialog: "editor"
  }), "action")
};

// packages/cli/src/ui/commands/exportCommand.ts
init_esbuild_shims();
import * as fs83 from "node:fs/promises";
import path91 from "node:path";

// packages/cli/src/ui/utils/export/index.ts
init_esbuild_shims();

// packages/cli/src/ui/utils/export/collect.ts
init_esbuild_shims();
import { randomUUID as randomUUID6 } from "node:crypto";

// packages/cli/src/acp-integration/session/HistoryReplayer.ts
init_esbuild_shims();

// packages/cli/src/acp-integration/session/emitters/MessageEmitter.ts
init_esbuild_shims();

// packages/cli/src/acp-integration/session/emitters/BaseEmitter.ts
init_esbuild_shims();
var BaseEmitter = class {
  constructor(ctx) {
    this.ctx = ctx;
  }
  static {
    __name(this, "BaseEmitter");
  }
  /**
   * Converts an ISO timestamp string or epoch ms to epoch ms number.
   * Returns undefined if the input is not a valid timestamp.
   */
  static toEpochMs(ts) {
    if (typeof ts === "number") {
      return Number.isFinite(ts) ? ts : void 0;
    }
    if (typeof ts === "string") {
      const ms = new Date(ts).getTime();
      return Number.isFinite(ms) ? ms : void 0;
    }
    return void 0;
  }
  /**
   * Sends a session update to the ACP client.
   */
  async sendUpdate(update2) {
    return this.ctx.sendUpdate(update2);
  }
  /**
   * Gets the session configuration.
   */
  get config() {
    return this.ctx.config;
  }
  /**
   * Gets the session ID.
   */
  get sessionId() {
    return this.ctx.sessionId;
  }
};

// packages/cli/src/acp-integration/session/emitters/MessageEmitter.ts
var MessageEmitter = class extends BaseEmitter {
  static {
    __name(this, "MessageEmitter");
  }
  /**
   * Emits a user message chunk.
   *
   * @param text - The user message text content
   * @param timestamp - Optional server-side timestamp (ISO string or ms) for message ordering
   */
  async emitUserMessage(text, timestamp) {
    const epochMs = BaseEmitter.toEpochMs(timestamp);
    await this.sendUpdate({
      sessionUpdate: "user_message_chunk",
      content: { type: "text", text },
      ...epochMs != null && { _meta: { timestamp: epochMs } }
    });
  }
  /**
   * Emits an agent thought chunk.
   *
   * @param text - The thought text content
   * @param timestamp - Optional server-side timestamp (ISO string or ms) for message ordering
   */
  async emitAgentThought(text, timestamp) {
    const epochMs = BaseEmitter.toEpochMs(timestamp);
    await this.sendUpdate({
      sessionUpdate: "agent_thought_chunk",
      content: { type: "text", text },
      ...epochMs != null && { _meta: { timestamp: epochMs } }
    });
  }
  /**
   * Emits an agent message chunk.
   *
   * @param text - The agent message text content
   * @param timestamp - Optional server-side timestamp (ISO string or ms) for message ordering
   */
  async emitAgentMessage(text, timestamp) {
    const epochMs = BaseEmitter.toEpochMs(timestamp);
    await this.sendUpdate({
      sessionUpdate: "agent_message_chunk",
      content: { type: "text", text },
      ...epochMs != null && { _meta: { timestamp: epochMs } }
    });
  }
  /**
   * Emits usage metadata.
   */
  async emitUsageMetadata(usageMetadata, text = "", durationMs, subagentMeta) {
    const usage2 = {
      promptTokens: usageMetadata.promptTokenCount,
      completionTokens: usageMetadata.candidatesTokenCount,
      thoughtsTokens: usageMetadata.thoughtsTokenCount,
      totalTokens: usageMetadata.totalTokenCount,
      cachedTokens: usageMetadata.cachedContentTokenCount
    };
    const meta = typeof durationMs === "number" ? { usage: usage2, durationMs, ...subagentMeta } : { usage: usage2, ...subagentMeta };
    await this.sendUpdate({
      sessionUpdate: "agent_message_chunk",
      content: { type: "text", text },
      _meta: meta
    });
  }
  /**
   * Emits a message chunk based on role and thought flag.
   * This is the unified method that handles all message types.
   *
   * @param text - The message text content
   * @param role - Whether this is a user or assistant message
   * @param isThought - Whether this is an assistant thought (only applies to assistant role)
   * @param timestamp - Optional server-side timestamp (ISO string or ms) for message ordering
   */
  async emitMessage(text, role, isThought = false, timestamp) {
    if (role === "user") {
      return this.emitUserMessage(text, timestamp);
    }
    return isThought ? this.emitAgentThought(text, timestamp) : this.emitAgentMessage(text, timestamp);
  }
};

// packages/cli/src/acp-integration/session/emitters/ToolCallEmitter.ts
init_esbuild_shims();

// packages/cli/src/acp-integration/session/emitters/PlanEmitter.ts
init_esbuild_shims();
var PlanEmitter = class extends BaseEmitter {
  static {
    __name(this, "PlanEmitter");
  }
  /**
   * Emits a plan update with the given todo items.
   *
   * @param todos - Array of todo items to send as plan entries
   */
  async emitPlan(todos) {
    const entries = todos.map((todo) => ({
      content: todo.content,
      priority: "medium",
      // Default priority since todos don't have priority
      status: todo.status
    }));
    await this.sendUpdate({
      sessionUpdate: "plan",
      entries
    });
  }
  /**
   * Extracts todos from tool result display or args.
   * Tries multiple sources in priority order:
   * 1. Result display object with type 'todo_list'
   * 2. Result display as JSON string
   * 3. Args with 'todos' array
   *
   * @param resultDisplay - The tool result display (object, string, or undefined)
   * @param args - The tool call arguments (fallback source)
   * @returns Array of todos if found, null otherwise
   */
  extractTodos(resultDisplay, args) {
    const fromDisplay = this.extractFromResultDisplay(resultDisplay);
    if (fromDisplay) return fromDisplay;
    if (args && Array.isArray(args["todos"])) {
      return args["todos"];
    }
    return null;
  }
  /**
   * Extracts todos from a result display value.
   * Handles both object and JSON string formats.
   */
  extractFromResultDisplay(resultDisplay) {
    if (!resultDisplay) return null;
    if (typeof resultDisplay === "object") {
      const obj = resultDisplay;
      if (obj["type"] === "todo_list" && Array.isArray(obj["todos"])) {
        return obj["todos"];
      }
    }
    if (typeof resultDisplay === "string") {
      try {
        const parsed = JSON.parse(resultDisplay);
        if (parsed?.["type"] === "todo_list" && Array.isArray(parsed["todos"])) {
          return parsed["todos"];
        }
      } catch {
      }
    }
    return null;
  }
};

// packages/cli/src/acp-integration/session/emitters/ToolCallEmitter.ts
var ToolCallEmitter = class extends BaseEmitter {
  static {
    __name(this, "ToolCallEmitter");
  }
  planEmitter;
  constructor(ctx) {
    super(ctx);
    this.planEmitter = new PlanEmitter(ctx);
  }
  /**
   * Emits a tool call start event.
   *
   * @param params - Tool call start parameters
   * @returns true if event was emitted, false if skipped (e.g., TodoWriteTool)
   */
  async emitStart(params) {
    if (this.isTodoWriteTool(params.toolName)) {
      return false;
    }
    const { title, locations, kind: kind2 } = this.resolveToolMetadata(
      params.toolName,
      params.args
    );
    await this.sendUpdate({
      sessionUpdate: "tool_call",
      toolCallId: params.callId,
      status: params.status || "pending",
      title,
      content: [],
      locations,
      kind: kind2,
      rawInput: params.args ?? {},
      _meta: {
        toolName: params.toolName,
        ...params.subagentMeta,
        ...BaseEmitter.toEpochMs(params.timestamp) != null && {
          timestamp: BaseEmitter.toEpochMs(params.timestamp)
        }
      }
    });
    return true;
  }
  /**
   * Emits a tool call result event.
   * Handles TodoWriteTool specially by routing to plan updates.
   *
   * @param params - Tool call result parameters
   */
  async emitResult(params) {
    if (this.isTodoWriteTool(params.toolName)) {
      const todos = this.planEmitter.extractTodos(
        params.resultDisplay,
        params.args
      );
      if (todos && todos.length > 0) {
        await this.planEmitter.emitPlan(todos);
      } else if (params.args && Array.isArray(params.args["todos"])) {
        await this.planEmitter.emitPlan([]);
      }
      return;
    }
    let contentArray = [];
    const diffContent = this.extractDiffContent(params.resultDisplay);
    if (diffContent) {
      contentArray = [diffContent];
    } else if (params.error) {
      contentArray = [
        {
          type: "content",
          content: { type: "text", text: params.error.message }
        }
      ];
    } else {
      contentArray = this.transformPartsToToolCallContent(params.message);
    }
    const update2 = {
      sessionUpdate: "tool_call_update",
      toolCallId: params.callId,
      status: params.success ? "completed" : "failed",
      content: contentArray,
      _meta: {
        toolName: params.toolName,
        ...params.subagentMeta,
        ...BaseEmitter.toEpochMs(params.timestamp) != null && {
          timestamp: BaseEmitter.toEpochMs(params.timestamp)
        }
      }
    };
    if (params.resultDisplay !== void 0) {
      update2["rawOutput"] = params.resultDisplay;
    }
    await this.sendUpdate(update2);
  }
  /**
   * Emits a tool call error event.
   * Use this for explicit error handling when not using emitResult.
   *
   * @param callId - The tool call ID
   * @param toolName - The tool name
   * @param error - The error that occurred
   * @param subagentMeta - Optional subagent metadata
   */
  async emitError(callId, toolName, error2, subagentMeta) {
    await this.sendUpdate({
      sessionUpdate: "tool_call_update",
      toolCallId: callId,
      status: "failed",
      content: [
        { type: "content", content: { type: "text", text: error2.message } }
      ],
      _meta: {
        toolName,
        ...subagentMeta
      }
    });
  }
  // ==================== Public Utilities ====================
  /**
   * Checks if a tool name is the TodoWriteTool.
   * Exposed for external use in components that need to check this.
   */
  isTodoWriteTool(toolName) {
    return toolName === TodoWriteTool.Name;
  }
  /**
   * Checks if a tool name is the ExitPlanModeTool.
   */
  isExitPlanModeTool(toolName) {
    return toolName === ExitPlanModeTool.Name;
  }
  /**
   * Resolves tool metadata from the registry.
   * Falls back to defaults if tool not found or build fails.
   *
   * @param toolName - Name of the tool
   * @param args - Tool call arguments (used to build invocation)
   */
  resolveToolMetadata(toolName, args) {
    const toolRegistry = this.config.getToolRegistry();
    const tool = toolRegistry.getTool(toolName);
    let title = tool?.displayName ?? toolName;
    let locations = [];
    let kind2 = "other";
    if (tool && args) {
      try {
        const invocation = tool.build(args);
        title = `${title}: ${invocation.getDescription()}`;
        locations = invocation.toolLocations().map((loc) => ({
          path: loc.path,
          line: loc.line ?? null
        }));
        kind2 = this.mapToolKind(tool.kind, toolName);
      } catch {
      }
    }
    return { title, locations, kind: kind2 };
  }
  /**
   * Maps core Tool Kind enum to ACP ToolKind string literals.
   *
   * @param kind - The core Kind enum value
   * @param toolName - Optional tool name to handle special cases like exit_plan_mode
   */
  mapToolKind(kind2, toolName) {
    if (toolName && this.isExitPlanModeTool(toolName)) {
      return "switch_mode";
    }
    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[kind2] ?? "other";
  }
  // ==================== Private Helpers ====================
  /**
   * Extracts diff content from resultDisplay if it's a diff type (edit tool result).
   * Returns null if not a diff.
   */
  extractDiffContent(resultDisplay) {
    if (!resultDisplay || typeof resultDisplay !== "object") return null;
    const obj = resultDisplay;
    if ("fileName" in obj && "newContent" in obj) {
      return {
        type: "diff",
        path: obj["fileName"],
        oldText: obj["originalContent"] ?? "",
        newText: obj["newContent"]
      };
    }
    return null;
  }
  /**
   * Transforms Part[] to ToolCallContent[].
   * Extracts text from functionResponse parts and text parts.
   */
  transformPartsToToolCallContent(parts) {
    const result = [];
    for (const part of parts) {
      if ("text" in part && part.text) {
        result.push({
          type: "content",
          content: { type: "text", text: part.text }
        });
      }
      if ("functionResponse" in part && part.functionResponse) {
        try {
          const resp = part.functionResponse.response;
          const outputField = resp["output"];
          const errorField = resp["error"];
          const responseText = typeof outputField === "string" ? outputField : typeof errorField === "string" ? errorField : JSON.stringify(resp);
          result.push({
            type: "content",
            content: { type: "text", text: responseText }
          });
        } catch {
        }
      }
    }
    return result;
  }
};

// packages/cli/src/acp-integration/session/HistoryReplayer.ts
var HistoryReplayer = class {
  static {
    __name(this, "HistoryReplayer");
  }
  ctx;
  messageEmitter;
  toolCallEmitter;
  constructor(ctx) {
    this.ctx = ctx;
    this.messageEmitter = new MessageEmitter(ctx);
    this.toolCallEmitter = new ToolCallEmitter(ctx);
  }
  /**
   * Replays all chat records from a loaded session.
   *
   * @param records - Array of chat records to replay
   */
  async replay(records) {
    for (const record2 of records) {
      await this.replayRecord(record2);
    }
  }
  /**
   * Replays a single chat record.
   */
  async replayRecord(record2) {
    this.setActiveRecordId(record2.uuid, record2.timestamp);
    switch (record2.type) {
      case "user":
        if (record2.message) {
          await this.replayContent(record2.message, "user", record2.timestamp);
        }
        break;
      case "assistant":
        if (record2.message) {
          await this.replayContent(
            record2.message,
            "assistant",
            record2.timestamp
          );
        }
        if (record2.usageMetadata) {
          await this.replayUsageMetadata(record2.usageMetadata);
        }
        break;
      case "tool_result":
        await this.replayToolResult(record2);
        break;
      default:
        break;
    }
    this.setActiveRecordId(null);
  }
  /**
   * Replays content from a message (user or assistant).
   * Handles text parts, thought parts, and function calls.
   *
   * @param content - The content to replay
   * @param role - The role (user or assistant)
   * @param timestamp - Optional server-side timestamp from the JSONL record
   */
  async replayContent(content, role, timestamp) {
    for (const part of content.parts ?? []) {
      if ("text" in part && part.text) {
        const isThought = part.thought ?? false;
        await this.messageEmitter.emitMessage(
          part.text,
          role,
          isThought,
          timestamp
        );
      }
      if ("functionCall" in part && part.functionCall) {
        const functionName = part.functionCall.name ?? "";
        const callId = part.functionCall.id ?? `${functionName}-${Date.now()}`;
        await this.toolCallEmitter.emitStart({
          toolName: functionName,
          callId,
          args: part.functionCall.args,
          status: "in_progress",
          timestamp
        });
      }
    }
  }
  /**
   * Replays usage metadata.
   * @param usageMetadata - The usage metadata to replay
   */
  async replayUsageMetadata(usageMetadata) {
    await this.messageEmitter.emitUsageMetadata(usageMetadata);
  }
  /**
   * Replays a tool result record.
   */
  async replayToolResult(record2) {
    if (!record2.message?.parts) {
      return;
    }
    const result = record2.toolCallResult;
    const callId = result?.callId ?? record2.uuid;
    const toolName = this.extractToolNameFromRecord(record2);
    await this.toolCallEmitter.emitResult({
      toolName,
      callId,
      success: !result?.error,
      message: record2.message.parts,
      resultDisplay: result?.resultDisplay,
      // For TodoWriteTool fallback, try to extract args from the record
      // Note: args aren't stored in tool_result records by default
      args: void 0,
      timestamp: record2.timestamp
    });
    const { resultDisplay } = result ?? {};
    if (!!resultDisplay && typeof resultDisplay === "object" && "type" in resultDisplay && resultDisplay.type === "task_execution") {
      await this.emitTaskUsageFromResultDisplay(
        resultDisplay
      );
    }
  }
  /**
   * Emits token usage from a TaskResultDisplay execution summary, if present.
   */
  async emitTaskUsageFromResultDisplay(resultDisplay) {
    const summary = resultDisplay.executionSummary;
    if (!summary) {
      return;
    }
    const usageMetadata = {};
    if (Number.isFinite(summary.inputTokens)) {
      usageMetadata.promptTokenCount = summary.inputTokens;
    }
    if (Number.isFinite(summary.outputTokens)) {
      usageMetadata.candidatesTokenCount = summary.outputTokens;
    }
    if (Number.isFinite(summary.thoughtTokens)) {
      usageMetadata.thoughtsTokenCount = summary.thoughtTokens;
    }
    if (Number.isFinite(summary.cachedTokens)) {
      usageMetadata.cachedContentTokenCount = summary.cachedTokens;
    }
    if (Number.isFinite(summary.totalTokens)) {
      usageMetadata.totalTokenCount = summary.totalTokens;
    }
    if (Object.keys(usageMetadata).length > 0) {
      await this.messageEmitter.emitUsageMetadata(usageMetadata);
    }
  }
  /**
   * Extracts tool name from a chat record's function response.
   */
  extractToolNameFromRecord(record2) {
    if (record2.message?.parts) {
      for (const part of record2.message.parts) {
        if ("functionResponse" in part && part.functionResponse?.name) {
          return part.functionResponse.name;
        }
      }
    }
    return "";
  }
  setActiveRecordId(recordId, timestamp) {
    const context2 = this.ctx;
    if (typeof context2.setActiveRecordId === "function") {
      context2.setActiveRecordId(recordId, timestamp);
    }
  }
};

// packages/cli/src/ui/utils/export/collect.ts
var ExportSessionContext = class {
  static {
    __name(this, "ExportSessionContext");
  }
  sessionId;
  config;
  messages = [];
  currentMessage = null;
  activeRecordId = null;
  activeRecordTimestamp = null;
  toolCallMap = /* @__PURE__ */ new Map();
  constructor(sessionId, config2) {
    this.sessionId = sessionId;
    this.config = config2;
  }
  async sendUpdate(update2) {
    switch (update2.sessionUpdate) {
      case "user_message_chunk":
        this.handleMessageChunk("user", update2.content);
        break;
      case "agent_message_chunk":
        this.handleMessageChunk("assistant", update2.content);
        break;
      case "agent_thought_chunk":
        this.handleMessageChunk("assistant", update2.content, "thinking");
        break;
      case "tool_call":
        this.flushCurrentMessage();
        this.handleToolCallStart(update2);
        break;
      case "tool_call_update":
        this.handleToolCallUpdate(update2);
        break;
      case "plan":
        this.flushCurrentMessage();
        this.handlePlanUpdate(update2);
        break;
      default:
        break;
    }
  }
  setActiveRecordId(recordId, timestamp) {
    this.activeRecordId = recordId;
    this.activeRecordTimestamp = timestamp ?? null;
  }
  getMessageTimestamp() {
    return this.activeRecordTimestamp ?? (/* @__PURE__ */ new Date()).toISOString();
  }
  getMessageUuid() {
    return this.activeRecordId ?? randomUUID6();
  }
  handleMessageChunk(role, content, messageRole = role) {
    if (content.type !== "text" || !content.text) return;
    if (this.currentMessage && (this.currentMessage.type !== role || this.currentMessage.role !== messageRole)) {
      this.flushCurrentMessage();
    }
    if (this.currentMessage && this.currentMessage.type === role && this.currentMessage.role === messageRole) {
      this.currentMessage.parts.push({ text: content.text });
    } else {
      this.currentMessage = {
        type: role,
        role: messageRole,
        parts: [{ text: content.text }],
        timestamp: Date.now()
      };
    }
  }
  handleToolCallStart(update2) {
    const toolCall = {
      toolCallId: update2.toolCallId,
      kind: update2.kind || "other",
      title: typeof update2.title === "string" ? update2.title : update2.title || "",
      status: update2.status || "pending",
      rawInput: update2.rawInput,
      locations: update2.locations,
      timestamp: Date.now()
    };
    this.toolCallMap.set(update2.toolCallId, toolCall);
    const uuid2 = this.getMessageUuid();
    this.messages.push({
      uuid: uuid2,
      sessionId: this.sessionId,
      timestamp: this.getMessageTimestamp(),
      type: "tool_call",
      toolCall
    });
  }
  handleToolCallUpdate(update2) {
    const toolCall = this.toolCallMap.get(update2.toolCallId);
    if (toolCall) {
      if (update2.status) toolCall.status = update2.status;
      if (update2.content) toolCall.content = update2.content;
      if (update2.title)
        toolCall.title = typeof update2.title === "string" ? update2.title : "";
    }
  }
  handlePlanUpdate(update2) {
    const uuid2 = this.getMessageUuid();
    const timestamp = this.getMessageTimestamp();
    const todoText = update2.entries.map((entry) => {
      const checkbox = entry.status === "completed" ? "[x]" : entry.status === "in_progress" ? "[-]" : "[ ]";
      return `- ${checkbox} ${entry.content}`;
    }).join("\n");
    const todoContent = [
      {
        type: "content",
        content: {
          type: "text",
          text: todoText
        }
      }
    ];
    this.messages.push({
      uuid: uuid2,
      sessionId: this.sessionId,
      timestamp,
      type: "tool_call",
      toolCall: {
        toolCallId: uuid2,
        // Use the same uuid as toolCallId for plan updates
        kind: "todowrite",
        title: "TodoWrite",
        status: "completed",
        content: todoContent,
        timestamp: Date.parse(timestamp)
      }
    });
  }
  flushCurrentMessage() {
    if (!this.currentMessage) return;
    const uuid2 = this.getMessageUuid();
    this.messages.push({
      uuid: uuid2,
      sessionId: this.sessionId,
      timestamp: this.getMessageTimestamp(),
      type: this.currentMessage.type,
      message: {
        role: this.currentMessage.role,
        parts: this.currentMessage.parts
      }
    });
    this.currentMessage = null;
  }
  flushMessages() {
    this.flushCurrentMessage();
  }
  getMessages() {
    return this.messages;
  }
};
async function collectSessionData(conversation, config2) {
  const exportContext = new ExportSessionContext(
    conversation.sessionId,
    config2
  );
  const replayer = new HistoryReplayer(exportContext);
  await replayer.replay(conversation.messages);
  exportContext.flushMessages();
  const messages = exportContext.getMessages();
  return {
    sessionId: conversation.sessionId,
    startTime: conversation.startTime,
    messages
  };
}
__name(collectSessionData, "collectSessionData");

// packages/cli/src/ui/utils/export/normalize.ts
init_esbuild_shims();
function normalizeSessionData(sessionData, originalRecords, config2) {
  const normalized2 = [...sessionData.messages];
  const toolCallIndexById = /* @__PURE__ */ new Map();
  normalized2.forEach((message, index) => {
    if (message.type === "tool_call" && message.toolCall?.toolCallId) {
      toolCallIndexById.set(message.toolCall.toolCallId, index);
    }
  });
  for (const record2 of originalRecords) {
    if (record2.type !== "tool_result") continue;
    const toolCallMessage = buildToolCallMessageFromResult(record2, config2);
    if (!toolCallMessage?.toolCall) continue;
    const existingIndex = toolCallIndexById.get(
      toolCallMessage.toolCall.toolCallId
    );
    if (existingIndex === void 0) {
      toolCallIndexById.set(
        toolCallMessage.toolCall.toolCallId,
        normalized2.length
      );
      normalized2.push(toolCallMessage);
      continue;
    }
    const existingMessage = normalized2[existingIndex];
    if (existingMessage.type !== "tool_call" || !existingMessage.toolCall) {
      continue;
    }
    mergeToolCallData(existingMessage.toolCall, toolCallMessage.toolCall);
  }
  return {
    ...sessionData,
    messages: normalized2
  };
}
__name(normalizeSessionData, "normalizeSessionData");
function mergeToolCallData(existing, incoming) {
  if (!existing.content || existing.content.length === 0) {
    existing.content = incoming.content;
  }
  if (existing.status === "pending" || existing.status === "in_progress") {
    existing.status = incoming.status;
  }
  if (!existing.rawInput && incoming.rawInput) {
    existing.rawInput = incoming.rawInput;
  }
  if (!existing.kind || existing.kind === "other") {
    existing.kind = incoming.kind;
  }
  if ((!existing.title || existing.title === "") && incoming.title) {
    existing.title = incoming.title;
  }
  if ((!existing.locations || existing.locations.length === 0) && incoming.locations && incoming.locations.length > 0) {
    existing.locations = incoming.locations;
  }
}
__name(mergeToolCallData, "mergeToolCallData");
function buildToolCallMessageFromResult(record2, config2) {
  const toolCallResult = record2.toolCallResult;
  const toolName = extractToolNameFromRecord(record2);
  if (toolName === ToolNames.TODO_WRITE) {
    return null;
  }
  const toolCallId = toolCallResult?.callId ?? record2.uuid;
  const functionCallArgs = extractFunctionCallArgs(record2);
  const { kind: kind2, title, locations } = resolveToolMetadata(
    config2,
    toolName,
    functionCallArgs ?? toolCallResult?.args
  );
  const rawInput = normalizeRawInput(
    functionCallArgs ?? toolCallResult?.args
  );
  const content = extractDiffContent(toolCallResult?.resultDisplay) ?? transformPartsToToolCallContent(record2.message?.parts ?? []);
  return {
    uuid: record2.uuid,
    parentUuid: record2.parentUuid,
    sessionId: record2.sessionId,
    timestamp: record2.timestamp,
    type: "tool_call",
    toolCall: {
      toolCallId,
      kind: kind2,
      title,
      status: toolCallResult?.error ? "failed" : "completed",
      rawInput,
      content,
      locations,
      timestamp: Date.parse(record2.timestamp)
    }
  };
}
__name(buildToolCallMessageFromResult, "buildToolCallMessageFromResult");
function extractToolNameFromRecord(record2) {
  if (!record2.message?.parts) {
    return "";
  }
  for (const part of record2.message.parts) {
    if ("functionResponse" in part && part.functionResponse?.name) {
      return part.functionResponse.name;
    }
  }
  return "";
}
__name(extractToolNameFromRecord, "extractToolNameFromRecord");
function extractFunctionCallArgs(record2) {
  if (!record2.message?.parts) {
    return void 0;
  }
  for (const part of record2.message.parts) {
    if ("functionCall" in part && part.functionCall?.args) {
      return part.functionCall.args;
    }
  }
  return void 0;
}
__name(extractFunctionCallArgs, "extractFunctionCallArgs");
function resolveToolMetadata(config2, toolName, args) {
  const toolRegistry = config2.getToolRegistry?.();
  const tool = toolName ? toolRegistry?.getTool?.(toolName) : void 0;
  let title = tool?.displayName ?? toolName ?? "tool_call";
  let locations;
  const kind2 = mapToolKind(tool?.kind, toolName);
  if (tool && args) {
    try {
      const invocation = tool.build(args);
      title = `${title}: ${invocation.getDescription()}`;
      locations = invocation.toolLocations().map((loc) => ({
        path: loc.path,
        line: loc.line ?? null
      }));
    } catch {
    }
  }
  return { kind: kind2, title, locations };
}
__name(resolveToolMetadata, "resolveToolMetadata");
function mapToolKind(kind2, toolName) {
  if (toolName && toolName === ExitPlanModeTool.Name) {
    return "switch_mode";
  }
  if (toolName && toolName === ToolNames.TODO_WRITE) {
    return "todowrite";
  }
  const allowedKinds = /* @__PURE__ */ new Set([
    "read",
    "edit",
    "delete",
    "move",
    "search",
    "execute",
    "think",
    "fetch",
    "other"
  ]);
  if (kind2 && allowedKinds.has(kind2)) {
    return kind2;
  }
  return "other";
}
__name(mapToolKind, "mapToolKind");
function extractDiffContent(resultDisplay) {
  if (!resultDisplay || typeof resultDisplay !== "object") {
    return null;
  }
  const display = resultDisplay;
  if ("fileName" in display && "newContent" in display) {
    return [
      {
        type: "diff",
        path: display["fileName"],
        oldText: display["originalContent"] ?? "",
        newText: display["newContent"]
      }
    ];
  }
  return null;
}
__name(extractDiffContent, "extractDiffContent");
function normalizeRawInput(value) {
  if (typeof value === "string") return value;
  if (typeof value === "object" && value !== null) return value;
  return void 0;
}
__name(normalizeRawInput, "normalizeRawInput");
function transformPartsToToolCallContent(parts) {
  const content = [];
  for (const part of parts) {
    if ("text" in part && part.text) {
      content.push({
        type: "content",
        content: { type: "text", text: part.text }
      });
      continue;
    }
    if ("functionResponse" in part && part.functionResponse) {
      const response = part.functionResponse.response;
      const outputField = response?.["output"];
      const errorField = response?.["error"];
      const responseText = typeof outputField === "string" ? outputField : typeof errorField === "string" ? errorField : JSON.stringify(response);
      content.push({
        type: "content",
        content: { type: "text", text: responseText }
      });
    }
  }
  return content;
}
__name(transformPartsToToolCallContent, "transformPartsToToolCallContent");

// packages/cli/src/ui/utils/export/formatters/markdown.ts
init_esbuild_shims();
function toMarkdown(sessionData) {
  const lines = [];
  lines.push("# Chat Session Export\n");
  lines.push(`- **Session ID**: \`${sanitizeText(sessionData.sessionId)}\``);
  lines.push(`- **Start Time**: ${sanitizeText(sessionData.startTime)}`);
  lines.push(`- **Exported**: ${(/* @__PURE__ */ new Date()).toISOString()}`);
  lines.push("\n---\n");
  for (const message of sessionData.messages) {
    if (message.type === "user") {
      lines.push("## User\n");
      lines.push(formatMessageContent(message));
    } else if (message.type === "assistant") {
      lines.push("## Assistant\n");
      lines.push(formatMessageContent(message));
    } else if (message.type === "tool_call") {
      lines.push(formatToolCall(message));
    } else if (message.type === "system") {
      lines.push("### System\n");
      const text = formatMessageContent(message);
      lines.push(`> ${text.replace(/\n/g, "\n> ")}`);
    }
    lines.push("\n");
  }
  return lines.join("\n");
}
__name(toMarkdown, "toMarkdown");
function formatMessageContent(message) {
  const text = extractTextFromMessage(message);
  const processedText = text.replace(
    /--- Content from referenced files ---\n([\s\S]*?)\n--- End of content ---/g,
    (match2, content) => `
> **Referenced Files:**

${createCodeBlock(content)}
`
  );
  return processedText;
}
__name(formatMessageContent, "formatMessageContent");
function formatToolCall(message) {
  if (!message.toolCall) return "";
  const lines = [];
  const { title, status, rawInput, content, locations } = message.toolCall;
  const titleStr = typeof title === "string" ? title : JSON.stringify(title);
  lines.push(`### Tool: ${sanitizeText(titleStr)}`);
  lines.push(`**Status**: ${sanitizeText(status)}
`);
  if (rawInput) {
    lines.push("**Input:**");
    const inputStr = typeof rawInput === "string" ? rawInput : JSON.stringify(rawInput, null, 2);
    lines.push(createCodeBlock(inputStr, "json"));
    lines.push("");
  }
  if (locations && locations.length > 0) {
    lines.push("**Affected Files:**");
    for (const loc of locations) {
      const lineSuffix = loc.line ? `:${loc.line}` : "";
      lines.push(`- \`${sanitizeText(loc.path)}${lineSuffix}\``);
    }
    lines.push("");
  }
  if (content && content.length > 0) {
    lines.push("**Output:**");
    for (const item of content) {
      if (item.type === "content" && item["content"]) {
        const contentData = item["content"];
        if (contentData.type === "text" && contentData.text) {
          let language = "";
          if (locations && locations.length === 1 && locations[0].path) {
            language = getLanguageFromPath(locations[0].path);
          }
          lines.push(createCodeBlock(contentData.text, language));
        }
      } else if (item.type === "diff") {
        const path125 = item["path"];
        const diffText = item["newText"];
        lines.push(`
*Diff for \`${sanitizeText(path125)}\`:*`);
        lines.push(createCodeBlock(diffText, "diff"));
      }
    }
  }
  return lines.join("\n");
}
__name(formatToolCall, "formatToolCall");
function extractTextFromMessage(message) {
  if (!message.message?.parts) return "";
  const textParts = [];
  for (const part of message.message.parts) {
    if ("text" in part) {
      textParts.push(part.text);
    }
  }
  return textParts.join("\n");
}
__name(extractTextFromMessage, "extractTextFromMessage");
function createCodeBlock(content, language = "") {
  const fence = buildFence(content);
  return `${fence}${language}
${content}
${fence}`;
}
__name(createCodeBlock, "createCodeBlock");
function sanitizeText(value) {
  return (value ?? "").replace(/&/g, "&amp;").replace(/</g, "&lt;");
}
__name(sanitizeText, "sanitizeText");
function buildFence(value) {
  const matches = (value ?? "").match(/`+/g);
  const maxRun = matches ? Math.max(...matches.map((match2) => match2.length)) : 0;
  const fenceLength = Math.max(3, maxRun + 1);
  return "`".repeat(fenceLength);
}
__name(buildFence, "buildFence");
function getLanguageFromPath(path125) {
  const ext2 = path125.split(".").pop()?.toLowerCase();
  switch (ext2) {
    case "ts":
    case "tsx":
      return "typescript";
    case "js":
    case "jsx":
    case "mjs":
    case "cjs":
      return "javascript";
    case "py":
      return "python";
    case "rb":
      return "ruby";
    case "go":
      return "go";
    case "rs":
      return "rust";
    case "java":
      return "java";
    case "c":
    case "cpp":
    case "h":
    case "hpp":
      return "cpp";
    case "cs":
      return "csharp";
    case "html":
      return "html";
    case "css":
      return "css";
    case "json":
      return "json";
    case "md":
      return "markdown";
    case "sh":
    case "bash":
    case "zsh":
      return "bash";
    case "yaml":
    case "yml":
      return "yaml";
    case "xml":
      return "xml";
    case "sql":
      return "sql";
    default:
      return "";
  }
}
__name(getLanguageFromPath, "getLanguageFromPath");

// packages/cli/src/ui/utils/export/formatters/html.ts
init_esbuild_shims();

// packages/web-templates/dist/index.js
init_esbuild_shims();

// packages/web-templates/dist/generated/insightTemplate.js
init_esbuild_shims();
var INSIGHT_JS = '(function(e,z){"use strict";function j({data:t}){const{totalMessages:l=0,totalLinesAdded:n=0,totalLinesRemoved:r=0,totalFiles:o=0}=t,a=Object.keys(t.heatmap||{});let s=0;if(a.length>0){const d=a.map(u=>new Date(u)).map(u=>u.getTime()),c=new Date(Math.min(...d)),g=new Date(Math.max(...d)),f=Math.abs(g.getTime()-c.getTime());s=Math.ceil(f/(1e3*60*60*24))+1}const i=s>0?Math.round(l/s):0;return e.createElement("div",{className:"stats-row"},e.createElement("div",{className:"stat"},e.createElement("div",{className:"stat-value"},l),e.createElement("div",{className:"stat-label"},"Messages")),e.createElement("div",{className:"stat"},e.createElement("div",{className:"stat-value"},"+",n,"/-",r),e.createElement("div",{className:"stat-label"},"Lines")),e.createElement("div",{className:"stat"},e.createElement("div",{className:"stat-value"},o),e.createElement("div",{className:"stat-label"},"Files")),e.createElement("div",{className:"stat"},e.createElement("div",{className:"stat-value"},s),e.createElement("div",{className:"stat-label"},"Days")),e.createElement("div",{className:"stat"},e.createElement("div",{className:"stat-value"},i),e.createElement("div",{className:"stat-label"},"Msgs/Day")))}function B({insights:t}){return e.createElement("div",{className:"grid gap-4 md:grid-cols-2 md:gap-6"},e.createElement(H,{activeHours:t.activeHours,cardClass:"glass-card p-6",sectionTitleClass:"text-lg font-semibold tracking-tight text-slate-900"}))}function H({activeHours:t,cardClass:l,sectionTitleClass:n}){const o=[{label:"Morning",time:"06:00 - 12:00",hours:[6,7,8,9,10,11],color:"#fbbf24"},{label:"Afternoon",time:"12:00 - 18:00",hours:[12,13,14,15,16,17],color:"#0ea5e9"},{label:"Evening",time:"18:00 - 22:00",hours:[18,19,20,21],color:"#6366f1"},{label:"Night",time:"22:00 - 06:00",hours:[22,23,0,1,2,3,4,5],color:"#475569"}].map(s=>{const i=s.hours.reduce((m,d)=>m+(t[d]||0),0);return{...s,total:i}}),a=Math.max(...o.map(s=>s.total));return e.createElement("div",{className:`${l} h-full flex flex-col min-h-[320px]`},e.createElement("div",{className:"flex items-center justify-between mb-4"},e.createElement("h3",{className:n},"Active Hours")),e.createElement("div",{className:"flex-1 flex flex-col justify-center gap-4"},o.map(s=>e.createElement("div",{key:s.label,className:"space-y-2"},e.createElement("div",{className:"flex justify-between items-center text-sm"},e.createElement("div",{className:"flex items-center gap-2"},e.createElement("span",{className:"rounded-full",style:{width:"12px",height:"12px",backgroundColor:s.color}}),e.createElement("span",{className:"font-medium text-slate-700"},s.label),e.createElement("span",{className:"text-xs text-slate-400 hidden xl:inline"},s.time)),e.createElement("span",{className:"font-semibold text-slate-900"},s.total)),e.createElement("div",{className:"w-full rounded-full overflow-hidden",style:{height:"12px",backgroundColor:"#e2e8f0"}},e.createElement("div",{className:"h-full rounded-full",style:{width:`${a>0?s.total/a*100:0}%`,backgroundColor:s.color}}))))))}function O({heatmap:t}){return e.createElement("div",{className:"glass-card p-6 mt-4 md:mt-6"},e.createElement("div",{className:"mb-3"},e.createElement("h3",{className:"text-lg font-semibold tracking-tight text-slate-900"},"Activity Heatmap"),e.createElement("p",{className:"text-xs text-slate-500"},"Showing past year of activity")),e.createElement("div",{className:"heatmap-container"},e.createElement("div",{className:"min-w-[720px] rounded-xl bg-white/70"},e.createElement(q,{heatmapData:t}))),e.createElement(F,null))}function q({heatmapData:t}){const a=new Date,s=new Date(a);s.setFullYear(a.getFullYear()-1);const i=[],m=new Date(s);for(;m<=a;)i.push(new Date(m)),m.setDate(m.getDate()+1);const d=[0,2,4,10,20],c=["#ebedf0","#9be9a8","#40c463","#30a14e","#216e39"];function g(h){if(h===0)return c[0];for(let E=d.length-1;E>=1;E--)if(h>=d[E])return c[E];return c[1]}const f=50,u=20,x=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],S=s.getDay(),A=[];let D=-1,_=-100;return i.forEach((h,E)=>{const C=E+S,T=Math.floor(C/7),y=f+T*16,v=h.getMonth();v!==D&&(y-_>30&&(A.push({x:y,text:x[v]}),_=y),D=v)}),e.createElement("svg",{className:"heatmap-svg",width:1e3,height:130,viewBox:"0 0 1000 130"},i.map((h,E)=>{const C=E+S,T=Math.floor(C/7),y=h.getDay(),v=f+T*16,I=u+y*16,b=h.toISOString().split("T")[0],w=t[b]||0,oe=g(w);return e.createElement("rect",{key:b,className:"heatmap-day",x:v,y:I,width:14,height:14,rx:"2",fill:oe,"data-date":b,"data-count":w},e.createElement("title",null,b,": ",w," activities"))}),A.map((h,E)=>e.createElement("text",{key:E,x:h.x,y:"15",fontSize:"12",fill:"#64748b"},h.text)))}function F(){const t=["#ebedf0","#9be9a8","#40c463","#30a14e","#216e39"];return e.createElement("div",{className:"flex items-center gap-2 mt-4"},e.createElement("span",{className:"text-xs text-slate-500"},"Less"),t.map((l,n)=>e.createElement("span",{key:n,className:"inline-block rounded",style:{width:"10px",height:"10px",backgroundColor:l}})),e.createElement("span",{className:"text-xs text-slate-500"},"More"))}function p({children:t}){if(!t||typeof t!="string")return t;const l=t.split(/(\\*\\*.*?\\*\\*)/g);return e.createElement(e.Fragment,null,l.map((n,r)=>n.startsWith("**")&&n.endsWith("**")&&n.length>=4?e.createElement("strong",{key:r},n.slice(2,-2)):n))}function M({text:t,label:l="Copy"}){const[n,r]=e.useState(!1),o=()=>{navigator.clipboard.writeText(t).then(()=>{r(!0),setTimeout(()=>r(!1),2e3)})};return e.createElement("button",{className:"copy-btn",onClick:o},n?"Copied!":l)}function L({qualitative:t}){const{atAGlance:l}=t;return l?e.createElement("div",{className:"at-a-glance"},e.createElement("div",{className:"glance-title"},"At a Glance"),e.createElement("div",{className:"glance-sections"},e.createElement("div",{className:"glance-section"},e.createElement("strong",null,"What\'s working:")," ",e.createElement(p,null,l.whats_working),e.createElement("a",{href:"#section-wins",className:"see-more"},"Impressive Things You Did \u2192")),e.createElement("div",{className:"glance-section"},e.createElement("strong",null,"What\'s hindering you:")," ",e.createElement(p,null,l.whats_hindering),e.createElement("a",{href:"#section-friction",className:"see-more"},"Where Things Go Wrong \u2192")),e.createElement("div",{className:"glance-section"},e.createElement("strong",null,"Quick wins to try:")," ",e.createElement(p,null,l.quick_wins),e.createElement("a",{href:"#section-features",className:"see-more"},"Features to Try \u2192")),e.createElement("div",{className:"glance-section"},e.createElement("strong",null,"Ambitious workflows:")," ",e.createElement(p,null,l.ambitious_workflows),e.createElement("a",{href:"#section-horizon",className:"see-more"},"On the Horizon \u2192")))):null}function $(){return e.createElement("nav",{className:"nav-toc"},e.createElement("a",{href:"#section-work"},"What You Work On"),e.createElement("a",{href:"#section-usage"},"How You Use Qwen Code"),e.createElement("a",{href:"#section-wins"},"Impressive Things"),e.createElement("a",{href:"#section-friction"},"Where Things Go Wrong"),e.createElement("a",{href:"#section-features"},"Features to Try"),e.createElement("a",{href:"#section-patterns"},"New Usage Patterns"),e.createElement("a",{href:"#section-horizon"},"On the Horizon"))}function Q({qualitative:t,topGoals:l,topTools:n}){const{projectAreas:r}=t,o=Array.isArray(n)?Object.fromEntries(n):n;return e.createElement(e.Fragment,null,e.createElement("h2",{id:"section-work",className:"text-xl font-semibold text-slate-900 mt-8 mb-4"},"What You Work On"),Array.isArray(r==null?void 0:r.areas)&&r.areas.length>0&&e.createElement("div",{className:"project-areas mb-6"},r.areas.map((a,s)=>e.createElement("div",{key:s,className:"project-area"},e.createElement("div",{className:"area-header"},e.createElement("span",{className:"area-name"},a.name),e.createElement("span",{className:"area-count"},"~",a.session_count," sessions")),e.createElement("div",{className:"area-desc"},e.createElement(p,null,a.description))))),e.createElement("div",{style:{display:"grid",gridTemplateColumns:"repeat(2, 1fr)",gap:"24px",marginBottom:"24px"}},l&&Object.keys(l).length>0&&e.createElement(N,{data:l,title:"What You Wanted",color:"#0ea5e9"}),o&&Object.keys(o).length>0&&e.createElement(N,{data:o,title:"Top Tools Used",color:"#6366f1"})))}function P({qualitative:t,insights:l}){const{interactionStyle:n}=t;return n?e.createElement(e.Fragment,null,e.createElement("h2",{id:"section-usage",className:"text-xl font-semibold text-slate-900 mt-8 mb-4"},"How You Use Qwen Code"),e.createElement("div",{className:"narrative"},e.createElement("p",null,e.createElement(p,null,n.narrative)),n.key_pattern&&e.createElement("div",{className:"key-insight"},e.createElement("strong",null,"Key pattern:")," ",e.createElement(p,null,n.key_pattern))),e.createElement(B,{insights:l}),e.createElement(O,{heatmap:l.heatmap})):null}function G({qualitative:t,primarySuccess:l,outcomes:n}){const{impressiveWorkflows:r}=t;return r?e.createElement(e.Fragment,null,e.createElement("h2",{id:"section-wins",className:"text-xl font-semibold text-slate-900 mt-8 mb-4"},"Impressive Things You Did"),r.intro&&e.createElement("p",{className:"section-intro"},e.createElement(p,null,r.intro)),e.createElement("div",{className:"big-wins"},Array.isArray(r.impressive_workflows)&&r.impressive_workflows.map((o,a)=>e.createElement("div",{key:a,className:"big-win"},e.createElement("div",{className:"big-win-title"},o.title),e.createElement("div",{className:"big-win-desc"},e.createElement(p,null,o.description))))),e.createElement("div",{style:{display:"grid",gridTemplateColumns:"repeat(2, 1fr)",gap:"24px",marginTop:"24px",marginBottom:"24px"}},l&&Object.keys(l).length>0&&e.createElement(N,{data:l,title:"What Helped Most (Qwen\'s Capabilities)",color:"#3b82f6",allowedKeys:["fast_accurate_search","correct_code_edits","good_explanations","proactive_help","multi_file_changes","good_debugging"]}),n&&Object.keys(n).length>0&&e.createElement(N,{data:n,title:"Outcomes",color:"#8b5cf6",allowedKeys:["fully_achieved","mostly_achieved","partially_achieved","not_achieved","unclear_from_transcript"]}))):null}function Y(t){return t==="unclear_from_transcript"?"Unclear":t.split("_").map(l=>l.charAt(0).toUpperCase()+l.slice(1)).join(" ")}function N({data:t,title:l,color:n="#3b82f6",allowedKeys:r=null}){if(!t||Object.keys(t).length===0)return null;let o=Object.entries(t);if(r&&(o=o.filter(([s])=>r.includes(s))),o.sort((s,i)=>i[1]-s[1]),o=o.slice(0,10),o.length===0)return null;const a=Math.max(...o.map(([,s])=>s));return e.createElement("div",{className:"bar-chart-card",style:{flex:1,minWidth:0,backgroundColor:"#ffffff",borderRadius:"12px",padding:"20px",boxShadow:"0 1px 3px rgba(0, 0, 0, 0.08)",border:"1px solid #e2e8f0"}},e.createElement("h3",{style:{fontSize:"13px",fontWeight:700,color:"#64748b",marginTop:0,marginBottom:"16px",textTransform:"uppercase",letterSpacing:"0.5px"}},l),e.createElement("div",{className:"bar-chart",style:{display:"flex",flexDirection:"column",gap:"10px"}},o.map(([s,i])=>{const m=a>0?i/a*100:0;return e.createElement("div",{key:s,className:"bar-row",style:{display:"flex",alignItems:"center",gap:"12px"}},e.createElement("div",{className:"bar-label",style:{width:"130px",fontSize:"13px",color:"#475569",textAlign:"left",flexShrink:0,whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"}},Y(s)),e.createElement("div",{className:"bar-wrapper",style:{flex:1,display:"flex",alignItems:"center",gap:"10px",minWidth:0}},e.createElement("div",{className:"bar-bg",style:{flex:1,height:"8px",backgroundColor:"#f1f5f9",borderRadius:"4px",overflow:"hidden"}},e.createElement("div",{className:"bar-fill",style:{width:`${m}%`,height:"100%",backgroundColor:n,borderRadius:"4px",transition:"width 0.3s ease"}})),e.createElement("span",{className:"bar-value",style:{fontSize:"13px",fontWeight:600,color:"#475569",minWidth:"24px",textAlign:"right"}},i)))})))}function U({qualitative:t,satisfaction:l,friction:n}){const{frictionPoints:r}=t;return r?e.createElement(e.Fragment,null,e.createElement("h2",{id:"section-friction",className:"text-xl font-semibold text-slate-900 mt-8 mb-4"},"Where Things Go Wrong"),r.intro&&e.createElement("p",{className:"section-intro"},e.createElement(p,null,r.intro)),e.createElement("div",{className:"friction-categories"},Array.isArray(r.categories)&&r.categories.map((o,a)=>e.createElement("div",{key:a,className:"friction-category"},e.createElement("div",{className:"friction-title"},o.category),e.createElement("div",{className:"friction-desc"},e.createElement(p,null,o.description)),Array.isArray(o.examples)&&o.examples.length>0&&e.createElement("ul",{className:"friction-examples"},o.examples.map((s,i)=>e.createElement("li",{key:i},e.createElement(p,null,s))))))),e.createElement("div",{style:{display:"grid",gridTemplateColumns:"repeat(2, 1fr)",gap:"24px",marginTop:"24px",marginBottom:"24px"}},n&&Object.keys(n).length>0&&e.createElement(N,{data:n,title:"Primary Friction Types",color:"#ef4444",allowedKeys:["misunderstood_request","wrong_approach","buggy_code","user_rejected_action","excessive_changes"]}),l&&Object.keys(l).length>0&&e.createElement(N,{data:l,title:"Inferred Satisfaction (model-estimated)",color:"#10b981",allowedKeys:["happy","satisfied","likely_satisfied","dissatisfied","frustrated"]}))):null}function K({additions:t}){const[l,n]=e.useState(new Array(t.length).fill(!0)),[r,o]=e.useState(!1),a=m=>{const d=l.map((c,g)=>g===m?!c:c);n(d)},s=()=>{const m=t.filter((d,c)=>l[c]).map(d=>d.addition).join(`\n\n`);m&&navigator.clipboard.writeText(m).then(()=>{o(!0),setTimeout(()=>o(!1),2e3)})},i=l.filter(Boolean).length;return e.createElement("div",{className:"qwen-md-section"},e.createElement("h3",null,"Suggested QWEN.md Additions"),e.createElement("p",{className:"text-xs text-slate-500 mb-3"},"Just copy this into Qwen Code to add it to your QWEN.md."),e.createElement("div",{className:"qwen-md-actions",style:{marginBottom:"12px"}},e.createElement("button",{className:`copy-all-btn ${r?"copied":""}`,onClick:s,disabled:i===0},r?"Copied All!":`Copy All Checked (${i})`)),t.map((m,d)=>e.createElement("div",{key:d,className:"qwen-md-item"},e.createElement("input",{type:"checkbox",checked:l[d],onChange:()=>a(d),className:"cmd-checkbox"}),e.createElement("div",{style:{flex:1}},e.createElement("code",{className:"cmd-code"},m.addition),e.createElement("div",{className:"cmd-why"},e.createElement(p,null,m.why))),e.createElement(M,{text:m.addition}))))}function J({qualitative:t}){const{improvements:l}=t;return l?e.createElement(e.Fragment,null,e.createElement("h2",{id:"section-features",className:"text-xl font-semibold text-slate-900 mt-8 mb-4"},"Existing Qwen Code Features to Try"),Array.isArray(l.Qwen_md_additions)&&l.Qwen_md_additions.length>0&&e.createElement(K,{additions:l.Qwen_md_additions}),e.createElement("p",{className:"text-xs text-slate-500 mb-3"},"Just copy this into Qwen Code and it\'ll set it up for you."),e.createElement("div",{className:"features-section"},Array.isArray(l.features_to_try)&&l.features_to_try.map((n,r)=>e.createElement("div",{key:r,className:"feature-card"},e.createElement("div",{className:"feature-title"},n.feature),e.createElement("div",{className:"feature-oneliner"},e.createElement(p,null,n.one_liner)),e.createElement("div",{className:"feature-why"},e.createElement("strong",null,"Why for you:")," ",e.createElement(p,null,n.why_for_you)),e.createElement("div",{className:"feature-examples"},e.createElement("div",{className:"feature-example"},e.createElement("div",{className:"example-code-row"},e.createElement("code",{className:"example-code"},n.example_code),e.createElement(M,{text:n.example_code}))))))),e.createElement("h2",{id:"section-patterns",className:"text-xl font-semibold text-slate-900 mt-8 mb-4"},"New Ways to Use Qwen Code"),e.createElement("p",{className:"text-xs text-slate-500 mb-3"},"Just copy this into Qwen Code and it\'ll walk you through it."),e.createElement("div",{className:"patterns-section"},Array.isArray(l.usage_patterns)&&l.usage_patterns.map((n,r)=>e.createElement("div",{key:r,className:"pattern-card"},e.createElement("div",{className:"pattern-title"},n.title),e.createElement("div",{className:"pattern-summary"},e.createElement(p,null,n.suggestion)),e.createElement("div",{className:"pattern-detail"},e.createElement(p,null,n.detail)),e.createElement("div",{className:"copyable-prompt-section"},e.createElement("div",{className:"prompt-label"},"Paste into Qwen Code:"),e.createElement("div",{className:"copyable-prompt-row"},e.createElement("code",{className:"copyable-prompt"},n.copyable_prompt),e.createElement(M,{text:n.copyable_prompt}))))))):null}function X({qualitative:t}){const{futureOpportunities:l}=t;return l?e.createElement(e.Fragment,null,e.createElement("h2",{id:"section-horizon",className:"text-xl font-semibold text-slate-900 mt-8 mb-4"},"On the Horizon"),l.intro&&e.createElement("p",{className:"section-intro"},e.createElement(p,null,l.intro)),e.createElement("div",{className:"horizon-section"},Array.isArray(l.opportunities)&&l.opportunities.map((n,r)=>e.createElement("div",{key:r,className:"horizon-card"},e.createElement("div",{className:"horizon-title"},n.title),e.createElement("div",{className:"horizon-possible"},e.createElement(p,null,n.whats_possible)),e.createElement("div",{className:"horizon-tip"},e.createElement("strong",null,"Getting started:")," ",e.createElement(p,null,n.how_to_try)),e.createElement("div",{className:"pattern-prompt"},e.createElement("div",{className:"prompt-label"},"Paste into Qwen Code:"),e.createElement("div",{style:{display:"flex",alignItems:"flex-start",gap:"8px"}},e.createElement("code",{style:{flex:1}},n.copyable_prompt),e.createElement(M,{text:n.copyable_prompt}))))))):null}function V({qualitative:t}){const{memorableMoment:l}=t;return l?e.createElement("div",{className:"fun-ending"},e.createElement("div",{className:"fun-headline"},\'"\',l.headline,\'"\'),e.createElement("div",{className:"fun-detail"},e.createElement(p,null,l.detail))):null}const Z={light:{background:"linear-gradient(135deg, #f8fafc 0%, #f1f5f9 100%)",textPrimary:"#0f172a",textSecondary:"#475569",textMuted:"#64748b",cardBackground:"rgba(255,255,255,0.7)",cardBackgroundSecondary:"rgba(255,255,255,0.5)",borderColor:"#e2e8f0",heatmapColors:["#9be9a8","#40c463","#30a14e","#216e39"],heatmapEmpty:"#ebedf0"},dark:{background:"linear-gradient(135deg, #0f172a 0%, #1e293b 100%)",textPrimary:"#f8fafc",textSecondary:"#e2e8f0",textMuted:"#94a3b8",cardBackground:"rgba(255,255,255,0.05)",cardBackgroundSecondary:"rgba(255,255,255,0.04)",borderColor:"rgba(255,255,255,0.08)",heatmapColors:["#0e4429","#006d32","#26a641","#39d353"],heatmapEmpty:"#2d333b"}};function R({data:t,theme:l="light"}){var D,_,h,E,C,T;const n=Z[l],{totalMessages:r=0,totalSessions:o=0,totalLinesAdded:a=0,totalLinesRemoved:s=0,totalFiles:i=0,currentStreak:m=0,longestStreak:d=0,activeHours:c={}}=t,g=Object.keys(t.heatmap||{});let f=0,u="";if(g.length>0){f=g.length;const y=g.map(w=>new Date(w).getTime()),v=new Date(Math.min(...y)),I=new Date(Math.max(...y)),b=w=>w.toISOString().split("T")[0];u=`${b(v)} \u2014 ${b(I)}`}const x=(h=(_=(D=t.qualitative)==null?void 0:D.interactionStyle)==null?void 0:_.key_pattern)!=null?h:null,S=(T=(C=(E=t.qualitative)==null?void 0:E.memorableMoment)==null?void 0:C.headline)!=null?T:null,A=te(t.heatmap||{},n);return e.createElement("div",{id:"share-card",style:{width:"1200px",background:n.background,color:n.textPrimary,fontFamily:\'ui-sans-serif, system-ui, sans-serif, "Apple Color Emoji", "Segoe UI Emoji"\',display:"flex",flexDirection:"column",padding:"48px 56px",position:"absolute",left:"-9999px",top:"-9999px",overflow:"hidden",boxSizing:"border-box"}},e.createElement("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"flex-start",marginBottom:"32px"}},e.createElement("div",null,e.createElement("div",{style:{fontSize:"32px",fontWeight:700,letterSpacing:"-0.02em",lineHeight:1.2}},"Qwen Code Insights"),e.createElement("div",{style:{fontSize:"14px",color:n.textMuted,marginTop:"6px"}},u)),e.createElement("div",{style:{fontSize:"11px",color:n.textMuted,textTransform:"uppercase",letterSpacing:"0.15em",paddingTop:"8px"}},"qwen.ai")),e.createElement("div",{style:{display:"grid",gridTemplateColumns:"repeat(6, 1fr)",gap:"16px",marginBottom:"32px"}},e.createElement(k,{value:String(r),label:"Messages",theme:n}),e.createElement(k,{value:String(o),label:"Sessions",theme:n}),e.createElement(k,{value:`+${a}/-${s}`,label:"Lines Changed",small:!0,theme:n}),e.createElement(k,{value:String(i),label:"Files",theme:n}),e.createElement(k,{value:`${m}d`,label:"Streak",theme:n}),e.createElement(k,{value:`${d}d`,label:"Best Streak",theme:n})),e.createElement("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:"24px",marginBottom:"16px"}},e.createElement("div",{style:{background:n.cardBackground,borderRadius:"12px",padding:"20px",display:"flex",flexDirection:"column"}},e.createElement("div",{style:{fontSize:"12px",fontWeight:600,color:n.textMuted,textTransform:"uppercase",letterSpacing:"0.08em",marginBottom:"12px"}},"Activity \xB7 ",f," active days"),e.createElement("div",{style:{flex:1,display:"flex",alignItems:"center",justifyContent:"center"}},e.createElement(le,{cells:A})),e.createElement(re,{theme:n})),e.createElement("div",{style:{display:"flex",flexDirection:"column",gap:"16px"}},e.createElement("div",{style:{background:n.cardBackground,borderRadius:"12px",padding:"20px",display:"flex",flexDirection:"column"}},e.createElement("div",{style:{fontSize:"12px",fontWeight:600,color:n.textMuted,textTransform:"uppercase",letterSpacing:"0.08em",marginBottom:"12px"}},"Active Hours"),e.createElement("div",{style:{flex:1,display:"flex",flexDirection:"column",justifyContent:"center",gap:"10px"}},e.createElement(ee,{activeHours:c,theme:n}))),e.createElement("div",{style:{background:n.cardBackgroundSecondary,borderRadius:"12px",padding:"16px 16px",position:"relative"}},e.createElement("div",{style:{position:"absolute",left:"12px",fontSize:"64px",fontWeight:700,color:l==="light"?"rgba(99,102,241,0.15)":"rgba(99,102,241,0.2)",lineHeight:1,fontFamily:\'Georgia, "Times New Roman", serif\',userSelect:"none",pointerEvents:"none"}},"\u201C"),e.createElement("div",{style:{paddingLeft:"40px",position:"relative"}},x&&e.createElement("div",{style:{fontSize:"13px",color:n.textSecondary,lineHeight:1.6,marginBottom:S?"8px":0}},x),S&&e.createElement("div",{style:{fontSize:"12px",color:n.textMuted,lineHeight:1.5,fontStyle:"italic"}},S))))),e.createElement("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginTop:"auto",paddingTop:"24px",borderTop:`1px solid ${n.borderColor}`,flexShrink:0}},e.createElement("div",{style:{fontSize:"12px",color:n.textMuted}},"Generated by Qwen Code \xB7 ",new Date().toISOString().split("T")[0]),e.createElement("div",{style:{fontSize:"12px",color:n.textMuted}},"github.com/QwenLM/qwen-code")))}function k({value:t,label:l,small:n,theme:r}){return e.createElement("div",{style:{textAlign:"center"}},e.createElement("div",{style:{fontSize:n?"18px":"28px",fontWeight:700,color:r.textPrimary,lineHeight:1.2}},t),e.createElement("div",{style:{fontSize:"11px",color:r.textMuted,textTransform:"uppercase",letterSpacing:"0.05em",marginTop:"4px"}},l))}function ee({activeHours:t,theme:l}){const r=[{label:"Morning",time:"06\u201312",hours:[6,7,8,9,10,11],color:"#fbbf24"},{label:"Afternoon",time:"12\u201318",hours:[12,13,14,15,16,17],color:"#0ea5e9"},{label:"Evening",time:"18\u201322",hours:[18,19,20,21],color:"#6366f1"},{label:"Night",time:"22\u201306",hours:[22,23,0,1,2,3,4,5],color:"#475569"}].map(a=>({...a,total:a.hours.reduce((s,i)=>s+(t[i]||0),0)})),o=Math.max(...r.map(a=>a.total),1);return e.createElement(e.Fragment,null,r.map(a=>{const s=o>0?a.total/o*100:0;return e.createElement("div",{key:a.label},e.createElement("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",fontSize:"12px",marginBottom:"4px"}},e.createElement("div",{style:{display:"flex",alignItems:"center",gap:"6px"}},e.createElement("span",{style:{width:"8px",height:"8px",borderRadius:"50%",backgroundColor:a.color,display:"inline-block",flexShrink:0}}),e.createElement("span",{style:{color:l.textSecondary,fontWeight:500}},a.label),e.createElement("span",{style:{color:l.textMuted,fontSize:"11px"}},a.time)),e.createElement("span",{style:{color:l.textMuted,fontWeight:600}},a.total)),e.createElement("div",{style:{height:"6px",background:l.borderColor,borderRadius:"3px",overflow:"hidden"}},e.createElement("div",{style:{width:`${s}%`,height:"100%",backgroundColor:a.color,borderRadius:"3px"}})))}))}function te(t,l){const n=new Date,o=26*7,a=new Date(n);a.setDate(a.getDate()-o+1),a.setDate(a.getDate()-a.getDay());const s=[],i=new Date(n);i.setDate(i.getDate()+(6-i.getDay()));const m=new Date(a);for(;m<=i;){const d=m.toISOString().split("T")[0],c=t[d]||0;s.push({color:ne(c,l)}),m.setDate(m.getDate()+1)}return s}function ne(t,l){return t===0?l.heatmapEmpty:t<2?l.heatmapColors[0]:t<4?l.heatmapColors[1]:t<10?l.heatmapColors[2]:l.heatmapColors[3]}function le({cells:t}){const n=Math.ceil(t.length/7),r=14,o=3,a=n*(r+o),s=7*(r+o);return e.createElement("svg",{width:a,height:s,viewBox:`0 0 ${a} ${s}`},t.map((i,m)=>{const d=Math.floor(m/7),c=m%7;return e.createElement("rect",{key:m,x:d*(r+o),y:c*(r+o),width:r,height:r,rx:2,fill:i.color})}))}function re({theme:t}){return e.createElement("div",{style:{display:"flex",alignItems:"center",gap:"8px",marginTop:"12px"}},e.createElement("span",{style:{fontSize:"11px",color:t.textMuted}},"Less"),[t.heatmapEmpty,t.heatmapColors[0],t.heatmapColors[1],t.heatmapColors[2],t.heatmapColors[3]].map((l,n)=>e.createElement("span",{key:n,style:{width:"10px",height:"10px",borderRadius:"2px",backgroundColor:l,display:"inline-block"}})),e.createElement("span",{style:{fontSize:"11px",color:t.textMuted}},"More"))}function ae({data:t}){var m;const[l,n]=e.useState("dark"),r=e.useRef(!1),o=async()=>{const d=document.getElementById("share-card");if(!d||!window.html2canvas){alert("Export functionality is not available.");return}try{const c=d.cloneNode(!0);c.style.position="fixed",c.style.left="-9999px",c.style.top="0",c.style.pointerEvents="none",document.body.appendChild(c);const g=await window.html2canvas(c,{scale:2,useCORS:!0,logging:!1,width:1200,height:c.scrollHeight});document.body.removeChild(c);const f=g.toDataURL("image/png"),u=document.createElement("a");u.href=f,u.download=`qwen-insights-card-${new Date().toISOString().slice(0,10)}.png`,u.click()}catch(c){console.error("Export card error:",c),alert("Failed to export card. Please try again.")}};e.useEffect(()=>{r.current&&(r.current=!1,o())},[l]);const a=d=>{d===l?o():(r.current=!0,n(d))};if(!t)return e.createElement("div",{className:"text-center text-slate-600"},"No insight data available");const s=Object.keys(t.heatmap||{});let i="";if(s.length>0){const c=s.map(x=>new Date(x)).map(x=>x.getTime()),g=new Date(Math.min(...c)),f=new Date(Math.max(...c)),u=x=>x.toISOString().split("T")[0];i=`${u(g)} to ${u(f)}`}return e.createElement("div",null,e.createElement("header",{className:"insights-header"},e.createElement("div",{className:"header-content"},e.createElement("div",{className:"header-title-section"},e.createElement("h1",{className:"header-title"},"Qwen Code Insights"),e.createElement("p",{className:"header-subtitle"},t.totalMessages?`${t.totalMessages.toLocaleString()} messages across ${(m=t.totalSessions)==null?void 0:m.toLocaleString()} sessions`:"Your personalized coding journey and patterns",i&&` \xB7 ${i}`)),e.createElement(se,{onExport:a}))),t.qualitative&&e.createElement(e.Fragment,null,e.createElement(L,{qualitative:t.qualitative}),e.createElement($,null)),e.createElement(j,{data:t}),t.qualitative&&e.createElement(e.Fragment,null,e.createElement(Q,{qualitative:t.qualitative,topGoals:t.topGoals,topTools:t.topTools})),t.qualitative&&e.createElement(e.Fragment,null,e.createElement(P,{qualitative:t.qualitative,insights:t})),t.qualitative&&e.createElement(e.Fragment,null,e.createElement(G,{qualitative:t.qualitative,primarySuccess:t.primarySuccess,outcomes:t.outcomes}),e.createElement(U,{qualitative:t.qualitative,satisfaction:t.satisfaction,friction:t.friction}),e.createElement(J,{qualitative:t.qualitative}),e.createElement(X,{qualitative:t.qualitative}),e.createElement(V,{qualitative:t.qualitative})),e.createElement(R,{data:t,theme:l}))}function se({onExport:t}){const[l,n]=e.useState(!1),r=e.useRef(null);e.useEffect(()=>{if(!l)return;const a=s=>{r.current&&!r.current.contains(s.target)&&n(!1)};return document.addEventListener("mousedown",a),()=>document.removeEventListener("mousedown",a)},[l]);const o=a=>{n(!1),t(a)};return e.createElement("div",{className:"export-dropdown-wrapper",ref:r},e.createElement("button",{className:"export-card-btn",onClick:()=>n(!l)},e.createElement("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},e.createElement("path",{d:"M4 12v8a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-8"}),e.createElement("polyline",{points:"16 6 12 2 8 6"}),e.createElement("line",{x1:"12",y1:"2",x2:"12",y2:"15"})),e.createElement("span",null,"Export Card"),e.createElement("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",className:`export-chevron ${l?"open":""}`},e.createElement("polyline",{points:"6 9 12 15 18 9"}))),l&&e.createElement("div",{className:"export-dropdown"},e.createElement("button",{className:"export-dropdown-item",onClick:()=>o("light")},e.createElement("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},e.createElement("circle",{cx:"12",cy:"12",r:"5"}),e.createElement("line",{x1:"12",y1:"1",x2:"12",y2:"3"}),e.createElement("line",{x1:"12",y1:"21",x2:"12",y2:"23"}),e.createElement("line",{x1:"4.22",y1:"4.22",x2:"5.64",y2:"5.64"}),e.createElement("line",{x1:"18.36",y1:"18.36",x2:"19.78",y2:"19.78"}),e.createElement("line",{x1:"1",y1:"12",x2:"3",y2:"12"}),e.createElement("line",{x1:"21",y1:"12",x2:"23",y2:"12"}),e.createElement("line",{x1:"4.22",y1:"19.78",x2:"5.64",y2:"18.36"}),e.createElement("line",{x1:"18.36",y1:"5.64",x2:"19.78",y2:"4.22"})),e.createElement("span",null,"Light Theme")),e.createElement("button",{className:"export-dropdown-item",onClick:()=>o("dark")},e.createElement("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},e.createElement("path",{d:"M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z"})),e.createElement("span",null,"Dark Theme"))))}const W=document.getElementById("react-root");W&&window.INSIGHT_DATA&&z?z.createRoot(W).render(e.createElement(ae,{data:window.INSIGHT_DATA})):console.error("Failed to mount React app:",{container:!!W,data:!!window.INSIGHT_DATA,ReactDOM:!!z})})(React,ReactDOM);';
var INSIGHT_CSS = '*,:before,:after,::backdrop{--tw-border-spacing-x: 0;--tw-border-spacing-y: 0;--tw-translate-x: 0;--tw-translate-y: 0;--tw-rotate: 0;--tw-skew-x: 0;--tw-skew-y: 0;--tw-scale-x: 1;--tw-scale-y: 1;--tw-pan-x: ;--tw-pan-y: ;--tw-pinch-zoom: ;--tw-scroll-snap-strictness: proximity;--tw-gradient-from-position: ;--tw-gradient-via-position: ;--tw-gradient-to-position: ;--tw-ordinal: ;--tw-slashed-zero: ;--tw-numeric-figure: ;--tw-numeric-spacing: ;--tw-numeric-fraction: ;--tw-ring-inset: ;--tw-ring-offset-width: 0px;--tw-ring-offset-color: #fff;--tw-ring-color: #3b82f680;--tw-ring-offset-shadow: 0 0 #0000;--tw-ring-shadow: 0 0 #0000;--tw-shadow: 0 0 #0000;--tw-shadow-colored: 0 0 #0000;--tw-blur: ;--tw-brightness: ;--tw-contrast: ;--tw-grayscale: ;--tw-hue-rotate: ;--tw-invert: ;--tw-saturate: ;--tw-sepia: ;--tw-drop-shadow: ;--tw-backdrop-blur: ;--tw-backdrop-brightness: ;--tw-backdrop-contrast: ;--tw-backdrop-grayscale: ;--tw-backdrop-hue-rotate: ;--tw-backdrop-invert: ;--tw-backdrop-opacity: ;--tw-backdrop-saturate: ;--tw-backdrop-sepia: ;--tw-contain-size: ;--tw-contain-layout: ;--tw-contain-paint: ;--tw-contain-style: }*,:before,:after{box-sizing:border-box;border:0 solid #e5e7eb}:before,:after{--tw-content: ""}html,:host{-webkit-text-size-adjust:100%;-moz-tab-size:4;-o-tab-size:4;tab-size:4;font-feature-settings:normal;font-variation-settings:normal;-webkit-tap-highlight-color:transparent;font-family:ui-sans-serif,system-ui,sans-serif,"Apple Color Emoji","Segoe UI Emoji",Segoe UI Symbol,"Noto Color Emoji";line-height:1.5}body{line-height:inherit;margin:0;background-image:linear-gradient(to bottom right,var(--tw-gradient-stops));--tw-gradient-from: #f8fafc var(--tw-gradient-from-position);--tw-gradient-to: #f1f5f9 var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), #fff var(--tw-gradient-via-position), var(--tw-gradient-to);--tw-text-opacity: 1;min-height:100vh;color:rgb(15 23 42 / var(--tw-text-opacity, 1));-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale}.glass-card{--tw-border-opacity: 1;border-width:1px;border-color:rgb(226 232 240 / var(--tw-border-opacity, 1));--tw-shadow: 0 10px 40px #0f172a14;--tw-shadow-colored: 0 10px 40px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow);--tw-backdrop-blur: blur(8px);backdrop-filter:var(--tw-backdrop-blur) var(--tw-backdrop-brightness) var(--tw-backdrop-contrast) var(--tw-backdrop-grayscale) var(--tw-backdrop-hue-rotate) var(--tw-backdrop-invert) var(--tw-backdrop-opacity) var(--tw-backdrop-saturate) var(--tw-backdrop-sepia);background-color:#fff9;border-radius:1rem}.col-span-2{grid-column:span 2 / span 2}.mx-auto{margin-left:auto;margin-right:auto}.mb-8{margin-bottom:2rem}.ml-2{margin-left:.5rem}.mt-1{margin-top:.25rem}.mt-2{margin-top:.5rem}.mt-4{margin-top:1rem}.mt-6{margin-top:1.5rem}.block{display:block}.flex{display:flex}.inline-flex{display:inline-flex}.grid{display:grid}.h-56{height:14rem}.h-full{height:100%}.min-h-screen{min-height:100vh}.w-full{width:100%}.min-w-\\[720px\\]{min-width:720px}.max-w-6xl{max-width:72rem}.grid-cols-2{grid-template-columns:repeat(2,minmax(0,1fr))}.grid-cols-3{grid-template-columns:repeat(3,minmax(0,1fr))}.flex-col{flex-direction:column}.items-start{align-items:flex-start}.items-center{align-items:center}.justify-center{justify-content:center}.justify-between{justify-content:space-between}.gap-1{gap:.25rem}.gap-2{gap:.5rem}.gap-3{gap:.75rem}.gap-4{gap:1rem}.space-y-3>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(.75rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(.75rem * var(--tw-space-y-reverse))}.space-y-4>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(1rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(1rem * var(--tw-space-y-reverse))}.divide-y>:not([hidden])~:not([hidden]){--tw-divide-y-reverse: 0;border-top-width:calc(1px * calc(1 - var(--tw-divide-y-reverse)));border-bottom-width:calc(1px * var(--tw-divide-y-reverse))}.divide-slate-200>:not([hidden])~:not([hidden]){--tw-divide-opacity: 1;border-color:rgb(226 232 240 / var(--tw-divide-opacity, 1))}.overflow-x-auto{overflow-x:auto}.rounded-full{border-radius:9999px}.rounded-xl{border-radius:1.25rem}.border{border-width:1px}.border-slate-100{--tw-border-opacity: 1;border-color:rgb(241 245 249 / var(--tw-border-opacity, 1))}.bg-emerald-50{--tw-bg-opacity: 1;background-color:rgb(236 253 245 / var(--tw-bg-opacity, 1))}.bg-slate-100{--tw-bg-opacity: 1;background-color:rgb(241 245 249 / var(--tw-bg-opacity, 1))}.bg-slate-50{--tw-bg-opacity: 1;background-color:rgb(248 250 252 / var(--tw-bg-opacity, 1))}.bg-slate-900{--tw-bg-opacity: 1;background-color:rgb(15 23 42 / var(--tw-bg-opacity, 1))}.bg-white\\/70{background-color:#ffffff73}.bg-gradient-to-br{background-image:linear-gradient(to bottom right,var(--tw-gradient-stops))}.from-slate-50{--tw-gradient-from: #f8fafc var(--tw-gradient-from-position);--tw-gradient-to: #f8fafc00 var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.via-white{--tw-gradient-to: #ffffff00 var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), #ffffff var(--tw-gradient-via-position), var(--tw-gradient-to)}.to-slate-100{--tw-gradient-to: #f1f5f9 var(--tw-gradient-to-position)}.p-4{padding:1rem}.p-6{padding:1.5rem}.px-3{padding-left:.75rem;padding-right:.75rem}.px-4{padding-left:1rem;padding-right:1rem}.px-5{padding-left:1.25rem;padding-right:1.25rem}.px-6{padding-left:1.5rem;padding-right:1.5rem}.px-8{padding-left:2rem;padding-right:2rem}.py-1{padding-top:.25rem;padding-bottom:.25rem}.py-10{padding-top:2.5rem;padding-bottom:2.5rem}.py-2{padding-top:.5rem;padding-bottom:.5rem}.py-3{padding-top:.75rem;padding-bottom:.75rem}.py-6{padding-top:1.5rem;padding-bottom:1.5rem}.text-left{text-align:left}.text-center{text-align:center}.text-2xl{font-size:1.5rem;line-height:2rem}.text-3xl{font-size:1.875rem;line-height:2.25rem}.text-4xl{font-size:2.25rem;line-height:2.5rem}.text-base{font-size:1rem;line-height:1.5rem}.text-lg{font-size:1.125rem;line-height:1.75rem}.text-sm{font-size:.875rem;line-height:1.25rem}.text-xl{font-size:1.25rem;line-height:1.75rem}.text-xs{font-size:.75rem;line-height:1rem}.font-bold{font-weight:700}.font-medium{font-weight:500}.font-semibold{font-weight:600}.uppercase{text-transform:uppercase}.tracking-\\[0\\.2em\\]{letter-spacing:.2em}.tracking-tight{letter-spacing:-.025em}.tracking-wide{letter-spacing:.025em}.text-emerald-700{--tw-text-opacity: 1;color:rgb(4 120 87 / var(--tw-text-opacity, 1))}.text-rose-700{--tw-text-opacity: 1;color:rgb(190 18 60 / var(--tw-text-opacity, 1))}.text-slate-200{--tw-text-opacity: 1;color:rgb(226 232 240 / var(--tw-text-opacity, 1))}.text-slate-400{--tw-text-opacity: 1;color:rgb(148 163 184 / var(--tw-text-opacity, 1))}.text-slate-500{--tw-text-opacity: 1;color:rgb(100 116 139 / var(--tw-text-opacity, 1))}.text-slate-600{--tw-text-opacity: 1;color:rgb(71 85 105 / var(--tw-text-opacity, 1))}.text-slate-700{--tw-text-opacity: 1;color:rgb(51 65 85 / var(--tw-text-opacity, 1))}.text-slate-900{--tw-text-opacity: 1;color:rgb(15 23 42 / var(--tw-text-opacity, 1))}.text-white{--tw-text-opacity: 1;color:rgb(255 255 255 / var(--tw-text-opacity, 1))}.shadow-inner{--tw-shadow: inset 0 2px 4px 0 #0000000d;--tw-shadow-colored: inset 0 2px 4px 0 var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.shadow-soft{--tw-shadow: 0 10px 40px #0f172a14;--tw-shadow-colored: 0 10px 40px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.shadow-slate-100{--tw-shadow-color: #f1f5f9;--tw-shadow: var(--tw-shadow-colored)}.transition{transition-property:color,background-color,border-color,text-decoration-color,fill,stroke,opacity,box-shadow,transform,filter,backdrop-filter;transition-duration:.15s;transition-timing-function:cubic-bezier(.4,0,.2,1)}.hover\\:-translate-y-\\[1px\\]:hover{--tw-translate-y: -1px;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.hover\\:shadow-lg:hover{--tw-shadow: 0 10px 15px -3px #0000001a, 0 4px 6px -4px #0000001a;--tw-shadow-colored: 0 10px 15px -3px var(--tw-shadow-color), 0 4px 6px -4px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.focus-visible\\:outline:focus-visible{outline-style:solid}.focus-visible\\:outline-2:focus-visible{outline-width:2px}.focus-visible\\:outline-offset-2:focus-visible{outline-offset:2px}.focus-visible\\:outline-slate-400:focus-visible{outline-color:#94a3b8}.active\\:translate-y-\\[1px\\]:active{--tw-translate-y: 1px;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.group:hover .group-hover\\:translate-x-0\\.5{--tw-translate-x: .125rem;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}@media (min-width: 768px){.md\\:mt-6{margin-top:1.5rem}.md\\:grid-cols-3{grid-template-columns:repeat(3,minmax(0,1fr))}.md\\:gap-6{gap:1.5rem}.md\\:py-12{padding-top:3rem;padding-bottom:3rem}.md\\:text-4xl{font-size:2.25rem;line-height:2.5rem}}.heatmap-container{width:100%;overflow-x:auto}.heatmap-svg{min-width:720px}.heatmap-day{cursor:pointer}.heatmap-day:hover{stroke:#00000024;stroke-width:1px}.heatmap-legend{display:flex;align-items:center;gap:4px;font-size:12px;color:#64748b;margin-top:8px}.heatmap-legend-item{width:10px;height:10px;border-radius:2px}.nav-toc{display:flex;flex-wrap:wrap;gap:8px;margin:24px 0 32px;padding:16px;background:#fff;border-radius:8px;border:1px solid #e2e8f0}.nav-toc a{font-size:12px;color:#64748b;text-decoration:none;padding:6px 12px;border-radius:6px;background:#f1f5f9;transition:all .15s}.nav-toc a:hover{background:#e2e8f0;color:#334155}.at-a-glance{background:linear-gradient(135deg,#fef3c7,#fde68a);border:1px solid #f59e0b;border-radius:12px;padding:20px 24px;margin-bottom:32px}.glance-title{font-size:16px;font-weight:700;color:#92400e;margin-bottom:16px}.glance-sections{display:flex;flex-direction:column;gap:12px}.glance-section{font-size:14px;color:#78350f;line-height:1.6}.glance-section strong{color:#92400e;font-weight:700}.see-more{color:#b45309;text-decoration:none;font-size:13px;white-space:nowrap;margin-left:4px}.see-more:hover{text-decoration:underline}.project-areas{display:flex;flex-direction:column;gap:12px;margin-bottom:32px}.project-area{background:#fff;border:1px solid #e2e8f0;border-radius:8px;padding:16px}.area-header{display:flex;justify-content:space-between;align-items:center;margin-bottom:8px}.area-name{font-weight:600;font-size:15px;color:#0f172a}.area-count{font-size:12px;color:#64748b;background:#f1f5f9;padding:2px 8px;border-radius:4px}.area-desc{font-size:14px;color:#475569;line-height:1.5}.narrative{background:#fff;border:1px solid #e2e8f0;border-radius:8px;padding:20px;margin-bottom:24px}.narrative p{margin-top:0;margin-bottom:12px;font-size:14px;color:#475569;line-height:1.7}.key-insight{background:#f0fdf4;border:1px solid #bbf7d0;border-radius:8px;padding:12px 16px;margin-top:12px;font-size:14px;color:#166534}.section-intro{font-size:14px;color:#64748b;margin-bottom:16px}.big-wins{display:flex;flex-direction:column;gap:12px;margin-bottom:24px}.big-win{background:#f0fdf4;border:1px solid #bbf7d0;border-radius:8px;padding:16px}.big-win-title{font-weight:600;font-size:15px;color:#166534;margin-bottom:8px}.big-win-desc{font-size:14px;color:#15803d;line-height:1.5}.friction-categories{display:flex;flex-direction:column;gap:16px;margin-bottom:24px}.friction-category{background:#fef2f2;border:1px solid #fca5a5;border-radius:8px;padding:16px}.friction-title{font-weight:600;font-size:15px;color:#991b1b;margin-bottom:6px}.friction-desc{font-size:13px;color:#7f1d1d;margin-bottom:10px}.friction-examples{margin:0 0 0 10px;padding:0;font-size:13px;color:#334155;list-style-type:disc}.friction-examples li{margin-bottom:4px}.qwen-md-section{background:#eff6ff;border:1px solid #bfdbfe;border-radius:8px;padding:12px;margin-bottom:20px}.qwen-md-section h3{font-size:13px;font-weight:600;color:#1e40af;margin:0 0 8px}.qwen-md-actions{margin-bottom:8px;padding-bottom:8px;border-bottom:1px solid #dbeafe}.copy-all-btn{background:#2563eb;color:#fff;border:none;border-radius:4px;padding:4px 10px;font-size:11px;cursor:pointer;font-weight:500;transition:all .2s}.copy-all-btn:hover{background:#1d4ed8}.copy-all-btn.copied{background:#16a34a}.qwen-md-item{display:flex;flex-wrap:wrap;align-items:flex-start;gap:8px;padding:8px 0;border-bottom:1px solid #dbeafe}.qwen-md-item:last-child{border-bottom:none}.cmd-checkbox{margin-top:2px}.cmd-code{background:#fff;padding:6px 10px;border-radius:4px;font-size:11px;color:#1e40af;border:1px solid #bfdbfe;font-family:monospace;display:block;white-space:pre-wrap;word-break:break-word;flex:1}.cmd-why{font-size:11px;color:#64748b;width:100%;padding-left:20px;margin-top:4px}.features-section,.patterns-section{display:flex;flex-direction:column;gap:12px;margin:16px 0}.feature-card{background:#f0fdf4;border:1px solid #86efac;border-radius:8px;padding:16px}.pattern-card{background:#f0f9ff;border:1px solid #7dd3fc;border-radius:8px;padding:16px}.feature-title,.pattern-title{font-weight:600;font-size:15px;color:#0f172a;margin-bottom:6px}.feature-oneliner,.pattern-summary{font-size:14px;color:#475569;margin-bottom:8px}.feature-why,.pattern-detail{font-size:13px;color:#334155;line-height:1.5}.feature-examples{margin-top:12px}.feature-example{padding:8px 0;border-top:1px solid #d1fae5}.feature-example:first-child{border-top:none}.example-code-row,.copyable-prompt-row{display:flex;align-items:flex-start;gap:8px}.example-code{flex:1;background:#f1f5f9;padding:8px 12px;border-radius:4px;font-family:monospace;font-size:12px;color:#334155;overflow-x:auto;white-space:pre-wrap}.copyable-prompt-section{margin-top:12px;padding-top:12px;border-top:1px solid #e2e8f0}.copyable-prompt{flex:1;background:#f8fafc;padding:10px 12px;border-radius:4px;font-family:monospace;font-size:12px;color:#334155;border:1px solid #e2e8f0;white-space:pre-wrap;line-height:1.5}.prompt-label{font-size:11px;font-weight:600;text-transform:uppercase;color:#64748b;margin-bottom:6px}.copy-btn{background:#e2e8f0;border:none;border-radius:4px;padding:4px 8px;font-size:11px;cursor:pointer;color:#475569;flex-shrink:0;transition:all .2s}.copy-btn:hover{background:#cbd5e1}.horizon-section{display:flex;flex-direction:column;gap:16px}.horizon-card{background:linear-gradient(135deg,#faf5ff,#f5f3ff);border:1px solid #c4b5fd;border-radius:8px;padding:16px}.horizon-title{font-weight:600;font-size:15px;color:#5b21b6;margin-bottom:8px}.horizon-possible{font-size:14px;color:#334155;margin-bottom:10px;line-height:1.5}.horizon-tip{font-size:13px;color:#6b21a8;background:#fff9;padding:8px 12px;border-radius:4px}.pattern-prompt{background:#f8fafc;padding:12px;border-radius:6px;margin-top:12px;border:1px solid #e2e8f0;display:flex;flex-direction:column;gap:8px}.pattern-prompt code{font-family:monospace;font-size:12px;color:#334155;display:block;white-space:pre-wrap}.fun-ending{background:linear-gradient(135deg,#fef3c7,#fde68a);border:1px solid #fbbf24;border-radius:12px;padding:24px;margin-top:40px;text-align:center}.fun-headline{font-size:18px;font-weight:600;color:#78350f;margin-bottom:8px}.fun-detail{font-size:14px;color:#92400e}.stats-row{display:flex;gap:24px;margin-bottom:40px;padding:20px 0;border-top:1px solid #e2e8f0;border-bottom:1px solid #e2e8f0;flex-wrap:wrap}.stat{text-align:center}.stat-value{font-size:24px;font-weight:700;color:#0f172a}.stat-label{font-size:11px;color:#64748b;text-transform:uppercase}@media (max-width: 640px){.stats-row{justify-content:center}}.header-with-action{position:relative}.insights-header{margin-bottom:2rem;padding:1.5rem 0;border-bottom:1px solid #e2e8f0}.header-content{display:flex;justify-content:space-between;align-items:center;gap:1.5rem;flex-wrap:wrap}.header-title-section{flex:1;min-width:0}.header-title{font-size:1.75rem;font-weight:700;color:#0f172a;letter-spacing:-.02em;margin:0 0 .375rem;line-height:1.2}.header-subtitle{font-size:.875rem;color:#64748b;margin:0;font-weight:400}.export-dropdown-wrapper{position:relative}.export-card-btn{display:inline-flex;align-items:center;gap:.5rem;height:36px;padding:0 .875rem;border:1px solid #e2e8f0;border-radius:8px;background:#fff;color:#334155;font-size:.8125rem;font-weight:500;cursor:pointer;transition:all .15s ease}.export-card-btn:hover{background:#f8fafc;border-color:#cbd5e1}.export-card-btn:active{background:#f1f5f9}.export-chevron{transition:transform .15s ease;opacity:.5}.export-chevron.open{transform:rotate(180deg)}.export-dropdown{position:absolute;top:calc(100% + 4px);right:0;min-width:160px;background:#fff;border:1px solid #e2e8f0;border-radius:8px;box-shadow:0 4px 16px #00000014;padding:4px;z-index:50}.export-dropdown-item{display:flex;align-items:center;gap:.5rem;width:100%;padding:.5rem .75rem;border:none;border-radius:6px;background:none;color:#334155;font-size:.8125rem;font-weight:400;cursor:pointer;transition:background .1s ease}.export-dropdown-item:hover{background:#f1f5f9}.export-dropdown-item:active{background:#e2e8f0}@media (max-width: 640px){.header-content{flex-direction:column;align-items:flex-start;gap:1rem}.header-title{font-size:1.5rem}}';

// packages/web-templates/dist/generated/exportHtmlTemplate.js
init_esbuild_shims();
var HTML_TEMPLATE = `<!doctype html>
<html lang="en" class="dark">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <link
      rel="icon"
      type="image/svg+xml"
      href="data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20viewBox%3D%220%200%20141.38%20140%22%3E%0A%20%20%3Cpath%0A%20%20%20%20fill%3D%22%23000000%22%0A%20%20%20%20d%3D%22m140.93%2085-16.35-28.33-1.93-3.34%208.66-15a3.323%203.323%200%200%200%200-3.34l-9.62-16.67c-.3-.51-.72-.93-1.22-1.22s-1.07-.45-1.67-.45H82.23l-8.66-15a3.33%203.33%200%200%200-2.89-1.67H51.43c-.59%200-1.17.16-1.66.45-.5.29-.92.71-1.22%201.22L32.19%2029.98l-1.92%203.33H12.96c-.59%200-1.17.16-1.66.45-.5.29-.93.71-1.22%201.22L.45%2051.66a3.323%203.323%200%200%200%200%203.34l18.28%2031.67-8.66%2015a3.32%203.32%200%200%200%200%203.34l9.62%2016.67c.3.51.72.93%201.22%201.22s1.07.45%201.67.45h36.56l8.66%2015a3.35%203.35%200%200%200%202.89%201.67h19.25a3.34%203.34%200%200%200%202.89-1.67l18.28-31.67h17.32c.6%200%201.17-.16%201.67-.45s.92-.71%201.22-1.22l9.62-16.67a3.323%203.323%200%200%200%200-3.34ZM51.44%203.33%2061.07%2020l-9.63%2016.66h76.98l-9.62%2016.66H45.67l-11.54-20zM57.21%20120H22.58l9.63-16.67h19.25l-38.5-66.67h19.25l9.62%2016.67L68.78%20100l-11.55%2020Zm61.59-33.34-9.62-16.67-38.49%2066.67-9.63-16.67%209.63-16.66%2026.94-46.67h23.1l17.32%2030z%22%0A%20%20%2F%3E%0A%3C%2Fsvg%3E"
    />
    <script
      crossorigin
      src="https://unpkg.com/react@18.2.0/umd/react.production.min.js"
    ></script>
    <script
      crossorigin
      src="https://unpkg.com/react-dom@18.2.0/umd/react-dom.production.min.js"
    ></script>
    <script>
      const withKey = (props, key) =>
        key == null ? props : Object.assign({}, props, { key });
      const jsx = (type, props, key) =>
        React.createElement(type, withKey(props, key));
      const jsxRuntime = {
        Fragment: React.Fragment,
        jsx,
        jsxs: jsx,
        jsxDEV: jsx,
      };
      window.ReactJSXRuntime = jsxRuntime;
      window['react/jsx-runtime'] = jsxRuntime;
      window['react/jsx-dev-runtime'] = jsxRuntime;
    </script>
    <script src="https://unpkg.com/@qwen-code/webui@latest/dist/index.umd.js"></script>
    <link
      rel="stylesheet"
      href="https://unpkg.com/@qwen-code/webui@latest/dist/styles.css"
    />
    <title>Qwen Code Chat Export</title>
    <style>
      @font-face {
        font-family: "Press Start 2P";
        font-style: normal;
        font-weight: 400;
        font-display: swap;
        src: url("data:font/woff2;base64,d09GMgABAAAAAALQAAwAAAAABfwAAAKBAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAHCgGYABUEQgKgkSCDAsOAAE2AiQDDgQgBYRKByAb4QTIBB76Oev9JKW02x5ClpELSxHm1M0JQ+OBJAtDpAAVUQ7i///V+A/YgLVswlGo/7a+lmW3sfnUvoBFcUKzUFEnKo08S0F2T8TiAAJQieDvSGUVdW3smBv2LuCGjSpG3jQTD/m9OI5lTDomdQG1hkoMkCJu1ZYsmL42dEu7W8q5gUan/J6yyO+FX5NO5qQPxaqGnEINZ2q7kDf0+i4UigAXdiQUNMppoJnOzcxnDMwX5lXzinnJPDtkzhQFwjTx0DGrx1zkoNhIYr5LTKHjclcs+z3Frrh2ue3Kvk6bxzoRJLsIQpWcQhW27bgJwoUHYXNi2WWnVRUWaVNS0XMJ1eIUHlSX0l3l7BZOOos1ySk7NUWl6+eobG3Nfpj96g8EvukB3Qjouo4+O6svG9/0b8ZyKmfoZj9gzBqq8I2MS7Pf2JquL9vZwHJ51djyD01vbVHRDxSslvFBZwMHjQvexMxIvz3oyftul2+k9yBS+xGM+l+d+Pvo/zH5fVXMRvsHhG4u9/dRsgQyF67l9+jYgZuy+Ath2O6EUzU7E6BxF41nQk2cgkN8IIlOPKecMgWccSrE4XdaOECf00oUaeTm34EpvHhZIodEEllllBWmWcJLyQmsPjNHAousMEkijVRQR5OgNc4qq7TiZZg89pJCE/G0MM4kPuYqqIOKrQw3WmQBjVQSSLLm1H1NiGmCN21uwK/JpZRuWignd/klmbWXFEtZZIn1o8cmkaDqX5JIJgWNNqYYR9s0GsRFZhhntKJSjI+KTaFDZ+MoRllkjHWK2ADCxilLQGTkJZo4NAJMDwhAiK0CJD+jjKFRwWBapYFh5rdzfogQC/m1XLplXiEFEwAA") format("woff2");
      }
      :root{--bg-primary: #18181b;--bg-secondary: #27272a;--text-primary: #f4f4f5;--text-secondary: #a1a1aa;--border-color: #3f3f46;--accent-color: #3b82f6}body{font-family:ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,Liberation Mono,Courier New,monospace;margin:0;padding:0;background-color:var(--bg-primary);color:var(--text-primary);line-height:1.6;-webkit-font-smoothing:antialiased}.page-wrapper{min-height:100vh;display:flex;flex-direction:column;align-items:center}.header{width:100%;padding:16px 24px;border-bottom:1px solid var(--border-color);background-color:#18181bf2;backdrop-filter:blur(8px);position:sticky;top:0;z-index:100;display:flex;justify-content:space-between;align-items:center;box-sizing:border-box}.header-left{display:flex;align-items:center;gap:12px}.logo-icon{width:24px;height:24px;flex-shrink:0;display:flex;align-items:center;justify-content:center}.logo-icon svg{width:100%;height:100%}.logo{display:flex;flex-direction:column;line-height:1}.logo-text{font-family:"Press Start 2P",cursive;font-weight:400;font-size:24px;letter-spacing:-.05em;position:relative;color:#fff}.logo-text-inner{background:linear-gradient(to right,#60a5fa,#a855f7);-webkit-background-clip:text;-webkit-text-fill-color:transparent;position:relative;z-index:2}.logo-text:before,.logo-text:after{content:attr(data-text);position:absolute;top:0;left:0;width:100%;height:100%;z-index:1;background:none;-webkit-text-fill-color:transparent;-webkit-text-stroke:1px rgba(96,165,250,.3)}.logo-text:before{transform:translate(2px,2px);-webkit-text-stroke:1px rgba(168,85,247,.3)}.logo-text:after{transform:translate(4px,4px);opacity:.4}.logo-sub{font-size:11px;font-weight:600;color:var(--text-secondary);letter-spacing:.05em;text-transform:uppercase;margin-top:4px}.badge{font-size:11px;padding:2px 8px;border-radius:999px;background-color:var(--bg-secondary);color:var(--text-secondary);border:1px solid var(--border-color);font-weight:500}.meta{display:flex;gap:24px;font-size:13px;color:var(--text-secondary)}.meta-item{display:flex;align-items:center;gap:8px}.meta-label{color:#71717a}.chat-container{width:100%;max-width:900px;padding:40px 20px;box-sizing:border-box;flex:1}::-webkit-scrollbar{width:10px;height:10px}::-webkit-scrollbar-track{background:var(--bg-primary)}::-webkit-scrollbar-thumb{background:var(--bg-secondary);border-radius:5px;border:2px solid var(--bg-primary)}::-webkit-scrollbar-thumb:hover{background:#52525b}@media (max-width: 768px){.chat-container{max-width:100%;padding:20px 16px}.header{padding:12px 16px;flex-direction:column;align-items:flex-start;gap:12px}.header-left{width:100%;justify-content:space-between}.meta{width:100%;flex-direction:column;gap:6px}}@media (max-width: 480px){.chat-container{padding:16px 12px}}
    </style>
  </head>
  <body>
    <div id="app"></div>

    <script id="chat-data" type="application/json"></script>
    <script>
      (()=>{var a=\`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 141.38 140">
  <path
    fill="#000000"
    d="m140.93 85-16.35-28.33-1.93-3.34 8.66-15a3.323 3.323 0 0 0 0-3.34l-9.62-16.67c-.3-.51-.72-.93-1.22-1.22s-1.07-.45-1.67-.45H82.23l-8.66-15a3.33 3.33 0 0 0-2.89-1.67H51.43c-.59 0-1.17.16-1.66.45-.5.29-.92.71-1.22 1.22L32.19 29.98l-1.92 3.33H12.96c-.59 0-1.17.16-1.66.45-.5.29-.93.71-1.22 1.22L.45 51.66a3.323 3.323 0 0 0 0 3.34l18.28 31.67-8.66 15a3.32 3.32 0 0 0 0 3.34l9.62 16.67c.3.51.72.93 1.22 1.22s1.07.45 1.67.45h36.56l8.66 15a3.35 3.35 0 0 0 2.89 1.67h19.25a3.34 3.34 0 0 0 2.89-1.67l18.28-31.67h17.32c.6 0 1.17-.16 1.67-.45s.92-.71 1.22-1.22l9.62-16.67a3.323 3.323 0 0 0 0-3.34ZM51.44 3.33 61.07 20l-9.63 16.66h76.98l-9.62 16.66H45.67l-11.54-20zM57.21 120H22.58l9.63-16.67h19.25l-38.5-66.67h19.25l9.62 16.67L68.78 100l-11.55 20Zm61.59-33.34-9.62-16.67-38.49 66.67-9.63-16.67 9.63-16.66 26.94-46.67h23.1l17.32 30z"
  />
</svg>
\`;var c=window.ReactDOM,{ChatViewer:p,PlatformProvider:g}=QwenCodeWebUI,m=a?a.replace(/<svg([^>]*)>/,'<svg$1><defs><linearGradient id="qwen-logo-gradient" x1="0%" y1="0%" x2="100%" y2="0%"><stop offset="0%" stop-color="#60a5fa" /><stop offset="100%" stop-color="#a855f7" /></linearGradient></defs>').replace(/fill="[^"]*"/,'fill="url(#qwen-logo-gradient)"'):a,f={platform:"web",postMessage:e=>{console.log("Posted message:",e)},onMessage:e=>(window.addEventListener("message",e),()=>window.removeEventListener("message",e)),openFile:e=>{console.log("Opening file:",e)},getResourceUrl:()=>{},features:{canOpenFile:!1,canCopy:!0}},x=e=>!!e&&typeof e=="object",h=()=>{let e=document.getElementById("chat-data");if(!(e!=null&&e.textContent))return{};try{let t=JSON.parse(e.textContent);return t&&typeof t=="object"?t:{}}catch(t){return console.error("Failed to parse chat data.",t),{}}},b=e=>{if(!e)return"-";try{return new Date(e).toLocaleString(void 0,{year:"numeric",month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}catch(t){return e}},u=()=>{var o;let e=h(),n=(Array.isArray(e.messages)?e.messages:[]).filter(x).filter(l=>l.type!=="system"),s=(o=e.sessionId)!=null?o:"-",i=b(e.startTime);return React.createElement("div",{className:"page-wrapper"},React.createElement("header",{className:"header"},React.createElement("div",{className:"header-left"},React.createElement("div",{className:"logo-icon","aria-hidden":"true",dangerouslySetInnerHTML:{__html:m}}),React.createElement("div",{className:"logo"},React.createElement("div",{className:"logo-text","data-text":"QWEN"},React.createElement("span",{className:"logo-text-inner"},"QWEN")))),React.createElement("div",{className:"meta"},React.createElement("div",{className:"meta-item"},React.createElement("span",{className:"meta-label"},"Session Id"),React.createElement("span",{className:"font-mono"},s)),React.createElement("div",{className:"meta-item"},React.createElement("span",{className:"meta-label"},"Export Time"),React.createElement("span",null,i)))),React.createElement("div",{className:"chat-container"},React.createElement(g,{value:f},React.createElement(p,{messages:n,autoScroll:!1,theme:"dark"}))))},r=document.getElementById("app");r?c.createRoot(r).render(React.createElement(u,null)):console.error("App container not found.");})();;
    </script>
  </body>
</html>
`;

// packages/cli/src/ui/utils/export/formatters/html.ts
function escapeJsonForHtml(json2) {
  return json2.replace(/<\/script/gi, "<\\/script").replace(/&/g, "\\u0026").replace(/</g, "\\u003c").replace(/>/g, "\\u003e").replace(/\u2028/g, "\\u2028").replace(/\u2029/g, "\\u2029");
}
__name(escapeJsonForHtml, "escapeJsonForHtml");
function loadHtmlTemplate() {
  return HTML_TEMPLATE;
}
__name(loadHtmlTemplate, "loadHtmlTemplate");
function injectDataIntoHtmlTemplate(template, data) {
  const jsonData = JSON.stringify(data, null, 2);
  const escapedJsonData = escapeJsonForHtml(jsonData);
  const idAttribute = 'id="chat-data"';
  const idIndex = template.indexOf(idAttribute);
  if (idIndex === -1) {
    return template;
  }
  const openTagStart = template.lastIndexOf("<script", idIndex);
  if (openTagStart === -1) {
    return template;
  }
  const openTagEnd = template.indexOf(">", idIndex);
  if (openTagEnd === -1) {
    return template;
  }
  const closeTagStart = template.indexOf("</script>", openTagEnd);
  if (closeTagStart === -1) {
    return template;
  }
  const lineStart = template.lastIndexOf("\n", openTagStart);
  const lineIndent = lineStart === -1 ? "" : template.slice(lineStart + 1, openTagStart);
  const indentedJson = escapedJsonData.split("\n").map((line) => `${lineIndent}${line}`).join("\n");
  const before = template.slice(0, openTagEnd + 1);
  const after = template.slice(closeTagStart);
  return `${before}
${indentedJson}
${after}`;
}
__name(injectDataIntoHtmlTemplate, "injectDataIntoHtmlTemplate");
function toHtml(sessionData) {
  const template = loadHtmlTemplate();
  return injectDataIntoHtmlTemplate(template, sessionData);
}
__name(toHtml, "toHtml");

// packages/cli/src/ui/utils/export/formatters/json.ts
init_esbuild_shims();
function toJson(sessionData) {
  return JSON.stringify(sessionData, null, 2);
}
__name(toJson, "toJson");

// packages/cli/src/ui/utils/export/formatters/jsonl.ts
init_esbuild_shims();
function toJsonl(sessionData) {
  const lines = [];
  lines.push(
    JSON.stringify({
      type: "session_metadata",
      sessionId: sessionData.sessionId,
      startTime: sessionData.startTime
    })
  );
  for (const message of sessionData.messages) {
    lines.push(JSON.stringify(message));
  }
  return lines.join("\n");
}
__name(toJsonl, "toJsonl");

// packages/cli/src/ui/utils/export/utils.ts
init_esbuild_shims();
function generateExportFilename(extension) {
  const timestamp = (/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-");
  return `qwen-code-export-${timestamp}.${extension}`;
}
__name(generateExportFilename, "generateExportFilename");

// packages/cli/src/ui/commands/exportCommand.ts
async function exportMarkdownAction(context2) {
  const { services } = context2;
  const { config: config2 } = services;
  if (!config2) {
    return {
      type: "message",
      messageType: "error",
      content: "Configuration not available."
    };
  }
  const cwd7 = config2.getWorkingDir() || config2.getProjectRoot();
  if (!cwd7) {
    return {
      type: "message",
      messageType: "error",
      content: "Could not determine current working directory."
    };
  }
  try {
    const sessionService = new SessionService(cwd7);
    const sessionData = await sessionService.loadLastSession();
    if (!sessionData) {
      return {
        type: "message",
        messageType: "error",
        content: "No active session found to export."
      };
    }
    const { conversation } = sessionData;
    const exportData = await collectSessionData(conversation, config2);
    const normalizedData = normalizeSessionData(
      exportData,
      conversation.messages,
      config2
    );
    const markdown2 = toMarkdown(normalizedData);
    const filename = generateExportFilename("md");
    const filepath = path91.join(cwd7, filename);
    await fs83.writeFile(filepath, markdown2, "utf-8");
    return {
      type: "message",
      messageType: "info",
      content: `Session exported to markdown: ${filename}`
    };
  } catch (error2) {
    return {
      type: "message",
      messageType: "error",
      content: `Failed to export session: ${error2 instanceof Error ? error2.message : String(error2)}`
    };
  }
}
__name(exportMarkdownAction, "exportMarkdownAction");
async function exportHtmlAction(context2) {
  const { services } = context2;
  const { config: config2 } = services;
  if (!config2) {
    return {
      type: "message",
      messageType: "error",
      content: "Configuration not available."
    };
  }
  const cwd7 = config2.getWorkingDir() || config2.getProjectRoot();
  if (!cwd7) {
    return {
      type: "message",
      messageType: "error",
      content: "Could not determine current working directory."
    };
  }
  try {
    const sessionService = new SessionService(cwd7);
    const sessionData = await sessionService.loadLastSession();
    if (!sessionData) {
      return {
        type: "message",
        messageType: "error",
        content: "No active session found to export."
      };
    }
    const { conversation } = sessionData;
    const exportData = await collectSessionData(conversation, config2);
    const normalizedData = normalizeSessionData(
      exportData,
      conversation.messages,
      config2
    );
    const html2 = toHtml(normalizedData);
    const filename = generateExportFilename("html");
    const filepath = path91.join(cwd7, filename);
    await fs83.writeFile(filepath, html2, "utf-8");
    return {
      type: "message",
      messageType: "info",
      content: `Session exported to HTML: ${filename}`
    };
  } catch (error2) {
    return {
      type: "message",
      messageType: "error",
      content: `Failed to export session: ${error2 instanceof Error ? error2.message : String(error2)}`
    };
  }
}
__name(exportHtmlAction, "exportHtmlAction");
async function exportJsonAction(context2) {
  const { services } = context2;
  const { config: config2 } = services;
  if (!config2) {
    return {
      type: "message",
      messageType: "error",
      content: "Configuration not available."
    };
  }
  const cwd7 = config2.getWorkingDir() || config2.getProjectRoot();
  if (!cwd7) {
    return {
      type: "message",
      messageType: "error",
      content: "Could not determine current working directory."
    };
  }
  try {
    const sessionService = new SessionService(cwd7);
    const sessionData = await sessionService.loadLastSession();
    if (!sessionData) {
      return {
        type: "message",
        messageType: "error",
        content: "No active session found to export."
      };
    }
    const { conversation } = sessionData;
    const exportData = await collectSessionData(conversation, config2);
    const normalizedData = normalizeSessionData(
      exportData,
      conversation.messages,
      config2
    );
    const json2 = toJson(normalizedData);
    const filename = generateExportFilename("json");
    const filepath = path91.join(cwd7, filename);
    await fs83.writeFile(filepath, json2, "utf-8");
    return {
      type: "message",
      messageType: "info",
      content: `Session exported to JSON: ${filename}`
    };
  } catch (error2) {
    return {
      type: "message",
      messageType: "error",
      content: `Failed to export session: ${error2 instanceof Error ? error2.message : String(error2)}`
    };
  }
}
__name(exportJsonAction, "exportJsonAction");
async function exportJsonlAction(context2) {
  const { services } = context2;
  const { config: config2 } = services;
  if (!config2) {
    return {
      type: "message",
      messageType: "error",
      content: "Configuration not available."
    };
  }
  const cwd7 = config2.getWorkingDir() || config2.getProjectRoot();
  if (!cwd7) {
    return {
      type: "message",
      messageType: "error",
      content: "Could not determine current working directory."
    };
  }
  try {
    const sessionService = new SessionService(cwd7);
    const sessionData = await sessionService.loadLastSession();
    if (!sessionData) {
      return {
        type: "message",
        messageType: "error",
        content: "No active session found to export."
      };
    }
    const { conversation } = sessionData;
    const exportData = await collectSessionData(conversation, config2);
    const normalizedData = normalizeSessionData(
      exportData,
      conversation.messages,
      config2
    );
    const jsonl = toJsonl(normalizedData);
    const filename = generateExportFilename("jsonl");
    const filepath = path91.join(cwd7, filename);
    await fs83.writeFile(filepath, jsonl, "utf-8");
    return {
      type: "message",
      messageType: "info",
      content: `Session exported to JSONL: ${filename}`
    };
  } catch (error2) {
    return {
      type: "message",
      messageType: "error",
      content: `Failed to export session: ${error2 instanceof Error ? error2.message : String(error2)}`
    };
  }
}
__name(exportJsonlAction, "exportJsonlAction");
var exportCommand = {
  name: "export",
  description: "Export current session message history to a file",
  kind: "built-in" /* BUILT_IN */,
  subCommands: [
    {
      name: "html",
      description: "Export session to HTML format",
      kind: "built-in" /* BUILT_IN */,
      action: exportHtmlAction
    },
    {
      name: "md",
      description: "Export session to markdown format",
      kind: "built-in" /* BUILT_IN */,
      action: exportMarkdownAction
    },
    {
      name: "json",
      description: "Export session to JSON format",
      kind: "built-in" /* BUILT_IN */,
      action: exportJsonAction
    },
    {
      name: "jsonl",
      description: "Export session to JSONL format (one message per line)",
      kind: "built-in" /* BUILT_IN */,
      action: exportJsonlAction
    }
  ]
};

// packages/cli/src/ui/commands/extensionsCommand.ts
init_esbuild_shims();
init_open();
var debugLogger76 = createDebugLogger("EXTENSIONS_COMMAND");
var EXTENSION_EXPLORE_URL = {
  Gemini: "https://geminicli.com/extensions/",
  ClaudeCode: "https://claudemarketplaces.com/"
};
function showMessageIfNoExtensions(context2, extensions) {
  if (extensions.length === 0) {
    context2.ui.addItem(
      {
        type: "info" /* INFO */,
        text: t4("No extensions installed.")
      },
      Date.now()
    );
    return true;
  }
  return false;
}
__name(showMessageIfNoExtensions, "showMessageIfNoExtensions");
async function exploreAction(context2, args) {
  const source2 = args.trim();
  const extensionsUrl = source2 ? EXTENSION_EXPLORE_URL[source2] : "";
  if (!extensionsUrl) {
    context2.ui.addItem(
      {
        type: "error" /* ERROR */,
        text: t4("Unknown extensions source: {{source}}.", { source: source2 })
      },
      Date.now()
    );
    return;
  }
  if (process.env["NODE_ENV"] === "test") {
    context2.ui.addItem(
      {
        type: "info" /* INFO */,
        text: t4(
          "Would open extensions page in your browser: {{url}} (skipped in test environment)",
          { url: extensionsUrl }
        )
      },
      Date.now()
    );
  } else if (process.env["SANDBOX"] && process.env["SANDBOX"] !== "sandbox-exec") {
    context2.ui.addItem(
      {
        type: "info" /* INFO */,
        text: t4("View available extensions at {{url}}", { url: extensionsUrl })
      },
      Date.now()
    );
  } else {
    context2.ui.addItem(
      {
        type: "info" /* INFO */,
        text: t4("Opening extensions page in your browser: {{url}}", {
          url: extensionsUrl
        })
      },
      Date.now()
    );
    try {
      await open_default(extensionsUrl);
    } catch (_error) {
      context2.ui.addItem(
        {
          type: "error" /* ERROR */,
          text: t4(
            "Failed to open browser. Check out the extensions gallery at {{url}}",
            { url: extensionsUrl }
          )
        },
        Date.now()
      );
    }
  }
}
__name(exploreAction, "exploreAction");
async function listAction(context2) {
  const extensions = context2.services.config ? context2.services.config.getExtensions() : [];
  if (showMessageIfNoExtensions(context2, extensions)) {
    return;
  }
  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;
  if (!all2 && names?.length === 0) {
    context2.ui.addItem(
      {
        type: "error" /* ERROR */,
        text: t4("Usage: /extensions update <extension-names>|--all")
      },
      Date.now()
    );
    return;
  }
  let updateInfos = [];
  const extensionManager = context2.services.config.getExtensionManager();
  const extensions = context2.services.config ? context2.services.config.getExtensions() : [];
  if (showMessageIfNoExtensions(context2, extensions)) {
    return Promise.resolve();
  }
  try {
    context2.ui.dispatchExtensionStateUpdate({ type: "BATCH_CHECK_START" });
    await extensionManager.checkForAllExtensionUpdates(
      (extensionName, state) => context2.ui.dispatchExtensionStateUpdate({
        type: "SET_STATE",
        payload: { name: extensionName, state }
      })
    );
    context2.ui.dispatchExtensionStateUpdate({ type: "BATCH_CHECK_END" });
    context2.ui.setPendingItem({
      type: "extensions_list" /* EXTENSIONS_LIST */
    });
    if (all2) {
      updateInfos = await extensionManager.updateAllUpdatableExtensions(
        context2.ui.extensionsUpdateState,
        (extensionName, state) => context2.ui.dispatchExtensionStateUpdate({
          type: "SET_STATE",
          payload: { name: extensionName, state }
        })
      );
    } else if (names?.length) {
      const extensions2 = context2.services.config.getExtensions();
      for (const name3 of names) {
        const extension = extensions2.find(
          (extension2) => extension2.name === name3
        );
        if (!extension) {
          context2.ui.addItem(
            {
              type: "error" /* ERROR */,
              text: t4('Extension "{{name}}" not found.', { name: name3 })
            },
            Date.now()
          );
          continue;
        }
        const updateInfo = await extensionManager.updateExtension(
          extension,
          context2.ui.extensionsUpdateState.get(extension.name)?.status ?? "unknown" /* UNKNOWN */,
          (extensionName, state) => context2.ui.dispatchExtensionStateUpdate({
            type: "SET_STATE",
            payload: { name: extensionName, state }
          })
        );
        if (updateInfo) updateInfos.push(updateInfo);
      }
    }
    if (updateInfos.length === 0) {
      context2.ui.addItem(
        {
          type: "info" /* INFO */,
          text: t4("No extensions to update.")
        },
        Date.now()
      );
      return;
    }
  } catch (error2) {
    context2.ui.addItem(
      {
        type: "error" /* ERROR */,
        text: getErrorMessage3(error2)
      },
      Date.now()
    );
  } finally {
    context2.ui.addItem(
      {
        type: "extensions_list" /* EXTENSIONS_LIST */
      },
      Date.now()
    );
    context2.ui.reloadCommands();
    context2.ui.setPendingItem(null);
  }
}
__name(updateAction, "updateAction");
async function installAction(context2, args) {
  const extensionManager = context2.services.config?.getExtensionManager();
  if (!(extensionManager instanceof ExtensionManager)) {
    debugLogger76.error(
      `Cannot ${context2.invocation?.name} extensions in this environment`
    );
    return;
  }
  const source2 = args.trim();
  if (!source2) {
    context2.ui.addItem(
      {
        type: "error" /* ERROR */,
        text: t4("Usage: /extensions install <source>")
      },
      Date.now()
    );
    return;
  }
  try {
    const installMetadata = await parseInstallSource(source2);
    context2.ui.addItem(
      {
        type: "info" /* INFO */,
        text: t4('Installing extension from "{{source}}"...', { source: source2 })
      },
      Date.now()
    );
    const extension = await extensionManager.installExtension(installMetadata);
    context2.ui.addItem(
      {
        type: "info" /* INFO */,
        text: t4('Extension "{{name}}" installed successfully.', {
          name: extension.name
        })
      },
      Date.now()
    );
    context2.ui.reloadCommands();
  } catch (error2) {
    context2.ui.addItem(
      {
        type: "error" /* ERROR */,
        text: t4('Failed to install extension from "{{source}}": {{error}}', {
          source: source2,
          error: getErrorMessage3(error2)
        })
      },
      Date.now()
    );
    return;
  }
}
__name(installAction, "installAction");
async function uninstallAction(context2, args) {
  const extensionManager = context2.services.config?.getExtensionManager();
  if (!(extensionManager instanceof ExtensionManager)) {
    debugLogger76.error(
      `Cannot ${context2.invocation?.name} extensions in this environment`
    );
    return;
  }
  const name3 = args.trim();
  if (!name3) {
    context2.ui.addItem(
      {
        type: "error" /* ERROR */,
        text: t4("Usage: /extensions uninstall <extension-name>")
      },
      Date.now()
    );
    return;
  }
  context2.ui.addItem(
    {
      type: "info" /* INFO */,
      text: t4('Uninstalling extension "{{name}}"...', { name: name3 })
    },
    Date.now()
  );
  try {
    await extensionManager.uninstallExtension(name3, false);
    context2.ui.addItem(
      {
        type: "info" /* INFO */,
        text: t4('Extension "{{name}}" uninstalled successfully.', { name: name3 })
      },
      Date.now()
    );
    context2.ui.reloadCommands();
  } catch (error2) {
    context2.ui.addItem(
      {
        type: "error" /* ERROR */,
        text: t4('Failed to uninstall extension "{{name}}": {{error}}', {
          name: name3,
          error: getErrorMessage3(error2)
        })
      },
      Date.now()
    );
  }
}
__name(uninstallAction, "uninstallAction");
function getEnableDisableContext(context2, argumentsString) {
  const extensionManager = context2.services.config?.getExtensionManager();
  if (!(extensionManager instanceof ExtensionManager)) {
    debugLogger76.error(
      `Cannot ${context2.invocation?.name} extensions in this environment`
    );
    return null;
  }
  const parts = argumentsString.split(" ");
  const name3 = parts[0];
  if (name3 === "" || !(parts.length === 2 && parts[1].startsWith("--scope=") || // --scope=<scope>
  parts.length === 3 && parts[1] === "--scope")) {
    context2.ui.addItem(
      {
        type: "error" /* ERROR */,
        text: t4(
          "Usage: /extensions {{command}} <extension> [--scope=<user|workspace>]",
          {
            command: context2.invocation?.name ?? ""
          }
        )
      },
      Date.now()
    );
    return null;
  }
  let scope;
  if (parts.length === 2) {
    parts.push(...parts[1].split("="));
    parts.splice(1, 1);
  }
  switch (parts[2].toLowerCase()) {
    case "workspace":
      scope = "Workspace" /* Workspace */;
      break;
    case "user":
      scope = "User" /* User */;
      break;
    default:
      context2.ui.addItem(
        {
          type: "error" /* ERROR */,
          text: t4(
            'Unsupported scope "{{scope}}", should be one of "user" or "workspace"',
            {
              scope: parts[2]
            }
          )
        },
        Date.now()
      );
      return null;
  }
  let names = [];
  if (name3 === "--all") {
    let extensions = extensionManager.getLoadedExtensions();
    if (context2.invocation?.name === "enable") {
      extensions = extensions.filter((ext2) => !ext2.isActive);
    }
    if (context2.invocation?.name === "disable") {
      extensions = extensions.filter((ext2) => ext2.isActive);
    }
    names = extensions.map((ext2) => ext2.name);
  } else {
    names = [name3];
  }
  return {
    extensionManager,
    names,
    scope
  };
}
__name(getEnableDisableContext, "getEnableDisableContext");
async function disableAction(context2, args) {
  const enableContext = getEnableDisableContext(context2, args);
  if (!enableContext) return;
  const { names, scope, extensionManager } = enableContext;
  for (const name3 of names) {
    await extensionManager.disableExtension(name3, scope);
    context2.ui.addItem(
      {
        type: "info" /* INFO */,
        text: t4('Extension "{{name}}" disabled for scope "{{scope}}"', {
          name: name3,
          scope
        })
      },
      Date.now()
    );
    context2.ui.reloadCommands();
  }
}
__name(disableAction, "disableAction");
async function enableAction(context2, args) {
  const enableContext = getEnableDisableContext(context2, args);
  if (!enableContext) return;
  const { names, scope, extensionManager } = enableContext;
  for (const name3 of names) {
    await extensionManager.enableExtension(name3, scope);
    context2.ui.addItem(
      {
        type: "info" /* INFO */,
        text: t4('Extension "{{name}}" enabled for scope "{{scope}}"', {
          name: name3,
          scope
        })
      },
      Date.now()
    );
    context2.ui.reloadCommands();
  }
}
__name(enableAction, "enableAction");
async function detailAction(context2, args) {
  const extensionManager = context2.services.config?.getExtensionManager();
  if (!(extensionManager instanceof ExtensionManager)) {
    debugLogger76.error(
      `Cannot ${context2.invocation?.name} extensions in this environment`
    );
    return;
  }
  const name3 = args.trim();
  if (!name3) {
    context2.ui.addItem(
      {
        type: "error" /* ERROR */,
        text: t4("Usage: /extensions detail <extension-name>")
      },
      Date.now()
    );
    return;
  }
  const extensions = context2.services.config.getExtensions();
  const extension = extensions.find((extension2) => extension2.name === name3);
  if (!extension) {
    context2.ui.addItem(
      {
        type: "error" /* ERROR */,
        text: t4('Extension "{{name}}" not found.', { name: name3 })
      },
      Date.now()
    );
    return;
  }
  context2.ui.addItem(
    {
      type: "info" /* INFO */,
      text: extensionToOutputString(
        extension,
        extensionManager,
        process.cwd(),
        true
      )
    },
    Date.now()
  );
}
__name(detailAction, "detailAction");
async function completeExtensions(context2, partialArg) {
  let extensions = context2.services.config?.getExtensions() ?? [];
  if (context2.invocation?.name === "enable") {
    extensions = extensions.filter((ext2) => !ext2.isActive);
  }
  if (context2.invocation?.name === "disable" || context2.invocation?.name === "restart") {
    extensions = extensions.filter((ext2) => ext2.isActive);
  }
  const extensionNames = extensions.map((ext2) => ext2.name);
  const suggestions = extensionNames.filter(
    (name3) => name3.startsWith(partialArg)
  );
  if (context2.invocation?.name !== "uninstall" && context2.invocation?.name !== "detail") {
    if ("--all".startsWith(partialArg) || "all".startsWith(partialArg)) {
      suggestions.unshift("--all");
    }
  }
  return suggestions;
}
__name(completeExtensions, "completeExtensions");
async function completeExtensionsAndScopes(context2, partialArg) {
  const completions = await completeExtensions(context2, partialArg);
  return completions.flatMap((s5) => [
    `${s5} --scope user`,
    `${s5} --scope workspace`
  ]);
}
__name(completeExtensionsAndScopes, "completeExtensionsAndScopes");
async function completeExtensionsExplore(context2, partialArg) {
  const suggestions = Object.keys(EXTENSION_EXPLORE_URL).filter(
    (name3) => name3.startsWith(partialArg)
  );
  return suggestions;
}
__name(completeExtensionsExplore, "completeExtensionsExplore");
var exploreExtensionsCommand = {
  name: "explore",
  get description() {
    return t4("Open extensions page in your browser");
  },
  kind: "built-in" /* BUILT_IN */,
  action: exploreAction,
  completion: completeExtensionsExplore
};
var listExtensionsCommand = {
  name: "list",
  get description() {
    return t4("List active extensions");
  },
  kind: "built-in" /* BUILT_IN */,
  action: listAction
};
var updateExtensionsCommand = {
  name: "update",
  get description() {
    return t4("Update extensions. Usage: update <extension-names>|--all");
  },
  kind: "built-in" /* BUILT_IN */,
  action: updateAction,
  completion: completeExtensions
};
var disableCommand2 = {
  name: "disable",
  get description() {
    return t4("Disable an extension");
  },
  kind: "built-in" /* BUILT_IN */,
  action: disableAction,
  completion: completeExtensionsAndScopes
};
var enableCommand2 = {
  name: "enable",
  get description() {
    return t4("Enable an extension");
  },
  kind: "built-in" /* BUILT_IN */,
  action: enableAction,
  completion: completeExtensionsAndScopes
};
var installCommand2 = {
  name: "install",
  get description() {
    return t4("Install an extension from a git repo or local path");
  },
  kind: "built-in" /* BUILT_IN */,
  action: installAction
};
var uninstallCommand2 = {
  name: "uninstall",
  get description() {
    return t4("Uninstall an extension");
  },
  kind: "built-in" /* BUILT_IN */,
  action: uninstallAction,
  completion: completeExtensions
};
var detailCommand = {
  name: "detail",
  get description() {
    return t4("Get detail of an extension");
  },
  kind: "built-in" /* BUILT_IN */,
  action: detailAction,
  completion: completeExtensions
};
var extensionsCommand2 = {
  name: "extensions",
  get description() {
    return t4("Manage extensions");
  },
  kind: "built-in" /* BUILT_IN */,
  subCommands: [
    listExtensionsCommand,
    updateExtensionsCommand,
    disableCommand2,
    enableCommand2,
    installCommand2,
    uninstallCommand2,
    exploreExtensionsCommand,
    detailCommand
  ],
  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 */,
  get description() {
    return t4("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 path92 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 basename26 = path92.basename(file.path);
    basenameCounts.set(basename26, (basenameCounts.get(basename26) || 0) + 1);
  }
  const fileList = openFiles.map((file) => {
    const basename26 = path92.basename(file.path);
    const isDuplicate = (basenameCounts.get(basename26) || 0) > 1;
    const parentDir = path92.basename(path92.dirname(file.path));
    const displayName = isDuplicate ? `${basename26} (/${parentDir})` : basename26;
    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(config2, value) {
  config2.setIdeMode(value);
  const ideClient = await IdeClient.getInstance();
  if (value) {
    await ideClient.connect();
    logIdeConnection(config2, 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",
      get description() {
        return t4("manage IDE integration");
      },
      kind: "built-in" /* BUILT_IN */,
      action: /* @__PURE__ */ __name(() => ({
        type: "message",
        messageType: "error",
        content: t4(
          "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",
    get description() {
      return t4("manage IDE integration");
    },
    kind: "built-in" /* BUILT_IN */,
    subCommands: []
  };
  const statusCommand = {
    name: "status",
    get description() {
      return t4("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 installCommand3 = {
    name: "install",
    get description() {
      const ideName = ideClient.getDetectedIdeDisplayName() ?? "IDE";
      return t4("install required IDE companion for {{ideName}}", {
        ideName
      });
    },
    kind: "built-in" /* BUILT_IN */,
    action: /* @__PURE__ */ __name(async (context2) => {
      const installer = getIdeInstaller(currentIDE);
      const isSandBox = !!process.env["SANDBOX"];
      if (isSandBox) {
        context2.ui.addItem(
          {
            type: "info",
            text: `IDE integration needs to be installed on the host. If you have already installed it, you can directly connect the ide`
          },
          Date.now()
        );
        return;
      }
      if (!installer) {
        const ideName = ideClient.getDetectedIdeDisplayName();
        context2.ui.addItem(
          {
            type: "error",
            text: `Automatic installation is not supported for ${ideName}. 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 i3 = 0; i3 < 10; i3++) {
          await setIdeModeAndSyncConnection(context2.services.config, true);
          if (ideClient.getConnectionStatus().status === IDEConnectionStatus.Connected) {
            break;
          }
          await new Promise((resolve30) => setTimeout(resolve30, 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 enableCommand3 = {
    name: "enable",
    get description() {
      return t4("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 disableCommand3 = {
    name: "disable",
    get description() {
      return t4("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, disableCommand3];
  } else {
    ideSlashCommand.subCommands = [
      enableCommand3,
      statusCommand,
      installCommand3
    ];
  }
  return ideSlashCommand;
}, "ideCommand");

// packages/cli/src/ui/commands/initCommand.ts
init_esbuild_shims();
import * as fs84 from "node:fs";
import * as path93 from "node:path";
var import_react27 = __toESM(require_react(), 1);
var initCommand = {
  name: "init",
  get description() {
    return t4("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: t4("Configuration not available.")
      };
    }
    const targetDir = context2.services.config.getTargetDir();
    const contextFileName = getCurrentGeminiMdFilename();
    const contextFilePath = path93.join(targetDir, contextFileName);
    try {
      if (fs84.existsSync(contextFilePath)) {
        try {
          const existing = fs84.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_react27.default.createElement(
                  Text3,
                  null,
                  `A ${contextFileName} file already exists in this directory. Do you want to regenerate it?`
                ),
                originalInvocation: {
                  raw: context2.invocation?.raw || "/init"
                }
              };
            }
          }
        } catch {
        }
      }
      try {
        fs84.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 (error2) {
      return {
        type: "message",
        messageType: "error",
        content: `Unexpected error preparing ${contextFileName}: ${error2 instanceof Error ? error2.message : String(error2)}`
      };
    }
    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/languageCommand.ts
init_esbuild_shims();

// packages/cli/src/utils/languageUtils.ts
init_esbuild_shims();
import * as fs85 from "node:fs";
import * as path94 from "node:path";
var LLM_OUTPUT_LANGUAGE_RULE_FILENAME = "output-language.md";
var LLM_OUTPUT_LANGUAGE_MARKER_PREFIX = "qwen-code:llm-output-language:";
var OUTPUT_LANGUAGE_AUTO = "auto";
function isAutoLanguage(value) {
  return !value || value.toLowerCase() === OUTPUT_LANGUAGE_AUTO;
}
__name(isAutoLanguage, "isAutoLanguage");
function normalizeOutputLanguage(language) {
  const lowered = language.toLowerCase();
  const fullName = getLanguageNameFromLocale(lowered);
  if (fullName !== "English" || lowered === "en") {
    return fullName;
  }
  return language;
}
__name(normalizeOutputLanguage, "normalizeOutputLanguage");
function resolveOutputLanguage(value) {
  if (isAutoLanguage(value)) {
    const detectedLocale = detectSystemLanguage();
    return getLanguageNameFromLocale(detectedLocale);
  }
  return normalizeOutputLanguage(value);
}
__name(resolveOutputLanguage, "resolveOutputLanguage");
function getOutputLanguageFilePath() {
  return path94.join(
    Storage.getGlobalQwenDir(),
    LLM_OUTPUT_LANGUAGE_RULE_FILENAME
  );
}
__name(getOutputLanguageFilePath, "getOutputLanguageFilePath");
function sanitizeForMarker(language) {
  return language.replace(/[\r\n]/g, " ").replace(/--!?>/g, "").replace(/--/g, "");
}
__name(sanitizeForMarker, "sanitizeForMarker");
function generateOutputLanguageFileContent(language) {
  const safeLanguage = sanitizeForMarker(language);
  return `# Output language preference: ${language}
<!-- ${LLM_OUTPUT_LANGUAGE_MARKER_PREFIX} ${safeLanguage} -->

## Goal
Prefer responding in **${language}** for normal assistant messages and explanations.

## Keep technical artifacts unchanged
Do **not** translate or rewrite:
- Code blocks, CLI commands, file paths, stack traces, logs, JSON keys, identifiers
- Exact quoted text from the user (keep quotes verbatim)

## When a conflict exists
If higher-priority instructions (system/developer) require a different behavior, follow them.

## Tool / system outputs
Raw tool/system outputs may contain fixed-format English. Preserve them verbatim, and if needed, add a short **${language}** explanation below.
`;
}
__name(generateOutputLanguageFileContent, "generateOutputLanguageFileContent");
function parseOutputLanguageFromContent(content) {
  const markerRegex = new RegExp(
    String.raw`<!--\s*${LLM_OUTPUT_LANGUAGE_MARKER_PREFIX}\s*(.*?)\s*-->`,
    "i"
  );
  const markerMatch = content.match(markerRegex);
  if (markerMatch?.[1]?.trim()) {
    return markerMatch[1].trim();
  }
  const headingMatch = content.match(
    /^#.*?CRITICAL:\s*(.*?)\s+Output Language Rule\b/im
  );
  if (headingMatch?.[1]?.trim()) {
    return headingMatch[1].trim();
  }
  return null;
}
__name(parseOutputLanguageFromContent, "parseOutputLanguageFromContent");
function readOutputLanguageFromFile() {
  const filePath = getOutputLanguageFilePath();
  if (!fs85.existsSync(filePath)) {
    return null;
  }
  try {
    const content = fs85.readFileSync(filePath, "utf-8");
    return parseOutputLanguageFromContent(content);
  } catch {
    return null;
  }
}
__name(readOutputLanguageFromFile, "readOutputLanguageFromFile");
function writeOutputLanguageFile(language) {
  const filePath = getOutputLanguageFilePath();
  const content = generateOutputLanguageFileContent(language);
  const dir = path94.dirname(filePath);
  fs85.mkdirSync(dir, { recursive: true });
  fs85.writeFileSync(filePath, content, "utf-8");
}
__name(writeOutputLanguageFile, "writeOutputLanguageFile");
function updateOutputLanguageFile(settingValue) {
  const resolved = resolveOutputLanguage(settingValue);
  writeOutputLanguageFile(resolved);
}
__name(updateOutputLanguageFile, "updateOutputLanguageFile");
function initializeLlmOutputLanguage(outputLanguage) {
  const resolved = resolveOutputLanguage(outputLanguage);
  const currentFileLanguage = readOutputLanguageFromFile();
  if (currentFileLanguage !== resolved) {
    writeOutputLanguageFile(resolved);
  }
}
__name(initializeLlmOutputLanguage, "initializeLlmOutputLanguage");

// packages/cli/src/ui/commands/languageCommand.ts
var debugLogger77 = createDebugLogger("LANGUAGE_COMMAND");
function getCurrentOutputLanguage(context2) {
  const settingValue = context2?.services?.settings?.merged?.general?.outputLanguage || OUTPUT_LANGUAGE_AUTO;
  const resolved = resolveOutputLanguage(settingValue);
  return { setting: settingValue, resolved };
}
__name(getCurrentOutputLanguage, "getCurrentOutputLanguage");
function parseUiLanguageArg(input) {
  const lowered = input.trim().toLowerCase();
  if (!lowered) return null;
  for (const lang of SUPPORTED_LANGUAGES) {
    if (lowered === lang.code || lowered === lang.id.toLowerCase() || lowered === lang.fullName.toLowerCase()) {
      return lang.code;
    }
  }
  return null;
}
__name(parseUiLanguageArg, "parseUiLanguageArg");
function formatUiLanguageDisplay(lang) {
  const option2 = SUPPORTED_LANGUAGES.find((o3) => o3.code === lang);
  if (!option2) return lang;
  return option2.nativeName && option2.nativeName !== option2.fullName ? `${option2.nativeName} (${option2.fullName}) [${option2.id}]` : `${option2.fullName} [${option2.id}]`;
}
__name(formatUiLanguageDisplay, "formatUiLanguageDisplay");
async function setUiLanguage(context2, lang) {
  const { services } = context2;
  if (!services.config) {
    return {
      type: "message",
      messageType: "error",
      content: t4("Configuration not available.")
    };
  }
  await setLanguageAsync(lang);
  if (services.settings?.setValue) {
    try {
      services.settings.setValue("User" /* User */, "general.language", lang);
    } catch (error2) {
      debugLogger77.warn("Failed to save language setting:", error2);
    }
  }
  context2.ui.reloadCommands();
  return {
    type: "message",
    messageType: "info",
    content: t4("UI language changed to {{lang}}", {
      lang: formatUiLanguageDisplay(lang)
    })
  };
}
__name(setUiLanguage, "setUiLanguage");
async function setOutputLanguage(context2, language) {
  try {
    const isAuto = isAutoLanguage(language);
    const resolved = resolveOutputLanguage(language);
    const settingValue = isAuto ? OUTPUT_LANGUAGE_AUTO : resolved;
    updateOutputLanguageFile(settingValue);
    if (context2.services.settings?.setValue) {
      try {
        context2.services.settings.setValue(
          "User" /* User */,
          "general.outputLanguage",
          settingValue
        );
      } catch (error2) {
        debugLogger77.warn("Failed to save output language setting:", error2);
      }
    }
    const displayLang = isAuto ? `${t4("Auto (detect from system)")} \u2192 ${resolved}` : resolved;
    return {
      type: "message",
      messageType: "info",
      content: [
        t4("LLM output language set to {{lang}}", { lang: displayLang }),
        "",
        t4("Please restart the application for the changes to take effect.")
      ].join("\n")
    };
  } catch (error2) {
    return {
      type: "message",
      messageType: "error",
      content: t4(
        "Failed to generate LLM output language rule file: {{error}}",
        {
          error: error2 instanceof Error ? error2.message : String(error2)
        }
      )
    };
  }
}
__name(setOutputLanguage, "setOutputLanguage");
var languageCommand = {
  name: "language",
  get description() {
    return t4("View or change the language setting");
  },
  kind: "built-in" /* BUILT_IN */,
  action: /* @__PURE__ */ __name(async (context2, args) => {
    if (!context2.services.config) {
      return {
        type: "message",
        messageType: "error",
        content: t4("Configuration not available.")
      };
    }
    const trimmedArgs = args.trim();
    if (trimmedArgs) {
      const [firstArg, ...rest] = trimmedArgs.split(/\s+/);
      const subCommandName = firstArg.toLowerCase();
      const subArgs = rest.join(" ");
      if (subCommandName === "ui" || subCommandName === "output") {
        const subCommand = languageCommand.subCommands?.find(
          (s5) => s5.name === subCommandName
        );
        if (subCommand?.action) {
          return subCommand.action(
            context2,
            subArgs
          );
        }
      }
      const targetLang = parseUiLanguageArg(trimmedArgs);
      if (targetLang) {
        return setUiLanguage(context2, targetLang);
      }
      return {
        type: "message",
        messageType: "error",
        content: [
          t4("Invalid command. Available subcommands:"),
          `  - /language ui [${getSupportedLanguageIds()}] - ${t4("Set UI language")}`,
          `  - /language output <language> - ${t4("Set LLM output language")}`
        ].join("\n")
      };
    }
    const currentUiLang = getCurrentLanguage();
    const { setting: outputSetting, resolved: outputResolved } = getCurrentOutputLanguage(context2);
    const outputLangDisplay = isAutoLanguage(outputSetting) ? `${t4("Auto (detect from system)")} \u2192 ${outputResolved}` : outputResolved;
    return {
      type: "message",
      messageType: "info",
      content: [
        t4("Current UI language: {{lang}}", {
          lang: formatUiLanguageDisplay(currentUiLang)
        }),
        t4("Current LLM output language: {{lang}}", { lang: outputLangDisplay }),
        "",
        t4("Available subcommands:"),
        `  /language ui [${getSupportedLanguageIds()}] - ${t4("Set UI language")}`,
        `  /language output <language> - ${t4("Set LLM output language")}`
      ].join("\n")
    };
  }, "action"),
  subCommands: [
    // /language ui subcommand
    {
      name: "ui",
      get description() {
        return t4("Set UI language");
      },
      kind: "built-in" /* BUILT_IN */,
      action: /* @__PURE__ */ __name(async (context2, args) => {
        const trimmedArgs = args.trim();
        if (!trimmedArgs) {
          return {
            type: "message",
            messageType: "info",
            content: [
              t4("Set UI language"),
              "",
              t4("Usage: /language ui [{{options}}]", {
                options: getSupportedLanguageIds()
              }),
              "",
              t4("Available options:"),
              ...SUPPORTED_LANGUAGES.map(
                (o3) => `  - ${o3.id}: ${o3.nativeName || o3.fullName}`
              ),
              "",
              t4(
                "To request additional UI language packs, please open an issue on GitHub."
              )
            ].join("\n")
          };
        }
        const targetLang = parseUiLanguageArg(trimmedArgs);
        if (!targetLang) {
          return {
            type: "message",
            messageType: "error",
            content: t4("Invalid language. Available: {{options}}", {
              options: getSupportedLanguageIds(",")
            })
          };
        }
        return setUiLanguage(context2, targetLang);
      }, "action"),
      // Nested subcommands for each supported language (e.g., /language ui zh-CN)
      subCommands: SUPPORTED_LANGUAGES.map(
        (lang) => ({
          name: lang.id,
          get description() {
            return t4("Set UI language to {{name}}", {
              name: lang.nativeName || lang.fullName
            });
          },
          kind: "built-in" /* BUILT_IN */,
          action: /* @__PURE__ */ __name(async (context2, args) => {
            if (args.trim()) {
              return {
                type: "message",
                messageType: "error",
                content: t4(
                  "Language subcommands do not accept additional arguments."
                )
              };
            }
            return setUiLanguage(context2, lang.code);
          }, "action")
        })
      )
    },
    // /language output subcommand
    {
      name: "output",
      get description() {
        return t4("Set LLM output language");
      },
      kind: "built-in" /* BUILT_IN */,
      action: /* @__PURE__ */ __name(async (context2, args) => {
        const trimmedArgs = args.trim();
        if (!trimmedArgs) {
          return {
            type: "message",
            messageType: "info",
            content: [
              t4("Set LLM output language"),
              "",
              t4("Usage: /language output <language>"),
              `  ${t4("Example: /language output \u4E2D\u6587")}`,
              `  ${t4("Example: /language output English")}`,
              `  ${t4("Example: /language output \u65E5\u672C\u8A9E")}`
            ].join("\n")
          };
        }
        return setOutputLanguage(context2, trimmedArgs);
      }, "action")
    }
  ]
};

// packages/cli/src/ui/commands/mcpCommand.ts
init_esbuild_shims();
var authCommand2 = {
  name: "auth",
  get description() {
    return t4("Authenticate with an OAuth-enabled MCP server");
  },
  kind: "built-in" /* BUILT_IN */,
  action: /* @__PURE__ */ __name(async (context2, args) => {
    const serverName = args.trim();
    const { config: config2 } = context2.services;
    if (!config2) {
      return {
        type: "message",
        messageType: "error",
        content: t4("Config not loaded.")
      };
    }
    const mcpServers = config2.getMcpServers() || {};
    if (!serverName) {
      const oauthServers = Object.entries(mcpServers).filter(([_2, server2]) => server2.oauth?.enabled).map(([name3, _2]) => name3);
      if (oauthServers.length === 0) {
        return {
          type: "message",
          messageType: "info",
          content: t4("No MCP servers configured with OAuth authentication.")
        };
      }
      return {
        type: "message",
        messageType: "info",
        content: `${t4("MCP servers with OAuth authentication:")}
${oauthServers.map((s5) => `  - ${s5}`).join("\n")}

${t4("Use /mcp auth <server-name> to authenticate.")}`
      };
    }
    const server = mcpServers[serverName];
    if (!server) {
      return {
        type: "message",
        messageType: "error",
        content: t4("MCP server '{{name}}' not found.", { name: serverName })
      };
    }
    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: t4(
            "Starting OAuth authentication for MCP server '{{name}}'...",
            {
              name: 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: t4(
            "Successfully authenticated and refreshed tools for '{{name}}'.",
            {
              name: serverName
            }
          )
        },
        Date.now()
      );
      const toolRegistry = config2.getToolRegistry();
      if (toolRegistry) {
        context2.ui.addItem(
          {
            type: "info",
            text: t4("Re-discovering tools from '{{name}}'...", {
              name: serverName
            })
          },
          Date.now()
        );
        await toolRegistry.discoverToolsForServer(serverName);
      }
      const geminiClient = config2.getGeminiClient();
      if (geminiClient) {
        await geminiClient.setTools();
      }
      context2.ui.reloadCommands();
      return {
        type: "message",
        messageType: "info",
        content: t4(
          "Successfully authenticated and refreshed tools for '{{name}}'.",
          {
            name: serverName
          }
        )
      };
    } catch (error2) {
      return {
        type: "message",
        messageType: "error",
        content: t4(
          "Failed to authenticate with MCP server '{{name}}': {{error}}",
          {
            name: serverName,
            error: getErrorMessage(error2)
          }
        )
      };
    } finally {
      appEvents.removeListener("oauth-display-message" /* OauthDisplayMessage */, displayListener);
    }
  }, "action"),
  completion: /* @__PURE__ */ __name(async (context2, partialArg) => {
    const { config: config2 } = context2.services;
    if (!config2) return [];
    const mcpServers = config2.getMcpServers() || {};
    return Object.keys(mcpServers).filter(
      (name3) => name3.startsWith(partialArg)
    );
  }, "completion")
};
var listCommand4 = {
  name: "list",
  get description() {
    return t4("List configured MCP servers and tools");
  },
  kind: "built-in" /* BUILT_IN */,
  action: /* @__PURE__ */ __name(async (context2, args) => {
    const { config: config2 } = context2.services;
    if (!config2) {
      return {
        type: "message",
        messageType: "error",
        content: t4("Config not loaded.")
      };
    }
    const toolRegistry = config2.getToolRegistry();
    if (!toolRegistry) {
      return {
        type: "message",
        messageType: "error",
        content: t4("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 = config2.getMcpServers() || {};
    const serverNames = Object.keys(mcpServers);
    const blockedMcpServers = config2.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 config2.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",
  get description() {
    return t4("Restarts MCP servers.");
  },
  kind: "built-in" /* BUILT_IN */,
  action: /* @__PURE__ */ __name(async (context2) => {
    const { config: config2 } = context2.services;
    if (!config2) {
      return {
        type: "message",
        messageType: "error",
        content: t4("Config not loaded.")
      };
    }
    const toolRegistry = config2.getToolRegistry();
    if (!toolRegistry) {
      return {
        type: "message",
        messageType: "error",
        content: t4("Could not retrieve tool registry.")
      };
    }
    context2.ui.addItem(
      {
        type: "info",
        text: t4("Restarting MCP servers...")
      },
      Date.now()
    );
    await toolRegistry.restartMcpServers();
    const geminiClient = config2.getGeminiClient();
    if (geminiClient) {
      await geminiClient.setTools();
    }
    context2.ui.reloadCommands();
    return listCommand4.action(context2, "");
  }, "action")
};
var mcpCommand2 = {
  name: "mcp",
  get description() {
    return t4(
      "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 path95 from "node:path";
import os31 from "node:os";
import fs86 from "node:fs/promises";
var memoryCommand = {
  name: "memory",
  get description() {
    return t4("Commands for interacting with memory.");
  },
  kind: "built-in" /* BUILT_IN */,
  subCommands: [
    {
      name: "show",
      get description() {
        return t4("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 ? `${t4("Current memory content from {{count}} file(s):", { count: String(fileCount) })}

---
${memoryContent}
---` : t4("Memory is currently empty.");
        context2.ui.addItem(
          {
            type: "info" /* INFO */,
            text: messageContent
          },
          Date.now()
        );
      }, "action"),
      subCommands: [
        {
          name: "--project",
          get description() {
            return t4("Show project-level memory contents.");
          },
          kind: "built-in" /* BUILT_IN */,
          action: /* @__PURE__ */ __name(async (context2) => {
            try {
              const workingDir = context2.services.config?.getWorkingDir?.() ?? process.cwd();
              const projectMemoryPath = path95.join(
                workingDir,
                getCurrentGeminiMdFilename()
              );
              const memoryContent = await fs86.readFile(
                projectMemoryPath,
                "utf-8"
              );
              const messageContent = memoryContent.trim().length > 0 ? t4(
                "Project memory content from {{path}}:\n\n---\n{{content}}\n---",
                {
                  path: projectMemoryPath,
                  content: memoryContent
                }
              ) : t4("Project memory is currently empty.");
              context2.ui.addItem(
                {
                  type: "info" /* INFO */,
                  text: messageContent
                },
                Date.now()
              );
            } catch (_error) {
              context2.ui.addItem(
                {
                  type: "info" /* INFO */,
                  text: t4(
                    "Project memory file not found or is currently empty."
                  )
                },
                Date.now()
              );
            }
          }, "action")
        },
        {
          name: "--global",
          get description() {
            return t4("Show global memory contents.");
          },
          kind: "built-in" /* BUILT_IN */,
          action: /* @__PURE__ */ __name(async (context2) => {
            try {
              const globalMemoryPath = path95.join(
                os31.homedir(),
                QWEN_DIR,
                getCurrentGeminiMdFilename()
              );
              const globalMemoryContent = await fs86.readFile(
                globalMemoryPath,
                "utf-8"
              );
              const messageContent = globalMemoryContent.trim().length > 0 ? t4("Global memory content:\n\n---\n{{content}}\n---", {
                content: globalMemoryContent
              }) : t4("Global memory is currently empty.");
              context2.ui.addItem(
                {
                  type: "info" /* INFO */,
                  text: messageContent
                },
                Date.now()
              );
            } catch (_error) {
              context2.ui.addItem(
                {
                  type: "info" /* INFO */,
                  text: t4(
                    "Global memory file not found or is currently empty."
                  )
                },
                Date.now()
              );
            }
          }, "action")
        }
      ]
    },
    {
      name: "add",
      get description() {
        return t4(
          "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: t4(
              "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: t4(
              "Usage: /memory add [--global|--project] <text to remember>"
            )
          };
        } else {
          fact = trimmedArgs;
        }
        if (!fact || fact.trim() === "") {
          return {
            type: "message",
            messageType: "error",
            content: t4(
              "Usage: /memory add [--global|--project] <text to remember>"
            )
          };
        }
        const scopeText = scope ? `(${scope})` : "";
        context2.ui.addItem(
          {
            type: "info" /* INFO */,
            text: t4('Attempting to save to memory {{scope}}: "{{fact}}"', {
              scope: scopeText,
              fact
            })
          },
          Date.now()
        );
        return {
          type: "tool",
          toolName: "save_memory",
          toolArgs: scope ? { fact, scope } : { fact }
        };
      }, "action"),
      subCommands: [
        {
          name: "--project",
          get description() {
            return t4("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: t4("Usage: /memory add --project <text to remember>")
              };
            }
            context2.ui.addItem(
              {
                type: "info" /* INFO */,
                text: t4('Attempting to save to project memory: "{{text}}"', {
                  text: args.trim()
                })
              },
              Date.now()
            );
            return {
              type: "tool",
              toolName: "save_memory",
              toolArgs: { fact: args.trim(), scope: "project" }
            };
          }, "action")
        },
        {
          name: "--global",
          get description() {
            return t4("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: t4("Usage: /memory add --global <text to remember>")
              };
            }
            context2.ui.addItem(
              {
                type: "info" /* INFO */,
                text: t4('Attempting to save to global memory: "{{text}}"', {
                  text: args.trim()
                })
              },
              Date.now()
            );
            return {
              type: "tool",
              toolName: "save_memory",
              toolArgs: { fact: args.trim(), scope: "global" }
            };
          }, "action")
        }
      ]
    },
    {
      name: "refresh",
      get description() {
        return t4("Refresh the memory from the source.");
      },
      kind: "built-in" /* BUILT_IN */,
      action: /* @__PURE__ */ __name(async (context2) => {
        context2.ui.addItem(
          {
            type: "info" /* INFO */,
            text: t4("Refreshing memory from source files...")
          },
          Date.now()
        );
        try {
          const config2 = context2.services.config;
          if (config2) {
            const { memoryContent, fileCount } = await loadServerHierarchicalMemory(
              config2.getWorkingDir(),
              config2.shouldLoadMemoryFromIncludeDirectories() ? config2.getWorkspaceContext().getDirectories() : [],
              config2.getFileService(),
              config2.getExtensionContextFilePaths(),
              config2.getFolderTrust(),
              context2.services.settings.merged.context?.importFormat || "tree"
              // Use setting or default to 'tree'
            );
            config2.setUserMemory(memoryContent);
            config2.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 (error2) {
          const errorMessage = getErrorMessage(error2);
          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",
  get description() {
    return t4("Switch the model for this session");
  },
  kind: "built-in" /* BUILT_IN */,
  action: /* @__PURE__ */ __name(async (context2) => {
    const { services } = context2;
    const { config: config2 } = services;
    if (!config2) {
      return {
        type: "message",
        messageType: "error",
        content: t4("Configuration not available.")
      };
    }
    const contentGeneratorConfig = config2.getContentGeneratorConfig();
    if (!contentGeneratorConfig) {
      return {
        type: "message",
        messageType: "error",
        content: t4("Content generator configuration not available.")
      };
    }
    const authType = contentGeneratorConfig.authType;
    if (!authType) {
      return {
        type: "message",
        messageType: "error",
        content: t4("Authentication type not available.")
      };
    }
    return {
      type: "dialog",
      dialog: "model"
    };
  }, "action")
};

// packages/cli/src/ui/commands/permissionsCommand.ts
init_esbuild_shims();
var permissionsCommand = {
  name: "permissions",
  get description() {
    return t4("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 quitCommand = {
  name: "quit",
  altNames: ["exit"],
  get description() {
    return t4("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 fs87 from "node:fs/promises";
import path96 from "node:path";
async function restoreAction(context2, args) {
  const { services, ui: ui2 } = context2;
  const { config: config2, git: gitService } = services;
  const { addItem, loadHistory } = ui2;
  const checkpointDir = config2?.storage.getProjectTempCheckpointsDir();
  if (!checkpointDir) {
    return {
      type: "message",
      messageType: "error",
      content: "Could not determine the .qwen directory path."
    };
  }
  try {
    await fs87.mkdir(checkpointDir, { recursive: true });
    const files = await fs87.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 = path96.join(checkpointDir, selectedFile);
    const data = await fs87.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 config2?.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 (error2) {
    return {
      type: "message",
      messageType: "error",
      content: `Could not read restorable tool calls. This is the error: ${error2}`
    };
  }
}
__name(restoreAction, "restoreAction");
async function completion2(context2, _partialArg) {
  const { services } = context2;
  const { config: config2 } = services;
  const checkpointDir = config2?.storage.getProjectTempCheckpointsDir();
  if (!checkpointDir) {
    return [];
  }
  try {
    const files = await fs87.readdir(checkpointDir);
    return files.filter((file) => file.endsWith(".json")).map((file) => file.replace(".json", ""));
  } catch (_err) {
    return [];
  }
}
__name(completion2, "completion");
var restoreCommand = /* @__PURE__ */ __name((config2) => {
  if (!config2?.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/resumeCommand.ts
init_esbuild_shims();
var resumeCommand = {
  name: "resume",
  kind: "built-in" /* BUILT_IN */,
  get description() {
    return t4("Resume a previous session");
  },
  action: /* @__PURE__ */ __name(async () => ({
    type: "dialog",
    dialog: "resume"
  }), "action")
};

// packages/cli/src/ui/commands/settingsCommand.ts
init_esbuild_shims();
var settingsCommand2 = {
  name: "settings",
  get description() {
    return t4("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/skillsCommand.ts
init_esbuild_shims();
init_fzf_es();
var debugLogger78 = createDebugLogger("SKILLS_COMMAND");
var skillsCommand = {
  name: "skills",
  get description() {
    return t4("List available skills.");
  },
  kind: "built-in" /* BUILT_IN */,
  action: /* @__PURE__ */ __name(async (context2, args) => {
    const rawArgs = args?.trim() ?? "";
    const [skillName = ""] = rawArgs.split(/\s+/);
    const skillManager = context2.services.config?.getSkillManager();
    if (!skillManager) {
      context2.ui.addItem(
        {
          type: "error" /* ERROR */,
          text: t4("Could not retrieve skill manager.")
        },
        Date.now()
      );
      return;
    }
    const skills = await skillManager.listSkills();
    if (skills.length === 0) {
      context2.ui.addItem(
        {
          type: "info" /* INFO */,
          text: t4("No skills are currently available.")
        },
        Date.now()
      );
      return;
    }
    if (!skillName) {
      const sortedSkills = [...skills].sort(
        (left3, right3) => left3.name.localeCompare(right3.name)
      );
      const skillsListItem = {
        type: "skills_list" /* SKILLS_LIST */,
        skills: sortedSkills.map((skill) => ({ name: skill.name }))
      };
      context2.ui.addItem(skillsListItem, Date.now());
      return;
    }
    const normalizedName = skillName.toLowerCase();
    const hasSkill = skills.some(
      (skill) => skill.name.toLowerCase() === normalizedName
    );
    if (!hasSkill) {
      context2.ui.addItem(
        {
          type: "error" /* ERROR */,
          text: t4("Unknown skill: {{name}}", { name: skillName })
        },
        Date.now()
      );
      return;
    }
    const rawInput = context2.invocation?.raw ?? `/skills ${rawArgs}`;
    return {
      type: "submit_prompt",
      content: [{ text: rawInput }]
    };
  }, "action"),
  completion: /* @__PURE__ */ __name(async (context2, partialArg) => {
    const skillManager = context2.services.config?.getSkillManager();
    if (!skillManager) {
      return [];
    }
    const skills = await skillManager.listSkills();
    const normalizedPartial = partialArg.trim();
    const matches = await getSkillMatches(skills, normalizedPartial);
    return matches.map((skill) => ({
      value: skill.name,
      description: skill.description
    }));
  }, "completion")
};
async function getSkillMatches(skills, query) {
  if (!query) {
    return skills;
  }
  const names = skills.map((skill) => skill.name);
  const skillMap = new Map(skills.map((skill) => [skill.name, skill]));
  try {
    const fzf = new AsyncFzf(names, {
      fuzzy: "v2",
      casing: "case-insensitive"
    });
    const results = await fzf.find(query);
    return results.map((result) => skillMap.get(result.item)).filter((skill) => !!skill);
  } catch (error2) {
    debugLogger78.error("[skillsCommand] Fuzzy match failed:", error2);
    const lowerQuery = query.toLowerCase();
    return skills.filter(
      (skill) => skill.name.toLowerCase().startsWith(lowerQuery)
    );
  }
}
__name(getSkillMatches, "getSkillMatches");

// packages/cli/src/ui/commands/statsCommand.ts
init_esbuild_shims();
var statsCommand = {
  name: "stats",
  altNames: ["usage"],
  get description() {
    return t4("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: t4("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",
      get description() {
        return t4("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",
      get description() {
        return t4("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 fsPromises5 from "fs/promises";
import path97 from "path";
var summaryCommand = {
  name: "summary",
  get description() {
    return t4(
      "Generate a project summary and save it to .qwen/PROJECT_SUMMARY.md"
    );
  },
  kind: "built-in" /* BUILT_IN */,
  action: /* @__PURE__ */ __name(async (context2) => {
    const { config: config2 } = context2.services;
    const { ui: ui2 } = context2;
    const executionMode = context2.executionMode ?? "interactive";
    const abortSignal = context2.abortSignal;
    if (!config2) {
      return {
        type: "message",
        messageType: "error",
        content: t4("Config not loaded.")
      };
    }
    const geminiClient = config2.getGeminiClient();
    if (!geminiClient) {
      return {
        type: "message",
        messageType: "error",
        content: t4("No chat client available to generate summary.")
      };
    }
    if (executionMode === "interactive" && ui2.pendingItem) {
      ui2.addItem(
        {
          type: "error",
          text: t4(
            "Already generating summary, wait for previous request to complete"
          )
        },
        Date.now()
      );
      return {
        type: "message",
        messageType: "error",
        content: t4(
          "Already generating summary, wait for previous request to complete"
        )
      };
    }
    const getChatHistory = /* @__PURE__ */ __name(() => {
      const chat = geminiClient.getChat();
      return chat.getHistory();
    }, "getChatHistory");
    const validateChatHistory = /* @__PURE__ */ __name((history2) => {
      if (history2.length <= 2) {
        throw new Error(t4("No conversation found to summarize."));
      }
    }, "validateChatHistory");
    const generateSummaryMarkdown = /* @__PURE__ */ __name(async (history2) => {
      const conversationContext = history2.map((message) => ({
        role: message.role,
        parts: message.parts
      }));
      const response = await geminiClient.generateContent(
        [
          ...conversationContext,
          {
            role: "user",
            parts: [
              {
                text: getProjectSummaryPrompt()
              }
            ]
          }
        ],
        {},
        abortSignal ?? new AbortController().signal,
        config2.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(
          t4(
            "Failed to generate summary - no text content received from LLM response"
          )
        );
      }
      return markdownSummary;
    }, "generateSummaryMarkdown");
    const saveSummaryToDisk = /* @__PURE__ */ __name(async (markdownSummary) => {
      const projectRoot = config2.getProjectRoot();
      const qwenDir = path97.join(projectRoot, ".qwen");
      try {
        await fsPromises5.mkdir(qwenDir, { recursive: true });
      } catch (_err) {
      }
      const summaryPath = path97.join(qwenDir, "PROJECT_SUMMARY.md");
      const summaryContent = `${markdownSummary}

---

## Summary Metadata
**Update time**: ${(/* @__PURE__ */ new Date()).toISOString()} 
`;
      await fsPromises5.writeFile(summaryPath, summaryContent, "utf8");
      return {
        filePathForDisplay: ".qwen/PROJECT_SUMMARY.md",
        fullPath: summaryPath
      };
    }, "saveSummaryToDisk");
    const emitInteractivePending = /* @__PURE__ */ __name((stage) => {
      if (executionMode !== "interactive") {
        return;
      }
      const pendingMessage = {
        type: "summary",
        summary: {
          isPending: true,
          stage
        }
      };
      ui2.setPendingItem(pendingMessage);
    }, "emitInteractivePending");
    const completeInteractive = /* @__PURE__ */ __name((filePathForDisplay) => {
      if (executionMode !== "interactive") {
        return;
      }
      ui2.setPendingItem(null);
      const completedSummaryItem = {
        type: "summary",
        summary: {
          isPending: false,
          stage: "completed",
          filePath: filePathForDisplay
        }
      };
      ui2.addItem(completedSummaryItem, Date.now());
    }, "completeInteractive");
    const formatErrorMessage = /* @__PURE__ */ __name((error2) => t4("Failed to generate project context summary: {{error}}", {
      error: error2 instanceof Error ? error2.message : String(error2)
    }), "formatErrorMessage");
    const failInteractive = /* @__PURE__ */ __name((error2) => {
      if (executionMode !== "interactive") {
        return;
      }
      if (abortSignal?.aborted) {
        return;
      }
      ui2.setPendingItem(null);
      ui2.addItem(
        {
          type: "error",
          text: `\u274C ${formatErrorMessage(error2)}`
        },
        Date.now()
      );
    }, "failInteractive");
    const formatSuccessMessage = /* @__PURE__ */ __name((filePathForDisplay) => t4("Saved project summary to {{filePathForDisplay}}.", {
      filePathForDisplay
    }), "formatSuccessMessage");
    const returnNoConversationMessage = /* @__PURE__ */ __name(() => {
      const msg = t4("No conversation found to summarize.");
      if (executionMode === "acp") {
        const messages = /* @__PURE__ */ __name(async function* () {
          yield {
            messageType: "info",
            content: msg
          };
        }, "messages");
        return {
          type: "stream_messages",
          messages: messages()
        };
      }
      return {
        type: "message",
        messageType: "info",
        content: msg
      };
    }, "returnNoConversationMessage");
    const executeSummaryGeneration = /* @__PURE__ */ __name(async (history2) => {
      emitInteractivePending("generating");
      const markdownSummary = await generateSummaryMarkdown(history2);
      if (abortSignal?.aborted) {
        throw new DOMException("Summary generation cancelled.", "AbortError");
      }
      emitInteractivePending("saving");
      const { filePathForDisplay } = await saveSummaryToDisk(markdownSummary);
      completeInteractive(filePathForDisplay);
      return { markdownSummary, filePathForDisplay };
    }, "executeSummaryGeneration");
    const history = getChatHistory();
    try {
      validateChatHistory(history);
    } catch (_error) {
      return returnNoConversationMessage();
    }
    if (executionMode === "acp") {
      const messages = /* @__PURE__ */ __name(async function* () {
        try {
          yield {
            messageType: "info",
            content: t4("Generating project summary...")
          };
          const { filePathForDisplay } = await executeSummaryGeneration(history);
          yield {
            messageType: "info",
            content: formatSuccessMessage(filePathForDisplay)
          };
        } catch (error2) {
          failInteractive(error2);
          yield {
            messageType: "error",
            content: formatErrorMessage(error2)
          };
        }
      }, "messages");
      return {
        type: "stream_messages",
        messages: messages()
      };
    }
    try {
      const { filePathForDisplay } = await executeSummaryGeneration(history);
      if (executionMode === "non_interactive") {
        return {
          type: "message",
          messageType: "info",
          content: formatSuccessMessage(filePathForDisplay)
        };
      }
      return {
        type: "message",
        messageType: "info",
        content: ""
      };
    } catch (error2) {
      failInteractive(error2);
      return {
        type: "message",
        messageType: "error",
        content: formatErrorMessage(error2)
      };
    }
  }, "action")
};

// packages/cli/src/ui/commands/terminalSetupCommand.ts
init_esbuild_shims();

// packages/cli/src/ui/utils/terminalSetup.ts
init_esbuild_shims();
import { promises as fs88 } from "node:fs";
import * as os32 from "node:os";
import * as path98 from "node:path";
import { exec as exec3 } from "node:child_process";
import { promisify as promisify9 } 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((resolve30) => {
    if (!process.stdin.isTTY || !process.stdout.isTTY) {
      detectionComplete = true;
      resolve30(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;
      resolve30(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;
        resolve30(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/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/utils/terminalSetup.ts
var debugLogger79 = createDebugLogger("TERMINAL_SETUP");
var execAsync2 = promisify9(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 (error2) {
      debugLogger79.debug("Parent process detection failed:", error2);
    }
  }
  return null;
}
__name(detectTerminal, "detectTerminal");
async function backupFile(filePath) {
  try {
    const timestamp = (/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-");
    const backupPath = `${filePath}.backup.${timestamp}`;
    await fs88.copyFile(filePath, backupPath);
  } catch (error2) {
    debugLogger79.warn(`Failed to create backup of ${filePath}:`, error2);
  }
}
__name(backupFile, "backupFile");
function getVSCodeStyleConfigDir(appName) {
  const platform16 = os32.platform();
  if (platform16 === "darwin") {
    return path98.join(
      os32.homedir(),
      "Library",
      "Application Support",
      appName,
      "User"
    );
  } else if (platform16 === "win32") {
    if (!process.env["APPDATA"]) {
      return null;
    }
    return path98.join(process.env["APPDATA"], appName, "User");
  } else {
    return path98.join(os32.homedir(), ".config", appName, "User");
  }
}
__name(getVSCodeStyleConfigDir, "getVSCodeStyleConfigDir");
async function configureVSCodeStyle(terminalName, appName) {
  const configDir = getVSCodeStyleConfigDir(appName);
  if (!configDir) {
    return {
      success: false,
      message: t4(
        "Could not determine {{terminalName}} config path on Windows: APPDATA environment variable is not set.",
        { terminalName }
      )
    };
  }
  const keybindingsFile = path98.join(configDir, "keybindings.json");
  try {
    await fs88.mkdir(configDir, { recursive: true });
    let keybindings = [];
    try {
      const content = await fs88.readFile(keybindingsFile, "utf8");
      await backupFile(keybindingsFile);
      try {
        const cleanContent = stripJsonComments3(content);
        const parsedContent = JSON.parse(cleanContent);
        if (!Array.isArray(parsedContent)) {
          return {
            success: false,
            message: t4(
              "{{terminalName}} keybindings.json exists but is not a valid JSON array. Please fix the file manually or delete it to allow automatic configuration.",
              { terminalName }
            ) + "\n" + t4("File: {{file}}", { file: keybindingsFile })
          };
        }
        keybindings = parsedContent;
      } catch (parseError) {
        return {
          success: false,
          message: t4(
            "Failed to parse {{terminalName}} keybindings.json. The file contains invalid JSON. Please fix the file manually or delete it to allow automatic configuration.",
            { terminalName }
          ) + "\n" + t4("File: {{file}}", { file: keybindingsFile }) + "\n" + t4("Error: {{error}}", { error: String(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("- " + t4("Shift+Enter binding already exists"));
      }
      if (existingCtrlEnter) {
        messages.push("- " + t4("Ctrl+Enter binding already exists"));
      }
      return {
        success: false,
        message: t4(
          "Existing keybindings detected. Will not modify to avoid conflicts."
        ) + "\n" + messages.join("\n") + "\n" + t4("Please check and modify manually if needed: {{file}}", {
          file: 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 fs88.writeFile(keybindingsFile, JSON.stringify(keybindings, null, 4));
      return {
        success: true,
        message: t4(
          "Added Shift+Enter and Ctrl+Enter keybindings to {{terminalName}}.",
          {
            terminalName
          }
        ) + "\n" + t4("Modified: {{file}}", { file: keybindingsFile }),
        requiresRestart: true
      };
    } else {
      return {
        success: true,
        message: t4("{{terminalName}} keybindings already configured.", {
          terminalName
        })
      };
    }
  } catch (error2) {
    return {
      success: false,
      message: t4("Failed to configure {{terminalName}}.", { terminalName }) + "\n" + t4("File: {{file}}", { file: keybindingsFile }) + "\n" + t4("Error: {{error}}", { error: String(error2) })
    };
  }
}
__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: t4(
        "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: t4(
        "Could not detect terminal type. Supported terminals: VS Code, Cursor, Windsurf, and Trae."
      )
    };
  }
  switch (terminal) {
    case "vscode":
      return configureVSCode();
    case "cursor":
      return configureCursor();
    case "windsurf":
      return configureWindsurf();
    case "trae":
      return configureTrae();
    default:
      return {
        success: false,
        message: t4('Terminal "{{terminal}}" is not supported yet.', {
          terminal
        })
      };
  }
}
__name(terminalSetup, "terminalSetup");

// packages/cli/src/ui/commands/terminalSetupCommand.ts
var terminalSetupCommand = {
  name: "terminal-setup",
  get description() {
    return t4(
      "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\n" + t4("Please restart your terminal for the changes to take effect.");
      }
      return {
        type: "message",
        content,
        messageType: result.success ? "info" : "error"
      };
    } catch (error2) {
      return {
        type: "message",
        content: t4("Failed to configure terminal: {{error}}", {
          error: String(error2)
        }),
        messageType: "error"
      };
    }
  }, "action")
};

// packages/cli/src/ui/commands/themeCommand.ts
init_esbuild_shims();
var themeCommand = {
  name: "theme",
  get description() {
    return t4("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",
  get description() {
    return t4("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: t4("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",
  get description() {
    return t4("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_undici6 = __toESM(require_undici2(), 1);
import path99 from "node:path";
import * as fs89 from "node:fs";
import { Writable } from "node:stream";

// packages/cli/src/utils/gitUtils.ts
init_esbuild_shims();
var import_undici5 = __toESM(require_undici2(), 1);
import { execSync as execSync6 } from "node:child_process";
var debugLogger80 = createDebugLogger("GIT");
var isGitHubRepository = /* @__PURE__ */ __name(() => {
  try {
    const remotes = (execSync6("git remote -v", {
      encoding: "utf-8"
    }) || "").trim();
    const pattern = /github\.com/;
    return pattern.test(remotes);
  } catch (_error) {
    debugLogger80.debug(`Failed to get git remote:`, _error);
    return false;
  }
}, "isGitHubRepository");
var getGitRepoRoot = /* @__PURE__ */ __name(() => {
  const gitRepoRoot = (execSync6("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/QwenLM/qwen-code-action/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_undici5.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) {
    debugLogger80.debug(
      `Failed to determine latest qwen-code-action release:`,
      _error
    );
    throw new Error(
      `Unable to determine the latest qwen-code-action release on GitHub.`
    );
  }
}, "getLatestGitHubRelease");
function getGitHubRepoInfo() {
  const remoteUrl = execSync6("git remote get-url origin", {
    encoding: "utf-8"
  }).trim();
  let urlToParse = remoteUrl;
  if (remoteUrl.startsWith("git@github.com:")) {
    urlToParse = remoteUrl.replace("git@github.com:", "");
  } else if (remoteUrl.startsWith("git@")) {
    throw new Error(
      `Owner & repo could not be extracted from remote URL: ${remoteUrl}`
    );
  }
  let parsedUrl;
  try {
    parsedUrl = new URL(urlToParse, "https://github.com");
  } catch {
    throw new Error(
      `Owner & repo could not be extracted from remote URL: ${remoteUrl}`
    );
  }
  if (parsedUrl.host !== "github.com") {
    throw new Error(
      `Owner & repo could not be extracted from remote URL: ${remoteUrl}`
    );
  }
  const parts = parsedUrl.pathname.split("/").filter((part) => part !== "");
  if (parts.length !== 2 || !parts[0] || !parts[1]) {
    throw new Error(
      `Owner & repo could not be extracted from remote URL: ${remoteUrl}`
    );
  }
  return { owner: parts[0], repo: parts[1].replace(/\.git$/, "") };
}
__name(getGitHubRepoInfo, "getGitHubRepoInfo");

// packages/cli/src/ui/commands/setupGithubCommand.ts
var debugLogger81 = createDebugLogger("SETUP_GITHUB");
var GITHUB_WORKFLOW_PATHS = [
  "qwen-dispatch/qwen-dispatch.yml",
  "qwen-assistant/qwen-invoke.yml",
  "issue-triage/qwen-triage.yml",
  "issue-triage/qwen-scheduled-triage.yml",
  "pr-review/qwen-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 = [".qwen/", "gha-creds-*.json"];
  const gitignorePath = path99.join(gitRepoRoot, ".gitignore");
  try {
    let existingContent = "";
    let fileExists2 = true;
    try {
      existingContent = await fs89.promises.readFile(gitignorePath, "utf8");
    } catch (_error) {
      fileExists2 = false;
    }
    if (!fileExists2) {
      const contentToWrite = gitignoreEntries.join("\n") + "\n";
      await fs89.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 fs89.promises.appendFile(gitignorePath, contentToAdd);
      }
    }
  } catch (error2) {
    debugLogger81.debug("Failed to update .gitignore:", error2);
  }
}
__name(updateGitignore, "updateGitignore");
var setupGithubCommand = {
  name: "setup-github",
  get description() {
    return t4("Set up GitHub Actions");
  },
  kind: "built-in" /* BUILT_IN */,
  action: /* @__PURE__ */ __name(async (context2) => {
    const abortController = new AbortController();
    if (context2.abortSignal) {
      context2.abortSignal.addEventListener(
        "abort",
        () => abortController.abort(),
        { once: true }
      );
    }
    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) {
      debugLogger81.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/QwenLM/qwen-code-action/blob/${releaseTag}/README.md#quick-start`;
    const githubWorkflowsDir = path99.join(gitRepoRoot, ".github", "workflows");
    try {
      await fs89.promises.mkdir(githubWorkflowsDir, { recursive: true });
    } catch (_error) {
      debugLogger81.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/QwenLM/qwen-code-action/refs/tags/${releaseTag}/examples/workflows/${workflow}`;
          const response = await fetch(endpoint, {
            method: "GET",
            dispatcher: proxy ? new import_undici6.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 = path99.resolve(
            githubWorkflowsDir,
            path99.basename(workflow)
          );
          const fileStream = fs89.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 Qwen.",
        command: command2,
        is_background: false
      }
    };
  }, "action")
};

// packages/cli/src/ui/commands/insightCommand.ts
init_esbuild_shims();
import { join as join41 } from "path";
import os34 from "os";

// packages/cli/src/services/insight/generators/StaticInsightGenerator.ts
init_esbuild_shims();
import fs91 from "fs/promises";
import path101 from "path";
import os33 from "os";

// packages/cli/src/services/insight/generators/DataProcessor.ts
init_esbuild_shims();
import fs90 from "fs/promises";
import path100 from "path";

// packages/cli/node_modules/p-limit/index.js
init_esbuild_shims();

// packages/cli/node_modules/yocto-queue/index.js
init_esbuild_shims();
var Node4 = class {
  static {
    __name(this, "Node");
  }
  value;
  next;
  constructor(value) {
    this.value = value;
  }
};
var Queue = class {
  static {
    __name(this, "Queue");
  }
  #head;
  #tail;
  #size;
  constructor() {
    this.clear();
  }
  enqueue(value) {
    const node = new Node4(value);
    if (this.#head) {
      this.#tail.next = node;
      this.#tail = node;
    } else {
      this.#head = node;
      this.#tail = node;
    }
    this.#size++;
  }
  dequeue() {
    const current = this.#head;
    if (!current) {
      return;
    }
    this.#head = this.#head.next;
    this.#size--;
    if (!this.#head) {
      this.#tail = void 0;
    }
    return current.value;
  }
  peek() {
    if (!this.#head) {
      return;
    }
    return this.#head.value;
  }
  clear() {
    this.#head = void 0;
    this.#tail = void 0;
    this.#size = 0;
  }
  get size() {
    return this.#size;
  }
  *[Symbol.iterator]() {
    let current = this.#head;
    while (current) {
      yield current.value;
      current = current.next;
    }
  }
  *drain() {
    while (this.#head) {
      yield this.dequeue();
    }
  }
};

// packages/cli/node_modules/p-limit/index.js
function pLimit(concurrency) {
  let rejectOnClear = false;
  if (typeof concurrency === "object") {
    ({ concurrency, rejectOnClear = false } = concurrency);
  }
  validateConcurrency(concurrency);
  if (typeof rejectOnClear !== "boolean") {
    throw new TypeError("Expected `rejectOnClear` to be a boolean");
  }
  const queue = new Queue();
  let activeCount = 0;
  const resumeNext = /* @__PURE__ */ __name(() => {
    if (activeCount < concurrency && queue.size > 0) {
      activeCount++;
      queue.dequeue().run();
    }
  }, "resumeNext");
  const next = /* @__PURE__ */ __name(() => {
    activeCount--;
    resumeNext();
  }, "next");
  const run = /* @__PURE__ */ __name(async (function_, resolve30, arguments_) => {
    const result = (async () => function_(...arguments_))();
    resolve30(result);
    try {
      await result;
    } catch {
    }
    next();
  }, "run");
  const enqueue = /* @__PURE__ */ __name((function_, resolve30, reject, arguments_) => {
    const queueItem = { reject };
    new Promise((internalResolve) => {
      queueItem.run = internalResolve;
      queue.enqueue(queueItem);
    }).then(run.bind(void 0, function_, resolve30, arguments_));
    if (activeCount < concurrency) {
      resumeNext();
    }
  }, "enqueue");
  const generator = /* @__PURE__ */ __name((function_, ...arguments_) => new Promise((resolve30, reject) => {
    enqueue(function_, resolve30, reject, arguments_);
  }), "generator");
  Object.defineProperties(generator, {
    activeCount: {
      get: /* @__PURE__ */ __name(() => activeCount, "get")
    },
    pendingCount: {
      get: /* @__PURE__ */ __name(() => queue.size, "get")
    },
    clearQueue: {
      value() {
        if (!rejectOnClear) {
          queue.clear();
          return;
        }
        const abortError = AbortSignal.abort().reason;
        while (queue.size > 0) {
          queue.dequeue().reject(abortError);
        }
      }
    },
    concurrency: {
      get: /* @__PURE__ */ __name(() => concurrency, "get"),
      set(newConcurrency) {
        validateConcurrency(newConcurrency);
        concurrency = newConcurrency;
        queueMicrotask(() => {
          while (activeCount < concurrency && queue.size > 0) {
            resumeNext();
          }
        });
      }
    },
    map: {
      async value(iterable, function_) {
        const promises8 = Array.from(iterable, (value, index) => this(function_, value, index));
        return Promise.all(promises8);
      }
    }
  });
  return generator;
}
__name(pLimit, "pLimit");
function validateConcurrency(concurrency) {
  if (!((Number.isInteger(concurrency) || concurrency === Number.POSITIVE_INFINITY) && concurrency > 0)) {
    throw new TypeError("Expected `concurrency` to be a number from 1 and up");
  }
}
__name(validateConcurrency, "validateConcurrency");

// packages/cli/src/services/insight/generators/DataProcessor.ts
var logger3 = createDebugLogger("DataProcessor");
var CONCURRENCY_LIMIT = 4;
var DataProcessor = class {
  constructor(config2) {
    this.config = config2;
  }
  static {
    __name(this, "DataProcessor");
  }
  // Helper function to format date as YYYY-MM-DD
  formatDate(date4) {
    return date4.toISOString().split("T")[0];
  }
  // Format chat records for LLM analysis
  formatRecordsForAnalysis(records) {
    let output = "";
    const sessionStart = records.length > 0 ? new Date(records[0].timestamp) : /* @__PURE__ */ new Date();
    output += `Session: ${records[0]?.sessionId || "unknown"}
`;
    output += `Date: ${sessionStart.toISOString()}
`;
    output += `Duration: ${records.length} turns

`;
    for (const record2 of records) {
      if (record2.type === "user") {
        const text = record2.message?.parts?.map((p2) => "text" in p2 ? p2.text : "").join("") || "";
        output += `[User]: ${text}
`;
      } else if (record2.type === "assistant") {
        if (record2.message?.parts) {
          for (const part of record2.message.parts) {
            if ("text" in part && part.text) {
              output += `[Assistant]: ${part.text}
`;
            } else if ("functionCall" in part) {
              const call = part.functionCall;
              if (call) {
                output += `[Tool: ${call.name}]
`;
              }
            }
          }
        }
      }
    }
    return output;
  }
  // Only analyze conversational sessions for facets (skip system-only logs).
  hasUserAndAssistantRecords(records) {
    let hasUser = false;
    let hasAssistant = false;
    for (const record2 of records) {
      if (record2.type === "user") {
        hasUser = true;
      } else if (record2.type === "assistant") {
        hasAssistant = true;
      }
      if (hasUser && hasAssistant) {
        return true;
      }
    }
    return false;
  }
  // Analyze a single session using LLM
  async analyzeSession(records) {
    if (records.length === 0) return null;
    const INSIGHT_SCHEMA = {
      type: "object",
      properties: {
        underlying_goal: {
          type: "string",
          description: "What the user fundamentally wanted to achieve"
        },
        goal_categories: {
          type: "object",
          additionalProperties: { type: "number" }
        },
        outcome: {
          type: "string",
          enum: [
            "fully_achieved",
            "mostly_achieved",
            "partially_achieved",
            "not_achieved",
            "unclear_from_transcript"
          ]
        },
        user_satisfaction_counts: {
          type: "object",
          additionalProperties: { type: "number" }
        },
        Qwen_helpfulness: {
          type: "string",
          enum: [
            "unhelpful",
            "slightly_helpful",
            "moderately_helpful",
            "very_helpful",
            "essential"
          ]
        },
        session_type: {
          type: "string",
          enum: [
            "single_task",
            "multi_task",
            "iterative_refinement",
            "exploration",
            "quick_question"
          ]
        },
        friction_counts: {
          type: "object",
          additionalProperties: { type: "number" }
        },
        friction_detail: {
          type: "string",
          description: "One sentence describing friction or empty"
        },
        primary_success: {
          type: "string",
          enum: [
            "none",
            "fast_accurate_search",
            "correct_code_edits",
            "good_explanations",
            "proactive_help",
            "multi_file_changes",
            "good_debugging"
          ]
        },
        brief_summary: {
          type: "string",
          description: "One sentence: what user wanted and whether they got it"
        }
      },
      required: [
        "underlying_goal",
        "goal_categories",
        "outcome",
        "user_satisfaction_counts",
        "Qwen_helpfulness",
        "session_type",
        "friction_counts",
        "friction_detail",
        "primary_success",
        "brief_summary"
      ]
    };
    const sessionText = this.formatRecordsForAnalysis(records);
    const prompt = `${getInsightPrompt("analysis")}

SESSION:
${sessionText}`;
    try {
      const result = await this.config.getBaseLlmClient().generateJson({
        // Use the configured model
        model: this.config.getModel(),
        contents: [{ role: "user", parts: [{ text: prompt }] }],
        schema: INSIGHT_SCHEMA,
        abortSignal: AbortSignal.timeout(6e5)
        // 10 minute timeout per session
      });
      if (!result || Object.keys(result).length === 0) {
        return null;
      }
      return {
        ...result,
        session_id: records[0].sessionId
      };
    } catch (error2) {
      logger3.error(
        `Failed to analyze session ${records[0]?.sessionId}:`,
        error2
      );
      return null;
    }
  }
  // Calculate streaks from activity dates
  calculateStreaks(dates) {
    if (dates.length === 0) {
      return { currentStreak: 0, longestStreak: 0, dates: [] };
    }
    const dateObjects = dates.map((dateStr) => new Date(dateStr));
    dateObjects.sort((a2, b2) => a2.getTime() - b2.getTime());
    let currentStreak = 1;
    let maxStreak = 1;
    let currentDate = new Date(dateObjects[0]);
    currentDate.setHours(0, 0, 0, 0);
    for (let i3 = 1; i3 < dateObjects.length; i3++) {
      const nextDate = new Date(dateObjects[i3]);
      nextDate.setHours(0, 0, 0, 0);
      const diffDays = Math.floor(
        (nextDate.getTime() - currentDate.getTime()) / (1e3 * 60 * 60 * 24)
      );
      if (diffDays === 1) {
        currentStreak++;
        maxStreak = Math.max(maxStreak, currentStreak);
      } else if (diffDays > 1) {
        currentStreak = 1;
      }
      currentDate = nextDate;
    }
    const today = /* @__PURE__ */ new Date();
    today.setHours(0, 0, 0, 0);
    const yesterday = new Date(today);
    yesterday.setDate(yesterday.getDate() - 1);
    if (currentDate.getTime() === today.getTime() || currentDate.getTime() === yesterday.getTime()) {
    }
    return {
      currentStreak,
      longestStreak: maxStreak,
      dates
    };
  }
  // Process chat files from all projects in the base directory and generate insights
  async generateInsights(baseDir, facetsOutputDir, onProgress) {
    if (onProgress) onProgress("Scanning chat history...", 0);
    const allChatFiles = await this.scanChatFiles(baseDir);
    if (onProgress) onProgress("Crunching the numbers", 10);
    const metrics2 = await this.generateMetrics(allChatFiles, onProgress);
    if (onProgress) onProgress("Preparing sessions...", 20);
    const facets = await this.generateFacets(
      allChatFiles,
      facetsOutputDir,
      onProgress
    );
    if (onProgress) onProgress("Generating personalized insights...", 80);
    const qualitative = await this.generateQualitativeInsights(metrics2, facets);
    const {
      satisfactionAgg,
      frictionAgg,
      primarySuccessAgg,
      outcomesAgg,
      goalsAgg
    } = this.aggregateFacetsData(facets);
    if (onProgress) onProgress("Assembling report...", 100);
    return {
      ...metrics2,
      qualitative,
      satisfaction: satisfactionAgg,
      friction: frictionAgg,
      primarySuccess: primarySuccessAgg,
      outcomes: outcomesAgg,
      topGoals: goalsAgg
    };
  }
  // Aggregate satisfaction and friction data from facets
  aggregateFacetsData(facets) {
    const satisfactionAgg = {};
    const frictionAgg = {};
    const primarySuccessAgg = {};
    const outcomesAgg = {};
    const goalsAgg = {};
    facets.forEach((facet) => {
      Object.entries(facet.user_satisfaction_counts).forEach(([sat, count]) => {
        satisfactionAgg[sat] = (satisfactionAgg[sat] || 0) + count;
      });
      Object.entries(facet.friction_counts).forEach(([fric, count]) => {
        frictionAgg[fric] = (frictionAgg[fric] || 0) + count;
      });
      if (facet.primary_success && facet.primary_success !== "none") {
        primarySuccessAgg[facet.primary_success] = (primarySuccessAgg[facet.primary_success] || 0) + 1;
      }
      if (facet.outcome) {
        outcomesAgg[facet.outcome] = (outcomesAgg[facet.outcome] || 0) + 1;
      }
      Object.entries(facet.goal_categories).forEach(([goal, count]) => {
        goalsAgg[goal] = (goalsAgg[goal] || 0) + count;
      });
    });
    return {
      satisfactionAgg,
      frictionAgg,
      primarySuccessAgg,
      outcomesAgg,
      goalsAgg
    };
  }
  async generateQualitativeInsights(metrics2, facets) {
    if (facets.length === 0) {
      return void 0;
    }
    logger3.info("Generating qualitative insights...");
    const commonData = this.prepareCommonPromptData(metrics2, facets);
    const generate2 = /* @__PURE__ */ __name(async (promptTemplate, schema) => {
      const prompt = `${promptTemplate}

${commonData}`;
      try {
        const result = await this.config.getBaseLlmClient().generateJson({
          model: this.config.getModel(),
          contents: [{ role: "user", parts: [{ text: prompt }] }],
          schema,
          abortSignal: AbortSignal.timeout(6e5)
        });
        return result;
      } catch (error2) {
        logger3.error("Failed to generate insight:", error2);
        throw error2;
      }
    }, "generate");
    const schemaImpressiveWorkflows = {
      type: "object",
      properties: {
        intro: { type: "string" },
        impressive_workflows: {
          type: "array",
          items: {
            type: "object",
            properties: {
              title: { type: "string" },
              description: { type: "string" }
            },
            required: ["title", "description"]
          }
        }
      },
      required: ["intro", "impressive_workflows"]
    };
    const schemaProjectAreas = {
      type: "object",
      properties: {
        areas: {
          type: "array",
          items: {
            type: "object",
            properties: {
              name: { type: "string" },
              session_count: { type: "number" },
              description: { type: "string" }
            },
            required: ["name", "session_count", "description"]
          }
        }
      },
      required: ["areas"]
    };
    const schemaFutureOpportunities = {
      type: "object",
      properties: {
        intro: { type: "string" },
        opportunities: {
          type: "array",
          items: {
            type: "object",
            properties: {
              title: { type: "string" },
              whats_possible: { type: "string" },
              how_to_try: { type: "string" },
              copyable_prompt: { type: "string" }
            },
            required: [
              "title",
              "whats_possible",
              "how_to_try",
              "copyable_prompt"
            ]
          }
        }
      },
      required: ["intro", "opportunities"]
    };
    const schemaFrictionPoints = {
      type: "object",
      properties: {
        intro: { type: "string" },
        categories: {
          type: "array",
          items: {
            type: "object",
            properties: {
              category: { type: "string" },
              description: { type: "string" },
              examples: { type: "array", items: { type: "string" } }
            },
            required: ["category", "description", "examples"]
          }
        }
      },
      required: ["intro", "categories"]
    };
    const schemaMemorableMoment = {
      type: "object",
      properties: {
        headline: { type: "string" },
        detail: { type: "string" }
      },
      required: ["headline", "detail"]
    };
    const schemaImprovements = {
      type: "object",
      properties: {
        Qwen_md_additions: {
          type: "array",
          items: {
            type: "object",
            properties: {
              addition: { type: "string" },
              why: { type: "string" },
              prompt_scaffold: { type: "string" }
            },
            required: ["addition", "why", "prompt_scaffold"]
          }
        },
        features_to_try: {
          type: "array",
          items: {
            type: "object",
            properties: {
              feature: { type: "string" },
              one_liner: { type: "string" },
              why_for_you: { type: "string" },
              example_code: { type: "string" }
            },
            required: ["feature", "one_liner", "why_for_you", "example_code"]
          }
        },
        usage_patterns: {
          type: "array",
          items: {
            type: "object",
            properties: {
              title: { type: "string" },
              suggestion: { type: "string" },
              detail: { type: "string" },
              copyable_prompt: { type: "string" }
            },
            required: ["title", "suggestion", "detail", "copyable_prompt"]
          }
        }
      },
      required: ["Qwen_md_additions", "features_to_try", "usage_patterns"]
    };
    const schemaInteractionStyle = {
      type: "object",
      properties: {
        narrative: { type: "string" },
        key_pattern: { type: "string" }
      },
      required: ["narrative", "key_pattern"]
    };
    const schemaAtAGlance = {
      type: "object",
      properties: {
        whats_working: { type: "string" },
        whats_hindering: { type: "string" },
        quick_wins: { type: "string" },
        ambitious_workflows: { type: "string" }
      },
      required: [
        "whats_working",
        "whats_hindering",
        "quick_wins",
        "ambitious_workflows"
      ]
    };
    const limit2 = pLimit(CONCURRENCY_LIMIT);
    try {
      const [
        impressiveWorkflows,
        projectAreas,
        futureOpportunities,
        frictionPoints,
        memorableMoment,
        improvements,
        interactionStyle,
        atAGlance
      ] = await Promise.all([
        limit2(
          () => generate2(
            getInsightPrompt("impressive_workflows"),
            schemaImpressiveWorkflows
          )
        ),
        limit2(
          () => generate2(
            getInsightPrompt("project_areas"),
            schemaProjectAreas
          )
        ),
        limit2(
          () => generate2(
            getInsightPrompt("future_opportunities"),
            schemaFutureOpportunities
          )
        ),
        limit2(
          () => generate2(
            getInsightPrompt("friction_points"),
            schemaFrictionPoints
          )
        ),
        limit2(
          () => generate2(
            getInsightPrompt("memorable_moment"),
            schemaMemorableMoment
          )
        ),
        limit2(
          () => generate2(
            getInsightPrompt("improvements"),
            schemaImprovements
          )
        ),
        limit2(
          () => generate2(
            getInsightPrompt("interaction_style"),
            schemaInteractionStyle
          )
        ),
        limit2(
          () => generate2(
            getInsightPrompt("at_a_glance"),
            schemaAtAGlance
          )
        )
      ]);
      logger3.debug(
        JSON.stringify(
          {
            impressiveWorkflows,
            projectAreas,
            futureOpportunities,
            frictionPoints,
            memorableMoment,
            improvements,
            interactionStyle,
            atAGlance
          },
          null,
          2
        )
      );
      return {
        impressiveWorkflows,
        projectAreas,
        futureOpportunities,
        frictionPoints,
        memorableMoment,
        improvements,
        interactionStyle,
        atAGlance
      };
    } catch (e4) {
      logger3.error("Error generating qualitative insights:", e4);
      return void 0;
    }
  }
  prepareCommonPromptData(metrics2, facets) {
    const goalsAgg = {};
    const outcomesAgg = {};
    const satisfactionAgg = {};
    const frictionAgg = {};
    const successAgg = {};
    facets.forEach((facet) => {
      Object.entries(facet.goal_categories).forEach(([goal, count]) => {
        goalsAgg[goal] = (goalsAgg[goal] || 0) + count;
      });
      outcomesAgg[facet.outcome] = (outcomesAgg[facet.outcome] || 0) + 1;
      Object.entries(facet.user_satisfaction_counts).forEach(([sat, count]) => {
        satisfactionAgg[sat] = (satisfactionAgg[sat] || 0) + count;
      });
      Object.entries(facet.friction_counts).forEach(([fric, count]) => {
        frictionAgg[fric] = (frictionAgg[fric] || 0) + count;
      });
      if (facet.primary_success && facet.primary_success !== "none") {
        successAgg[facet.primary_success] = (successAgg[facet.primary_success] || 0) + 1;
      }
    });
    const topGoals = Object.entries(goalsAgg).sort((a2, b2) => b2[1] - a2[1]).slice(0, 8);
    const dataObj = {
      sessions: metrics2.totalSessions || facets.length,
      analyzed: facets.length,
      date_range: {
        start: Object.keys(metrics2.heatmap).sort()[0] || "N/A",
        end: Object.keys(metrics2.heatmap).sort().pop() || "N/A"
      },
      messages: metrics2.totalMessages || 0,
      hours: metrics2.totalHours || 0,
      commits: 0,
      // Not tracked yet
      top_tools: metrics2.topTools || [],
      top_goals: topGoals,
      outcomes: outcomesAgg,
      satisfaction: satisfactionAgg,
      friction: frictionAgg,
      success: successAgg
    };
    const sessionSummaries = facets.map((f5) => `- ${f5.brief_summary}`).join("\n");
    const frictionDetails = facets.filter((f5) => f5.friction_detail && f5.friction_detail.trim().length > 0).map((f5) => `- ${f5.friction_detail}`).join("\n");
    return `DATA:
${JSON.stringify(dataObj, null, 2)}

SESSION SUMMARIES:
${sessionSummaries}

FRICTION DETAILS:
${frictionDetails}

USER INSTRUCTIONS TO Qwen:
None captured`;
  }
  async scanChatFiles(baseDir) {
    const allChatFiles = [];
    try {
      const projectDirs = await fs90.readdir(baseDir);
      for (const projectDir of projectDirs) {
        const projectPath = path100.join(baseDir, projectDir);
        const stats = await fs90.stat(projectPath);
        if (stats.isDirectory()) {
          const chatsDir = path100.join(projectPath, "chats");
          try {
            const files = await fs90.readdir(chatsDir);
            const chatFiles = files.filter((file) => file.endsWith(".jsonl"));
            for (const file of chatFiles) {
              const filePath = path100.join(chatsDir, file);
              try {
                const fileStats = await fs90.stat(filePath);
                allChatFiles.push({ path: filePath, mtime: fileStats.mtimeMs });
              } catch (e4) {
                logger3.error(`Failed to stat file ${filePath}:`, e4);
              }
            }
          } catch (error2) {
            if (error2.code !== "ENOENT") {
              logger3.error(
                `Error reading chats directory for project ${projectDir}: ${error2}`
              );
            }
            continue;
          }
        }
      }
    } catch (error2) {
      if (error2.code === "ENOENT") {
        logger3.info(`Base directory does not exist: ${baseDir}`);
      } else {
        logger3.error(`Error reading base directory: ${error2}`);
      }
    }
    return allChatFiles;
  }
  async generateMetrics(files, onProgress) {
    const heatmap = {};
    const activeHours = {};
    const sessionStartTimes = {};
    const sessionEndTimes = {};
    let totalMessages = 0;
    let totalLinesAdded = 0;
    let totalLinesRemoved = 0;
    const uniqueFiles = /* @__PURE__ */ new Set();
    const toolUsage = {};
    const BATCH_SIZE = 50;
    const totalFiles = files.length;
    for (let i3 = 0; i3 < totalFiles; i3 += BATCH_SIZE) {
      const batchEnd = Math.min(i3 + BATCH_SIZE, totalFiles);
      const batch = files.slice(i3, batchEnd);
      for (const fileInfo of batch) {
        try {
          const records = await read(fileInfo.path);
          for (const record2 of records) {
            const timestamp = new Date(record2.timestamp);
            const dateKey = this.formatDate(timestamp);
            const hour = timestamp.getHours();
            const isUserMessage = record2.type === "user";
            const isSlashCommand2 = record2.type === "system" && record2.subtype === "slash_command";
            if (isUserMessage || isSlashCommand2) {
              totalMessages++;
              heatmap[dateKey] = (heatmap[dateKey] || 0) + 1;
              activeHours[hour] = (activeHours[hour] || 0) + 1;
            }
            if (!sessionStartTimes[record2.sessionId]) {
              sessionStartTimes[record2.sessionId] = timestamp;
            }
            sessionEndTimes[record2.sessionId] = timestamp;
            if (record2.type === "assistant" && record2.message?.parts) {
              for (const part of record2.message.parts) {
                if ("functionCall" in part) {
                  const name3 = part.functionCall.name;
                  toolUsage[name3] = (toolUsage[name3] || 0) + 1;
                }
              }
            }
            if (record2.type === "tool_result" && record2.toolCallResult?.resultDisplay) {
              const display = record2.toolCallResult.resultDisplay;
              if (typeof display === "object" && display !== null && "fileName" in display) {
                const diff4 = display;
                if (typeof diff4.fileName === "string") {
                  uniqueFiles.add(diff4.fileName);
                }
                if (diff4.diffStat) {
                  totalLinesAdded += diff4.diffStat.model_added_lines || 0;
                  totalLinesRemoved += diff4.diffStat.model_removed_lines || 0;
                }
              }
            }
          }
        } catch (error2) {
          logger3.error(
            `Failed to process metrics for file ${fileInfo.path}:`,
            error2
          );
        }
      }
      if (onProgress) {
        const percentComplete = batchEnd / totalFiles;
        const overallProgress = 10 + Math.round(percentComplete * 10);
        onProgress(
          `Crunching the numbers (${batchEnd}/${totalFiles})`,
          overallProgress
        );
      }
      await new Promise((resolve30) => setTimeout(resolve30, 0));
    }
    const streakData = this.calculateStreaks(Object.keys(heatmap));
    let longestWorkDuration = 0;
    let longestWorkDate = null;
    let totalDurationMs = 0;
    const sessionIds = Object.keys(sessionStartTimes);
    const totalSessions = sessionIds.length;
    for (const sessionId of sessionIds) {
      const start = sessionStartTimes[sessionId];
      const end = sessionEndTimes[sessionId];
      const durationMs = end.getTime() - start.getTime();
      const durationMinutes = Math.round(durationMs / (1e3 * 60));
      totalDurationMs += durationMs;
      if (durationMinutes > longestWorkDuration) {
        longestWorkDuration = durationMinutes;
        longestWorkDate = this.formatDate(start);
      }
    }
    const totalHours = Math.round(totalDurationMs / (1e3 * 60 * 60));
    let latestActiveTime = null;
    let latestTimestamp = /* @__PURE__ */ new Date(0);
    for (const dateStr in heatmap) {
      const date4 = new Date(dateStr);
      if (date4 > latestTimestamp) {
        latestTimestamp = date4;
        latestActiveTime = date4.toLocaleTimeString([], {
          hour: "2-digit",
          minute: "2-digit"
        });
      }
    }
    const topTools = Object.entries(toolUsage).sort((a2, b2) => b2[1] - a2[1]).slice(0, 10);
    return {
      heatmap,
      currentStreak: streakData.currentStreak,
      longestStreak: streakData.longestStreak,
      longestWorkDate,
      longestWorkDuration,
      activeHours,
      latestActiveTime,
      totalSessions,
      totalMessages,
      totalHours,
      topTools,
      totalLinesAdded,
      totalLinesRemoved,
      totalFiles: uniqueFiles.size
    };
  }
  async generateFacets(allFiles, facetsOutputDir, onProgress) {
    const MAX_ELIGIBLE_SESSIONS = 50;
    const sortedFiles = [...allFiles].sort((a2, b2) => b2.mtime - a2.mtime);
    const eligibleSessions = [];
    for (const fileInfo of sortedFiles) {
      if (eligibleSessions.length >= MAX_ELIGIBLE_SESSIONS) {
        break;
      }
      try {
        const records = await read(fileInfo.path);
        if (!this.hasUserAndAssistantRecords(records)) {
          continue;
        }
        eligibleSessions.push({ fileInfo, records });
      } catch (e4) {
        logger3.error(
          `Error reading session file ${fileInfo.path} for facet eligibility:`,
          e4
        );
      }
    }
    logger3.info(
      `Analyzing ${eligibleSessions.length} eligible recent sessions with LLM...`
    );
    const limit2 = pLimit(CONCURRENCY_LIMIT);
    let completed = 0;
    const total = eligibleSessions.length;
    const analysisPromises = eligibleSessions.map(
      ({ fileInfo, records }) => limit2(async () => {
        try {
          if (records.length > 0 && facetsOutputDir) {
            const sessionId = records[0].sessionId;
            if (sessionId) {
              const existingFacetPath = path100.join(
                facetsOutputDir,
                `${sessionId}.json`
              );
              try {
                const existingData = await fs90.readFile(
                  existingFacetPath,
                  "utf-8"
                );
                const existingFacet = JSON.parse(existingData);
                completed++;
                if (onProgress) {
                  const percent = 20 + Math.round(completed / total * 60);
                  onProgress(
                    "Analyzing sessions",
                    percent,
                    `${completed}/${total}`
                  );
                }
                return existingFacet;
              } catch (readError) {
                if (readError.code !== "ENOENT") {
                  logger3.warn(
                    `Failed to read existing facet for ${sessionId}, regenerating:`,
                    readError
                  );
                }
              }
            }
          }
          const facet = await this.analyzeSession(records);
          if (facet && facetsOutputDir) {
            try {
              const facetPath = path100.join(
                facetsOutputDir,
                `${facet.session_id}.json`
              );
              await fs90.writeFile(
                facetPath,
                JSON.stringify(facet, null, 2),
                "utf-8"
              );
            } catch (writeError) {
              logger3.error(
                `Failed to write facet file for session ${facet.session_id}:`,
                writeError
              );
            }
          }
          completed++;
          if (onProgress) {
            const percent = 20 + Math.round(completed / total * 60);
            onProgress("Analyzing sessions", percent, `${completed}/${total}`);
          }
          return facet;
        } catch (e4) {
          logger3.error(`Error analyzing session file ${fileInfo.path}:`, e4);
          completed++;
          if (onProgress) {
            const percent = 20 + Math.round(completed / total * 60);
            onProgress("Analyzing sessions", percent, `${completed}/${total}`);
          }
          return null;
        }
      })
    );
    const sessionFacetsWithNulls = await Promise.all(analysisPromises);
    const facets = sessionFacetsWithNulls.filter(
      (f5) => f5 !== null
    );
    return facets;
  }
};

// packages/cli/src/services/insight/generators/TemplateRenderer.ts
init_esbuild_shims();
var TemplateRenderer = class {
  static {
    __name(this, "TemplateRenderer");
  }
  // Render the complete HTML file
  async renderInsightHTML(insights) {
    const html2 = `<!doctype html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Qwen Code Insights</title>
    <style>
      ${INSIGHT_CSS}
    </style>
  </head>
  <body>
    <div class="min-h-screen" id="container">
      <div class="mx-auto max-w-6xl px-6 py-10 md:py-12">
        <div id="react-root"></div>
      </div>
    </div>

    <!-- React CDN -->
    <script crossorigin src="https://unpkg.com/react@18/umd/react.production.min.js"></script>
    <script crossorigin src="https://unpkg.com/react-dom@18/umd/react-dom.production.min.js"></script>

    <!-- CDN Libraries -->
    <script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.1/dist/chart.umd.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/html2canvas@1.4.1/dist/html2canvas.min.js"></script>

    <!-- Application Data -->
    <script>
      window.INSIGHT_DATA = ${JSON.stringify(insights)};
    </script>

    <!-- App Script -->
    <script>
      ${INSIGHT_JS}
    </script>
  </body>
</html>`;
    return html2;
  }
};

// packages/cli/src/services/insight/generators/StaticInsightGenerator.ts
var logger4 = createDebugLogger("StaticInsightGenerator");
var StaticInsightGenerator = class {
  static {
    __name(this, "StaticInsightGenerator");
  }
  dataProcessor;
  templateRenderer;
  constructor(config2) {
    this.dataProcessor = new DataProcessor(config2);
    this.templateRenderer = new TemplateRenderer();
  }
  // Ensure the output directory exists
  async ensureOutputDirectory() {
    const outputDir = path101.join(os33.homedir(), ".qwen", "insights");
    await fs91.mkdir(outputDir, { recursive: true });
    return outputDir;
  }
  // Generate timestamped filename with collision detection
  async generateOutputPath(outputDir) {
    const now = /* @__PURE__ */ new Date();
    const date4 = now.toISOString().split("T")[0];
    const time3 = now.toTimeString().slice(0, 8).replace(/:/g, "");
    let outputPath = path101.join(outputDir, `insight-${date4}.html`);
    try {
      await fs91.access(outputPath);
      outputPath = path101.join(outputDir, `insight-${date4}-${time3}.html`);
    } catch {
    }
    return outputPath;
  }
  // Create or update the "latest" alias (symlink preferred, copy as fallback)
  async updateLatestAlias(outputDir, targetPath) {
    const latestPath = path101.join(outputDir, "insight.html");
    const relativeTarget = path101.relative(outputDir, targetPath);
    try {
      await fs91.unlink(latestPath);
    } catch {
    }
    try {
      await fs91.symlink(relativeTarget, latestPath);
      logger4.debug("Created insight symlink:", relativeTarget);
      return;
    } catch (error2) {
      logger4.debug(
        "Failed to create insight symlink, falling back to copy:",
        error2
      );
    }
    try {
      await fs91.copyFile(targetPath, latestPath);
      logger4.debug("Created insight copy:", targetPath);
    } catch (error2) {
      logger4.debug("Failed to create insight latest alias:", error2);
    }
  }
  // Generate the static insight HTML file
  async generateStaticInsight(baseDir, onProgress) {
    const outputDir = await this.ensureOutputDirectory();
    const facetsDir = path101.join(outputDir, "facets");
    await fs91.mkdir(facetsDir, { recursive: true });
    const insights = await this.dataProcessor.generateInsights(
      baseDir,
      facetsDir,
      onProgress
    );
    const html2 = await this.templateRenderer.renderInsightHTML(insights);
    const outputPath = await this.generateOutputPath(outputDir);
    await fs91.writeFile(outputPath, html2, "utf-8");
    await this.updateLatestAlias(outputDir, outputPath);
    return outputPath;
  }
};

// packages/cli/src/ui/commands/insightCommand.ts
init_open();
var logger5 = createDebugLogger("DataProcessor");
var insightCommand = {
  name: "insight",
  get description() {
    return t4(
      "generate personalized programming insights from your chat history"
    );
  },
  kind: "built-in" /* BUILT_IN */,
  action: /* @__PURE__ */ __name(async (context2) => {
    try {
      context2.ui.setDebugMessage(t4("Generating insights..."));
      const projectsDir = join41(os34.homedir(), ".qwen", "projects");
      if (!context2.services.config) {
        throw new Error("Config service is not available");
      }
      const insightGenerator = new StaticInsightGenerator(
        context2.services.config
      );
      const updateProgress = /* @__PURE__ */ __name((stage, progress, detail) => {
        const progressItem = {
          type: "insight_progress" /* INSIGHT_PROGRESS */,
          progress: {
            stage,
            progress,
            detail
          }
        };
        context2.ui.setPendingItem(progressItem);
      }, "updateProgress");
      context2.ui.addItem(
        {
          type: "info" /* INFO */,
          text: t4("This may take a couple minutes. Sit tight!")
        },
        Date.now()
      );
      updateProgress(t4("Starting insight generation..."), 0);
      const outputPath = await insightGenerator.generateStaticInsight(
        projectsDir,
        updateProgress
      );
      context2.ui.setPendingItem(null);
      context2.ui.addItem(
        {
          type: "info" /* INFO */,
          text: t4("Insight report generated successfully!")
        },
        Date.now()
      );
      try {
        await open_default(outputPath);
        context2.ui.addItem(
          {
            type: "info" /* INFO */,
            text: t4("Opening insights in your browser: {{path}}", {
              path: outputPath
            })
          },
          Date.now()
        );
      } catch (browserError) {
        logger5.error("Failed to open browser automatically:", browserError);
        context2.ui.addItem(
          {
            type: "info" /* INFO */,
            text: t4(
              "Insights generated at: {{path}}. Please open this file in your browser.",
              {
                path: outputPath
              }
            )
          },
          Date.now()
        );
      }
      context2.ui.setDebugMessage(t4("Insights ready."));
    } catch (error2) {
      context2.ui.setPendingItem(null);
      context2.ui.addItem(
        {
          type: "error" /* ERROR */,
          text: t4("Failed to generate insights: {{error}}", {
            error: error2.message
          })
        },
        Date.now()
      );
      logger5.error("Insight generation error:", error2);
    }
  }, "action")
};

// packages/cli/src/services/BuiltinCommandLoader.ts
var BuiltinCommandLoader = class {
  constructor(config2) {
    this.config = config2;
  }
  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,
      clearCommand,
      compressCommand,
      copyCommand,
      docsCommand,
      directoryCommand,
      editorCommand,
      exportCommand,
      extensionsCommand2,
      helpCommand,
      await ideCommand(),
      initCommand,
      languageCommand,
      mcpCommand2,
      memoryCommand,
      modelCommand,
      ...this.config?.getFolderTrust() ? [permissionsCommand] : [],
      quitCommand,
      restoreCommand(this.config),
      resumeCommand,
      skillsCommand,
      statsCommand,
      summaryCommand,
      themeCommand,
      toolsCommand,
      settingsCommand2,
      vimCommand,
      setupGithubCommand,
      terminalSetupCommand,
      insightCommand
    ];
    return allDefinitions.filter((cmd) => cmd !== null);
  }
};

// packages/cli/src/services/FileCommandLoader.ts
init_esbuild_shims();
var import_toml2 = __toESM(require_toml(), 1);
init_esm11();
init_zod();
import { promises as fs92 } from "node:fs";
import * as fsSync5 from "node:fs";
import path103 from "node:path";

// packages/cli/src/services/markdown-command-parser.ts
init_esbuild_shims();
init_zod();
var MarkdownCommandDefSchema = external_exports.object({
  frontmatter: external_exports.object({
    description: external_exports.string().optional()
  }).optional(),
  prompt: external_exports.string({
    required_error: "The prompt content is required.",
    invalid_type_error: "The prompt content must be a string."
  })
});
function parseMarkdownCommand(content) {
  const frontmatterRegex = /^---\n([\s\S]*?)---\n([\s\S]*)$/;
  const match2 = content.match(frontmatterRegex);
  if (!match2) {
    return {
      prompt: content.trim()
    };
  }
  const [, frontmatterYaml, body] = match2;
  let frontmatter;
  if (frontmatterYaml.trim()) {
    try {
      frontmatter = parse6(frontmatterYaml);
    } catch (error2) {
      throw new Error(
        `Failed to parse YAML frontmatter: ${error2 instanceof Error ? error2.message : String(error2)}`
      );
    }
  }
  return {
    frontmatter,
    prompt: body.trim()
  };
}
__name(parseMarkdownCommand, "parseMarkdownCommand");

// packages/cli/src/services/command-factory.ts
init_esbuild_shims();
import path102 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 config2 = context2.services.config;
    if (!config2) {
      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, config2, sessionShellAllowlist);
      const allowedTools = config2.getAllowedTools() || [];
      const invocation = {
        params: { command: command2 }
      };
      const isAllowedBySettings = doesToolInvocationMatch(
        "run_shell_command",
        invocation,
        allowedTools
      );
      if (!allAllowed) {
        if (isHardDenial) {
          throw new Error(
            `${this.commandName} cannot be run. Blocked command: "${command2}". Reason: ${blockReason || "Blocked by configuration."}`
          );
        }
        if (isAllowedBySettings) {
          continue;
        }
        if (config2.getApprovalMode() === ApprovalMode.YOLO) {
          continue;
        }
        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 = {
          ...config2.getShellExecutionConfig(),
          defaultFg: activeTheme.colors.Foreground,
          defaultBg: activeTheme.colors.Background
        };
        const { result } = await ShellExecutionService.execute(
          injection.resolvedCommand,
          config2.getTargetDir(),
          () => {
          },
          new AbortController().signal,
          config2.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 debugLogger82 = createDebugLogger("AT_FILE_PROCESSOR");
var AtFileProcessor = class {
  constructor(commandName) {
    this.commandName = commandName;
  }
  static {
    __name(this, "AtFileProcessor");
  }
  async process(input, context2) {
    const config2 = context2.services.config;
    if (!config2) {
      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, config2);
          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 (error2) {
          const message = error2 instanceof Error ? error2.message : String(error2);
          const uiMessage = `Failed to inject content for '@{${pathStr}}': ${message}`;
          debugLogger82.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/command-factory.ts
var debugLogger83 = createDebugLogger("COMMAND_FACTORY");
function createSlashCommandFromDefinition(filePath, baseDir, definition, extensionName, fileExtension) {
  const relativePathWithExt = path102.relative(baseDir, filePath);
  const relativePath = relativePathWithExt.substring(
    0,
    relativePathWithExt.length - fileExtension.length
  );
  const baseCommandName = relativePath.split(path102.sep).map((segment) => segment.replaceAll(":", "_")).join(":");
  const defaultDescription = `Custom command from ${path102.basename(filePath)}`;
  let description = definition.description || defaultDescription;
  if (extensionName) {
    description = `[${extensionName}] ${description}`;
  }
  const processors = [];
  const usesArgs = definition.prompt.includes(SHORTHAND_ARGS_PLACEHOLDER);
  const usesShellInjection = definition.prompt.includes(
    SHELL_INJECTION_TRIGGER
  );
  const usesAtFileInjection = definition.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) {
        debugLogger83.error(
          `[FileCommandLoader] Critical error: Command '${baseCommandName}' was executed without invocation context.`
        );
        return {
          type: "submit_prompt",
          content: [{ text: definition.prompt }]
          // Fallback to unprocessed prompt
        };
      }
      try {
        let processedContent = [
          { text: definition.prompt }
        ];
        for (const processor of processors) {
          processedContent = await processor.process(processedContent, context2);
        }
        return {
          type: "submit_prompt",
          content: processedContent
        };
      } catch (e4) {
        if (e4 instanceof ConfirmationRequiredError) {
          return {
            type: "confirm_shell_commands",
            commandsToConfirm: e4.commandsToConfirm,
            originalInvocation: {
              raw: context2.invocation.raw
            }
          };
        }
        throw e4;
      }
    }, "action")
  };
}
__name(createSlashCommandFromDefinition, "createSlashCommandFromDefinition");

// packages/cli/src/services/FileCommandLoader.ts
var debugLogger84 = createDebugLogger("FILE_COMMAND_LOADER");
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(config2) {
    this.config = config2;
    this.folderTrustEnabled = !!config2?.getFolderTrustFeature();
    this.folderTrust = !!config2?.getFolderTrust();
    this.projectRoot = config2?.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 tomlFiles = await glob("**/*.toml", {
          ...globOptions,
          cwd: dirInfo.path
        });
        const mdFiles = await glob("**/*.md", {
          ...globOptions,
          cwd: dirInfo.path
        });
        if (this.folderTrustEnabled && !this.folderTrust) {
          return [];
        }
        const tomlCommandPromises = tomlFiles.map(
          (file) => this.parseAndAdaptTomlFile(
            path103.join(dirInfo.path, file),
            dirInfo.path,
            dirInfo.extensionName
          )
        );
        const mdCommandPromises = mdFiles.map(
          (file) => this.parseAndAdaptMarkdownFile(
            path103.join(dirInfo.path, file),
            dirInfo.path,
            dirInfo.extensionName
          )
        );
        const commands = (await Promise.all([...tomlCommandPromises, ...mdCommandPromises])).filter((cmd) => cmd !== null);
        allCommands.push(...commands);
      } catch (error2) {
        const isEnoent = error2.code === "ENOENT";
        const isAbortError3 = error2 instanceof Error && error2.name === "AbortError";
        if (!isEnoent && !isAbortError3) {
          debugLogger84.error(
            `[FileCommandLoader] Error loading commands from ${dirInfo.path}:`,
            error2
          );
        }
      }
    }
    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((a2, b2) => a2.name.localeCompare(b2.name));
      for (const ext2 of activeExtensions) {
        const commandsPaths = this.getExtensionCommandsPaths(ext2);
        for (const cmdPath of commandsPaths) {
          dirs.push({
            path: cmdPath,
            extensionName: ext2.name
          });
        }
      }
    }
    return dirs;
  }
  /**
   * Get commands paths from an extension.
   * Returns paths from config.commands if specified, otherwise defaults to 'commands' directory.
   */
  getExtensionCommandsPaths(ext2) {
    try {
      const configPath = path103.join(ext2.path, EXTENSIONS_CONFIG_FILENAME);
      if (fsSync5.existsSync(configPath)) {
        const configContent = fsSync5.readFileSync(configPath, "utf-8");
        const config2 = JSON.parse(configContent);
        if (config2.commands) {
          const commandsArray = Array.isArray(config2.commands) ? config2.commands : [config2.commands];
          return commandsArray.map(
            (cmdPath) => path103.isAbsolute(cmdPath) ? cmdPath : path103.join(ext2.path, cmdPath)
          ).filter((cmdPath) => {
            try {
              return fsSync5.existsSync(cmdPath);
            } catch {
              return false;
            }
          });
        }
      }
    } catch (error2) {
      debugLogger84.warn(
        `Failed to read extension config for ${ext2.name}:`,
        error2
      );
    }
    const defaultPath = path103.join(ext2.path, "commands");
    try {
      if (fsSync5.existsSync(defaultPath)) {
        return [defaultPath];
      }
    } catch {
    }
    return [];
  }
  /**
   * 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 parseAndAdaptTomlFile(filePath, baseDir, extensionName) {
    let fileContent;
    try {
      fileContent = await fs92.readFile(filePath, "utf-8");
    } catch (error2) {
      debugLogger84.error(
        `[FileCommandLoader] Failed to read file ${filePath}:`,
        error2 instanceof Error ? error2.message : String(error2)
      );
      return null;
    }
    let parsed;
    try {
      parsed = import_toml2.default.parse(fileContent);
    } catch (error2) {
      debugLogger84.error(
        `[FileCommandLoader] Failed to parse TOML file ${filePath}:`,
        error2 instanceof Error ? error2.message : String(error2)
      );
      return null;
    }
    const validationResult = TomlCommandDefSchema.safeParse(parsed);
    if (!validationResult.success) {
      debugLogger84.error(
        `[FileCommandLoader] Skipping invalid command file: ${filePath}. Validation errors:`,
        validationResult.error.flatten()
      );
      return null;
    }
    const validDef = validationResult.data;
    return createSlashCommandFromDefinition(
      filePath,
      baseDir,
      validDef,
      extensionName,
      ".toml"
    );
  }
  /**
   * Parses a single .md file and transforms it into a SlashCommand object.
   * @param filePath The absolute path to the .md 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 parseAndAdaptMarkdownFile(filePath, baseDir, extensionName) {
    let fileContent;
    try {
      fileContent = await fs92.readFile(filePath, "utf-8");
    } catch (error2) {
      debugLogger84.error(
        `[FileCommandLoader] Failed to read file ${filePath}:`,
        error2 instanceof Error ? error2.message : String(error2)
      );
      return null;
    }
    let parsed;
    try {
      parsed = parseMarkdownCommand(fileContent);
    } catch (error2) {
      debugLogger84.error(
        `[FileCommandLoader] Failed to parse Markdown file ${filePath}:`,
        error2 instanceof Error ? error2.message : String(error2)
      );
      return null;
    }
    const validationResult = MarkdownCommandDefSchema.safeParse(parsed);
    if (!validationResult.success) {
      debugLogger84.error(
        `[FileCommandLoader] Skipping invalid command file: ${filePath}. Validation errors:`,
        validationResult.error.flatten()
      );
      return null;
    }
    const validDef = validationResult.data;
    const definition = {
      prompt: validDef.prompt,
      description: validDef.frontmatter?.description && typeof validDef.frontmatter.description === "string" ? validDef.frontmatter.description : void 0
    };
    return createSlashCommandFromDefinition(
      filePath,
      baseDir,
      definition,
      extensionName,
      ".md"
    );
  }
};

// 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"),
    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
var debugLogger85 = createDebugLogger("NON_INTERACTIVE_COMMANDS");
var ALLOWED_BUILTIN_COMMANDS_NON_INTERACTIVE = [
  "init",
  "summary",
  "compress",
  "bug"
];
function handleCommandResult(result) {
  switch (result.type) {
    case "submit_prompt":
      return {
        type: "submit_prompt",
        content: result.content
      };
    case "message":
      return {
        type: "message",
        messageType: result.messageType,
        content: result.content
      };
    case "stream_messages":
      return {
        type: "stream_messages",
        messages: result.messages
      };
    /**
     * Currently return types below are never generated due to the
     * whitelist of allowed slash commands in ACP and non-interactive mode.
     * We'll try to add more supported return types in the future.
     */
    case "tool":
      return {
        type: "unsupported",
        reason: "Tool execution from slash commands is not supported in non-interactive mode.",
        originalType: "tool"
      };
    case "quit":
      return {
        type: "unsupported",
        reason: "Quit command is not supported in non-interactive mode. The process will exit naturally after completion.",
        originalType: "quit"
      };
    case "dialog":
      return {
        type: "unsupported",
        reason: `Dialog '${result.dialog}' cannot be opened in non-interactive mode.`,
        originalType: "dialog"
      };
    case "load_history":
      return {
        type: "unsupported",
        reason: "Loading history is not supported in non-interactive mode. Each invocation starts with a fresh context.",
        originalType: "load_history"
      };
    case "confirm_shell_commands":
      return {
        type: "unsupported",
        reason: "Shell command confirmation is not supported in non-interactive mode. Use YOLO mode or pre-approve commands.",
        originalType: "confirm_shell_commands"
      };
    case "confirm_action":
      return {
        type: "unsupported",
        reason: "Action confirmation is not supported in non-interactive mode. Commands requiring confirmation cannot be executed.",
        originalType: "confirm_action"
      };
    default: {
      const _exhaustive = result;
      return {
        type: "unsupported",
        reason: `Unknown command result type: ${_exhaustive.type}`,
        originalType: "unknown"
      };
    }
  }
}
__name(handleCommandResult, "handleCommandResult");
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, config2, settings, allowedBuiltinCommandNames = [
  ...ALLOWED_BUILTIN_COMMANDS_NON_INTERACTIVE
]) => {
  const trimmed2 = rawQuery.trim();
  if (!trimmed2.startsWith("/")) {
    return { type: "no_command" };
  }
  const isAcpMode = config2.getExperimentalZedIntegration();
  const isInteractive = config2.isInteractive();
  const executionMode = isAcpMode ? "acp" : isInteractive ? "interactive" : "non_interactive";
  const allowedBuiltinSet = new Set(allowedBuiltinCommandNames ?? []);
  const allLoaders = [
    new BuiltinCommandLoader(config2),
    new FileCommandLoader(config2)
  ];
  const commandService = await CommandService.create(
    allLoaders,
    abortController.signal
  );
  const allCommands = commandService.getCommands();
  const filteredCommands = filterCommandsForNonInteractive(
    allCommands,
    allowedBuiltinSet
  );
  const { commandToExecute, args } = parseSlashCommand(
    rawQuery,
    filteredCommands
  );
  if (!commandToExecute) {
    const { commandToExecute: knownCommand } = parseSlashCommand(
      rawQuery,
      allCommands
    );
    if (knownCommand) {
      return {
        type: "unsupported",
        reason: t4(
          'The command "/{{command}}" is not supported in non-interactive mode.',
          { command: knownCommand.name }
        ),
        originalType: "filtered_command"
      };
    }
    return { type: "no_command" };
  }
  if (!commandToExecute.action) {
    return { type: "no_command" };
  }
  const sessionStats = {
    sessionId: config2?.getSessionId(),
    sessionStartTime: /* @__PURE__ */ new Date(),
    metrics: uiTelemetryService.getMetrics(),
    lastPromptTokenCount: 0,
    promptCount: 1
  };
  const logger6 = new Logger(config2?.getSessionId() || "", config2?.storage);
  const context2 = {
    executionMode,
    services: {
      config: config2,
      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) {
    return {
      type: "message",
      messageType: "info",
      content: "Command executed successfully."
    };
  }
  return handleCommandResult(result);
}, "handleSlashCommand");
var getAvailableCommands = /* @__PURE__ */ __name(async (config2, abortSignal, allowedBuiltinCommandNames = [
  ...ALLOWED_BUILTIN_COMMANDS_NON_INTERACTIVE
]) => {
  try {
    const allowedBuiltinSet = new Set(allowedBuiltinCommandNames ?? []);
    const loaders = allowedBuiltinSet.size > 0 ? [new BuiltinCommandLoader(config2), new FileCommandLoader(config2)] : [new FileCommandLoader(config2)];
    const commandService = await CommandService.create(loaders, abortSignal);
    const commands = commandService.getCommands();
    const filteredCommands = filterCommandsForNonInteractive(
      commands,
      allowedBuiltinSet
    );
    return filteredCommands.filter((cmd) => !cmd.hidden);
  } catch (error2) {
    debugLogger85.error("Error loading available commands:", error2);
    return [];
  }
}, "getAvailableCommands");

// packages/cli/src/utils/nonInteractiveHelpers.ts
var debugLogger86 = createDebugLogger("NON_INTERACTIVE");
function normalizePartList(parts) {
  if (!parts) {
    return [];
  }
  if (typeof parts === "string") {
    return [{ text: parts }];
  }
  if (Array.isArray(parts)) {
    return parts.map(
      (part) => typeof part === "string" ? { text: part } : part
    );
  }
  return [parts];
}
__name(normalizePartList, "normalizePartList");
function extractPartsFromUserMessage(message) {
  if (!message) {
    return null;
  }
  const content = message.message?.content;
  if (typeof content === "string") {
    return content;
  }
  if (Array.isArray(content)) {
    const parts = [];
    for (const block2 of content) {
      if (!block2 || typeof block2 !== "object" || !("type" in block2)) {
        continue;
      }
      if (block2.type === "text" && "text" in block2 && block2.text) {
        parts.push({ text: block2.text });
      } else {
        parts.push({ text: JSON.stringify(block2) });
      }
    }
    return parts.length > 0 ? parts : null;
  }
  return null;
}
__name(extractPartsFromUserMessage, "extractPartsFromUserMessage");
function computeUsageFromMetrics(metrics2) {
  const stats = computeSessionStats(metrics2);
  const { models } = metrics2;
  const totalOutputTokens = Object.values(models).reduce(
    (acc, model) => acc + model.tokens.candidates,
    0
  );
  const totalTokens = Object.values(models).reduce(
    (acc, model) => acc + model.tokens.total,
    0
  );
  const usage2 = {
    input_tokens: stats.totalPromptTokens,
    output_tokens: totalOutputTokens,
    cache_read_input_tokens: stats.totalCachedTokens
  };
  if (totalTokens > 0) {
    usage2.total_tokens = totalTokens;
  }
  return usage2;
}
__name(computeUsageFromMetrics, "computeUsageFromMetrics");
async function loadSlashCommandNames(config2, allowedBuiltinCommandNames) {
  const controller = new AbortController();
  try {
    const commands = await getAvailableCommands(
      config2,
      controller.signal,
      allowedBuiltinCommandNames
    );
    return commands.map((cmd) => cmd.name).sort();
  } catch (error2) {
    debugLogger86.error(
      "[buildSystemMessage] Failed to load slash commands:",
      error2
    );
    return [];
  } finally {
    controller.abort();
  }
}
__name(loadSlashCommandNames, "loadSlashCommandNames");
async function buildSystemMessage(config2, sessionId, permissionMode, allowedBuiltinCommandNames) {
  const toolRegistry = config2.getToolRegistry();
  const tools = toolRegistry ? toolRegistry.getAllToolNames() : [];
  const mcpServers = config2.getMcpServers();
  const mcpServerList = mcpServers ? Object.keys(mcpServers).map((name3) => ({
    name: name3,
    status: getMCPServerStatus(name3)
  })) : [];
  const slashCommands = await loadSlashCommandNames(
    config2,
    allowedBuiltinCommandNames
  );
  let agentNames = [];
  try {
    const subagentManager = config2.getSubagentManager();
    const subagents = await subagentManager.listSubagents();
    agentNames = subagents.map((subagent) => subagent.name);
  } catch (error2) {
    debugLogger86.error("[buildSystemMessage] Failed to load subagents:", error2);
  }
  const systemMessage = {
    type: "system",
    subtype: "init",
    uuid: sessionId,
    session_id: sessionId,
    cwd: config2.getTargetDir(),
    tools,
    mcp_servers: mcpServerList,
    model: config2.getModel(),
    permission_mode: permissionMode,
    slash_commands: slashCommands,
    qwen_code_version: config2.getCliVersion() || "unknown",
    agents: agentNames
  };
  return systemMessage;
}
__name(buildSystemMessage, "buildSystemMessage");
function isMcpToolProgressData(output) {
  return typeof output === "object" && output !== null && "type" in output && output.type === "mcp_tool_progress";
}
__name(isMcpToolProgressData, "isMcpToolProgressData");
function createToolProgressHandler(request4, adapter) {
  const handler = /* @__PURE__ */ __name((_callId, output) => {
    if (isMcpToolProgressData(output)) {
      adapter.emitToolProgress(request4, output);
    }
  }, "handler");
  return { handler };
}
__name(createToolProgressHandler, "createToolProgressHandler");
function createTaskToolProgressHandler(config2, taskToolCallId, adapter) {
  const previousTaskStates = /* @__PURE__ */ new Map();
  const emittedToolUseIds = /* @__PURE__ */ new Set();
  const emittedToolResultIds = /* @__PURE__ */ new Set();
  const buildRequest = /* @__PURE__ */ __name((toolCall) => ({
    callId: toolCall.callId,
    name: toolCall.name,
    args: toolCall.args || {},
    isClientInitiated: true,
    prompt_id: "",
    response_id: void 0
  }), "buildRequest");
  const buildResponse = /* @__PURE__ */ __name((toolCall) => ({
    callId: toolCall.callId,
    error: toolCall.status === "failed" ? new Error(toolCall.error || "Tool execution failed") : void 0,
    errorType: toolCall.status === "failed" ? ToolErrorType.EXECUTION_FAILED : void 0,
    resultDisplay: toolCall.resultDisplay,
    responseParts: toolCall.responseParts || []
  }), "buildResponse");
  const hasResultContent = /* @__PURE__ */ __name((toolCall) => {
    if (typeof toolCall.resultDisplay === "string" && toolCall.resultDisplay.trim().length > 0) {
      return true;
    }
    if (toolCall.responseParts && toolCall.responseParts.length > 0) {
      return true;
    }
    return toolCall.status === "failed";
  }, "hasResultContent");
  const emitToolUseIfNeeded = /* @__PURE__ */ __name((toolCall, fallbackStatus) => {
    if (emittedToolUseIds.has(toolCall.callId)) {
      return;
    }
    const toolCallToEmit = fallbackStatus ? {
      ...toolCall,
      status: fallbackStatus
    } : toolCall;
    if (toolCallToEmit.status === "executing" || toolCallToEmit.status === "awaiting_approval") {
      if (adapter.processSubagentToolCall) {
        adapter.processSubagentToolCall(toolCallToEmit, taskToolCallId);
        emittedToolUseIds.add(toolCall.callId);
      }
    }
  }, "emitToolUseIfNeeded");
  const emitToolResultIfNeeded = /* @__PURE__ */ __name((toolCall) => {
    if (emittedToolResultIds.has(toolCall.callId)) {
      return;
    }
    if (!hasResultContent(toolCall)) {
      return;
    }
    emittedToolResultIds.add(toolCall.callId);
    const request4 = buildRequest(toolCall);
    const response = buildResponse(toolCall);
    if ("emitToolResult" in adapter && typeof adapter.emitToolResult === "function") {
      adapter.emitToolResult(request4, response, taskToolCallId);
    } else {
      adapter.emitToolResult(request4, response);
    }
  }, "emitToolResultIfNeeded");
  const processToolCall = /* @__PURE__ */ __name((toolCall, previousCall) => {
    const isCompleted = toolCall.status === "success" || toolCall.status === "failed";
    const isExecuting = toolCall.status === "executing" || toolCall.status === "awaiting_approval";
    const wasExecuting = previousCall && (previousCall.status === "executing" || previousCall.status === "awaiting_approval");
    if (isExecuting) {
      emitToolUseIfNeeded(toolCall);
    } else if (isCompleted && !emittedToolUseIds.has(toolCall.callId)) {
      emitToolUseIfNeeded(toolCall, "executing");
    } else if (wasExecuting && isCompleted) {
      emitToolUseIfNeeded(toolCall, "executing");
    }
    if (isCompleted) {
      emitToolResultIfNeeded(toolCall);
    }
  }, "processToolCall");
  const outputUpdateHandler = /* @__PURE__ */ __name((callId, outputChunk) => {
    if (typeof outputChunk === "object" && outputChunk !== null && "type" in outputChunk && outputChunk.type === "task_execution") {
      const taskDisplay = outputChunk;
      const previous = previousTaskStates.get(callId);
      if (!adapter.processSubagentToolCall || !adapter.emitSubagentErrorResult) {
        previousTaskStates.set(callId, taskDisplay);
        return;
      }
      if (taskDisplay.toolCalls) {
        if (!previous || !previous.toolCalls) {
          for (const toolCall of taskDisplay.toolCalls) {
            processToolCall(toolCall);
          }
        } else {
          for (const toolCall of taskDisplay.toolCalls) {
            const previousCall = previous.toolCalls.find(
              (tc) => tc.callId === toolCall.callId
            );
            processToolCall(toolCall, previousCall);
          }
        }
      }
      if (taskDisplay.status === "failed" || taskDisplay.status === "cancelled") {
        const previousStatus = previous?.status;
        if (previousStatus !== "failed" && previousStatus !== "cancelled" && previousStatus !== void 0) {
          const errorMessage = taskDisplay.terminateReason || (taskDisplay.status === "cancelled" ? "Task was cancelled" : "Task execution failed");
          adapter.emitSubagentErrorResult(errorMessage, 0, taskToolCallId);
        }
      }
      if (!previous && taskDisplay.taskPrompt && !config2.isInteractive() && (config2.getOutputFormat() === OutputFormat.JSON || config2.getOutputFormat() === OutputFormat.STREAM_JSON)) {
        adapter.emitUserMessage(
          [{ text: taskDisplay.taskPrompt }],
          taskToolCallId
        );
      }
      previousTaskStates.set(callId, taskDisplay);
    }
  }, "outputUpdateHandler");
  return {
    handler: outputUpdateHandler
  };
}
__name(createTaskToolProgressHandler, "createTaskToolProgressHandler");
function functionResponsePartsToString(parts) {
  return parts.map((part) => {
    if ("functionResponse" in part) {
      const content = part.functionResponse?.response?.["output"] ?? "";
      return content;
    }
    return JSON.stringify(part);
  }).join("");
}
__name(functionResponsePartsToString, "functionResponsePartsToString");

// packages/cli/src/nonInteractive/io/BaseJsonOutputAdapter.ts
var BaseJsonOutputAdapter = class {
  static {
    __name(this, "BaseJsonOutputAdapter");
  }
  config;
  // Main agent message state
  mainAgentMessageState;
  // Subagent message states keyed by parentToolUseId
  subagentMessageStates = /* @__PURE__ */ new Map();
  // Last assistant message for result generation
  lastAssistantMessage = null;
  // Track permission denials (execution denied tool calls)
  permissionDenials = [];
  constructor(config2) {
    this.config = config2;
    this.mainAgentMessageState = this.createMessageState();
  }
  /**
   * Creates a new message state with default values.
   */
  createMessageState() {
    return {
      messageId: null,
      blocks: [],
      openBlocks: /* @__PURE__ */ new Set(),
      usage: this.createUsage(),
      messageStarted: false,
      finalized: false,
      currentBlockType: null
    };
  }
  /**
   * Gets or creates message state for a given context.
   *
   * @param parentToolUseId - null for main agent, string for subagent
   * @returns MessageState for the context
   */
  getMessageState(parentToolUseId) {
    if (parentToolUseId === null) {
      return this.mainAgentMessageState;
    }
    let state = this.subagentMessageStates.get(parentToolUseId);
    if (!state) {
      state = this.createMessageState();
      this.subagentMessageStates.set(parentToolUseId, state);
    }
    return state;
  }
  /**
   * Creates a Usage object from metadata.
   *
   * @param metadata - Optional usage metadata from Gemini API
   * @returns Usage object
   */
  createUsage(metadata) {
    const usage2 = {
      input_tokens: 0,
      output_tokens: 0
    };
    if (!metadata) {
      return usage2;
    }
    if (typeof metadata.promptTokenCount === "number") {
      usage2.input_tokens = metadata.promptTokenCount;
    }
    if (typeof metadata.candidatesTokenCount === "number") {
      usage2.output_tokens = metadata.candidatesTokenCount;
    }
    if (typeof metadata.cachedContentTokenCount === "number") {
      usage2.cache_read_input_tokens = metadata.cachedContentTokenCount;
    }
    if (typeof metadata.totalTokenCount === "number") {
      usage2.total_tokens = metadata.totalTokenCount;
    }
    return usage2;
  }
  /**
   * Builds a CLIAssistantMessage from the current message state.
   *
   * @param parentToolUseId - null for main agent, string for subagent
   * @returns CLIAssistantMessage
   */
  buildMessage(parentToolUseId) {
    const state = this.getMessageState(parentToolUseId);
    if (!state.messageId) {
      throw new Error("Message not started");
    }
    if (state.blocks.length > 0) {
      const blockTypes = new Set(state.blocks.map((block2) => block2.type));
      if (blockTypes.size > 1) {
        throw new Error(
          `Assistant message must contain only one type of ContentBlock, found: ${Array.from(blockTypes).join(", ")}`
        );
      }
    }
    const stopReason = state.blocks.length > 0 && state.blocks.every((block2) => block2.type === "tool_use") ? "tool_use" : null;
    return {
      type: "assistant",
      uuid: state.messageId,
      session_id: this.config.getSessionId(),
      parent_tool_use_id: parentToolUseId,
      message: {
        id: state.messageId,
        type: "message",
        role: "assistant",
        model: this.config.getModel(),
        content: state.blocks,
        stop_reason: stopReason,
        usage: state.usage
      }
    };
  }
  /**
   * Finalizes pending blocks (text or thinking) by closing them.
   *
   * @param state - Message state to finalize blocks for
   * @param parentToolUseId - null for main agent, string for subagent (optional, defaults to null)
   */
  finalizePendingBlocks(state, parentToolUseId) {
    const actualParentToolUseId = parentToolUseId ?? null;
    const lastBlock = state.blocks[state.blocks.length - 1];
    if (!lastBlock) {
      return;
    }
    if (lastBlock.type === "text") {
      const index = state.blocks.length - 1;
      this.onBlockClosed(state, index, actualParentToolUseId);
      this.closeBlock(state, index);
    } else if (lastBlock.type === "thinking") {
      const index = state.blocks.length - 1;
      this.onBlockClosed(state, index, actualParentToolUseId);
      this.closeBlock(state, index);
    }
  }
  /**
   * Opens a block (adds to openBlocks set).
   *
   * @param state - Message state
   * @param index - Block index
   * @param _block - Content block
   */
  openBlock(state, index, _block) {
    state.openBlocks.add(index);
  }
  /**
   * Closes a block (removes from openBlocks set).
   *
   * @param state - Message state
   * @param index - Block index
   */
  closeBlock(state, index) {
    if (!state.openBlocks.has(index)) {
      return;
    }
    state.openBlocks.delete(index);
  }
  /**
   * Guarantees that a single assistant message aggregates only one
   * content block category (text, thinking, or tool use). When a new
   * block type is requested, the current message is finalized and a fresh
   * assistant message is started to honour the single-type constraint.
   *
   * @param state - Message state
   * @param targetType - Target block type
   * @param parentToolUseId - null for main agent, string for subagent
   */
  ensureBlockTypeConsistency(state, targetType, parentToolUseId) {
    if (state.currentBlockType === targetType) {
      return;
    }
    if (state.currentBlockType === null) {
      state.currentBlockType = targetType;
      return;
    }
    this.finalizeAssistantMessageInternal(state, parentToolUseId);
    this.startAssistantMessageInternal(state);
    state.currentBlockType = targetType;
  }
  /**
   * Starts a new assistant message, resetting state.
   *
   * @param state - Message state to reset
   */
  startAssistantMessageInternal(state) {
    state.messageId = randomUUID7();
    state.blocks = [];
    state.openBlocks = /* @__PURE__ */ new Set();
    state.usage = this.createUsage();
    state.messageStarted = false;
    state.finalized = false;
    state.currentBlockType = null;
  }
  /**
   * Finalizes an assistant message.
   *
   * @param state - Message state to finalize
   * @param parentToolUseId - null for main agent, string for subagent
   * @returns CLIAssistantMessage
   */
  finalizeAssistantMessageInternal(state, parentToolUseId) {
    if (state.finalized) {
      return this.buildMessage(parentToolUseId);
    }
    state.finalized = true;
    this.finalizePendingBlocks(state, parentToolUseId);
    const orderedOpenBlocks = Array.from(state.openBlocks).sort(
      (a2, b2) => a2 - b2
    );
    for (const index of orderedOpenBlocks) {
      this.onBlockClosed(state, index, parentToolUseId);
      this.closeBlock(state, index);
    }
    const message = this.buildMessage(parentToolUseId);
    this.emitMessageImpl(message);
    return message;
  }
  /**
   * Hook method called when a text block is created.
   * Subclasses can override this to emit stream events.
   *
   * @param state - Message state
   * @param index - Block index
   * @param block - Text block that was created
   * @param parentToolUseId - null for main agent, string for subagent
   */
  onTextBlockCreated(_state, _index, _block, _parentToolUseId) {
  }
  /**
   * Hook method called when text content is appended.
   * Subclasses can override this to emit stream events.
   *
   * @param state - Message state
   * @param index - Block index
   * @param fragment - Text fragment that was appended
   * @param parentToolUseId - null for main agent, string for subagent
   */
  onTextAppended(_state, _index, _fragment, _parentToolUseId) {
  }
  /**
   * Hook method called when a thinking block is created.
   * Subclasses can override this to emit stream events.
   *
   * @param state - Message state
   * @param index - Block index
   * @param block - Thinking block that was created
   * @param parentToolUseId - null for main agent, string for subagent
   */
  onThinkingBlockCreated(_state, _index, _block, _parentToolUseId) {
  }
  /**
   * Hook method called when thinking content is appended.
   * Subclasses can override this to emit stream events.
   *
   * @param state - Message state
   * @param index - Block index
   * @param fragment - Thinking fragment that was appended
   * @param parentToolUseId - null for main agent, string for subagent
   */
  onThinkingAppended(_state, _index, _fragment, _parentToolUseId) {
  }
  /**
   * Hook method called when a tool_use block is created.
   * Subclasses can override this to emit stream events.
   *
   * @param state - Message state
   * @param index - Block index
   * @param block - Tool use block that was created
   * @param parentToolUseId - null for main agent, string for subagent
   */
  onToolUseBlockCreated(_state, _index, _block, _parentToolUseId) {
  }
  /**
   * Hook method called when tool_use input is set.
   * Subclasses can override this to emit stream events.
   *
   * @param state - Message state
   * @param index - Block index
   * @param input - Tool use input that was set
   * @param parentToolUseId - null for main agent, string for subagent
   */
  onToolUseInputSet(_state, _index, _input, _parentToolUseId) {
  }
  /**
   * Hook method called when a block is closed.
   * Subclasses can override this to emit stream events.
   *
   * @param state - Message state
   * @param index - Block index
   * @param parentToolUseId - null for main agent, string for subagent
   */
  onBlockClosed(_state, _index, _parentToolUseId) {
  }
  /**
   * Hook method called to ensure message is started.
   * Subclasses can override this to emit message_start events.
   *
   * @param state - Message state
   * @param parentToolUseId - null for main agent, string for subagent
   */
  onEnsureMessageStarted(_state, _parentToolUseId) {
  }
  /**
   * Gets the session ID from config.
   *
   * @returns Session ID
   */
  getSessionId() {
    return this.config.getSessionId();
  }
  /**
   * Gets the model name from config.
   *
   * @returns Model name
   */
  getModel() {
    return this.config.getModel();
  }
  // ========== Main Agent APIs ==========
  /**
   * Starts a new assistant message for the main agent.
   * This is a shared implementation used by both streaming and non-streaming adapters.
   */
  startAssistantMessage() {
    this.startAssistantMessageInternal(this.mainAgentMessageState);
  }
  /**
   * Processes a stream event from the Gemini API.
   * This is a shared implementation used by both streaming and non-streaming adapters.
   *
   * @param event - Stream event from Gemini API
   */
  processEvent(event) {
    const state = this.mainAgentMessageState;
    if (state.finalized) {
      return;
    }
    switch (event.type) {
      case GeminiEventType.Content:
        this.appendText(state, event.value, null);
        break;
      case GeminiEventType.Citation:
        if (typeof event.value === "string") {
          this.appendText(state, `
${event.value}`, null);
        }
        break;
      case GeminiEventType.Thought:
        this.appendThinking(
          state,
          event.value.subject,
          event.value.description,
          null
        );
        break;
      case GeminiEventType.ToolCallRequest:
        this.appendToolUse(state, event.value, null);
        break;
      case GeminiEventType.Finished:
        if (event.value?.usageMetadata) {
          state.usage = this.createUsage(event.value.usageMetadata);
        }
        this.finalizePendingBlocks(state, null);
        break;
      case GeminiEventType.Error: {
        const errorText = parseAndFormatApiError(
          event.value.error,
          this.config.getContentGeneratorConfig()?.authType
        );
        this.appendText(state, errorText, null);
        break;
      }
      default:
        break;
    }
  }
  // ========== Subagent APIs ==========
  /**
   * Starts a new assistant message for a subagent.
   * This is a shared implementation used by both streaming and non-streaming adapters.
   *
   * @param parentToolUseId - Parent tool use ID
   */
  startSubagentAssistantMessage(parentToolUseId) {
    const state = this.getMessageState(parentToolUseId);
    this.startAssistantMessageInternal(state);
  }
  /**
   * Finalizes a subagent assistant message.
   * This is a shared implementation used by both streaming and non-streaming adapters.
   *
   * @param parentToolUseId - Parent tool use ID
   * @returns CLIAssistantMessage
   */
  finalizeSubagentAssistantMessage(parentToolUseId) {
    const state = this.getMessageState(parentToolUseId);
    const message = this.finalizeAssistantMessageInternal(
      state,
      parentToolUseId
    );
    this.updateLastAssistantMessage(message);
    return message;
  }
  /**
   * Emits a subagent error result message.
   * This is a shared implementation used by both streaming and non-streaming adapters.
   *
   * @param errorMessage - Error message
   * @param numTurns - Number of turns
   * @param parentToolUseId - Parent tool use ID
   */
  emitSubagentErrorResult(errorMessage, numTurns, parentToolUseId) {
    const state = this.getMessageState(parentToolUseId);
    if (state.messageStarted && !state.finalized) {
      this.finalizeSubagentAssistantMessage(parentToolUseId);
    }
    const errorResult = this.buildSubagentErrorResult(errorMessage, numTurns);
    this.emitMessageImpl(errorResult);
  }
  /**
   * Processes a subagent tool call.
   * This is a shared implementation used by both streaming and non-streaming adapters.
   * Uses template method pattern with hooks for stream events.
   *
   * @param toolCall - Tool call information
   * @param parentToolUseId - Parent tool use ID
   */
  processSubagentToolCall(toolCall, parentToolUseId) {
    const state = this.getMessageState(parentToolUseId);
    const hasText = state.blocks.some((b2) => b2.type === "text") || state.currentBlockType === "text" && state.blocks.length > 0;
    if (hasText) {
      this.finalizeSubagentAssistantMessage(parentToolUseId);
      this.startSubagentAssistantMessage(parentToolUseId);
    }
    if (!state.messageId || !state.messageStarted) {
      this.startAssistantMessageInternal(state);
    }
    this.ensureBlockTypeConsistency(state, "tool_use", parentToolUseId);
    this.ensureMessageStarted(state, parentToolUseId);
    this.finalizePendingBlocks(state, parentToolUseId);
    const { index } = this.createSubagentToolUseBlock(
      state,
      toolCall,
      parentToolUseId
    );
    this.processSubagentToolUseBlock(state, index, toolCall, parentToolUseId);
    this.finalizeSubagentAssistantMessage(parentToolUseId);
    this.startSubagentAssistantMessage(parentToolUseId);
  }
  /**
   * Processes a tool use block for subagent.
   * This method is called by processSubagentToolCall to handle tool use block creation,
   * input setting, and closure. Subclasses can override this to customize behavior.
   *
   * @param state - Message state
   * @param index - Block index
   * @param toolCall - Tool call information
   * @param parentToolUseId - Parent tool use ID
   */
  processSubagentToolUseBlock(state, index, toolCall, parentToolUseId) {
    const startBlock = {
      type: "tool_use",
      id: toolCall.callId,
      name: toolCall.name,
      input: {}
    };
    this.onToolUseBlockCreated(state, index, startBlock, parentToolUseId);
    this.onToolUseInputSet(state, index, toolCall.args ?? {}, parentToolUseId);
    this.onBlockClosed(state, index, parentToolUseId);
    this.closeBlock(state, index);
  }
  /**
   * Updates the last assistant message.
   * Subclasses can override this to customize tracking behavior.
   *
   * @param message - Assistant message to track
   */
  updateLastAssistantMessage(message) {
    this.lastAssistantMessage = message;
  }
  // ========== Shared Content Block Methods ==========
  /**
   * Appends text content to the current message.
   * Uses template method pattern with hooks for stream events.
   *
   * @param state - Message state
   * @param fragment - Text fragment to append
   * @param parentToolUseId - null for main agent, string for subagent
   */
  appendText(state, fragment, parentToolUseId) {
    if (fragment.length === 0) {
      return;
    }
    this.ensureBlockTypeConsistency(state, "text", parentToolUseId);
    this.ensureMessageStarted(state, parentToolUseId);
    let current = state.blocks[state.blocks.length - 1];
    const isNewBlock = !current || current.type !== "text";
    if (isNewBlock) {
      current = { type: "text", text: "" };
      const index2 = state.blocks.length;
      state.blocks.push(current);
      this.openBlock(state, index2, current);
      this.onTextBlockCreated(state, index2, current, parentToolUseId);
    }
    current.text += fragment;
    const index = state.blocks.length - 1;
    this.onTextAppended(state, index, fragment, parentToolUseId);
  }
  /**
   * Appends thinking content to the current message.
   * Uses template method pattern with hooks for stream events.
   *
   * @param state - Message state
   * @param subject - Thinking subject
   * @param description - Thinking description
   * @param parentToolUseId - null for main agent, string for subagent
   */
  appendThinking(state, subject, description, parentToolUseId) {
    const actualParentToolUseId = parentToolUseId ?? null;
    const parts = [];
    if (subject && subject.length > 0) {
      parts.push(subject);
    }
    if (description && description.length > 0) {
      parts.push(description);
    }
    const fragment = parts.join(": ");
    if (!fragment) {
      return;
    }
    this.ensureBlockTypeConsistency(state, "thinking", actualParentToolUseId);
    this.ensureMessageStarted(state, actualParentToolUseId);
    let current = state.blocks[state.blocks.length - 1];
    const isNewBlock = !current || current.type !== "thinking";
    if (isNewBlock) {
      current = {
        type: "thinking",
        thinking: "",
        signature: subject
      };
      const index2 = state.blocks.length;
      state.blocks.push(current);
      this.openBlock(state, index2, current);
      this.onThinkingBlockCreated(state, index2, current, actualParentToolUseId);
    }
    current.thinking = `${current.thinking ?? ""}${fragment}`;
    const index = state.blocks.length - 1;
    this.onThinkingAppended(state, index, fragment, actualParentToolUseId);
  }
  /**
   * Appends a tool_use block to the current message.
   * Uses template method pattern with hooks for stream events.
   *
   * @param state - Message state
   * @param request - Tool call request info
   * @param parentToolUseId - null for main agent, string for subagent
   */
  appendToolUse(state, request4, parentToolUseId) {
    this.ensureBlockTypeConsistency(state, "tool_use", parentToolUseId);
    this.ensureMessageStarted(state, parentToolUseId);
    this.finalizePendingBlocks(state, parentToolUseId);
    const index = state.blocks.length;
    const block2 = {
      type: "tool_use",
      id: request4.callId,
      name: request4.name,
      input: request4.args
    };
    state.blocks.push(block2);
    this.openBlock(state, index, block2);
    const startBlock = {
      type: "tool_use",
      id: request4.callId,
      name: request4.name,
      input: {}
    };
    this.onToolUseBlockCreated(state, index, startBlock, parentToolUseId);
    this.onToolUseInputSet(state, index, request4.args ?? {}, parentToolUseId);
    this.onBlockClosed(state, index, parentToolUseId);
    this.closeBlock(state, index);
  }
  /**
   * Ensures that a message has been started.
   * Calls hook method for subclasses to emit message_start events.
   *
   * @param state - Message state
   * @param parentToolUseId - null for main agent, string for subagent
   */
  ensureMessageStarted(state, parentToolUseId) {
    if (state.messageStarted) {
      return;
    }
    state.messageStarted = true;
    this.onEnsureMessageStarted(state, parentToolUseId);
  }
  /**
   * Creates and adds a tool_use block to the state.
   * This is a shared helper method used by processSubagentToolCall implementations.
   *
   * @param state - Message state
   * @param toolCall - Tool call information
   * @param parentToolUseId - Parent tool use ID
   * @returns The created block and its index
   */
  createSubagentToolUseBlock(state, toolCall, _parentToolUseId) {
    const index = state.blocks.length;
    const block2 = {
      type: "tool_use",
      id: toolCall.callId,
      name: toolCall.name,
      input: toolCall.args || {}
    };
    state.blocks.push(block2);
    this.openBlock(state, index, block2);
    return { block: block2, index };
  }
  /**
   * Emits a user message.
   * @param parts - Array of Part objects
   * @param parentToolUseId - Optional parent tool use ID for subagent messages
   */
  emitUserMessage(parts, parentToolUseId) {
    const content = partsToContentBlock(parts);
    const message = {
      type: "user",
      uuid: randomUUID7(),
      session_id: this.getSessionId(),
      parent_tool_use_id: parentToolUseId ?? null,
      message: {
        role: "user",
        content
      }
    };
    this.emitMessageImpl(message);
  }
  /**
   * Checks if responseParts contain any functionResponse with an error.
   * This handles cancelled responses and other error cases where the error
   * is embedded in responseParts rather than the top-level error field.
   * @param responseParts - Array of Part objects
   * @returns Error message if found, undefined otherwise
   */
  checkResponsePartsForError(responseParts) {
    return checkResponsePartsForError(responseParts);
  }
  /**
   * Emits a tool result message.
   * Collects execution denied tool calls for inclusion in result messages.
   * Handles both explicit errors (response.error) and errors embedded in
   * responseParts (e.g., cancelled responses).
   * @param request - Tool call request info
   * @param response - Tool call response info
   * @param parentToolUseId - Parent tool use ID (null for main agent)
   */
  emitToolResult(request4, response, parentToolUseId = null) {
    const responsePartsError = this.checkResponsePartsForError(
      response.responseParts
    );
    const hasError = Boolean(response.error) || Boolean(responsePartsError);
    if (response.error && response.errorType === ToolErrorType.EXECUTION_DENIED) {
      const denial = {
        tool_name: request4.name,
        tool_use_id: request4.callId,
        tool_input: request4.args
      };
      this.permissionDenials.push(denial);
    }
    const block2 = {
      type: "tool_result",
      tool_use_id: request4.callId,
      is_error: hasError
    };
    const content = toolResultContent(response);
    if (content !== void 0) {
      block2.content = content;
    }
    const message = {
      type: "user",
      uuid: randomUUID7(),
      session_id: this.getSessionId(),
      parent_tool_use_id: parentToolUseId,
      message: {
        role: "user",
        content: [block2]
      }
    };
    this.emitMessageImpl(message);
  }
  /**
   * Emits a system message.
   * @param subtype - System message subtype
   * @param data - Optional data payload
   */
  emitSystemMessage(subtype, data) {
    const systemMessage = {
      type: "system",
      subtype,
      uuid: randomUUID7(),
      session_id: this.getSessionId(),
      parent_tool_use_id: null,
      data
    };
    this.emitMessageImpl(systemMessage);
  }
  /**
   * Emits a tool progress stream event.
   * Default implementation is a no-op. StreamJsonOutputAdapter overrides this
   * to emit stream events when includePartialMessages is enabled.
   *
   * @param _request - Tool call request info
   * @param _progress - Structured MCP progress data
   */
  emitToolProgress(_request, _progress) {
  }
  /**
   * Builds a result message from options.
   * Helper method used by both emitResult implementations.
   * Includes permission denials collected from execution denied tool calls.
   * @param options - Result options
   * @param lastAssistantMessage - Last assistant message for text extraction
   * @returns CLIResultMessage
   */
  buildResultMessage(options2, lastAssistantMessage) {
    const usage2 = options2.usage ?? createExtendedUsage();
    const resultText = options2.summary ?? (lastAssistantMessage ? extractTextFromBlocks(lastAssistantMessage.message.content) : "");
    const baseUuid = randomUUID7();
    const baseSessionId = this.getSessionId();
    if (options2.isError) {
      const errorMessage = options2.errorMessage ?? "Unknown error";
      return {
        type: "result",
        subtype: options2.subtype ?? "error_during_execution",
        uuid: baseUuid,
        session_id: baseSessionId,
        is_error: true,
        duration_ms: options2.durationMs,
        duration_api_ms: options2.apiDurationMs,
        num_turns: options2.numTurns,
        usage: usage2,
        permission_denials: [...this.permissionDenials],
        error: { message: errorMessage }
      };
    } else {
      const success = {
        type: "result",
        subtype: options2.subtype ?? "success",
        uuid: baseUuid,
        session_id: baseSessionId,
        is_error: false,
        duration_ms: options2.durationMs,
        duration_api_ms: options2.apiDurationMs,
        num_turns: options2.numTurns,
        result: resultText,
        usage: usage2,
        permission_denials: [...this.permissionDenials]
      };
      if (options2.stats) {
        success.stats = options2.stats;
      }
      return success;
    }
  }
  /**
   * Builds a subagent error result message.
   * Helper method used by both emitSubagentErrorResult implementations.
   * Note: Subagent permission denials are not included here as they are tracked
   * separately and would be included in the main agent's result message.
   * @param errorMessage - Error message
   * @param numTurns - Number of turns
   * @returns CLIResultMessageError
   */
  buildSubagentErrorResult(errorMessage, numTurns) {
    const usage2 = {
      input_tokens: 0,
      output_tokens: 0
    };
    return {
      type: "result",
      subtype: "error_during_execution",
      uuid: randomUUID7(),
      session_id: this.getSessionId(),
      is_error: true,
      duration_ms: 0,
      duration_api_ms: 0,
      num_turns: numTurns,
      usage: usage2,
      permission_denials: [],
      error: { message: errorMessage }
    };
  }
};
function partsToContentBlock(parts) {
  const blocks = [];
  let currentTextBlock = null;
  for (const part of parts) {
    let textContent2 = null;
    if ("text" in part && typeof part.text === "string") {
      textContent2 = part.text;
    } else if ("functionResponse" in part && part.functionResponse) {
      const output = part.functionResponse.response?.["output"] ?? part.functionResponse.response?.["content"] ?? "";
      textContent2 = typeof output === "string" ? output : JSON.stringify(output);
    } else {
      textContent2 = JSON.stringify(part);
    }
    if (textContent2 !== null && textContent2.length > 0) {
      if (currentTextBlock === null) {
        currentTextBlock = {
          type: "text",
          text: textContent2
        };
        blocks.push(currentTextBlock);
      } else {
        currentTextBlock.text += textContent2;
      }
    }
  }
  return blocks;
}
__name(partsToContentBlock, "partsToContentBlock");
function checkResponsePartsForError(responseParts) {
  if (!responseParts || responseParts.length === 0) {
    return void 0;
  }
  for (const part of responseParts) {
    if ("functionResponse" in part && part.functionResponse?.response && typeof part.functionResponse.response === "object" && "error" in part.functionResponse.response && part.functionResponse.response["error"]) {
      const error2 = part.functionResponse.response["error"];
      return typeof error2 === "string" ? error2 : String(error2);
    }
  }
  return void 0;
}
__name(checkResponsePartsForError, "checkResponsePartsForError");
function toolResultContent(response) {
  if (response.error) {
    return response.error.message;
  }
  const responsePartsError = checkResponsePartsForError(response.responseParts);
  if (responsePartsError) {
    return responsePartsError;
  }
  if (typeof response.resultDisplay === "string" && response.resultDisplay.trim().length > 0) {
    return response.resultDisplay;
  }
  if (response.responseParts && response.responseParts.length > 0) {
    return functionResponsePartsToString(response.responseParts);
  }
  return void 0;
}
__name(toolResultContent, "toolResultContent");
function extractTextFromBlocks(blocks) {
  return blocks.filter((block2) => block2.type === "text").map((block2) => block2.type === "text" ? block2.text : "").join("");
}
__name(extractTextFromBlocks, "extractTextFromBlocks");
function createExtendedUsage() {
  return {
    input_tokens: 0,
    output_tokens: 0
  };
}
__name(createExtendedUsage, "createExtendedUsage");

// packages/cli/src/nonInteractive/io/JsonOutputAdapter.ts
var JsonOutputAdapter = class extends BaseJsonOutputAdapter {
  static {
    __name(this, "JsonOutputAdapter");
  }
  messages = [];
  constructor(config2) {
    super(config2);
  }
  /**
   * Emits message to the messages array (batch mode).
   * Tracks the last assistant message for efficient result text extraction.
   */
  emitMessageImpl(message) {
    this.messages.push(message);
    if (typeof message === "object" && message !== null && "type" in message && message.type === "assistant") {
      this.updateLastAssistantMessage(message);
    }
  }
  /**
   * JSON mode does not emit stream events.
   */
  shouldEmitStreamEvents() {
    return false;
  }
  finalizeAssistantMessage() {
    const message = this.finalizeAssistantMessageInternal(
      this.mainAgentMessageState,
      null
    );
    this.updateLastAssistantMessage(message);
    return message;
  }
  emitResult(options2) {
    const resultMessage = this.buildResultMessage(
      options2,
      this.lastAssistantMessage
    );
    this.messages.push(resultMessage);
    if (this.config.getOutputFormat() === "text") {
      if (resultMessage.is_error) {
        process.stderr.write(`${resultMessage.error?.message || ""}`);
      } else {
        process.stdout.write(`${resultMessage.result}`);
      }
    } else {
      const json2 = JSON.stringify(this.messages);
      process.stdout.write(`${json2}
`);
    }
  }
  emitMessage(message) {
    this.messages.push(message);
  }
};

// packages/cli/src/nonInteractive/io/StreamJsonOutputAdapter.ts
init_esbuild_shims();
import { randomUUID as randomUUID8 } from "node:crypto";
var StreamJsonOutputAdapter = class extends BaseJsonOutputAdapter {
  constructor(config2, includePartialMessages) {
    super(config2);
    this.includePartialMessages = includePartialMessages;
  }
  static {
    __name(this, "StreamJsonOutputAdapter");
  }
  /**
   * Emits message immediately to stdout (stream mode).
   */
  emitMessageImpl(message) {
    if (typeof message === "object" && message !== null && "type" in message && message.type === "assistant") {
      this.updateLastAssistantMessage(message);
    }
    process.stdout.write(`${JSON.stringify(message)}
`);
  }
  /**
   * Stream mode emits stream events when includePartialMessages is enabled.
   */
  shouldEmitStreamEvents() {
    return this.includePartialMessages;
  }
  finalizeAssistantMessage() {
    const state = this.mainAgentMessageState;
    if (state.finalized) {
      return this.buildMessage(null);
    }
    state.finalized = true;
    this.finalizePendingBlocks(state, null);
    const orderedOpenBlocks = Array.from(state.openBlocks).sort(
      (a2, b2) => a2 - b2
    );
    for (const index of orderedOpenBlocks) {
      this.onBlockClosed(state, index, null);
      this.closeBlock(state, index);
    }
    if (state.messageStarted && this.includePartialMessages) {
      this.emitStreamEventIfEnabled({ type: "message_stop" }, null);
    }
    const message = this.buildMessage(null);
    this.updateLastAssistantMessage(message);
    this.emitMessageImpl(message);
    return message;
  }
  emitResult(options2) {
    const resultMessage = this.buildResultMessage(
      options2,
      this.lastAssistantMessage
    );
    this.emitMessageImpl(resultMessage);
  }
  emitMessage(message) {
    this.emitMessageImpl(message);
  }
  send(message) {
    this.emitMessage(message);
  }
  /**
   * Overrides base class hook to emit stream event when text block is created.
   */
  onTextBlockCreated(state, index, block2, parentToolUseId) {
    this.emitStreamEventIfEnabled(
      {
        type: "content_block_start",
        index,
        content_block: block2
      },
      parentToolUseId
    );
  }
  /**
   * Overrides base class hook to emit stream event when text is appended.
   */
  onTextAppended(state, index, fragment, parentToolUseId) {
    this.emitStreamEventIfEnabled(
      {
        type: "content_block_delta",
        index,
        delta: { type: "text_delta", text: fragment }
      },
      parentToolUseId
    );
  }
  /**
   * Overrides base class hook to emit stream event when thinking block is created.
   */
  onThinkingBlockCreated(state, index, block2, parentToolUseId) {
    this.emitStreamEventIfEnabled(
      {
        type: "content_block_start",
        index,
        content_block: block2
      },
      parentToolUseId
    );
  }
  /**
   * Overrides base class hook to emit stream event when thinking is appended.
   */
  onThinkingAppended(state, index, fragment, parentToolUseId) {
    this.emitStreamEventIfEnabled(
      {
        type: "content_block_delta",
        index,
        delta: { type: "thinking_delta", thinking: fragment }
      },
      parentToolUseId
    );
  }
  /**
   * Overrides base class hook to emit stream event when tool_use block is created.
   */
  onToolUseBlockCreated(state, index, block2, parentToolUseId) {
    this.emitStreamEventIfEnabled(
      {
        type: "content_block_start",
        index,
        content_block: block2
      },
      parentToolUseId
    );
  }
  /**
   * Overrides base class hook to emit stream event when tool_use input is set.
   */
  onToolUseInputSet(state, index, input, parentToolUseId) {
    this.emitStreamEventIfEnabled(
      {
        type: "content_block_delta",
        index,
        delta: {
          type: "input_json_delta",
          partial_json: JSON.stringify(input)
        }
      },
      parentToolUseId
    );
  }
  /**
   * Overrides base class hook to emit stream event when block is closed.
   */
  onBlockClosed(state, index, parentToolUseId) {
    if (this.includePartialMessages) {
      this.emitStreamEventIfEnabled(
        {
          type: "content_block_stop",
          index
        },
        parentToolUseId
      );
    }
  }
  /**
   * Overrides base class hook to emit message_start event when message is started.
   * Only emits for main agent, not for subagents.
   */
  onEnsureMessageStarted(state, parentToolUseId) {
    if (parentToolUseId === null) {
      this.emitStreamEventIfEnabled(
        {
          type: "message_start",
          message: {
            id: state.messageId,
            role: "assistant",
            model: this.config.getModel()
          }
        },
        null
      );
    }
  }
  /**
   * Emits a tool progress stream event when partial messages are enabled.
   * This overrides the no-op in BaseJsonOutputAdapter.
   */
  emitToolProgress(request4, progress) {
    if (!this.includePartialMessages) {
      return;
    }
    const partial2 = {
      type: "stream_event",
      uuid: randomUUID8(),
      session_id: this.getSessionId(),
      parent_tool_use_id: null,
      event: {
        type: "tool_progress",
        tool_use_id: request4.callId,
        content: progress
      }
    };
    this.emitMessageImpl(partial2);
  }
  /**
   * Emits stream events when partial messages are enabled.
   * This is a private method specific to StreamJsonOutputAdapter.
   * @param event - Stream event to emit
   * @param parentToolUseId - null for main agent, string for subagent
   */
  emitStreamEventIfEnabled(event, parentToolUseId) {
    if (!this.includePartialMessages) {
      return;
    }
    const state = this.getMessageState(parentToolUseId);
    const enrichedEvent = state.messageStarted ? { ...event, message_id: state.messageId } : event;
    const partial2 = {
      type: "stream_event",
      uuid: randomUUID8(),
      session_id: this.getSessionId(),
      parent_tool_use_id: parentToolUseId,
      event: enrichedEvent
    };
    this.emitMessageImpl(partial2);
  }
};

// packages/cli/src/ui/hooks/atCommandProcessor.ts
init_esbuild_shims();
import * as fs93 from "node:fs/promises";
import * as path104 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: config2,
  onDebugMessage,
  messageId: userMessageTimestamp,
  signal,
  addItem
}) {
  const commandParts = parseAllAtCommands(query);
  const atPathCommandParts = commandParts.filter(
    (part) => part.type === "atPath"
  );
  const addToolGroup = /* @__PURE__ */ __name((result) => {
    if (!addItem) return;
    if (result.toolDisplays && result.toolDisplays.length > 0) {
      const toolGroupItem = {
        type: "tool_group",
        tools: result.toolDisplays
      };
      addItem(toolGroupItem, userMessageTimestamp);
    }
  }, "addToolGroup");
  if (atPathCommandParts.length === 0) {
    return { processedQuery: [{ text: query }], shouldProceed: true };
  }
  const fileDiscovery = config2.getFileService();
  const respectFileIgnore = config2.getFileFilteringOptions();
  const pathSpecsToRead = [];
  const atPathToResolvedSpecMap = /* @__PURE__ */ new Map();
  const contentLabelsForDisplay = [];
  const ignoredByReason = {
    git: [],
    qwen: [],
    both: []
  };
  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);
    const workspaceContext = config2.getWorkspaceContext();
    const projectTempDir = Storage.getGlobalTempDir();
    const absolutePathName = path104.isAbsolute(pathName) ? pathName : path104.resolve(workspaceContext.getDirectories()[0] || "", pathName);
    if (!absolutePathName.startsWith(projectTempDir) && !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;
    }
    let resolvedSuccessfully = false;
    let sawNotFound = false;
    for (const dir of config2.getWorkspaceContext().getDirectories()) {
      let currentPathSpec = pathName;
      try {
        const absolutePath = path104.resolve(dir, pathName);
        const stats = await fs93.stat(absolutePath);
        if (stats.isDirectory()) {
          currentPathSpec = pathName;
          onDebugMessage(`Path ${pathName} resolved to directory.`);
        } else {
          onDebugMessage(`Path ${pathName} resolved to file: ${absolutePath}`);
        }
        resolvedSuccessfully = true;
      } catch (error2) {
        if (isNodeError(error2) && error2.code === "ENOENT") {
          sawNotFound = true;
          continue;
        } else {
          onDebugMessage(
            `Error stating path ${pathName}: ${getErrorMessage(error2)}. Path ${pathName} will be skipped.`
          );
        }
      }
      if (resolvedSuccessfully) {
        pathSpecsToRead.push(currentPathSpec);
        atPathToResolvedSpecMap.set(originalAtPath, currentPathSpec);
        contentLabelsForDisplay.push(pathName);
        break;
      }
    }
    if (!resolvedSuccessfully && sawNotFound) {
      onDebugMessage(
        `Path ${pathName} not found. Path ${pathName} will be skipped.`
      );
    }
  }
  let initialQueryText = "";
  for (let i3 = 0; i3 < commandParts.length; i3++) {
    const part = commandParts[i3];
    if (part.type === "text") {
      initialQueryText += part.content;
    } else {
      const resolvedSpec = atPathToResolvedSpecMap.get(part.content);
      if (i3 > 0 && initialQueryText.length > 0 && !initialQueryText.endsWith(" ")) {
        const prevPart = commandParts[i3 - 1];
        if (prevPart.type === "text" || prevPart.type === "atPath" && atPathToResolvedSpecMap.has(prevPart.content)) {
          initialQueryText += " ";
        }
      }
      if (resolvedSpec) {
        initialQueryText += `@${resolvedSpec}`;
      } else {
        if (i3 > 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")}`;
    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
    };
  }
  try {
    const result = await readManyFiles(config2, {
      paths: pathSpecsToRead,
      signal
    });
    const parts = Array.isArray(result.contentParts) ? result.contentParts : [result.contentParts];
    const toolCallDisplays = result.files.map(
      (file, index) => ({
        callId: `client-read-${userMessageTimestamp}-${index}`,
        name: file.isDirectory ? "Read Directory" : "Read File",
        description: file.isDirectory ? `Read directory ${path104.basename(file.filePath)}` : `Read file ${path104.basename(file.filePath)}`,
        status: "Success" /* Success */,
        resultDisplay: void 0,
        confirmationDetails: void 0
      })
    );
    const processedQueryParts = [{ text: initialQueryText }];
    if (parts.length > 0 && !result.error) {
      for (const part of parts) {
        if (typeof part === "string") {
          processedQueryParts.push({ text: part });
        } else {
          processedQueryParts.push(part);
        }
      }
    } else {
      onDebugMessage("readManyFiles returned no content or empty content.");
    }
    const processedResult = {
      processedQuery: processedQueryParts,
      shouldProceed: true,
      toolDisplays: toolCallDisplays,
      filesRead: contentLabelsForDisplay
    };
    const chatRecorder = config2.getChatRecordingService?.();
    chatRecorder?.recordAtCommand({
      filesRead: contentLabelsForDisplay,
      status: "success",
      userText: query
    });
    addToolGroup(processedResult);
    return processedResult;
  } catch (error2) {
    const errorToolCallDisplay = {
      callId: `client-read-${userMessageTimestamp}`,
      name: "Read File(s)",
      description: "Error attempting to read files",
      status: "Error" /* Error */,
      resultDisplay: `Error reading files (${contentLabelsForDisplay.join(", ")}): ${getErrorMessage(error2)}`,
      confirmationDetails: void 0
    };
    const chatRecorder = config2.getChatRecordingService?.();
    const errorMessage = typeof errorToolCallDisplay.resultDisplay === "string" ? errorToolCallDisplay.resultDisplay : void 0;
    chatRecorder?.recordAtCommand({
      filesRead: contentLabelsForDisplay,
      status: "error",
      message: errorMessage,
      userText: query
    });
    const result = {
      processedQuery: null,
      shouldProceed: false,
      toolDisplays: [errorToolCallDisplay],
      filesRead: contentLabelsForDisplay
    };
    addToolGroup(result);
    return result;
  }
}
__name(handleAtCommand, "handleAtCommand");

// packages/cli/src/nonInteractiveCli.ts
var debugLogger87 = createDebugLogger("NON_INTERACTIVE_CLI");
async function emitNonInteractiveFinalMessage(params) {
  const { message, isError, adapter, config: config2 } = params;
  adapter.startAssistantMessage();
  adapter.processEvent({
    type: GeminiEventType.Content,
    value: message
  });
  adapter.finalizeAssistantMessage();
  const metrics2 = uiTelemetryService.getMetrics();
  const usage2 = computeUsageFromMetrics(metrics2);
  const outputFormat = config2.getOutputFormat();
  const stats = outputFormat === OutputFormat.JSON ? uiTelemetryService.getMetrics() : void 0;
  adapter.emitResult({
    isError,
    durationMs: Date.now() - params.startTimeMs,
    apiDurationMs: 0,
    numTurns: 0,
    errorMessage: isError ? message : void 0,
    usage: usage2,
    stats,
    summary: message
  });
}
__name(emitNonInteractiveFinalMessage, "emitNonInteractiveFinalMessage");
async function runNonInteractive(config2, settings, input, prompt_id, options2 = {}) {
  return promptIdContext.run(prompt_id, async () => {
    let adapter;
    const outputFormat = config2.getOutputFormat();
    if (options2.adapter) {
      adapter = options2.adapter;
    } else if (outputFormat === OutputFormat.STREAM_JSON) {
      adapter = new StreamJsonOutputAdapter(
        config2,
        config2.getIncludePartialMessages()
      );
    } else {
      adapter = new JsonOutputAdapter(config2);
    }
    const sessionId = config2.getSessionId();
    const permissionMode = config2.getApprovalMode();
    let turnCount = 0;
    let totalApiDurationMs = 0;
    const startTime = Date.now();
    const stdoutErrorHandler = /* @__PURE__ */ __name((err) => {
      if (err.code === "EPIPE") {
        process.stdout.removeListener("error", stdoutErrorHandler);
        process.exit(0);
      }
    }, "stdoutErrorHandler");
    const geminiClient = config2.getGeminiClient();
    const abortController = options2.abortController ?? new AbortController();
    const shutdownHandler = /* @__PURE__ */ __name(() => {
      debugLogger87.debug("[runNonInteractive] Shutdown signal received");
      abortController.abort();
    }, "shutdownHandler");
    try {
      process.stdout.on("error", stdoutErrorHandler);
      process.on("SIGINT", shutdownHandler);
      process.on("SIGTERM", shutdownHandler);
      const systemMessage = await buildSystemMessage(
        config2,
        sessionId,
        permissionMode
      );
      adapter.emitMessage(systemMessage);
      let initialPartList = extractPartsFromUserMessage(
        options2.userMessage
      );
      if (!initialPartList) {
        let slashHandled = false;
        if (isSlashCommand(input)) {
          const slashCommandResult = await handleSlashCommand(
            input,
            abortController,
            config2,
            settings
          );
          switch (slashCommandResult.type) {
            case "submit_prompt":
              initialPartList = slashCommandResult.content;
              slashHandled = true;
              break;
            case "message": {
              await emitNonInteractiveFinalMessage({
                message: slashCommandResult.content,
                isError: slashCommandResult.messageType === "error",
                adapter,
                config: config2,
                startTimeMs: startTime
              });
              return;
            }
            case "stream_messages":
              throw new FatalInputError(
                "Stream messages mode is not supported in non-interactive CLI"
              );
            case "unsupported": {
              await emitNonInteractiveFinalMessage({
                message: slashCommandResult.reason,
                isError: true,
                adapter,
                config: config2,
                startTimeMs: startTime
              });
              return;
            }
            case "no_command":
              break;
            default: {
              const _exhaustive = slashCommandResult;
              throw new FatalInputError(
                `Unhandled slash command result type: ${_exhaustive.type}`
              );
            }
          }
        }
        if (!slashHandled) {
          const { processedQuery, shouldProceed } = await handleAtCommand({
            query: input,
            config: config2,
            onDebugMessage: /* @__PURE__ */ __name(() => {
            }, "onDebugMessage"),
            messageId: Date.now(),
            signal: abortController.signal
          });
          if (!shouldProceed || !processedQuery) {
            throw new FatalInputError(
              "Exiting due to an error processing the @ command."
            );
          }
          initialPartList = processedQuery;
        }
      }
      if (!initialPartList) {
        initialPartList = [{ text: input }];
      }
      const initialParts = normalizePartList(initialPartList);
      let currentMessages = [{ role: "user", parts: initialParts }];
      let isFirstTurn = true;
      while (true) {
        turnCount++;
        if (config2.getMaxSessionTurns() >= 0 && turnCount > config2.getMaxSessionTurns()) {
          handleMaxTurnsExceededError(config2);
        }
        const toolCallRequests = [];
        const apiStartTime = Date.now();
        const responseStream = geminiClient.sendMessageStream(
          currentMessages[0]?.parts || [],
          abortController.signal,
          prompt_id,
          { isContinuation: !isFirstTurn }
        );
        isFirstTurn = false;
        adapter.startAssistantMessage();
        for await (const event of responseStream) {
          if (abortController.signal.aborted) {
            handleCancellationError(config2);
          }
          adapter.processEvent(event);
          if (event.type === GeminiEventType.ToolCallRequest) {
            toolCallRequests.push(event.value);
          }
          if (outputFormat === OutputFormat.TEXT && event.type === GeminiEventType.Error) {
            const errorText = parseAndFormatApiError(
              event.value.error,
              config2.getContentGeneratorConfig()?.authType
            );
            process.stderr.write(`${errorText}
`);
            throw new Error(errorText);
          }
        }
        adapter.finalizeAssistantMessage();
        totalApiDurationMs += Date.now() - apiStartTime;
        if (toolCallRequests.length > 0) {
          const toolResponseParts = [];
          for (const requestInfo of toolCallRequests) {
            const finalRequestInfo = requestInfo;
            const inputFormat = typeof config2.getInputFormat === "function" ? config2.getInputFormat() : InputFormat.TEXT;
            const toolCallUpdateCallback = inputFormat === InputFormat.STREAM_JSON && options2.controlService ? options2.controlService.permission.getToolCallUpdateCallback() : void 0;
            const isTaskTool = finalRequestInfo.name === "task";
            const { handler: outputUpdateHandler } = isTaskTool ? createTaskToolProgressHandler(
              config2,
              finalRequestInfo.callId,
              adapter
            ) : createToolProgressHandler(finalRequestInfo, adapter);
            const toolResponse = await executeToolCall(
              config2,
              finalRequestInfo,
              abortController.signal,
              {
                outputUpdateHandler,
                ...toolCallUpdateCallback && {
                  onToolCallsUpdate: toolCallUpdateCallback
                }
              }
            );
            if (toolResponse.error) {
              handleToolError(
                finalRequestInfo.name,
                toolResponse.error,
                config2,
                toolResponse.errorType || "TOOL_EXECUTION_ERROR",
                typeof toolResponse.resultDisplay === "string" ? toolResponse.resultDisplay : void 0
              );
            }
            adapter.emitToolResult(finalRequestInfo, toolResponse);
            if (toolResponse.responseParts) {
              toolResponseParts.push(...toolResponse.responseParts);
            }
          }
          currentMessages = [{ role: "user", parts: toolResponseParts }];
        } else {
          const metrics2 = uiTelemetryService.getMetrics();
          const usage2 = computeUsageFromMetrics(metrics2);
          const stats = outputFormat === OutputFormat.JSON ? uiTelemetryService.getMetrics() : void 0;
          adapter.emitResult({
            isError: false,
            durationMs: Date.now() - startTime,
            apiDurationMs: totalApiDurationMs,
            numTurns: turnCount,
            usage: usage2,
            stats
          });
          return;
        }
      }
    } catch (error2) {
      const message = error2 instanceof Error ? error2.message : String(error2);
      const metrics2 = uiTelemetryService.getMetrics();
      const usage2 = computeUsageFromMetrics(metrics2);
      const stats = outputFormat === OutputFormat.JSON ? uiTelemetryService.getMetrics() : void 0;
      adapter.emitResult({
        isError: true,
        durationMs: Date.now() - startTime,
        apiDurationMs: totalApiDurationMs,
        numTurns: turnCount,
        errorMessage: message,
        usage: usage2,
        stats
      });
      handleError(error2, config2);
    } finally {
      process.stdout.removeListener("error", stdoutErrorHandler);
      process.removeListener("SIGINT", shutdownHandler);
      process.removeListener("SIGTERM", shutdownHandler);
      if (isTelemetrySdkInitialized()) {
        await shutdownTelemetry();
      }
    }
  });
}
__name(runNonInteractive, "runNonInteractive");

// packages/cli/src/nonInteractive/session.ts
init_esbuild_shims();

// packages/cli/src/nonInteractive/io/StreamJsonInputReader.ts
init_esbuild_shims();
import { createInterface } from "node:readline/promises";
import process32 from "node:process";
var StreamJsonParseError = class extends Error {
  static {
    __name(this, "StreamJsonParseError");
  }
};
var StreamJsonInputReader = class {
  static {
    __name(this, "StreamJsonInputReader");
  }
  input;
  constructor(input = process32.stdin) {
    this.input = input;
  }
  async *read() {
    const rl = createInterface({
      input: this.input,
      crlfDelay: Number.POSITIVE_INFINITY,
      terminal: false
    });
    try {
      for await (const rawLine of rl) {
        const line = rawLine.trim();
        if (!line) {
          continue;
        }
        yield this.parse(line);
      }
    } finally {
      rl.close();
    }
  }
  parse(line) {
    try {
      const parsed = JSON.parse(line);
      if (!parsed || typeof parsed !== "object") {
        throw new StreamJsonParseError("Parsed value is not an object");
      }
      if (!("type" in parsed) || typeof parsed.type !== "string") {
        throw new StreamJsonParseError('Missing required "type" field');
      }
      return parsed;
    } catch (error2) {
      if (error2 instanceof StreamJsonParseError) {
        throw error2;
      }
      const reason = error2 instanceof Error ? error2.message : String(error2);
      throw new StreamJsonParseError(
        `Failed to parse stream-json line: ${reason}`
      );
    }
  }
};

// packages/cli/src/nonInteractive/control/ControlContext.ts
init_esbuild_shims();
var ControlContext = class {
  static {
    __name(this, "ControlContext");
  }
  config;
  streamJson;
  sessionId;
  abortSignal;
  debugMode;
  permissionMode;
  sdkMcpServers;
  mcpClients;
  inputClosed;
  onInterrupt;
  constructor(options2) {
    this.config = options2.config;
    this.streamJson = options2.streamJson;
    this.sessionId = options2.sessionId;
    this.abortSignal = options2.abortSignal;
    this.debugMode = options2.config.getDebugMode();
    this.permissionMode = options2.permissionMode || "default";
    this.sdkMcpServers = /* @__PURE__ */ new Set();
    this.mcpClients = /* @__PURE__ */ new Map();
    this.inputClosed = false;
    this.onInterrupt = options2.onInterrupt;
  }
};

// packages/cli/src/nonInteractive/control/ControlDispatcher.ts
init_esbuild_shims();

// packages/cli/src/nonInteractive/control/controllers/systemController.ts
init_esbuild_shims();

// packages/cli/src/nonInteractive/control/controllers/baseController.ts
init_esbuild_shims();
import { randomUUID as randomUUID9 } from "node:crypto";
var DEFAULT_REQUEST_TIMEOUT_MS = 3e4;
var BaseController = class {
  static {
    __name(this, "BaseController");
  }
  context;
  registry;
  controllerName;
  debugLogger;
  constructor(context2, registry2, controllerName) {
    this.context = context2;
    this.registry = registry2;
    this.controllerName = controllerName;
    this.debugLogger = createDebugLogger();
  }
  /**
   * Handle an incoming control request
   *
   * Manages lifecycle: register -> process -> deregister
   */
  async handleRequest(payload, requestId) {
    const requestAbortController = new AbortController();
    const timeoutId = setTimeout(() => {
      requestAbortController.abort();
      this.registry.deregisterIncomingRequest(requestId);
      this.debugLogger.warn(
        `[${this.controllerName}] Request timeout: ${requestId}`
      );
    }, DEFAULT_REQUEST_TIMEOUT_MS);
    this.registry.registerIncomingRequest(
      requestId,
      this.controllerName,
      requestAbortController,
      timeoutId
    );
    try {
      const response = await this.handleRequestPayload(
        payload,
        requestAbortController.signal
      );
      this.registry.deregisterIncomingRequest(requestId);
      return response;
    } catch (error2) {
      this.registry.deregisterIncomingRequest(requestId);
      throw error2;
    }
  }
  /**
   * Send an outgoing control request to SDK
   *
   * Manages lifecycle: register -> send -> wait for response -> deregister
   * Respects the provided AbortSignal for cancellation.
   */
  async sendControlRequest(payload, timeoutMs = DEFAULT_REQUEST_TIMEOUT_MS, signal) {
    if (this.context.inputClosed) {
      throw new Error("Input closed");
    }
    if (signal?.aborted) {
      throw new Error("Request aborted");
    }
    const requestId = randomUUID9();
    return new Promise((resolve30, reject) => {
      const abortHandler = /* @__PURE__ */ __name(() => {
        this.registry.deregisterOutgoingRequest(requestId);
        reject(new Error("Request aborted"));
        this.debugLogger.warn(
          `[${this.controllerName}] Outgoing request aborted: ${requestId}`
        );
      }, "abortHandler");
      if (signal) {
        signal.addEventListener("abort", abortHandler, { once: true });
      }
      const timeoutId = setTimeout(() => {
        if (signal) {
          signal.removeEventListener("abort", abortHandler);
        }
        this.registry.deregisterOutgoingRequest(requestId);
        reject(new Error("Control request timeout"));
        this.debugLogger.warn(
          `[${this.controllerName}] Outgoing request timeout: ${requestId}`
        );
      }, timeoutMs);
      const wrappedResolve = /* @__PURE__ */ __name((response) => {
        if (signal) {
          signal.removeEventListener("abort", abortHandler);
        }
        resolve30(response);
      }, "wrappedResolve");
      const wrappedReject = /* @__PURE__ */ __name((error2) => {
        if (signal) {
          signal.removeEventListener("abort", abortHandler);
        }
        reject(error2);
      }, "wrappedReject");
      this.registry.registerOutgoingRequest(
        requestId,
        this.controllerName,
        wrappedResolve,
        wrappedReject,
        timeoutId
      );
      const request4 = {
        type: "control_request",
        request_id: requestId,
        request: payload
      };
      try {
        this.context.streamJson.send(request4);
      } catch (error2) {
        if (signal) {
          signal.removeEventListener("abort", abortHandler);
        }
        this.registry.deregisterOutgoingRequest(requestId);
        reject(error2);
      }
    });
  }
  /**
   * Cleanup resources
   */
  cleanup() {
  }
};

// packages/cli/src/nonInteractive/control/controllers/systemController.ts
var debugLogger88 = createDebugLogger("SYSTEM_CONTROLLER");
var SystemController = class extends BaseController {
  static {
    __name(this, "SystemController");
  }
  /**
   * Handle system control requests
   */
  async handleRequestPayload(payload, signal) {
    if (signal.aborted) {
      throw new Error("Request aborted");
    }
    switch (payload.subtype) {
      case "initialize":
        return this.handleInitialize(
          payload,
          signal
        );
      case "interrupt":
        return this.handleInterrupt();
      case "set_model":
        return this.handleSetModel(
          payload,
          signal
        );
      case "supported_commands":
        return this.handleSupportedCommands(signal);
      default:
        throw new Error(`Unsupported request subtype in SystemController`);
    }
  }
  /**
   * Handle initialize request
   *
   * Processes SDK MCP servers config.
   * SDK servers are registered in context.sdkMcpServers
   * and added to config.mcpServers with the sdk type flag.
   * External MCP servers are configured separately in settings.
   */
  async handleInitialize(payload, signal) {
    if (signal.aborted) {
      throw new Error("Request aborted");
    }
    this.context.config.setSdkMode(true);
    if (payload.sdkMcpServers && typeof payload.sdkMcpServers === "object" && payload.sdkMcpServers !== null) {
      const sdkServers = {};
      for (const [key, wireConfig] of Object.entries(payload.sdkMcpServers)) {
        const name3 = typeof wireConfig?.name === "string" && wireConfig.name.trim().length ? wireConfig.name : key;
        this.context.sdkMcpServers.add(name3);
        sdkServers[name3] = new MCPServerConfig(
          void 0,
          // command
          void 0,
          // args
          void 0,
          // env
          void 0,
          // cwd
          void 0,
          // url
          void 0,
          // httpUrl
          void 0,
          // headers
          void 0,
          // tcp
          void 0,
          // timeout
          true,
          // trust - SDK servers are trusted
          void 0,
          // description
          void 0,
          // includeTools
          void 0,
          // excludeTools
          void 0,
          // extensionName
          void 0,
          // oauth
          void 0,
          // authProviderType
          void 0,
          // targetAudience
          void 0,
          // targetServiceAccount
          "sdk"
          // type
        );
      }
      const sdkServerCount = Object.keys(sdkServers).length;
      if (sdkServerCount > 0) {
        try {
          this.context.config.addMcpServers(sdkServers);
          debugLogger88.debug(
            `[SystemController] Added ${sdkServerCount} SDK MCP servers to config`
          );
        } catch (error2) {
          debugLogger88.error(
            "[SystemController] Failed to add SDK MCP servers:",
            error2
          );
        }
      }
    }
    if (payload.mcpServers && typeof payload.mcpServers === "object" && payload.mcpServers !== null) {
      const externalServers = {};
      for (const [name3, serverConfig] of Object.entries(payload.mcpServers)) {
        const normalized2 = this.normalizeMcpServerConfig(
          name3,
          serverConfig
        );
        if (normalized2) {
          externalServers[name3] = normalized2;
        }
      }
      const externalCount = Object.keys(externalServers).length;
      if (externalCount > 0) {
        try {
          this.context.config.addMcpServers(externalServers);
          debugLogger88.debug(
            `[SystemController] Added ${externalCount} external MCP servers to config`
          );
        } catch (error2) {
          debugLogger88.error(
            "[SystemController] Failed to add external MCP servers:",
            error2
          );
        }
      }
    }
    if (payload.agents && Array.isArray(payload.agents)) {
      try {
        this.context.config.setSessionSubagents(payload.agents);
        debugLogger88.debug(
          `[SystemController] Added ${payload.agents.length} session subagents to config`
        );
      } catch (error2) {
        debugLogger88.error(
          "[SystemController] Failed to add session subagents:",
          error2
        );
      }
    }
    const capabilities = this.buildControlCapabilities();
    debugLogger88.debug(
      `[SystemController] Initialized with ${this.context.sdkMcpServers.size} SDK MCP servers`
    );
    return {
      subtype: "initialize",
      session_id: this.context.config.getSessionId(),
      capabilities
    };
  }
  /**
   * Build control capabilities for initialize control response
   *
   * This method constructs the control capabilities object that indicates
   * what control features are available. It is used exclusively in the
   * initialize control response.
   */
  buildControlCapabilities() {
    const capabilities = {
      can_handle_can_use_tool: true,
      can_handle_hook_callback: false,
      can_set_permission_mode: typeof this.context.config.setApprovalMode === "function",
      can_set_model: typeof this.context.config.setModel === "function",
      // SDK MCP servers are supported - messages routed through control plane
      can_handle_mcp_message: true
    };
    return capabilities;
  }
  normalizeMcpServerConfig(serverName, config2) {
    if (!config2 || typeof config2 !== "object") {
      debugLogger88.warn(
        `[SystemController] Ignoring invalid MCP server config for '${serverName}'`
      );
      return null;
    }
    const authProvider = this.normalizeAuthProviderType(
      config2.authProviderType
    );
    const oauthConfig = this.normalizeOAuthConfig(config2.oauth);
    return new MCPServerConfig(
      config2.command,
      config2.args,
      config2.env,
      config2.cwd,
      config2.url,
      config2.httpUrl,
      config2.headers,
      config2.tcp,
      config2.timeout,
      config2.trust,
      config2.description,
      config2.includeTools,
      config2.excludeTools,
      config2.extensionName,
      oauthConfig,
      authProvider,
      config2.targetAudience,
      config2.targetServiceAccount
    );
  }
  normalizeAuthProviderType(value) {
    if (!value) {
      return void 0;
    }
    switch (value) {
      case AuthProviderType.DYNAMIC_DISCOVERY:
      case AuthProviderType.GOOGLE_CREDENTIALS:
      case AuthProviderType.SERVICE_ACCOUNT_IMPERSONATION:
        return value;
      default:
        debugLogger88.warn(
          `[SystemController] Unsupported authProviderType '${value}', skipping`
        );
        return void 0;
    }
  }
  normalizeOAuthConfig(oauth) {
    if (!oauth) {
      return void 0;
    }
    return {
      enabled: oauth.enabled,
      clientId: oauth.clientId,
      clientSecret: oauth.clientSecret,
      authorizationUrl: oauth.authorizationUrl,
      tokenUrl: oauth.tokenUrl,
      scopes: oauth.scopes,
      audiences: oauth.audiences,
      redirectUri: oauth.redirectUri,
      tokenParamName: oauth.tokenParamName,
      registrationUrl: oauth.registrationUrl
    };
  }
  /**
   * Handle interrupt request
   *
   * Triggers the interrupt callback to cancel current operations
   */
  async handleInterrupt() {
    if (this.context.onInterrupt) {
      this.context.onInterrupt();
    }
    if (this.context.abortSignal && !this.context.abortSignal.aborted) {
      debugLogger88.debug("[SystemController] Interrupt signal triggered");
    }
    debugLogger88.debug("[SystemController] Interrupt handled");
    return { subtype: "interrupt" };
  }
  /**
   * Handle set_model request
   *
   * Implements actual model switching with validation and error handling
   */
  async handleSetModel(payload, signal) {
    if (signal.aborted) {
      throw new Error("Request aborted");
    }
    const model = payload.model;
    if (typeof model !== "string" || model.trim() === "") {
      throw new Error("Invalid model specified for set_model request");
    }
    try {
      await this.context.config.setModel(model);
      debugLogger88.info(`[SystemController] Model switched to: ${model}`);
      return {
        subtype: "set_model",
        model
      };
    } catch (error2) {
      const errorMessage = error2 instanceof Error ? error2.message : "Failed to set model";
      debugLogger88.error(
        `[SystemController] Failed to set model ${model}:`,
        error2
      );
      throw new Error(errorMessage);
    }
  }
  /**
   * Handle supported_commands request
   *
   * Returns list of supported slash commands loaded dynamically
   */
  async handleSupportedCommands(signal) {
    if (signal.aborted) {
      throw new Error("Request aborted");
    }
    const slashCommands = await this.loadSlashCommandNames(signal);
    return {
      subtype: "supported_commands",
      commands: slashCommands
    };
  }
  /**
   * Load slash command names using getAvailableCommands
   *
   * @param signal - AbortSignal to respect for cancellation
   * @returns Promise resolving to array of slash command names
   */
  async loadSlashCommandNames(signal) {
    if (signal.aborted) {
      return [];
    }
    try {
      const commands = await getAvailableCommands(this.context.config, signal);
      if (signal.aborted) {
        return [];
      }
      return commands.map((cmd) => cmd.name).sort();
    } catch (error2) {
      if (signal.aborted) {
        return [];
      }
      debugLogger88.error(
        "[SystemController] Failed to load slash commands:",
        error2
      );
      return [];
    }
  }
};

// packages/cli/src/nonInteractive/control/controllers/permissionController.ts
init_esbuild_shims();
var PermissionController = class extends BaseController {
  static {
    __name(this, "PermissionController");
  }
  pendingOutgoingRequests = /* @__PURE__ */ new Set();
  /**
   * Handle permission control requests
   */
  async handleRequestPayload(payload, signal) {
    if (signal.aborted) {
      throw new Error("Request aborted");
    }
    switch (payload.subtype) {
      case "can_use_tool":
        return this.handleCanUseTool(
          payload,
          signal
        );
      case "set_permission_mode":
        return this.handleSetPermissionMode(
          payload,
          signal
        );
      default:
        throw new Error(`Unsupported request subtype in PermissionController`);
    }
  }
  /**
   * Handle can_use_tool request
   *
   * Comprehensive permission evaluation based on:
   * - Permission mode (approval level)
   * - Tool registry validation
   * - Error handling with safe defaults
   */
  async handleCanUseTool(payload, signal) {
    if (signal.aborted) {
      throw new Error("Request aborted");
    }
    const toolName = payload.tool_name;
    if (!toolName || typeof toolName !== "string" || toolName.trim().length === 0) {
      return {
        subtype: "can_use_tool",
        behavior: "deny",
        message: "Missing or invalid tool_name in can_use_tool request"
      };
    }
    let behavior = "allow";
    let message;
    try {
      const permissionResult = this.checkPermissionMode();
      if (!permissionResult.allowed) {
        behavior = "deny";
        message = permissionResult.message;
      }
      if (behavior === "allow") {
        const registryResult = this.checkToolRegistry(toolName);
        if (!registryResult.allowed) {
          behavior = "deny";
          message = registryResult.message;
        }
      }
    } catch (error2) {
      behavior = "deny";
      message = error2 instanceof Error ? `Failed to evaluate tool permission: ${error2.message}` : "Failed to evaluate tool permission";
    }
    const response = {
      subtype: "can_use_tool",
      behavior
    };
    if (message) {
      response["message"] = message;
    }
    return response;
  }
  /**
   * Check permission mode for tool execution
   */
  checkPermissionMode() {
    const mode = this.context.permissionMode;
    switch (mode) {
      case "yolo":
      // Allow all tools
      case "auto-edit":
      // Auto-approve edit operations
      case "plan":
        return { allowed: true };
      case "default":
      // TODO: allow all tools for test
      default:
        return {
          allowed: false,
          message: "Tool execution requires manual approval. Update permission mode or approve via host."
        };
    }
  }
  /**
   * Check if tool exists in registry
   */
  checkToolRegistry(toolName) {
    try {
      const config2 = this.context.config;
      const registryProvider = config2;
      if (typeof registryProvider.getToolRegistry === "function") {
        const registry2 = registryProvider.getToolRegistry();
        if (registry2 && typeof registry2.getTool === "function" && !registry2.getTool(toolName)) {
          return {
            allowed: false,
            message: `Tool "${toolName}" is not registered.`
          };
        }
      }
      return { allowed: true };
    } catch (error2) {
      return {
        allowed: false,
        message: `Failed to check tool registry: ${error2 instanceof Error ? error2.message : "Unknown error"}`
      };
    }
  }
  /**
   * Handle set_permission_mode request
   *
   * Updates the permission mode in the context
   */
  async handleSetPermissionMode(payload, signal) {
    if (signal.aborted) {
      throw new Error("Request aborted");
    }
    const mode = payload.mode;
    const validModes = [
      "default",
      "plan",
      "auto-edit",
      "yolo"
    ];
    if (!validModes.includes(mode)) {
      throw new Error(
        `Invalid permission mode: ${mode}. Valid values are: ${validModes.join(", ")}`
      );
    }
    this.context.permissionMode = mode;
    this.context.config.setApprovalMode(mode);
    this.debugLogger.info(
      `[PermissionController] Permission mode updated to: ${mode}`
    );
    return { status: "updated", mode };
  }
  /**
   * Build permission suggestions for tool confirmation UI
   *
   * This method creates UI suggestions based on tool confirmation details,
   * helping the host application present appropriate permission options.
   */
  buildPermissionSuggestions(confirmationDetails) {
    if (!confirmationDetails || typeof confirmationDetails !== "object" || !("type" in confirmationDetails)) {
      return null;
    }
    const details = confirmationDetails;
    const type = String(details["type"] ?? "");
    const title = typeof details["title"] === "string" ? details["title"] : void 0;
    const confirmationType = type;
    switch (confirmationType) {
      case "exec":
        return [
          {
            type: "allow",
            label: "Allow Command",
            description: `Execute: ${details["command"]}`
          },
          {
            type: "deny",
            label: "Deny",
            description: "Block this command execution"
          }
        ];
      case "edit":
        return [
          {
            type: "allow",
            label: "Allow Edit",
            description: `Edit file: ${details["fileName"]}`
          },
          {
            type: "deny",
            label: "Deny",
            description: "Block this file edit"
          },
          {
            type: "modify",
            label: "Review Changes",
            description: "Review the proposed changes before applying"
          }
        ];
      case "plan":
        return [
          {
            type: "allow",
            label: "Approve Plan",
            description: title || "Execute the proposed plan"
          },
          {
            type: "deny",
            label: "Reject Plan",
            description: "Do not execute this plan"
          }
        ];
      case "mcp":
        return [
          {
            type: "allow",
            label: "Allow MCP Call",
            description: `${details["serverName"]}: ${details["toolName"]}`
          },
          {
            type: "deny",
            label: "Deny",
            description: "Block this MCP server call"
          }
        ];
      case "info":
        return [
          {
            type: "allow",
            label: "Allow Info Request",
            description: title || "Allow information request"
          },
          {
            type: "deny",
            label: "Deny",
            description: "Block this information request"
          }
        ];
      default:
        return [
          {
            type: "allow",
            label: "Allow",
            description: title || `Allow ${type} operation`
          },
          {
            type: "deny",
            label: "Deny",
            description: `Block ${type} operation`
          }
        ];
    }
  }
  /**
   * Get callback for monitoring tool calls and handling outgoing permission requests
   * This is passed to executeToolCall to hook into CoreToolScheduler updates
   */
  getToolCallUpdateCallback() {
    return (toolCalls) => {
      for (const call of toolCalls) {
        if (call && typeof call === "object" && call.status === "awaiting_approval") {
          const awaiting = call;
          if (typeof awaiting.confirmationDetails?.onConfirm === "function" && !this.pendingOutgoingRequests.has(awaiting.request.callId)) {
            this.pendingOutgoingRequests.add(awaiting.request.callId);
            void this.handleOutgoingPermissionRequest(awaiting);
          }
        }
      }
    };
  }
  /**
   * Handle outgoing permission request
   *
   * Behavior depends on input format:
   * - stream-json mode: Send can_use_tool to SDK and await response
   * - Other modes: Check local approval mode and decide immediately
   */
  async handleOutgoingPermissionRequest(toolCall) {
    try {
      if (this.context.abortSignal?.aborted) {
        await toolCall.confirmationDetails.onConfirm(
          ToolConfirmationOutcome.Cancel
        );
        return;
      }
      const inputFormat = this.context.config.getInputFormat?.();
      const isStreamJsonMode = inputFormat === InputFormat.STREAM_JSON;
      if (!isStreamJsonMode) {
        const modeCheck = this.checkPermissionMode();
        const outcome = modeCheck.allowed ? ToolConfirmationOutcome.ProceedOnce : ToolConfirmationOutcome.Cancel;
        await toolCall.confirmationDetails.onConfirm(outcome);
        return;
      }
      const permissionSuggestions = this.buildPermissionSuggestions(
        toolCall.confirmationDetails
      );
      const response = await this.sendControlRequest(
        {
          subtype: "can_use_tool",
          tool_name: toolCall.request.name,
          tool_use_id: toolCall.request.callId,
          input: toolCall.request.args,
          permission_suggestions: permissionSuggestions,
          blocked_path: null
        },
        void 0,
        // use default timeout
        this.context.abortSignal
      );
      if (response.subtype !== "success") {
        await toolCall.confirmationDetails.onConfirm(
          ToolConfirmationOutcome.Cancel
        );
        return;
      }
      const payload = response.response || {};
      const behavior = String(payload["behavior"] || "").toLowerCase();
      if (behavior === "allow") {
        const updatedInput = payload["updatedInput"];
        if (updatedInput && typeof updatedInput === "object") {
          toolCall.request.args = updatedInput;
        }
        await toolCall.confirmationDetails.onConfirm(
          ToolConfirmationOutcome.ProceedOnce
        );
      } else {
        const cancelMessage = typeof payload["message"] === "string" ? payload["message"] : void 0;
        await toolCall.confirmationDetails.onConfirm(
          ToolConfirmationOutcome.Cancel,
          cancelMessage ? { cancelMessage } : void 0
        );
      }
    } catch (error2) {
      this.debugLogger.error(
        "[PermissionController] Outgoing permission failed:",
        error2
      );
      const errorMessage = error2 instanceof Error ? error2.message : String(error2);
      const confirmationType = toolCall.confirmationDetails.type;
      if (["edit", "exec", "mcp"].includes(confirmationType)) {
        const execOrMcpDetails = toolCall.confirmationDetails;
        await execOrMcpDetails.onConfirm(ToolConfirmationOutcome.Cancel, {
          cancelMessage: `Error: ${errorMessage}`
        });
      } else {
        await toolCall.confirmationDetails.onConfirm(
          ToolConfirmationOutcome.Cancel,
          {
            cancelMessage: `Error: ${errorMessage}`
          }
        );
      }
    } finally {
      this.pendingOutgoingRequests.delete(toolCall.request.callId);
    }
  }
};

// packages/cli/src/nonInteractive/control/controllers/sdkMcpController.ts
init_esbuild_shims();
var MCP_REQUEST_TIMEOUT = 3e4;
var SdkMcpController = class extends BaseController {
  static {
    __name(this, "SdkMcpController");
  }
  /**
   * Handle SDK MCP control requests from ControlDispatcher
   *
   * Note: mcp_message requests are NOT handled here. CLI MCP clients
   * send messages via the sendSdkMcpMessage callback directly, not
   * through the control dispatcher.
   */
  async handleRequestPayload(payload, signal) {
    if (signal.aborted) {
      throw new Error("Request aborted");
    }
    switch (payload.subtype) {
      case "mcp_server_status":
        return this.handleMcpStatus();
      default:
        throw new Error(`Unsupported request subtype in SdkMcpController`);
    }
  }
  /**
   * Handle mcp_server_status request
   *
   * Returns status of all registered SDK MCP servers.
   * SDK servers are considered "connected" if they are registered.
   */
  async handleMcpStatus() {
    const status = {};
    for (const serverName of this.context.sdkMcpServers) {
      status[serverName] = "connected";
    }
    return {
      subtype: "mcp_server_status",
      status
    };
  }
  /**
   * Send MCP message to SDK server via control plane
   *
   * @param serverName - Name of the SDK MCP server
   * @param message - MCP JSON-RPC message to send
   * @returns MCP JSON-RPC response from SDK server
   */
  async sendMcpMessageToSdk(serverName, message) {
    this.debugLogger.debug(
      `[SdkMcpController] Sending MCP message to SDK server '${serverName}':`,
      JSON.stringify(message)
    );
    const response = await this.sendControlRequest(
      {
        subtype: "mcp_message",
        server_name: serverName,
        message
      },
      MCP_REQUEST_TIMEOUT,
      this.context.abortSignal
    );
    const responsePayload = response.response;
    const mcpResponse = responsePayload?.["mcp_response"];
    if (!mcpResponse) {
      throw new Error(
        `Invalid MCP response from SDK for server '${serverName}'`
      );
    }
    this.debugLogger.debug(
      `[SdkMcpController] Received MCP response from SDK server '${serverName}':`,
      JSON.stringify(mcpResponse)
    );
    return mcpResponse;
  }
  /**
   * Create a callback function for sending MCP messages to SDK servers.
   *
   * This callback is used by McpClientManager/SdkControlClientTransport to send
   * MCP messages from CLI MCP clients to SDK MCP servers via the control plane.
   *
   * @returns A function that sends MCP messages to SDK and returns the response
   */
  createSendSdkMcpMessage() {
    return (serverName, message) => this.sendMcpMessageToSdk(serverName, message);
  }
};

// packages/cli/src/nonInteractive/control/ControlDispatcher.ts
var debugLogger89 = createDebugLogger("CONTROL_DISPATCHER");
var ControlDispatcher = class {
  static {
    __name(this, "ControlDispatcher");
  }
  context;
  // Make controllers publicly accessible
  systemController;
  permissionController;
  sdkMcpController;
  // readonly hookController: HookController;
  // Central pending request registries
  pendingIncomingRequests = /* @__PURE__ */ new Map();
  pendingOutgoingRequests = /* @__PURE__ */ new Map();
  abortHandler = null;
  constructor(context2) {
    this.context = context2;
    this.systemController = new SystemController(
      context2,
      this,
      "SystemController"
    );
    this.permissionController = new PermissionController(
      context2,
      this,
      "PermissionController"
    );
    this.sdkMcpController = new SdkMcpController(
      context2,
      this,
      "SdkMcpController"
    );
    this.abortHandler = () => {
      this.shutdown();
    };
    this.context.abortSignal.addEventListener("abort", this.abortHandler);
  }
  /**
   * Routes an incoming request to the appropriate controller and sends response
   */
  async dispatch(request4) {
    const { request_id, request: payload } = request4;
    try {
      const controller = this.getControllerForRequest(payload.subtype);
      const response = await controller.handleRequest(payload, request_id);
      this.sendSuccessResponse(request_id, response);
    } catch (error2) {
      const errorMessage = error2 instanceof Error ? error2.message : String(error2);
      this.sendErrorResponse(request_id, errorMessage);
    }
  }
  /**
   * Processes response from SDK for an outgoing request
   */
  handleControlResponse(response) {
    const responsePayload = response.response;
    const requestId = responsePayload.request_id;
    const pending = this.pendingOutgoingRequests.get(requestId);
    if (!pending) {
      debugLogger89.debug(
        `[ControlDispatcher] No pending outgoing request for: ${requestId}`
      );
      return;
    }
    this.deregisterOutgoingRequest(requestId);
    if (responsePayload.subtype === "success") {
      pending.resolve(responsePayload);
    } else {
      const errorMessage = typeof responsePayload.error === "string" ? responsePayload.error : responsePayload.error?.message ?? "Unknown error";
      pending.reject(new Error(errorMessage));
    }
  }
  /**
   * Sends a control request to SDK and waits for response
   */
  async sendControlRequest(payload, timeoutMs) {
    return this.systemController.sendControlRequest(payload, timeoutMs);
  }
  /**
   * Cancels a specific request or all pending requests
   */
  handleCancel(requestId) {
    if (requestId) {
      const pending = this.pendingIncomingRequests.get(requestId);
      if (pending) {
        pending.abortController.abort();
        this.deregisterIncomingRequest(requestId);
        this.sendErrorResponse(requestId, "Request cancelled");
        debugLogger89.debug(
          `[ControlDispatcher] Cancelled incoming request: ${requestId}`
        );
      }
    } else {
      const requestIds = Array.from(this.pendingIncomingRequests.keys());
      for (const id of requestIds) {
        const pending = this.pendingIncomingRequests.get(id);
        if (pending) {
          pending.abortController.abort();
          this.deregisterIncomingRequest(id);
          this.sendErrorResponse(id, "All requests cancelled");
        }
      }
      debugLogger89.debug(
        `[ControlDispatcher] Cancelled all ${requestIds.length} pending incoming requests`
      );
    }
  }
  /**
   * Marks stdin as closed and rejects all pending outgoing requests.
   * After this is called, new outgoing requests will be rejected immediately.
   * This should be called when stdin closes to avoid waiting for responses.
   */
  markInputClosed() {
    if (this.context.inputClosed) {
      return;
    }
    this.context.inputClosed = true;
    const requestIds = Array.from(this.pendingOutgoingRequests.keys());
    if (this.context.debugMode) {
      debugLogger89.debug(
        `[ControlDispatcher] Input closed, rejecting ${requestIds.length} pending outgoing requests`
      );
    }
    for (const id of requestIds) {
      const pending = this.pendingOutgoingRequests.get(id);
      if (pending) {
        this.deregisterOutgoingRequest(id);
        pending.reject(new Error("Input closed"));
      }
    }
  }
  /**
   * Stops all pending requests and cleans up all controllers
   */
  shutdown() {
    debugLogger89.debug("[ControlDispatcher] Shutting down");
    if (this.abortHandler) {
      this.context.abortSignal.removeEventListener("abort", this.abortHandler);
      this.abortHandler = null;
    }
    for (const [
      _requestId,
      pending
    ] of this.pendingIncomingRequests.entries()) {
      pending.abortController.abort();
      clearTimeout(pending.timeoutId);
    }
    this.pendingIncomingRequests.clear();
    for (const [
      _requestId,
      pending
    ] of this.pendingOutgoingRequests.entries()) {
      clearTimeout(pending.timeoutId);
      pending.reject(new Error("Dispatcher shutdown"));
    }
    this.pendingOutgoingRequests.clear();
    this.systemController.cleanup();
    this.permissionController.cleanup();
    this.sdkMcpController.cleanup();
  }
  /**
   * Registers an incoming request in the pending registry.
   */
  registerIncomingRequest(requestId, controller, abortController, timeoutId) {
    this.pendingIncomingRequests.set(requestId, {
      controller,
      abortController,
      timeoutId
    });
  }
  /**
   * Removes an incoming request from the pending registry
   */
  deregisterIncomingRequest(requestId) {
    const pending = this.pendingIncomingRequests.get(requestId);
    if (pending) {
      clearTimeout(pending.timeoutId);
      this.pendingIncomingRequests.delete(requestId);
    }
  }
  /**
   * Registers an outgoing request in the pending registry
   */
  registerOutgoingRequest(requestId, controller, resolve30, reject, timeoutId) {
    this.pendingOutgoingRequests.set(requestId, {
      controller,
      resolve: resolve30,
      reject,
      timeoutId
    });
  }
  /**
   * Removes an outgoing request from the pending registry
   */
  deregisterOutgoingRequest(requestId) {
    const pending = this.pendingOutgoingRequests.get(requestId);
    if (pending) {
      clearTimeout(pending.timeoutId);
      this.pendingOutgoingRequests.delete(requestId);
    }
  }
  /**
   * Get count of pending incoming requests (for debugging)
   */
  getPendingIncomingRequestCount() {
    return this.pendingIncomingRequests.size;
  }
  /**
   * Wait for all incoming request handlers to complete.
   *
   * Uses polling since we don't have direct Promise references to handlers.
   * The pendingIncomingRequests map is managed by BaseController:
   * - Registered when handler starts (in handleRequest)
   * - Deregistered when handler completes (success or error)
   *
   * @param pollIntervalMs - How often to check (default 50ms)
   * @param timeoutMs - Maximum wait time (default 30s)
   */
  async waitForPendingIncomingRequests(pollIntervalMs = 50, timeoutMs = 3e4) {
    const startTime = Date.now();
    while (this.pendingIncomingRequests.size > 0) {
      if (Date.now() - startTime > timeoutMs) {
        debugLogger89.warn(
          `[ControlDispatcher] Timeout waiting for ${this.pendingIncomingRequests.size} pending incoming requests`
        );
        break;
      }
      await new Promise((resolve30) => setTimeout(resolve30, pollIntervalMs));
    }
    if (this.pendingIncomingRequests.size === 0) {
      debugLogger89.debug("[ControlDispatcher] All incoming requests completed");
    }
  }
  /**
   * Returns the controller that handles the given request subtype
   */
  getControllerForRequest(subtype) {
    switch (subtype) {
      case "initialize":
      case "interrupt":
      case "set_model":
      case "supported_commands":
        return this.systemController;
      case "can_use_tool":
      case "set_permission_mode":
        return this.permissionController;
      case "mcp_server_status":
        return this.sdkMcpController;
      // case 'hook_callback':
      //   return this.hookController;
      default:
        throw new Error(`Unknown control request subtype: ${subtype}`);
    }
  }
  /**
   * Sends a success response back to SDK
   */
  sendSuccessResponse(requestId, response) {
    const controlResponse = {
      type: "control_response",
      response: {
        subtype: "success",
        request_id: requestId,
        response
      }
    };
    this.context.streamJson.send(controlResponse);
  }
  /**
   * Sends an error response back to SDK
   */
  sendErrorResponse(requestId, error2) {
    const controlResponse = {
      type: "control_response",
      response: {
        subtype: "error",
        request_id: requestId,
        error: error2
      }
    };
    this.context.streamJson.send(controlResponse);
  }
};

// packages/cli/src/nonInteractive/control/ControlService.ts
init_esbuild_shims();
var ControlService = class {
  static {
    __name(this, "ControlService");
  }
  dispatcher;
  /**
   * Construct ControlService
   *
   * @param context - Control context (unused directly, passed to dispatcher)
   * @param dispatcher - Control dispatcher that owns the controller instances
   */
  constructor(context2, dispatcher) {
    this.dispatcher = dispatcher;
  }
  /**
   * Permission Domain API
   *
   * Handles tool execution permissions, approval checks, and callbacks.
   * Delegates to the shared PermissionController instance.
   */
  get permission() {
    const controller = this.dispatcher.permissionController;
    return {
      /**
       * Build UI suggestions for tool confirmation dialogs
       *
       * Creates actionable permission suggestions based on tool confirmation details.
       *
       * @param confirmationDetails - Tool confirmation details
       * @returns Array of permission suggestions or null
       */
      buildPermissionSuggestions: controller.buildPermissionSuggestions.bind(controller),
      /**
       * Get callback for monitoring tool call status updates
       *
       * Returns callback function for integration with CoreToolScheduler.
       *
       * @returns Callback function for tool call updates
       */
      getToolCallUpdateCallback: controller.getToolCallUpdateCallback.bind(controller)
    };
  }
  /**
   * System Domain API
   *
   * Handles system-level operations and session management.
   * Delegates to the shared SystemController instance.
   */
  get system() {
    const controller = this.dispatcher.systemController;
    return {
      /**
       * Get control capabilities
       *
       * Returns the control capabilities object indicating what control
       * features are available. Used exclusively for the initialize
       * control response. System messages do not include capabilities.
       *
       * @returns Control capabilities object
       */
      getControlCapabilities: /* @__PURE__ */ __name(() => controller.buildControlCapabilities(), "getControlCapabilities")
    };
  }
  /**
   * MCP Domain API
   *
   * Handles Model Context Protocol server interactions.
   * Delegates to the shared MCPController instance.
   */
  // get mcp(): McpServiceAPI {
  //   return {
  //     /**
  //      * Get or create MCP client for a server (lazy initialization)
  //      *
  //      * Returns existing client or creates new connection.
  //      *
  //      * @param serverName - Name of the MCP server
  //      * @returns Promise with client and config
  //      */
  //     getMcpClient: async (serverName: string) => {
  //       // MCPController has a private method getOrCreateMcpClient
  //       // We need to expose it via the API
  //       // For now, throw error as placeholder
  //       // The actual implementation will be added when we update MCPController
  //       throw new Error(
  //         `getMcpClient not yet implemented in ControlService. Server: ${serverName}`,
  //       );
  //     },
  //
  //     /**
  //      * List all available MCP servers
  //      *
  //      * Returns names of configured/connected MCP servers.
  //      *
  //      * @returns Array of server names
  //      */
  //     listServers: () => {
  //       // Get servers from context
  //       const sdkServers = Array.from(
  //         this.dispatcher.mcpController['context'].sdkMcpServers,
  //       );
  //       const cliServers = Array.from(
  //         this.dispatcher.mcpController['context'].mcpClients.keys(),
  //       );
  //       return [...new Set([...sdkServers, ...cliServers])];
  //     },
  //   };
  // }
  /**
   * Hook Domain API
   *
   * Handles hook callback processing (placeholder for future expansion).
   * Delegates to the shared HookController instance.
   */
  // get hook(): HookServiceAPI {
  //   // HookController has no public methods yet - controller access reserved for future use
  //   return {};
  // }
  /**
   * Cleanup all controllers
   *
   * Should be called on session shutdown. Delegates to dispatcher's shutdown
   * method to ensure all controllers are properly cleaned up.
   */
  cleanup() {
    this.dispatcher.shutdown();
  }
};

// packages/cli/src/nonInteractive/types.ts
init_esbuild_shims();
function isCLIUserMessage(msg) {
  return msg && typeof msg === "object" && msg.type === "user" && "message" in msg;
}
__name(isCLIUserMessage, "isCLIUserMessage");
function isCLIAssistantMessage(msg) {
  return msg && typeof msg === "object" && msg.type === "assistant" && "uuid" in msg && "message" in msg && "session_id" in msg && "parent_tool_use_id" in msg;
}
__name(isCLIAssistantMessage, "isCLIAssistantMessage");
function isCLISystemMessage(msg) {
  return msg && typeof msg === "object" && msg.type === "system" && "subtype" in msg && "uuid" in msg && "session_id" in msg;
}
__name(isCLISystemMessage, "isCLISystemMessage");
function isCLIResultMessage(msg) {
  return msg && typeof msg === "object" && msg.type === "result" && "subtype" in msg && "duration_ms" in msg && "is_error" in msg && "uuid" in msg && "session_id" in msg;
}
__name(isCLIResultMessage, "isCLIResultMessage");
function isCLIPartialAssistantMessage(msg) {
  return msg && typeof msg === "object" && msg.type === "stream_event" && "uuid" in msg && "session_id" in msg && "event" in msg && "parent_tool_use_id" in msg;
}
__name(isCLIPartialAssistantMessage, "isCLIPartialAssistantMessage");
function isControlRequest(msg) {
  return msg && typeof msg === "object" && msg.type === "control_request" && "request_id" in msg && "request" in msg;
}
__name(isControlRequest, "isControlRequest");
function isControlResponse(msg) {
  return msg && typeof msg === "object" && msg.type === "control_response" && "response" in msg;
}
__name(isControlResponse, "isControlResponse");
function isControlCancel(msg) {
  return msg && typeof msg === "object" && msg.type === "control_cancel_request" && "request_id" in msg;
}
__name(isControlCancel, "isControlCancel");

// packages/cli/src/nonInteractive/session.ts
var debugLogger90 = createDebugLogger("NON_INTERACTIVE_SESSION");
var Session2 = class {
  static {
    __name(this, "Session");
  }
  userMessageQueue = [];
  abortController;
  config;
  sessionId;
  promptIdCounter = 0;
  inputReader;
  outputAdapter;
  controlContext = null;
  dispatcher = null;
  controlService = null;
  controlSystemEnabled = null;
  shutdownHandler = null;
  initialPrompt = null;
  processingPromise = null;
  isShuttingDown = false;
  configInitialized = false;
  // Single initialization promise that resolves when session is ready for user messages.
  // Created lazily once initialization actually starts.
  initializationPromise = null;
  initializationResolve = null;
  initializationReject = null;
  constructor(config2, initialPrompt) {
    this.config = config2;
    this.sessionId = config2.getSessionId();
    this.abortController = new AbortController();
    this.initialPrompt = initialPrompt ?? null;
    this.inputReader = new StreamJsonInputReader();
    this.outputAdapter = new StreamJsonOutputAdapter(
      config2,
      config2.getIncludePartialMessages()
    );
    this.setupSignalHandlers();
  }
  ensureInitializationPromise() {
    if (this.initializationPromise) {
      return;
    }
    this.initializationPromise = new Promise((resolve30, reject) => {
      this.initializationResolve = () => {
        resolve30();
        this.initializationResolve = null;
        this.initializationReject = null;
      };
      this.initializationReject = (error2) => {
        reject(error2);
        this.initializationResolve = null;
        this.initializationReject = null;
      };
    });
  }
  getNextPromptId() {
    this.promptIdCounter++;
    return `${this.sessionId}########${this.promptIdCounter}`;
  }
  async ensureConfigInitialized(options2) {
    if (this.configInitialized) {
      return;
    }
    debugLogger90.debug("[Session] Initializing config");
    try {
      await this.config.initialize(options2);
      this.configInitialized = true;
    } catch (error2) {
      debugLogger90.error("[Session] Failed to initialize config:", error2);
      throw error2;
    }
  }
  /**
   * Mark initialization as complete
   */
  completeInitialization() {
    if (this.initializationResolve) {
      debugLogger90.debug("[Session] Initialization complete");
      this.initializationResolve();
      this.initializationResolve = null;
      this.initializationReject = null;
    }
  }
  /**
   * Mark initialization as failed
   */
  failInitialization(error2) {
    if (this.initializationReject) {
      debugLogger90.error("[Session] Initialization failed:", error2);
      this.initializationReject(error2);
      this.initializationResolve = null;
      this.initializationReject = null;
    }
  }
  /**
   * Wait for session to be ready for user messages
   */
  async waitForInitialization() {
    if (!this.initializationPromise) {
      return;
    }
    await this.initializationPromise;
  }
  ensureControlSystem() {
    if (this.controlContext && this.dispatcher && this.controlService) {
      return;
    }
    this.controlContext = new ControlContext({
      config: this.config,
      streamJson: this.outputAdapter,
      sessionId: this.sessionId,
      abortSignal: this.abortController.signal,
      permissionMode: this.config.getApprovalMode(),
      onInterrupt: /* @__PURE__ */ __name(() => this.handleInterrupt(), "onInterrupt")
    });
    this.dispatcher = new ControlDispatcher(this.controlContext);
    this.controlService = new ControlService(
      this.controlContext,
      this.dispatcher
    );
  }
  getDispatcher() {
    if (this.controlSystemEnabled !== true) {
      return null;
    }
    if (!this.dispatcher) {
      this.ensureControlSystem();
    }
    return this.dispatcher;
  }
  /**
   * Handle the first message to determine session mode (SDK vs direct).
   * This is synchronous from the message loop's perspective - it starts
   * async work but does not return a promise that the loop awaits.
   *
   * The initialization completes asynchronously and resolves initializationPromise
   * when ready for user messages.
   */
  handleFirstMessage(message) {
    if (isControlRequest(message)) {
      const request4 = message;
      this.controlSystemEnabled = true;
      this.ensureControlSystem();
      if (request4.request.subtype === "initialize") {
        void this.initializeSdkMode(request4);
        return;
      }
      debugLogger90.debug(
        "[Session] Ignoring non-initialize control request during initialization"
      );
      return;
    }
    if (isCLIUserMessage(message)) {
      this.controlSystemEnabled = false;
      void this.initializeDirectMode(message);
      return;
    }
    this.controlSystemEnabled = false;
  }
  /**
   * SDK mode initialization flow
   * Dispatches initialize request and initializes config with MCP support
   */
  async initializeSdkMode(request4) {
    this.ensureInitializationPromise();
    try {
      await this.dispatcher?.dispatch(request4);
      const sendSdkMcpMessage = this.dispatcher?.sdkMcpController.createSendSdkMcpMessage();
      await this.ensureConfigInitialized({ sendSdkMcpMessage });
      this.completeInitialization();
    } catch (error2) {
      debugLogger90.error("[Session] SDK mode initialization failed:", error2);
      this.failInitialization(
        error2 instanceof Error ? error2 : new Error(String(error2))
      );
    }
  }
  /**
   * Direct mode initialization flow
   * Initializes config and enqueues the first user message
   */
  async initializeDirectMode(userMessage) {
    this.ensureInitializationPromise();
    try {
      await this.ensureConfigInitialized();
      this.completeInitialization();
      this.enqueueUserMessage(userMessage);
    } catch (error2) {
      debugLogger90.error("[Session] Direct mode initialization failed:", error2);
      this.failInitialization(
        error2 instanceof Error ? error2 : new Error(String(error2))
      );
    }
  }
  /**
   * Handle control request asynchronously (fire-and-forget from main loop).
   * Errors are handled internally and responses sent by dispatcher.
   */
  handleControlRequestAsync(request4) {
    const dispatcher = this.getDispatcher();
    if (!dispatcher) {
      debugLogger90.warn("[Session] Control system not enabled");
      return;
    }
    void dispatcher.dispatch(request4).catch((error2) => {
      debugLogger90.error("[Session] Control request dispatch error:", error2);
    });
  }
  /**
   * Handle control response - MUST be synchronous
   * This resolves pending outgoing requests, breaking the deadlock cycle.
   */
  handleControlResponse(response) {
    const dispatcher = this.getDispatcher();
    if (!dispatcher) {
      return;
    }
    dispatcher.handleControlResponse(response);
  }
  handleControlCancel(cancelRequest) {
    const dispatcher = this.getDispatcher();
    if (!dispatcher) {
      return;
    }
    dispatcher.handleCancel(cancelRequest.request_id);
  }
  async processUserMessage(userMessage) {
    const input = extractUserMessageText(userMessage);
    if (!input) {
      debugLogger90.debug("[Session] No text content in user message");
      return;
    }
    await this.waitForInitialization();
    const promptId = this.getNextPromptId();
    try {
      await runNonInteractive(
        this.config,
        createMinimalSettings(),
        input,
        promptId,
        {
          abortController: this.abortController,
          adapter: this.outputAdapter,
          controlService: this.controlService ?? void 0
        }
      );
    } catch (error2) {
      debugLogger90.error("[Session] Query execution error:", error2);
    }
  }
  async processUserMessageQueue() {
    if (this.isShuttingDown || this.abortController.signal.aborted) {
      return;
    }
    while (this.userMessageQueue.length > 0 && !this.isShuttingDown && !this.abortController.signal.aborted) {
      const userMessage = this.userMessageQueue.shift();
      try {
        await this.processUserMessage(userMessage);
      } catch (error2) {
        debugLogger90.error("[Session] Error processing user message:", error2);
        this.emitErrorResult(error2);
      }
    }
  }
  enqueueUserMessage(userMessage) {
    this.userMessageQueue.push(userMessage);
    this.ensureProcessingStarted();
  }
  ensureProcessingStarted() {
    if (this.processingPromise) {
      return;
    }
    this.processingPromise = this.processUserMessageQueue().finally(() => {
      this.processingPromise = null;
      if (this.userMessageQueue.length > 0 && !this.isShuttingDown && !this.abortController.signal.aborted) {
        this.ensureProcessingStarted();
      }
    });
  }
  emitErrorResult(error2, numTurns = 0, durationMs = 0, apiDurationMs = 0) {
    const message = error2 instanceof Error ? error2.message : String(error2);
    this.outputAdapter.emitResult({
      isError: true,
      errorMessage: message,
      durationMs,
      apiDurationMs,
      numTurns,
      usage: void 0
    });
  }
  handleInterrupt() {
    debugLogger90.info("[Session] Interrupt requested");
    this.abortController.abort();
  }
  setupSignalHandlers() {
    this.shutdownHandler = () => {
      debugLogger90.info("[Session] Shutdown signal received");
      this.isShuttingDown = true;
      this.abortController.abort();
    };
    process.on("SIGINT", this.shutdownHandler);
    process.on("SIGTERM", this.shutdownHandler);
  }
  /**
   * Wait for all pending work to complete before shutdown
   */
  async waitForAllPendingWork() {
    try {
      await this.waitForInitialization();
    } catch (error2) {
      debugLogger90.error(
        "[Session] Initialization error during shutdown:",
        error2
      );
    }
    if (this.dispatcher) {
      const pendingCount = this.dispatcher.getPendingIncomingRequestCount();
      if (pendingCount > 0) {
        debugLogger90.debug(
          `[Session] Waiting for ${pendingCount} pending control request handlers`
        );
      }
      await this.dispatcher.waitForPendingIncomingRequests();
    }
    while (this.processingPromise) {
      debugLogger90.debug("[Session] Waiting for user message processing");
      try {
        await this.processingPromise;
      } catch (error2) {
        debugLogger90.error("[Session] Error in user message processing:", error2);
      }
    }
  }
  async shutdown() {
    debugLogger90.debug("[Session] Shutting down");
    this.isShuttingDown = true;
    await this.waitForAllPendingWork();
    this.dispatcher?.shutdown();
    this.cleanupSignalHandlers();
  }
  cleanupSignalHandlers() {
    if (this.shutdownHandler) {
      process.removeListener("SIGINT", this.shutdownHandler);
      process.removeListener("SIGTERM", this.shutdownHandler);
      this.shutdownHandler = null;
    }
  }
  /**
   * Main message processing loop
   *
   * CRITICAL: This loop must NEVER await handlers that might need to
   * send control requests and wait for responses. Such handlers must
   * be started in fire-and-forget mode, allowing the loop to continue
   * reading responses that resolve pending requests.
   *
   * Message handling order:
   * 1. control_response - FIRST, synchronously resolves pending requests
   * 2. First message - determines mode, starts async initialization
   * 3. control_request - fire-and-forget, tracked by dispatcher
   * 4. control_cancel - synchronous
   * 5. user_message - enqueued for processing
   */
  async run() {
    try {
      debugLogger90.info("[Session] Starting session", this.sessionId);
      if (this.initialPrompt !== null) {
        this.handleFirstMessage(this.initialPrompt);
      }
      try {
        for await (const message of this.inputReader.read()) {
          if (this.abortController.signal.aborted) {
            break;
          }
          if (isControlResponse(message)) {
            this.handleControlResponse(message);
            continue;
          }
          if (this.controlSystemEnabled === null) {
            this.handleFirstMessage(message);
            continue;
          }
          if (isControlRequest(message)) {
            this.handleControlRequestAsync(message);
          } else if (isControlCancel(message)) {
            this.handleControlCancel(message);
          } else if (isCLIUserMessage(message)) {
            this.enqueueUserMessage(message);
          } else if (!isCLIAssistantMessage(message) && !isCLISystemMessage(message) && !isCLIResultMessage(message) && !isCLIPartialAssistantMessage(message)) {
            debugLogger90.warn(
              "[Session] Unknown message type:",
              JSON.stringify(message, null, 2)
            );
          }
          if (this.isShuttingDown) {
            break;
          }
        }
      } catch (streamError) {
        debugLogger90.error("[Session] Stream reading error:", streamError);
        throw streamError;
      }
      if (this.dispatcher) {
        this.dispatcher.markInputClosed();
      }
      await this.waitForAllPendingWork();
      await this.shutdown();
    } catch (error2) {
      debugLogger90.error("[Session] Error:", error2);
      await this.shutdown();
      throw error2;
    } finally {
      this.cleanupSignalHandlers();
    }
  }
};
function extractUserMessageText(message) {
  const content = message.message.content;
  if (typeof content === "string") {
    return content;
  }
  if (Array.isArray(content)) {
    const parts = content.map((block2) => {
      if (!block2 || typeof block2 !== "object") {
        return "";
      }
      if ("type" in block2 && block2.type === "text" && "text" in block2) {
        return typeof block2.text === "string" ? block2.text : "";
      }
      return JSON.stringify(block2);
    }).filter((part) => part.length > 0);
    return parts.length > 0 ? parts.join("\n") : null;
  }
  return null;
}
__name(extractUserMessageText, "extractUserMessageText");
async function runNonInteractiveStreamJson(config2, input) {
  let initialPrompt = void 0;
  if (input && input.trim().length > 0) {
    const sessionId = config2.getSessionId();
    initialPrompt = {
      type: "user",
      session_id: sessionId,
      message: {
        role: "user",
        content: input.trim()
      },
      parent_tool_use_id: null
    };
  }
  const manager = new Session2(config2, initialPrompt);
  await manager.run();
}
__name(runNonInteractiveStreamJson, "runNonInteractiveStreamJson");

// packages/cli/src/ui/AppContainer.tsx
init_esbuild_shims();
var import_react133 = __toESM(require_react(), 1);

// packages/cli/src/ui/App.tsx
init_esbuild_shims();

// packages/cli/src/ui/contexts/UIStateContext.tsx
init_esbuild_shims();
var import_react32 = __toESM(require_react(), 1);

// packages/cli/src/ui/hooks/useHistoryManager.ts
init_esbuild_shims();
var import_react28 = __toESM(require_react(), 1);
function useHistory() {
  const [history, setHistory] = (0, import_react28.useState)([]);
  const messageIdCounterRef = (0, import_react28.useRef)(0);
  const getNextMessageId = (0, import_react28.useCallback)((baseTimestamp) => {
    messageIdCounterRef.current += 1;
    return baseTimestamp + messageIdCounterRef.current;
  }, []);
  const loadHistory = (0, import_react28.useCallback)((newHistory) => {
    setHistory(newHistory);
  }, []);
  const addItem = (0, import_react28.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_react28.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_react28.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_react30 = __toESM(require_react(), 1);

// packages/cli/src/ui/contexts/SettingsContext.tsx
init_esbuild_shims();
var import_react29 = __toESM(require_react(), 1);
var SettingsContext = import_react29.default.createContext(
  void 0
);
var useSettings = /* @__PURE__ */ __name(() => {
  const context2 = (0, import_react29.useContext)(SettingsContext);
  if (context2 === void 0) {
    throw new Error("useSettings must be used within a SettingsProvider");
  }
  return context2;
}, "useSettings");

// packages/cli/src/ui/hooks/useIdeTrustListener.ts
function useIdeTrustListener() {
  const settings = useSettings();
  const [connectionStatus, setConnectionStatus] = (0, import_react30.useState)(
    IDEConnectionStatus.Disconnected
  );
  const previousTrust = (0, import_react30.useRef)(void 0);
  const [restartReason, setRestartReason] = (0, import_react30.useState)("NONE");
  const [needsRestart, setNeedsRestart] = (0, import_react30.useState)(false);
  const subscribe = (0, import_react30.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_react30.useSyncExternalStore)(subscribe, getSnapshot);
  (0, import_react30.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/hooks/useCodingPlanUpdates.ts
init_esbuild_shims();
var import_react31 = __toESM(require_react(), 1);

// packages/cli/src/config/modelProvidersScope.ts
init_esbuild_shims();
function hasOwnModelProviders(settingsObj) {
  if (!settingsObj || typeof settingsObj !== "object") {
    return false;
  }
  const obj = settingsObj;
  return Object.prototype.hasOwnProperty.call(obj, "modelProviders");
}
__name(hasOwnModelProviders, "hasOwnModelProviders");
function getModelProvidersOwnerScope(settings) {
  if (settings.isTrusted && hasOwnModelProviders(settings.workspace.settings)) {
    return "Workspace" /* Workspace */;
  }
  if (hasOwnModelProviders(settings.user.settings)) {
    return "User" /* User */;
  }
  return void 0;
}
__name(getModelProvidersOwnerScope, "getModelProvidersOwnerScope");
function getPersistScopeForModelSelection(settings) {
  return getModelProvidersOwnerScope(settings) ?? "User" /* User */;
}
__name(getPersistScopeForModelSelection, "getPersistScopeForModelSelection");

// packages/cli/src/constants/codingPlan.ts
init_esbuild_shims();
import { createHash as createHash6 } from "node:crypto";
var CODING_PLAN_ENV_KEY = "BAILIAN_CODING_PLAN_API_KEY";
function computeCodingPlanVersion(template) {
  const templateString2 = JSON.stringify(template);
  return createHash6("sha256").update(templateString2).digest("hex");
}
__name(computeCodingPlanVersion, "computeCodingPlanVersion");
function generateCodingPlanTemplate(region) {
  if (region === "china" /* CHINA */) {
    return [
      {
        id: "qwen3.5-plus",
        name: "[Bailian Coding Plan] qwen3.5-plus",
        baseUrl: "https://coding.dashscope.aliyuncs.com/v1",
        envKey: CODING_PLAN_ENV_KEY,
        generationConfig: {
          extra_body: {
            enable_thinking: true
          },
          contextWindowSize: 1e6
        }
      },
      {
        id: "qwen3-coder-plus",
        name: "[Bailian Coding Plan] qwen3-coder-plus",
        baseUrl: "https://coding.dashscope.aliyuncs.com/v1",
        envKey: CODING_PLAN_ENV_KEY,
        generationConfig: {
          contextWindowSize: 1e6
        }
      },
      {
        id: "qwen3-coder-next",
        name: "[Bailian Coding Plan] qwen3-coder-next",
        baseUrl: "https://coding.dashscope.aliyuncs.com/v1",
        envKey: CODING_PLAN_ENV_KEY,
        generationConfig: {
          contextWindowSize: 262144
        }
      },
      {
        id: "qwen3-max-2026-01-23",
        name: "[Bailian Coding Plan] qwen3-max-2026-01-23",
        baseUrl: "https://coding.dashscope.aliyuncs.com/v1",
        envKey: CODING_PLAN_ENV_KEY,
        generationConfig: {
          extra_body: {
            enable_thinking: true
          },
          contextWindowSize: 262144
        }
      },
      {
        id: "glm-4.7",
        name: "[Bailian Coding Plan] glm-4.7",
        baseUrl: "https://coding.dashscope.aliyuncs.com/v1",
        envKey: CODING_PLAN_ENV_KEY,
        generationConfig: {
          extra_body: {
            enable_thinking: true
          },
          contextWindowSize: 202752
        }
      },
      {
        id: "glm-5",
        name: "[Bailian Coding Plan] glm-5",
        baseUrl: "https://coding.dashscope.aliyuncs.com/v1",
        envKey: CODING_PLAN_ENV_KEY,
        generationConfig: {
          extra_body: {
            enable_thinking: true
          },
          contextWindowSize: 202752
        }
      },
      {
        id: "MiniMax-M2.5",
        name: "[Bailian Coding Plan] MiniMax-M2.5",
        baseUrl: "https://coding.dashscope.aliyuncs.com/v1",
        envKey: CODING_PLAN_ENV_KEY,
        generationConfig: {
          extra_body: {
            enable_thinking: true
          },
          contextWindowSize: 1e6
        }
      },
      {
        id: "kimi-k2.5",
        name: "[Bailian Coding Plan] kimi-k2.5",
        baseUrl: "https://coding.dashscope.aliyuncs.com/v1",
        envKey: CODING_PLAN_ENV_KEY,
        generationConfig: {
          extra_body: {
            enable_thinking: true
          },
          contextWindowSize: 262144
        }
      }
    ];
  }
  return [
    {
      id: "qwen3.5-plus",
      name: "[Bailian Coding Plan for Global/Intl] qwen3.5-plus",
      baseUrl: "https://coding-intl.dashscope.aliyuncs.com/v1",
      envKey: CODING_PLAN_ENV_KEY,
      generationConfig: {
        extra_body: {
          enable_thinking: true
        },
        contextWindowSize: 1e6
      }
    },
    {
      id: "qwen3-coder-plus",
      name: "[Bailian Coding Plan for Global/Intl] qwen3-coder-plus",
      baseUrl: "https://coding-intl.dashscope.aliyuncs.com/v1",
      envKey: CODING_PLAN_ENV_KEY,
      generationConfig: {
        contextWindowSize: 1e6
      }
    },
    {
      id: "qwen3-coder-next",
      name: "[Bailian Coding Plan for Global/Intl] qwen3-coder-next",
      baseUrl: "https://coding-intl.dashscope.aliyuncs.com/v1",
      envKey: CODING_PLAN_ENV_KEY,
      generationConfig: {
        contextWindowSize: 262144
      }
    },
    {
      id: "qwen3-max-2026-01-23",
      name: "[Bailian Coding Plan for Global/Intl] qwen3-max-2026-01-23",
      baseUrl: "https://coding-intl.dashscope.aliyuncs.com/v1",
      envKey: CODING_PLAN_ENV_KEY,
      generationConfig: {
        extra_body: {
          enable_thinking: true
        },
        contextWindowSize: 262144
      }
    },
    {
      id: "glm-4.7",
      name: "[Bailian Coding Plan for Global/Intl] glm-4.7",
      baseUrl: "https://coding-intl.dashscope.aliyuncs.com/v1",
      envKey: CODING_PLAN_ENV_KEY,
      generationConfig: {
        extra_body: {
          enable_thinking: true
        },
        contextWindowSize: 202752
      }
    },
    {
      id: "glm-5",
      name: "[Bailian Coding Plan for Global/Intl] glm-5",
      baseUrl: "https://coding-intl.dashscope.aliyuncs.com/v1",
      envKey: CODING_PLAN_ENV_KEY,
      generationConfig: {
        extra_body: {
          enable_thinking: true
        },
        contextWindowSize: 202752
      }
    },
    {
      id: "MiniMax-M2.5",
      name: "[Bailian Coding Plan for Global/Intl] MiniMax-M2.5",
      baseUrl: "https://coding-intl.dashscope.aliyuncs.com/v1",
      envKey: CODING_PLAN_ENV_KEY,
      generationConfig: {
        extra_body: {
          enable_thinking: true
        },
        contextWindowSize: 1e6
      }
    },
    {
      id: "kimi-k2.5",
      name: "[Bailian Coding Plan for Global/Intl] kimi-k2.5",
      baseUrl: "https://coding-intl.dashscope.aliyuncs.com/v1",
      envKey: CODING_PLAN_ENV_KEY,
      generationConfig: {
        extra_body: {
          enable_thinking: true
        },
        contextWindowSize: 262144
      }
    }
  ];
}
__name(generateCodingPlanTemplate, "generateCodingPlanTemplate");
function getCodingPlanConfig(region) {
  const template = generateCodingPlanTemplate(region);
  const baseUrl = region === "china" /* CHINA */ ? "https://coding.dashscope.aliyuncs.com/v1" : "https://coding-intl.dashscope.aliyuncs.com/v1";
  const regionName = region === "china" /* CHINA */ ? "Coding Plan (Bailian, China)" : "Coding Plan (Bailian, Global/Intl)";
  return {
    template,
    baseUrl,
    regionName,
    version: computeCodingPlanVersion(template)
  };
}
__name(getCodingPlanConfig, "getCodingPlanConfig");
function isCodingPlanConfig(baseUrl, envKey) {
  if (!baseUrl || !envKey) {
    return false;
  }
  if (envKey !== CODING_PLAN_ENV_KEY) {
    return false;
  }
  if (baseUrl === "https://coding.dashscope.aliyuncs.com/v1") {
    return "china" /* CHINA */;
  }
  if (baseUrl === "https://coding-intl.dashscope.aliyuncs.com/v1") {
    return "global" /* GLOBAL */;
  }
  return false;
}
__name(isCodingPlanConfig, "isCodingPlanConfig");

// packages/cli/src/ui/hooks/useCodingPlanUpdates.ts
function useCodingPlanUpdates(settings, config2, addItem) {
  const [updateRequest, setUpdateRequest] = (0, import_react31.useState)();
  const executeUpdate = (0, import_react31.useCallback)(
    async (region = "china" /* CHINA */) => {
      try {
        const persistScope = getPersistScopeForModelSelection(settings);
        const currentConfigs = settings.merged.modelProviders?.[AuthType2.USE_OPENAI] || [];
        const nonCodingPlanConfigs = currentConfigs.filter(
          (cfg) => !isCodingPlanConfig(
            cfg["baseUrl"],
            cfg["envKey"]
          )
        );
        const { template, version: version2, regionName } = getCodingPlanConfig(region);
        const newConfigs = template.map((templateConfig) => ({
          ...templateConfig,
          envKey: CODING_PLAN_ENV_KEY
        }));
        const updatedConfigs = [
          ...newConfigs,
          ...nonCodingPlanConfigs
        ];
        const updatedModelProviders = {
          ...settings.merged.modelProviders,
          [AuthType2.USE_OPENAI]: updatedConfigs
        };
        config2.reloadModelProvidersConfig(
          updatedModelProviders
        );
        await config2.refreshAuth(AuthType2.USE_OPENAI);
        settings.setValue(
          persistScope,
          `modelProviders.${AuthType2.USE_OPENAI}`,
          updatedConfigs
        );
        settings.setValue(persistScope, "codingPlan.version", version2);
        settings.setValue(persistScope, "codingPlan.region", region);
        const activeModel = config2.getModel();
        addItem(
          {
            type: "info",
            text: t4(
              '{{region}} configuration updated successfully. Model switched to "{{model}}".',
              { region: regionName, model: activeModel }
            )
          },
          Date.now()
        );
        return true;
      } catch (error2) {
        const errorMessage = error2 instanceof Error ? error2.message : String(error2);
        addItem(
          {
            type: "error",
            text: t4("Failed to update Coding Plan configuration: {{message}}", {
              message: errorMessage
            })
          },
          Date.now()
        );
        return false;
      }
    },
    [settings, config2, addItem]
  );
  const checkForUpdates2 = (0, import_react31.useCallback)(() => {
    const mergedSettings = settings.merged;
    const region = mergedSettings.codingPlan?.region ?? "china" /* CHINA */;
    const savedVersion = mergedSettings.codingPlan?.version;
    if (!savedVersion) {
      return;
    }
    const currentVersion = getCodingPlanConfig(region).version;
    if (savedVersion !== currentVersion) {
      const { regionName } = getCodingPlanConfig(region);
      setUpdateRequest({
        prompt: t4(
          "New model configurations are available for {{region}}. Update now?",
          { region: regionName }
        ),
        onConfirm: /* @__PURE__ */ __name(async (confirmed) => {
          setUpdateRequest(void 0);
          if (confirmed) {
            await executeUpdate(region);
          }
        }, "onConfirm")
      });
    }
  }, [settings, executeUpdate]);
  (0, import_react31.useEffect)(() => {
    checkForUpdates2();
  }, [checkForUpdates2]);
  const dismissCodingPlanUpdate = (0, import_react31.useCallback)(() => {
    setUpdateRequest(void 0);
  }, []);
  return {
    codingPlanUpdateRequest: updateRequest,
    dismissCodingPlanUpdate
  };
}
__name(useCodingPlanUpdates, "useCodingPlanUpdates");

// packages/cli/src/ui/contexts/UIStateContext.tsx
var UIStateContext = (0, import_react32.createContext)(null);
var useUIState = /* @__PURE__ */ __name(() => {
  const context2 = (0, import_react32.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_react33 = __toESM(require_react(), 1);
var StreamingContext = (0, import_react33.createContext)(
  void 0
);
var useStreamingContext = /* @__PURE__ */ __name(() => {
  const context2 = import_react33.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_react67 = __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(string4, options2 = {}) {
  if (typeof string4 !== "string" || string4.length === 0) {
    return 0;
  }
  const {
    ambiguousIsNarrow = true,
    countAnsiEscapeCodes = false
  } = options2;
  if (!countAnsiEscapeCodes) {
    string4 = stripAnsi(string4);
  }
  if (string4.length === 0) {
    return 0;
  }
  let width = 0;
  const eastAsianWidthOptions = { ambiguousAsWide: !ambiguousIsNarrow };
  for (const { segment: character } of segmenter4.segment(string4)) {
    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 i3 = 0; i3 < str2.length; i3++) {
    if (str2.charCodeAt(i3) > 127) {
      isAscii2 = false;
      break;
    }
  }
  if (isAscii2) {
    return str2.split("");
  }
  if (str2.length <= MAX_STRING_LENGTH_TO_CACHE) {
    const cached2 = codePointsCache.get(str2);
    if (cached2) {
      return cached2;
    }
  }
  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 i3 = 0; i3 < obj.length; i3++) {
      const value = obj[i3];
      const escapedValue = escapeAnsiCtrlCodes(value);
      if (escapedValue !== value) {
        if (newArr === null) {
          newArr = [...obj];
        }
        newArr[i3] = 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();
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/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)(Text3, { 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)(Text3, { 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)(Text3, { color: theme.text.link, children: "$ " }),
    /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(Text3, { 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_react39 = __toESM(require_react(), 1);

// packages/cli/src/ui/utils/CodeColorizer.tsx
init_esbuild_shims();
var import_react36 = __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 c3(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(c3, "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(re3, substitution, depth) {
  if (depth === -1) return "";
  return re3.replace(substitution, (_2) => {
    return recurRegex(re3, 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 m3;
      const afterMatch = match2.input.substring(afterMatchIndex);
      if (m3 = afterMatch.match(/^\s*=/)) {
        response.ignoreMatch();
        return;
      }
      if (m3 = afterMatch.match(/^\s+extends\s+/)) {
        if (m3.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_TEMPLATE2 = {
    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_TEMPLATE2,
    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((x3) => `${x3}\\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_TEMPLATE2,
      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(c4) {
    return {
      // Less strings are not multiline (also include '~' for more consistent coloring of "escaped" strings)
      className: "string",
      begin: "~?" + c4 + ".*?" + c4
    };
  }, "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((m3) => {
    m3.contains = m3.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, open4, close = "\\1") => {
    const middle2 = close === "\\1" ? close : regex3.concat(close, open4);
    return regex3.concat(
      regex3.concat("(?:", prefix, ")"),
      open4,
      /(?:\\.|[^\\\/])*?/,
      middle2,
      /(?:\\.|[^\\\/])*?/,
      close,
      REGEX_MODIFIERS
    );
  }, "PAIRED_DOUBLE_RE");
  const PAIRED_RE = /* @__PURE__ */ __name((prefix, open4, close) => {
    return regex3.concat(
      regex3.concat("(?:", prefix, ")"),
      open4,
      /(?:\\.|[^\\\/])*?/,
      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((m3, resp) => {
      resp.data._beginMatch = m3[1] || m3[2];
    }, "on:begin"),
    "on:end": /* @__PURE__ */ __name((m3, resp) => {
      if (resp.data._beginMatch !== m3[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 r4(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(r4, "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((x3) => x3.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(re3) {
  if (!re3) return null;
  if (typeof re3 === "string") return re3;
  return re3.source;
}
__name(source, "source");
function lookahead(re3) {
  return concat("(?=", re3, ")");
}
__name(lookahead, "lookahead");
function concat(...args) {
  const joined = args.map((x3) => source(x3)).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((x3) => source(x3)).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 m3;
      const afterMatch = match2.input.substring(afterMatchIndex);
      if (m3 = afterMatch.match(/^\s*=/)) {
        response.ignoreMatch();
        return;
      }
      if (m3 = afterMatch.match(/^\s+extends\s+/)) {
        if (m3.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_TEMPLATE2 = {
    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_TEMPLATE2,
    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((x3) => `${x3}\\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_TEMPLATE2,
      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((m3) => m3.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((c4) => c4.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((m3) => m3.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: c3,
  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: r4,
  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_core18 = __toESM(require_core11(), 1);
var core_default = import_core18.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(d2, i3) {
      return i3 ? d2 + "_".repeat(i3) : self2.options.classPrefix + d2;
    });
    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_react35 = __toESM(require_react(), 1);

// packages/cli/src/ui/contexts/OverflowContext.tsx
init_esbuild_shims();
var import_react34 = __toESM(require_react(), 1);
var import_jsx_runtime3 = __toESM(require_jsx_runtime(), 1);
var OverflowStateContext = (0, import_react34.createContext)(
  void 0
);
var OverflowActionsContext = (0, import_react34.createContext)(
  void 0
);
var useOverflowState = /* @__PURE__ */ __name(() => (0, import_react34.useContext)(OverflowStateContext), "useOverflowState");
var useOverflowActions = /* @__PURE__ */ __name(() => (0, import_react34.useContext)(OverflowActionsContext), "useOverflowActions");
var OverflowProvider = /* @__PURE__ */ __name(({
  children
}) => {
  const [overflowingIds, setOverflowingIds] = (0, import_react34.useState)(/* @__PURE__ */ new Set());
  const addOverflowingId = (0, import_react34.useCallback)((id) => {
    setOverflowingIds((prevIds) => {
      if (prevIds.has(id)) {
        return prevIds;
      }
      const newIds = new Set(prevIds);
      newIds.add(id);
      return newIds;
    });
  }, []);
  const removeOverflowingId = (0, import_react34.useCallback)((id) => {
    setOverflowingIds((prevIds) => {
      if (!prevIds.has(id)) {
        return prevIds;
      }
      const newIds = new Set(prevIds);
      newIds.delete(id);
      return newIds;
    });
  }, []);
  const stateValue = (0, import_react34.useMemo)(
    () => ({
      overflowingIds
    }),
    [overflowingIds]
  );
  const actionsValue = (0, import_react34.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 debugLogger91 = createDebugLogger("MAX_SIZED_BOX");
var MINIMUM_MAX_HEIGHT = 2;
function setMaxSizedBoxDebugging(value) {
  enableDebugLog = value;
}
__name(setMaxSizedBoxDebugging, "setMaxSizedBoxDebugging");
function debugReportError(message, element) {
  if (!enableDebugLog) return;
  if (!import_react35.default.isValidElement(element)) {
    debugLogger91.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 (error2) {
    debugLogger91.error("Error while trying to get file name:", error2);
  }
  debugLogger91.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_react35.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_react35.default.isValidElement(element)) {
      return;
    }
    if (element.type === import_react35.Fragment) {
      import_react35.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_react35.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_react35.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)(Text3, { ...segment.props, children: segment.text }, segIndex)) : /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(Text3, { 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)(Text3, { 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)(Text3, { color: theme.text.secondary, wrap: "truncate", children: [
      "... last ",
      totalHiddenLines,
      " line",
      totalHiddenLines === 1 ? "" : "s",
      " ",
      "hidden ..."
    ] })
  ] });
}, "MaxSizedBox");
function visitBoxRow(element) {
  if (!import_react35.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_react35.default.isValidElement(element2)) {
      debugReportError("Invalid element.", element2);
      return;
    }
    if (element2.type === import_react35.Fragment) {
      import_react35.default.Children.forEach(
        element2.props.children,
        (child) => visitRowChild(child, parentProps)
      );
      return;
    }
    if (element2.type !== Text3) {
      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_react35.default.Children.forEach(
      children,
      (child) => visitRowChild(child, mergedProps)
    );
  }
  __name(visitRowChild, "visitRowChild");
  import_react35.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);
var debugLogger92 = createDebugLogger("CODE_COLORIZER");
function renderHastNode(node, theme2, inheritedColor) {
  if (node.type === "text") {
    const color = inheritedColor || theme2.defaultColor;
    return /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(Text3, { color, children: node.value });
  }
  if (node.type === "element") {
    const nodeClasses = node.properties?.["className"] || [];
    let elementColor = void 0;
    for (let i3 = nodeClasses.length - 1; i3 >= 0; i3--) {
      const color = theme2.getInkColor(nodeClasses[i3]);
      if (color) {
        elementColor = color;
        break;
      }
    }
    const colorToPassDown = elementColor || inheritedColor;
    const children = node.children?.map(
      (child, index) => /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(import_react36.default.Fragment, { children: renderHastNode(child, theme2, colorToPassDown) }, index)
    );
    return /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(import_react36.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_react36.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)(Text3, { color: activeTheme.colors.Gray, children: `${String(index + 1 + hiddenLinesCount).padStart(
              padWidth,
              " "
            )} ` }),
            /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(Text3, { color: activeTheme.defaultColor, wrap: "wrap", children: contentToRender })
          ] }, index);
        })
      }
    );
  } catch (error2) {
    debugLogger92.error(
      `[colorizeCode] Error highlighting code for language "${language}":`,
      error2
    );
    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)(Text3, { color: activeTheme.defaultColor, children: `${String(index + 1).padStart(padWidth, " ")} ` }),
          /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(Text3, { color: activeTheme.colors.Gray, children: line })
        ] }, index))
      }
    );
  }
}
__name(colorizeCode, "colorizeCode");

// packages/cli/src/ui/utils/TableRenderer.tsx
init_esbuild_shims();
var import_react38 = __toESM(require_react(), 1);

// packages/cli/src/ui/utils/InlineMarkdownRenderer.tsx
init_esbuild_shims();
var import_react37 = __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 debugLogger93 = createDebugLogger("INLINE_MARKDOWN");
var RenderInlineInternal = /* @__PURE__ */ __name(({
  text,
  textColor = theme.text.primary
}) => {
  if (!/[*_~`<[https?:]/.test(text)) {
    return /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(Text3, { color: textColor, 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)(Text3, { 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)(Text3, { 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)(Text3, { 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)(Text3, { 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)(Text3, { 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)(Text3, { children: [
            linkText,
            /* @__PURE__ */ (0, import_jsx_runtime6.jsxs)(Text3, { 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)(Text3, { 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)(Text3, { color: theme.text.link, children: fullMatch }, key);
      }
    } catch (e4) {
      debugLogger93.error("Error parsing inline markdown part:", fullMatch, e4);
      renderedNode = null;
    }
    nodes.push(renderedNode ?? /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(Text3, { children: fullMatch }, key));
    lastIndex = inlineRegex.lastIndex;
  }
  if (lastIndex < text.length) {
    nodes.push(/* @__PURE__ */ (0, import_jsx_runtime6.jsx)(Text3, { 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_react37.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,
  contentWidth
}) => {
  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 > contentWidth ? contentWidth / totalWidth : 1;
  const adjustedWidths = columnWidths.map(
    (width) => Math.floor(width * scaleFactor)
  );
  const renderCell = /* @__PURE__ */ __name((content, width, isHeader = false) => {
    const contentWidth2 = Math.max(0, width - 2);
    const displayWidth = getPlainTextLength(content);
    let cellContent = content;
    if (displayWidth > contentWidth2) {
      if (contentWidth2 <= 3) {
        cellContent = content.substring(
          0,
          Math.min(content.length, contentWidth2)
        );
      } 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 <= contentWidth2 - 3) {
            bestTruncated = candidate;
            left3 = mid + 1;
          } else {
            right3 = mid - 1;
          }
        }
        cellContent = bestTruncated + "...";
      }
    }
    const actualDisplayWidth = getPlainTextLength(cellContent);
    const paddingNeeded = Math.max(0, contentWidth2 - actualDisplayWidth);
    return /* @__PURE__ */ (0, import_jsx_runtime7.jsxs)(Text3, { children: [
      isHeader ? /* @__PURE__ */ (0, import_jsx_runtime7.jsx)(Text3, { 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((w2) => char.horizontal.repeat(w2));
    const border = char.left + borderParts.join(char.middle) + char.right;
    return /* @__PURE__ */ (0, import_jsx_runtime7.jsx)(Text3, { 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)(Text3, { color: theme.text.primary, children: [
      "\u2502",
      " ",
      renderedCells.map((cell, index) => /* @__PURE__ */ (0, import_jsx_runtime7.jsxs)(import_react38.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_react38.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,
  contentWidth,
  textColor = theme.text.primary
}) => {
  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,
              contentWidth
            },
            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)(Text3, { wrap: "wrap", children: /* @__PURE__ */ (0, import_jsx_runtime8.jsx)(RenderInline, { text: line, textColor }) }) }, 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,
              contentWidth
            },
            `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)(Text3, { wrap: "wrap", children: /* @__PURE__ */ (0, import_jsx_runtime8.jsx)(RenderInline, { text: line, textColor }) }) }, key)
        );
      }
    } else if (hrMatch) {
      addContentBlock(
        /* @__PURE__ */ (0, import_jsx_runtime8.jsx)(Box_default, { children: /* @__PURE__ */ (0, import_jsx_runtime8.jsx)(Text3, { 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)(Text3, { bold: true, color: textColor, children: /* @__PURE__ */ (0, import_jsx_runtime8.jsx)(RenderInline, { text: headerText, textColor }) });
          break;
        case 2:
          headerNode = /* @__PURE__ */ (0, import_jsx_runtime8.jsx)(Text3, { bold: true, color: textColor, children: /* @__PURE__ */ (0, import_jsx_runtime8.jsx)(RenderInline, { text: headerText, textColor }) });
          break;
        case 3:
          headerNode = /* @__PURE__ */ (0, import_jsx_runtime8.jsx)(Text3, { bold: true, color: textColor, children: /* @__PURE__ */ (0, import_jsx_runtime8.jsx)(RenderInline, { text: headerText, textColor }) });
          break;
        case 4:
          headerNode = /* @__PURE__ */ (0, import_jsx_runtime8.jsx)(Text3, { italic: true, color: textColor, children: /* @__PURE__ */ (0, import_jsx_runtime8.jsx)(RenderInline, { text: headerText, textColor }) });
          break;
        default:
          headerNode = /* @__PURE__ */ (0, import_jsx_runtime8.jsx)(Text3, { color: textColor, children: /* @__PURE__ */ (0, import_jsx_runtime8.jsx)(RenderInline, { text: headerText, textColor }) });
          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,
            textColor
          },
          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,
            textColor
          },
          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)(Text3, { wrap: "wrap", color: textColor, children: /* @__PURE__ */ (0, import_jsx_runtime8.jsx)(RenderInline, { text: line, textColor }) }) }, key)
        );
      }
    }
  });
  if (inCodeBlock) {
    addContentBlock(
      /* @__PURE__ */ (0, import_jsx_runtime8.jsx)(
        RenderCodeBlock,
        {
          content: codeBlockContent,
          lang: codeBlockLang,
          isPending,
          availableTerminalHeight,
          contentWidth
        },
        "line-eof"
      )
    );
  }
  if (inTable && tableHeaders.length > 0 && tableRows.length > 0) {
    addContentBlock(
      /* @__PURE__ */ (0, import_jsx_runtime8.jsx)(
        RenderTable,
        {
          headers: tableHeaders,
          rows: tableRows,
          contentWidth
        },
        `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,
  contentWidth
}) => {
  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)(Text3, { 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,
        contentWidth - 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)(Text3, { color: theme.text.secondary, children: "... generating more ..." })
      ] });
    }
  }
  const fullContent = content.join("\n");
  const colorizedCode = colorizeCode(
    fullContent,
    lang,
    availableTerminalHeight,
    contentWidth - CODE_BLOCK_PREFIX_PADDING,
    void 0,
    settings
  );
  return /* @__PURE__ */ (0, import_jsx_runtime8.jsx)(
    Box_default,
    {
      paddingLeft: CODE_BLOCK_PREFIX_PADDING,
      flexDirection: "column",
      width: contentWidth,
      flexShrink: 0,
      children: colorizedCode
    }
  );
}, "RenderCodeBlockInternal");
var RenderCodeBlock = import_react39.default.memo(RenderCodeBlockInternal);
var RenderListItemInternal = /* @__PURE__ */ __name(({
  itemText,
  type,
  marker,
  leadingWhitespace = "",
  textColor = theme.text.primary
}) => {
  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)(Text3, { color: textColor, children: prefix }) }),
        /* @__PURE__ */ (0, import_jsx_runtime8.jsx)(Box_default, { flexGrow: LIST_ITEM_TEXT_FLEX_GROW, children: /* @__PURE__ */ (0, import_jsx_runtime8.jsx)(Text3, { wrap: "wrap", color: textColor, children: /* @__PURE__ */ (0, import_jsx_runtime8.jsx)(RenderInline, { text: itemText, textColor }) }) })
      ]
    }
  );
}, "RenderListItemInternal");
var RenderListItem = import_react39.default.memo(RenderListItemInternal);
var RenderTableInternal = /* @__PURE__ */ __name(({
  headers,
  rows,
  contentWidth
}) => /* @__PURE__ */ (0, import_jsx_runtime8.jsx)(TableRenderer, { headers, rows, contentWidth }), "RenderTableInternal");
var RenderTable = import_react39.default.memo(RenderTableInternal);
var MarkdownDisplay = import_react39.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,
  contentWidth
}) => {
  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)(Text3, { 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,
        contentWidth: contentWidth - prefixWidth
      }
    ) })
  ] });
}, "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", children: [
    /* @__PURE__ */ (0, import_jsx_runtime10.jsx)(Box_default, { width: prefixWidth, children: /* @__PURE__ */ (0, import_jsx_runtime10.jsx)(Text3, { color: theme.status.warning, children: prefix }) }),
    /* @__PURE__ */ (0, import_jsx_runtime10.jsx)(Box_default, { flexGrow: 1, children: /* @__PURE__ */ (0, import_jsx_runtime10.jsx)(Text3, { wrap: "wrap", color: theme.status.warning, children: /* @__PURE__ */ (0, import_jsx_runtime10.jsx)(RenderInline, { text, textColor: theme.status.warning }) }) })
  ] });
}, "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", children: [
    /* @__PURE__ */ (0, import_jsx_runtime11.jsx)(Box_default, { width: prefixWidth, children: /* @__PURE__ */ (0, import_jsx_runtime11.jsx)(Text3, { color: theme.status.error, children: prefix }) }),
    /* @__PURE__ */ (0, import_jsx_runtime11.jsx)(Box_default, { flexGrow: 1, children: /* @__PURE__ */ (0, import_jsx_runtime11.jsx)(Text3, { wrap: "wrap", color: theme.status.error, children: text }) })
  ] });
}, "ErrorMessage");

// packages/cli/src/ui/components/messages/ToolGroupMessage.tsx
init_esbuild_shims();
var import_react64 = __toESM(require_react(), 1);

// packages/cli/src/ui/components/messages/ToolMessage.tsx
init_esbuild_shims();
var import_react62 = __toESM(require_react(), 1);

// packages/cli/src/ui/components/messages/DiffRenderer.tsx
init_esbuild_shims();
import crypto12 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,
  contentWidth,
  theme: theme2,
  settings
}) => {
  const screenReaderEnabled = use_is_screen_reader_enabled_default();
  if (!diffContent || typeof diffContent !== "string") {
    return /* @__PURE__ */ (0, import_jsx_runtime12.jsx)(Text3, { 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)(Text3, { 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)(Text3, { 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,
      contentWidth,
      theme2,
      settings
    );
  } else {
    renderedOutput = renderDiffContent(
      parsedLines,
      filename,
      tabWidth,
      availableTerminalHeight,
      contentWidth,
      settings
    );
  }
  return renderedOutput;
}, "DiffRenderer");
var renderDiffContent = /* @__PURE__ */ __name((parsedLines, filename, tabWidth = DEFAULT_TAB_WIDTH, availableTerminalHeight, contentWidth, settings) => {
  const normalizedLines = parsedLines.map((line) => ({
    ...line,
    content: line.content.replace(/\t/g, " ".repeat(tabWidth))
  }));
  const displayableLines = normalizedLines.filter(
    (l3) => l3.type !== "hunk" && l3.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)(Text3, { dimColor: true, children: "No changes detected." })
      }
    );
  }
  const showLineNumbers = settings?.merged.ui?.showLineNumbers ?? true;
  const maxLineNumber = Math.max(
    0,
    ...displayableLines.map((l3) => l3.oldLine ?? 0),
    ...displayableLines.map((l3) => l3.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-${crypto12.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: contentWidth,
      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)(Text3, { wrap: "truncate", color: theme.text.secondary, children: "\u2550".repeat(contentWidth) }) }, `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: [
            showLineNumbers && /* @__PURE__ */ (0, import_jsx_runtime12.jsxs)(
              Text3,
              {
                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)(Text3, { children: [
                prefixSymbol,
                " "
              ] }),
              /* @__PURE__ */ (0, import_jsx_runtime12.jsx)(Text3, { wrap: "wrap", children: colorizeLine(displayContent, language) })
            ] }) : /* @__PURE__ */ (0, import_jsx_runtime12.jsxs)(
              Text3,
              {
                backgroundColor: line.type === "add" ? theme.background.diff.added : theme.background.diff.removed,
                wrap: "wrap",
                children: [
                  /* @__PURE__ */ (0, import_jsx_runtime12.jsx)(
                    Text3,
                    {
                      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)(Text3, { children: line.length > 0 ? line.map((token2, tokenIndex) => /* @__PURE__ */ (0, import_jsx_runtime13.jsx)(
    Text3,
    {
      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_react40 = __toESM(require_react(), 1);
var import_cli_spinners = __toESM(require_cli_spinners(), 1);
function Spinner({ type = "dots" }) {
  const [frame, setFrame] = (0, import_react40.useState)(0);
  const spinner = import_cli_spinners.default[type];
  (0, import_react40.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_react40.default.createElement(Text3, 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)(Text3, { children: SCREEN_READER_LOADING }) : /* @__PURE__ */ (0, import_jsx_runtime14.jsx)(Text3, { 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)(Text3, { children: altText }) : /* @__PURE__ */ (0, import_jsx_runtime14.jsx)(Text3, { 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 AccentYellowDim() {
    return themeManager.getActiveTheme().colors.AccentYellowDim;
  },
  get AccentRedDim() {
    return themeManager.getActiveTheme().colors.AccentRedDim;
  },
  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)(Text3, { color: itemColor, children: statusIcon }) }),
    /* @__PURE__ */ (0, import_jsx_runtime15.jsx)(Box_default, { flexGrow: 1, children: /* @__PURE__ */ (0, import_jsx_runtime15.jsx)(Text3, { 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_react54 = __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 m4 = Math.floor(ms / 6e4);
    const s5 = Math.floor(ms % 6e4 / 1e3);
    return `${m4}m ${s5}s`;
  }
  const h3 = Math.floor(ms / 36e5);
  const m3 = Math.floor(ms % 36e5 / 6e4);
  return `${h3}h ${m3}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 kind2 = getStepKind(state.generationMethod, step);
  switch (kind2) {
    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_react45 = __toESM(require_react(), 1);

// packages/cli/src/ui/hooks/useSelectionList.ts
init_esbuild_shims();
var import_react44 = __toESM(require_react(), 1);

// packages/cli/src/ui/hooks/useKeypress.ts
init_esbuild_shims();
var import_react43 = __toESM(require_react(), 1);

// packages/cli/src/ui/contexts/KeypressContext.tsx
init_esbuild_shims();
var import_react42 = __toESM(require_react(), 1);
import readline3 from "node:readline";
import { PassThrough as PassThrough5 } from "node:stream";

// packages/cli/src/ui/utils/clipboardUtils.ts
init_esbuild_shims();
import * as fs94 from "node:fs/promises";
import * as path105 from "node:path";
var debugLogger94 = createDebugLogger("CLIPBOARD_UTILS");
var cachedClipboardModule = null;
var clipboardLoadAttempted = false;
async function getClipboardModule() {
  if (clipboardLoadAttempted) return cachedClipboardModule;
  clipboardLoadAttempted = true;
  try {
    const modName = "@teddyzhu/clipboard";
    cachedClipboardModule = await import(modName);
    return cachedClipboardModule;
  } catch (_e2) {
    debugLogger94.error(
      "Failed to load @teddyzhu/clipboard native module. Clipboard image features will be unavailable."
    );
    return null;
  }
}
__name(getClipboardModule, "getClipboardModule");
async function clipboardHasImage() {
  try {
    const mod2 = await getClipboardModule();
    if (!mod2) return false;
    const clipboard = new mod2.ClipboardManager();
    return clipboard.hasFormat("image");
  } catch (error2) {
    debugLogger94.error("Error checking clipboard for image:", error2);
    return false;
  }
}
__name(clipboardHasImage, "clipboardHasImage");
async function saveClipboardImage(targetDir) {
  try {
    const mod2 = await getClipboardModule();
    if (!mod2) return null;
    const clipboard = new mod2.ClipboardManager();
    if (!clipboard.hasFormat("image")) {
      return null;
    }
    const baseDir = targetDir || process.cwd();
    const tempDir = path105.join(baseDir, "clipboard");
    await fs94.mkdir(tempDir, { recursive: true });
    const timestamp = (/* @__PURE__ */ new Date()).getTime();
    const tempFilePath = path105.join(tempDir, `clipboard-${timestamp}.png`);
    const imageData = clipboard.getImageData();
    const buffer = imageData.data;
    if (!buffer) {
      return null;
    }
    await fs94.writeFile(tempFilePath, buffer);
    return tempFilePath;
  } catch (error2) {
    debugLogger94.error("Error saving clipboard image:", error2);
    return null;
  }
}
__name(saveClipboardImage, "saveClipboardImage");
async function cleanupOldClipboardImages(targetDir) {
  try {
    const baseDir = targetDir || process.cwd();
    const tempDir = path105.join(baseDir, "clipboard");
    const files = await fs94.readdir(tempDir);
    const MAX_IMAGES = 100;
    const CLEANUP_COUNT = 50;
    const imageFiles = [];
    for (const file of files) {
      if (file.startsWith("clipboard-") && (file.endsWith(".png") || file.endsWith(".jpg") || file.endsWith(".webp") || file.endsWith(".heic") || file.endsWith(".heif") || file.endsWith(".tiff") || file.endsWith(".gif") || file.endsWith(".bmp"))) {
        const filePath = path105.join(tempDir, file);
        const stats = await fs94.stat(filePath);
        imageFiles.push({
          name: file,
          path: filePath,
          atime: stats.atimeMs
        });
      }
    }
    if (imageFiles.length > MAX_IMAGES) {
      imageFiles.sort((a2, b2) => a2.atime - b2.atime);
      const removeCount = Math.min(
        CLEANUP_COUNT,
        imageFiles.length - MAX_IMAGES + CLEANUP_COUNT
      );
      const filesToRemove = imageFiles.slice(0, removeCount);
      for (const file of filesToRemove) {
        await fs94.unlink(file.path);
      }
    }
  } catch {
  }
}
__name(cleanupOldClipboardImages, "cleanupOldClipboardImages");

// packages/cli/src/ui/hooks/useFocus.ts
init_esbuild_shims();
var import_react41 = __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_react41.useState)(true);
  (0, import_react41.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(
    (_2) => {
      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_react42.createContext)(
  void 0
);
var debugLogger95 = createDebugLogger("KEYPRESS");
function useKeypressContext() {
  const context2 = (0, import_react42.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: config2,
  debugKeystrokeLogging
}) {
  const { stdin, setRawMode } = use_stdin_default();
  const subscribers = (0, import_react42.useRef)(/* @__PURE__ */ new Set()).current;
  const isDraggingRef = (0, import_react42.useRef)(false);
  const dragBufferRef = (0, import_react42.useRef)("");
  const draggingTimerRef = (0, import_react42.useRef)(null);
  const subscribe = (0, import_react42.useCallback)(
    (handler) => {
      subscribers.add(handler);
    },
    [subscribers]
  );
  const unsubscribe = (0, import_react42.useCallback)(
    (handler) => {
      subscribers.delete(handler);
    },
    [subscribers]
  );
  (0, import_react42.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 PassThrough5();
    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 m3 = buffer.match(revTabLegacy);
      if (m3) {
        return {
          key: {
            name: "tab",
            ctrl: false,
            meta: false,
            shift: true,
            paste: false,
            sequence: buffer.slice(0, m3[0].length),
            kittyProtocol: true
          },
          length: m3[0].length
        };
      }
      const revTabParam = new RegExp(`^${ESC2}\\[1;(\\d+)Z`);
      m3 = buffer.match(revTabParam);
      if (m3) {
        let mods = parseInt(m3[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, m3[0].length),
            kittyProtocol: true
          },
          length: m3[0].length
        };
      }
      const arrowPrefix = new RegExp(`^${ESC2}\\[1;(\\d+)([ABCDHFPQSR])`);
      m3 = buffer.match(arrowPrefix);
      if (m3) {
        let mods = parseInt(m3[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 = m3[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, m3[0].length),
            kittyProtocol: true
          },
          length: m3[0].length
        };
      }
      const csiUPrefix = new RegExp(`^${ESC2}\\[(\\d+)(;(\\d+))?([u~])`);
      m3 = buffer.match(csiUPrefix);
      if (m3) {
        const keyCode = parseInt(m3[1], 10);
        let modifiers = m3[3] ? parseInt(m3[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 = m3[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, m3[0].length),
                kittyProtocol: true
              },
              length: m3[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, m3[0].length),
              kittyProtocol: true
            },
            length: m3[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, m3[0].length),
              kittyProtocol: true
            },
            length: m3[0].length
          };
        }
      }
      const legacyFuncKey = new RegExp(`^${ESC2}\\[([ABCDHF])`);
      m3 = buffer.match(legacyFuncKey);
      if (m3) {
        const sym = m3[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, m3[0].length),
            kittyProtocol: true
          },
          length: m3[0].length
        };
      }
      return null;
    }, "parseKittyPrefix");
    const broadcast = /* @__PURE__ */ __name((key) => {
      for (const handler of subscribers) {
        handler(key);
      }
    }, "broadcast");
    const handleKeypress = /* @__PURE__ */ __name(async (_2, 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;
        if (pasteBuffer.toString().length > 0) {
          broadcast({
            name: "",
            ctrl: false,
            meta: false,
            shift: false,
            paste: true,
            sequence: pasteBuffer.toString()
          });
        } else {
          const hasImage = await clipboardHasImage();
          broadcast({
            name: "",
            ctrl: false,
            meta: false,
            shift: false,
            paste: true,
            pasteImage: hasImage,
            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) {
          debugLogger95.debug(
            "[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) {
            debugLogger95.debug(
              "[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) {
                  debugLogger95.debug(
                    "[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) {
                debugLogger95.debug(
                  "[DEBUG] Kitty sequence parsed successfully (prefix):",
                  parsedSequence
                );
              } else {
                debugLogger95.debug(
                  "[DEBUG] Kitty sequence parsed successfully:",
                  parsedSequence
                );
              }
            }
            kittySequenceBuffer = kittySequenceBuffer.slice(parsed.length);
            broadcast(parsed.key);
            parsedAny = true;
          }
          if (parsedAny) return;
          if (config2?.getDebugMode() || debugKeystrokeLogging) {
            const codes = Array.from(kittySequenceBuffer).map(
              (ch) => ch.charCodeAt(0)
            );
            debugLogger95.warn("Kitty sequence buffer has char codes:", codes);
          }
          if (kittySequenceBuffer.length > MAX_KITTY_SEQUENCE_LENGTH) {
            if (debugKeystrokeLogging) {
              debugLogger95.debug(
                "[DEBUG] Kitty buffer overflow, clearing:",
                kittySequenceBuffer
              );
            }
            if (config2) {
              const event = new KittySequenceOverflowEvent(
                kittySequenceBuffer.length,
                kittySequenceBuffer
              );
              logKittySequenceOverflow(config2, 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,
    config2,
    subscribers
  ]);
  return /* @__PURE__ */ (0, import_jsx_runtime16.jsx)(
    KeypressContext.Provider,
    {
      value: { subscribe, unsubscribe, pasteWorkaround },
      children
    }
  );
}
__name(KeypressProvider, "KeypressProvider");

// packages/cli/src/ui/hooks/useKeypress.ts
function useKeypress(onKeypress, { isActive }) {
  const { subscribe, unsubscribe } = useKeypressContext();
  (0, import_react43.useEffect)(() => {
    if (!isActive) {
      return;
    }
    subscribe(onKeypress);
    return () => {
      unsubscribe(onKeypress);
    };
  }, [isActive, onKeypress, subscribe, unsubscribe]);
}
__name(useKeypress, "useKeypress");

// packages/cli/src/ui/hooks/useSelectionList.ts
var debugLogger96 = createDebugLogger("SELECTION_LIST");
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 i3 = 0; i3 < len; i3++) {
    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 i3 = 0; i3 < items.length; i3++) {
      if (items[i3].key === initialKey && !items[i3].disabled) {
        return i3;
      }
    }
  }
  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;
      debugLogger96.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_react44.useReducer)(selectionListReducer, {
    activeIndex: computeInitialIndex(initialIndex, items),
    initialIndex,
    pendingHighlight: false,
    pendingSelect: false,
    items
  });
  const numberInputRef = (0, import_react44.useRef)("");
  const numberInputTimer = (0, import_react44.useRef)(null);
  (0, import_react44.useEffect)(() => {
    dispatch({ type: "INITIALIZE", payload: { initialIndex, items } });
  }, [initialIndex, items]);
  (0, import_react44.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_react44.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_react45.useState)(0);
  (0, import_react45.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)(
      Text3,
      {
        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)(
          Text3,
          {
            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)(Text3, { 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)(
      Text3,
      {
        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)(Text3, { color: titleColor, wrap: "truncate", children: [
            item.themeNameDisplay,
            " ",
            /* @__PURE__ */ (0, import_jsx_runtime18.jsx)(Text3, { color: theme.text.secondary, children: item.themeTypeDisplay })
          ] }, item.key);
        }
        return /* @__PURE__ */ (0, import_jsx_runtime18.jsx)(Text3, { 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 = [
  {
    get label() {
      return t4("Project Level (.qwen/agents/)");
    },
    value: "project"
  },
  {
    get label() {
      return t4("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 = [
  {
    get label() {
      return t4("Generate with Qwen Code (Recommended)");
    },
    value: "qwen"
  },
  {
    get label() {
      return t4("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_react48 = __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["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 uses only arrow keys
  // Ctrl+P/N are reserved for history navigation (HISTORY_UP/DOWN)
  ["completionUp" /* COMPLETION_UP */]: [{ key: "up" }],
  ["completionDown" /* COMPLETION_DOWN */]: [{ key: "down" }],
  // 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 */]: process.platform === "win32" ? [
    { key: "v", command: true },
    { key: "v", meta: true }
  ] : [
    { key: "v", ctrl: true },
    { key: "v", command: true }
  ],
  // App level bindings
  ["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;
  }
  if (keyBinding.meta !== void 0 && key.meta !== keyBinding.meta) {
    return false;
  }
  return true;
}
__name(matchKeyBinding, "matchKeyBinding");
function matchCommand(command2, key, config2 = defaultKeyBindings) {
  const bindings = config2[command2];
  return bindings.some((binding) => matchKeyBinding(binding, key));
}
__name(matchCommand, "matchCommand");
function createKeyMatchers(config2 = defaultKeyBindings) {
  const matchers = {};
  for (const command2 of Object.values(Command)) {
    matchers[command2] = (key) => matchCommand(command2, key, config2);
  }
  return matchers;
}
__name(createKeyMatchers, "createKeyMatchers");
var keyMatchers = createKeyMatchers(defaultKeyBindings);

// packages/cli/src/ui/components/shared/TextInput.tsx
init_esbuild_shims();
var import_chalk6 = __toESM(require_source(), 1);

// packages/cli/src/ui/components/shared/text-buffer.ts
init_esbuild_shims();
var import_react46 = __toESM(require_react(), 1);
import { spawnSync as spawnSync4 } from "node:child_process";
import fs95 from "node:fs";
import os35 from "node:os";
import pathMod from "node:path";

// packages/cli/src/ui/components/shared/vim-buffer-actions.ts
init_esbuild_shims();
function isAtEndOfBaseWord(lineCodePoints, col) {
  if (!isWordCharStrict(lineCodePoints[col])) return false;
  let i3 = col + 1;
  while (i3 < lineCodePoints.length && isCombiningMark(lineCodePoints[i3])) {
    i3++;
  }
  return i3 >= lineCodePoints.length || !isWordCharStrict(lineCodePoints[i3]);
}
__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 i3 = 0; i3 < count; i3++) {
        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 i3 = 0; i3 < count; i3++) {
        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 i3 = 0; i3 < count; i3++) {
        const wordEnd = findNextWordAcrossLines(lines, row, col, false);
        if (wordEnd) {
          endRow = wordEnd.row;
          endCol = wordEnd.col + 1;
          if (i3 < 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 i3 = 0; i3 < count; i3++) {
        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 i3 = 0; i3 < count; i3++) {
        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 i3 = 0; i3 < count; i3++) {
        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 i3 = 0; i3 < count; i3++) {
        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 i3 = 0; i3 < count; i3++) {
        if (i3 === 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
var debugLogger97 = createDebugLogger("TEXT_BUFFER");
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 i3 = col;
  if (i3 >= chars.length) return null;
  const currentChar = chars[i3];
  if (isWordCharStrict(currentChar)) {
    while (i3 < chars.length && isWordCharWithCombining(chars[i3])) {
      if (i3 + 1 < chars.length && isWordCharStrict(chars[i3 + 1]) && isDifferentScript(chars[i3], chars[i3 + 1])) {
        i3++;
        break;
      }
      i3++;
    }
  } else if (!isWhitespace4(currentChar)) {
    while (i3 < chars.length && !isWordCharStrict(chars[i3]) && !isWhitespace4(chars[i3])) {
      i3++;
    }
  }
  while (i3 < chars.length && isWhitespace4(chars[i3])) {
    i3++;
  }
  return i3 < chars.length ? i3 : null;
}, "findNextWordStartInLine");
var findPrevWordStartInLine = /* @__PURE__ */ __name((line, col) => {
  const chars = toCodePoints(line);
  let i3 = col;
  if (i3 <= 0) return null;
  i3--;
  while (i3 >= 0 && isWhitespace4(chars[i3])) {
    i3--;
  }
  if (i3 < 0) return null;
  if (isWordCharStrict(chars[i3])) {
    while (i3 >= 0 && isWordCharStrict(chars[i3])) {
      if (i3 - 1 >= 0 && isWordCharStrict(chars[i3 - 1]) && isDifferentScript(chars[i3], chars[i3 - 1])) {
        return i3;
      }
      i3--;
    }
    return i3 + 1;
  } else {
    while (i3 >= 0 && !isWordCharStrict(chars[i3]) && !isWhitespace4(chars[i3])) {
      i3--;
    }
    return i3 + 1;
  }
}, "findPrevWordStartInLine");
var findWordEndInLine = /* @__PURE__ */ __name((line, col) => {
  const chars = toCodePoints(line);
  let i3 = col;
  const atEndOfWordChar = i3 < chars.length && isWordCharWithCombining(chars[i3]) && (i3 + 1 >= chars.length || !isWordCharWithCombining(chars[i3 + 1]) || isWordCharStrict(chars[i3]) && i3 + 1 < chars.length && isWordCharStrict(chars[i3 + 1]) && isDifferentScript(chars[i3], chars[i3 + 1]));
  const atEndOfPunctuation = i3 < chars.length && !isWordCharWithCombining(chars[i3]) && !isWhitespace4(chars[i3]) && (i3 + 1 >= chars.length || isWhitespace4(chars[i3 + 1]) || isWordCharWithCombining(chars[i3 + 1]));
  if (atEndOfWordChar || atEndOfPunctuation) {
    i3++;
    while (i3 < chars.length && isWhitespace4(chars[i3])) {
      i3++;
    }
  }
  if (i3 < chars.length && !isWordCharWithCombining(chars[i3])) {
    while (i3 < chars.length && isWhitespace4(chars[i3])) {
      i3++;
    }
  }
  let foundWord = false;
  let lastBaseCharPos = -1;
  if (i3 < chars.length && isWordCharWithCombining(chars[i3])) {
    while (i3 < chars.length && isWordCharWithCombining(chars[i3])) {
      foundWord = true;
      if (isWordCharStrict(chars[i3])) {
        lastBaseCharPos = i3;
      }
      if (i3 + 1 < chars.length && isWordCharStrict(chars[i3 + 1]) && isDifferentScript(chars[i3], chars[i3 + 1])) {
        i3++;
        if (isWordCharStrict(chars[i3 - 1])) {
          lastBaseCharPos = i3 - 1;
        }
        break;
      }
      i3++;
    }
  } else if (i3 < chars.length && !isWhitespace4(chars[i3])) {
    while (i3 < chars.length && !isWordCharStrict(chars[i3]) && !isWhitespace4(chars[i3])) {
      foundWord = true;
      lastBaseCharPos = i3;
      i3++;
    }
  }
  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 i3 = 0; i3 < lines.length; i3++) {
    const lineLength = lines[i3].length + 1;
    if (offset + lineLength > startOffset) {
      startRow = i3;
      startCol = startOffset - offset;
      break;
    }
    offset += lineLength;
  }
  offset = 0;
  for (let i3 = 0; i3 < lines.length; i3++) {
    const lineLength = lines[i3].length + (i3 < lines.length - 1 ? 1 : 0);
    if (offset + lineLength >= endOffset) {
      endRow = i3;
      endCol = endOffset - offset;
      break;
    }
    offset += lineLength;
  }
  return { startRow, startCol, endRow, endCol };
}, "getPositionFromOffsets");
var getLineRangeOffsets = /* @__PURE__ */ __name((startRow, lineCount, lines) => {
  let startOffset = 0;
  for (let i3 = 0; i3 < startRow; i3++) {
    startOffset += lines[i3].length + 1;
  }
  let endOffset = startOffset;
  for (let i3 = 0; i3 < lineCount; i3++) {
    const lineIndex = startRow + i3;
    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(v2, min, max) {
  return v2 < min ? min : v2 > max ? max : v2;
}
__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 i3 = 0; i3 < lines.length; i3++) {
    const line = lines[i3];
    const lineLength = cpLen(line);
    const lineLengthWithNewline = lineLength + (i3 < lines.length - 1 ? 1 : 0);
    if (offset <= currentOffset + lineLength) {
      row = i3;
      col = offset - currentOffset;
      return [row, col];
    } else if (offset <= currentOffset + lineLengthWithNewline) {
      row = i3;
      col = lineLength;
      if (offset === currentOffset + lineLengthWithNewline && i3 < lines.length - 1) {
        return [i3 + 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 i3 = 0; i3 < actualRow; i3++) {
    offset += cpLen(lines[i3]) + 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 i3 = currentPosInLogLine; i3 < codePointsInLogLine.length; i3++) {
          const char = codePointsInLogLine[i3];
          const charVisualWidth = getCachedStringWidth(char);
          if (currentChunkVisualWidth + charVisualWidth > viewportWidth) {
            if (lastWordBreakPoint !== -1 && numCodePointsAtLastWordBreak > 0 && currentPosInLogLine + numCodePointsAtLastWordBreak < i3) {
              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 = i3;
            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((r5) => state.lines[r5] ?? "", "currentLine");
  const currentLineLen = /* @__PURE__ */ __name((r5) => cpLen(currentLine(r5)), "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((r5) => newLines[r5] ?? "", "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((r5) => newLines[r5] ?? "", "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;
            debugLogger97.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 i3 = 0; i3 < start; i3++) {
              if (isWordChar(arr[i3])) {
                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;
      debugLogger97.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_react46.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_react46.useReducer)(textBufferReducer, initialState2);
  const {
    lines,
    cursorRow,
    cursorCol,
    preferredCol,
    selectionAnchor,
    visualLayout
  } = state;
  const text = (0, import_react46.useMemo)(() => lines.join("\n"), [lines]);
  const visualCursor = (0, import_react46.useMemo)(
    () => calculateVisualCursorFromLayout(visualLayout, [cursorRow, cursorCol]),
    [visualLayout, cursorRow, cursorCol]
  );
  const { visualLines, visualToLogicalMap } = visualLayout;
  const [visualScrollRow, setVisualScrollRow] = (0, import_react46.useState)(0);
  (0, import_react46.useEffect)(() => {
    if (onChange) {
      onChange(text);
    }
  }, [text, onChange]);
  (0, import_react46.useEffect)(() => {
    dispatch({
      type: "set_viewport",
      payload: { width: viewport.width, height: viewport.height }
    });
  }, [viewport.width, viewport.height]);
  (0, import_react46.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_react46.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_react46.useCallback)(() => {
    dispatch({ type: "insert", payload: "\n" });
  }, []);
  const backspace = (0, import_react46.useCallback)(() => {
    dispatch({ type: "backspace" });
  }, []);
  const del = (0, import_react46.useCallback)(() => {
    dispatch({ type: "delete" });
  }, []);
  const move = (0, import_react46.useCallback)(
    (dir) => {
      dispatch({ type: "move", payload: { dir } });
    },
    [dispatch]
  );
  const undo = (0, import_react46.useCallback)(() => {
    dispatch({ type: "undo" });
  }, []);
  const redo = (0, import_react46.useCallback)(() => {
    dispatch({ type: "redo" });
  }, []);
  const setText = (0, import_react46.useCallback)((newText) => {
    dispatch({ type: "set_text", payload: newText });
  }, []);
  const deleteWordLeft = (0, import_react46.useCallback)(() => {
    dispatch({ type: "delete_word_left" });
  }, []);
  const deleteWordRight = (0, import_react46.useCallback)(() => {
    dispatch({ type: "delete_word_right" });
  }, []);
  const killLineRight = (0, import_react46.useCallback)(() => {
    dispatch({ type: "kill_line_right" });
  }, []);
  const killLineLeft = (0, import_react46.useCallback)(() => {
    dispatch({ type: "kill_line_left" });
  }, []);
  const vimDeleteWordForward = (0, import_react46.useCallback)((count) => {
    dispatch({ type: "vim_delete_word_forward", payload: { count } });
  }, []);
  const vimDeleteWordBackward = (0, import_react46.useCallback)((count) => {
    dispatch({ type: "vim_delete_word_backward", payload: { count } });
  }, []);
  const vimDeleteWordEnd = (0, import_react46.useCallback)((count) => {
    dispatch({ type: "vim_delete_word_end", payload: { count } });
  }, []);
  const vimChangeWordForward = (0, import_react46.useCallback)((count) => {
    dispatch({ type: "vim_change_word_forward", payload: { count } });
  }, []);
  const vimChangeWordBackward = (0, import_react46.useCallback)((count) => {
    dispatch({ type: "vim_change_word_backward", payload: { count } });
  }, []);
  const vimChangeWordEnd = (0, import_react46.useCallback)((count) => {
    dispatch({ type: "vim_change_word_end", payload: { count } });
  }, []);
  const vimDeleteLine = (0, import_react46.useCallback)((count) => {
    dispatch({ type: "vim_delete_line", payload: { count } });
  }, []);
  const vimChangeLine = (0, import_react46.useCallback)((count) => {
    dispatch({ type: "vim_change_line", payload: { count } });
  }, []);
  const vimDeleteToEndOfLine = (0, import_react46.useCallback)(() => {
    dispatch({ type: "vim_delete_to_end_of_line" });
  }, []);
  const vimChangeToEndOfLine = (0, import_react46.useCallback)(() => {
    dispatch({ type: "vim_change_to_end_of_line" });
  }, []);
  const vimChangeMovement = (0, import_react46.useCallback)(
    (movement, count) => {
      dispatch({ type: "vim_change_movement", payload: { movement, count } });
    },
    []
  );
  const vimMoveLeft = (0, import_react46.useCallback)((count) => {
    dispatch({ type: "vim_move_left", payload: { count } });
  }, []);
  const vimMoveRight = (0, import_react46.useCallback)((count) => {
    dispatch({ type: "vim_move_right", payload: { count } });
  }, []);
  const vimMoveUp = (0, import_react46.useCallback)((count) => {
    dispatch({ type: "vim_move_up", payload: { count } });
  }, []);
  const vimMoveDown = (0, import_react46.useCallback)((count) => {
    dispatch({ type: "vim_move_down", payload: { count } });
  }, []);
  const vimMoveWordForward = (0, import_react46.useCallback)((count) => {
    dispatch({ type: "vim_move_word_forward", payload: { count } });
  }, []);
  const vimMoveWordBackward = (0, import_react46.useCallback)((count) => {
    dispatch({ type: "vim_move_word_backward", payload: { count } });
  }, []);
  const vimMoveWordEnd = (0, import_react46.useCallback)((count) => {
    dispatch({ type: "vim_move_word_end", payload: { count } });
  }, []);
  const vimDeleteChar = (0, import_react46.useCallback)((count) => {
    dispatch({ type: "vim_delete_char", payload: { count } });
  }, []);
  const vimInsertAtCursor = (0, import_react46.useCallback)(() => {
    dispatch({ type: "vim_insert_at_cursor" });
  }, []);
  const vimAppendAtCursor = (0, import_react46.useCallback)(() => {
    dispatch({ type: "vim_append_at_cursor" });
  }, []);
  const vimOpenLineBelow = (0, import_react46.useCallback)(() => {
    dispatch({ type: "vim_open_line_below" });
  }, []);
  const vimOpenLineAbove = (0, import_react46.useCallback)(() => {
    dispatch({ type: "vim_open_line_above" });
  }, []);
  const vimAppendAtLineEnd = (0, import_react46.useCallback)(() => {
    dispatch({ type: "vim_append_at_line_end" });
  }, []);
  const vimInsertAtLineStart = (0, import_react46.useCallback)(() => {
    dispatch({ type: "vim_insert_at_line_start" });
  }, []);
  const vimMoveToLineStart = (0, import_react46.useCallback)(() => {
    dispatch({ type: "vim_move_to_line_start" });
  }, []);
  const vimMoveToLineEnd = (0, import_react46.useCallback)(() => {
    dispatch({ type: "vim_move_to_line_end" });
  }, []);
  const vimMoveToFirstNonWhitespace = (0, import_react46.useCallback)(() => {
    dispatch({ type: "vim_move_to_first_nonwhitespace" });
  }, []);
  const vimMoveToFirstLine = (0, import_react46.useCallback)(() => {
    dispatch({ type: "vim_move_to_first_line" });
  }, []);
  const vimMoveToLastLine = (0, import_react46.useCallback)(() => {
    dispatch({ type: "vim_move_to_last_line" });
  }, []);
  const vimMoveToLine = (0, import_react46.useCallback)((lineNumber) => {
    dispatch({ type: "vim_move_to_line", payload: { lineNumber } });
  }, []);
  const vimEscapeInsertMode = (0, import_react46.useCallback)(() => {
    dispatch({ type: "vim_escape_insert_mode" });
  }, []);
  const openInExternalEditor = (0, import_react46.useCallback)(
    async (opts = {}) => {
      const editor = opts.editor ?? process.env["VISUAL"] ?? process.env["EDITOR"] ?? (process.platform === "win32" ? "notepad" : "vi");
      const tmpDir = fs95.mkdtempSync(pathMod.join(os35.tmpdir(), "gemini-edit-"));
      const filePath = pathMod.join(tmpDir, "buffer.txt");
      fs95.writeFileSync(filePath, text, "utf8");
      dispatch({ type: "create_undo_snapshot" });
      const wasRaw = stdin?.isRaw ?? false;
      try {
        setRawMode?.(false);
        const { status, error: error2 } = spawnSync4(editor, [filePath], {
          stdio: "inherit"
        });
        if (error2) throw error2;
        if (typeof status === "number" && status !== 0)
          throw new Error(`External editor exited with status ${status}`);
        let newText = fs95.readFileSync(filePath, "utf8");
        newText = newText.replace(/\r\n?/g, "\n");
        dispatch({ type: "set_text", payload: newText, pushToUndo: false });
      } catch (err) {
        debugLogger97.error("[useTextBuffer] external editor error", err);
      } finally {
        if (wasRaw) setRawMode?.(true);
        try {
          fs95.unlinkSync(filePath);
        } catch {
        }
        try {
          fs95.rmdirSync(tmpDir);
        } catch {
        }
      }
    },
    [text, stdin, setRawMode]
  );
  const handleInput = (0, import_react46.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_react46.useMemo)(
    () => visualLines.slice(visualScrollRow, visualScrollRow + viewport.height),
    [visualLines, visualScrollRow, viewport.height]
  );
  const replaceRange = (0, import_react46.useCallback)(
    (startRow, startCol, endRow, endCol, text2) => {
      dispatch({
        type: "replace_range",
        payload: { startRow, startCol, endRow, endCol, text: text2 }
      });
    },
    []
  );
  const replaceRangeByOffset = (0, import_react46.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_react46.useCallback)((offset) => {
    dispatch({ type: "move_to_offset", payload: { offset } });
  }, []);
  const returnValue = (0, import_react46.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_react47 = __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_react47.useRef)(onChange);
  (0, import_react47.useEffect)(() => {
    onChangeRef.current = onChange;
  }, [onChange]);
  const stableOnChange = (0, import_react47.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)(Text3, { 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)(Text3, { children: [
        import_chalk6.default.inverse(placeholder.slice(0, 1)),
        /* @__PURE__ */ (0, import_jsx_runtime21.jsx)(Text3, { 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_chalk6.default.inverse(charToHighlight);
              display = cpSlice(display, 0, relativeVisualColForHighlight) + highlighted + cpSlice(display, relativeVisualColForHighlight + 1);
            } else if (relativeVisualColForHighlight === cpLen(display) && cpLen(display) === inputWidth) {
              display = display + import_chalk6.default.inverse(" ");
            }
          }
        }
        return /* @__PURE__ */ (0, import_jsx_runtime21.jsx)(Text3, { children: display }, `line-${visualIdxInRenderedSet}`);
      }) })
    ] }),
    validationErrors.length > 0 && /* @__PURE__ */ (0, import_jsx_runtime21.jsx)(Box_default, { flexDirection: "column", children: validationErrors.map((error2, index) => /* @__PURE__ */ (0, import_jsx_runtime21.jsxs)(Text3, { color: theme.status.error, children: [
      "\u26A0 ",
      error2
    ] }, 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: config2
}) {
  const abortControllerRef = (0, import_react48.useRef)(null);
  const handleTextChange = (0, import_react48.useCallback)(
    (text) => {
      const sanitized = sanitizeInput(text);
      dispatch({
        type: "SET_USER_DESCRIPTION",
        description: sanitized
      });
    },
    [dispatch]
  );
  const handleGenerate = (0, import_react48.useCallback)(
    async (userDescription, dispatch2, config3) => {
      const abortController = new AbortController();
      abortControllerRef.current = abortController;
      try {
        const generated = await subagentGenerator(
          userDescription,
          config3,
          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_react48.useCallback)(async () => {
    if (!state.canProceed || state.isGenerating) {
      return;
    }
    const inputValue = state.userDescription.trim();
    if (!inputValue) {
      return;
    }
    dispatch({ type: "SET_GENERATING", isGenerating: true });
    try {
      if (!config2) {
        throw new Error("Configuration not available");
      }
      await handleGenerate(inputValue, dispatch, config2);
    } catch (error2) {
      dispatch({ type: "SET_GENERATING", isGenerating: false });
      if (error2 instanceof Error && error2.name === "AbortError") {
        return;
      }
      dispatch({
        type: "SET_VALIDATION_ERRORS",
        errors: [
          t4("Failed to generate subagent: {{error}}", {
            error: error2 instanceof Error ? error2.message : "Unknown error"
          })
        ]
      });
    }
  }, [
    state.canProceed,
    state.isGenerating,
    state.userDescription,
    dispatch,
    config2,
    handleGenerate
  ]);
  const handleGenerationKeypress = (0, import_react48.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 = t4(
    "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)(Text3, { color: theme.text.secondary, children: t4(
      "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)(Text3, { color: theme.text.accent, children: t4("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_react49 = __toESM(require_react(), 1);
var import_jsx_runtime23 = __toESM(require_jsx_runtime(), 1);
function ToolSelector({
  tools = [],
  onSelect,
  config: config2
}) {
  const {
    toolCategories,
    readTools,
    editTools,
    executeTools,
    initialCategory
  } = (0, import_react49.useMemo)(() => {
    if (!config2) {
      return {
        toolCategories: [
          {
            id: "all",
            name: t4("All Tools (Default)"),
            tools: []
          }
        ],
        readTools: [],
        editTools: [],
        executeTools: [],
        initialCategory: "all"
      };
    }
    const toolRegistry = config2.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: t4("All Tools"),
        tools: []
      },
      {
        id: "read",
        name: t4("Read-only Tools"),
        tools: readTools2
      },
      {
        id: "edit",
        name: t4("Read & Edit Tools"),
        tools: [...readTools2, ...editTools2]
      },
      {
        id: "execute",
        name: t4("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
    };
  }, [config2, tools]);
  const [selectedCategory, setSelectedCategory] = (0, import_react49.useState)(initialCategory);
  (0, import_react49.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)(Text3, { color: theme.text.secondary, children: t4("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)(Text3, { color: theme.text.secondary, children: t4("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)(Text3, { color: theme.text.secondary, children: [
            "\u2022 ",
            t4("Read-only tools:"),
            " ",
            categoryReadTools.join(", ")
          ] }),
          categoryEditTools.length > 0 && /* @__PURE__ */ (0, import_jsx_runtime23.jsxs)(Text3, { color: theme.text.secondary, children: [
            "\u2022 ",
            t4("Edit tools:"),
            " ",
            categoryEditTools.join(", ")
          ] }),
          categoryExecuteTools.length > 0 && /* @__PURE__ */ (0, import_jsx_runtime23.jsxs)(Text3, { color: theme.text.secondary, children: [
            "\u2022 ",
            t4("Execution tools:"),
            " ",
            categoryExecuteTools.join(", ")
          ] })
        ] });
      })() })
    ] }) : null })
  ] });
}
__name(ToolSelector, "ToolSelector");

// packages/cli/src/ui/components/subagents/create/ColorSelector.tsx
init_esbuild_shims();
var import_react50 = __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_react50.useState)(color);
  (0, import_react50.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)(Text3, { color: theme.text.secondary, children: "Preview:" }),
      /* @__PURE__ */ (0, import_jsx_runtime24.jsx)(Box_default, { marginLeft: 2, children: /* @__PURE__ */ (0, import_jsx_runtime24.jsx)(Text3, { color: currentColor.value, children: ` ${agentName} ` }) })
    ] })
  ] });
}
__name(ColorSelector, "ColorSelector");

// packages/cli/src/ui/components/subagents/create/CreationSummary.tsx
init_esbuild_shims();
var import_react52 = __toESM(require_react(), 1);

// packages/cli/src/ui/hooks/useLaunchEditor.ts
init_esbuild_shims();
var import_react51 = __toESM(require_react(), 1);
import { spawnSync as spawnSync5 } from "child_process";
var commandExistsCache = /* @__PURE__ */ new Map();
function commandExists3(cmd) {
  if (commandExistsCache.has(cmd)) {
    return commandExistsCache.get(cmd);
  }
  const exists2 = commandExists(cmd);
  commandExistsCache.set(cmd, exists2);
  return exists2;
}
__name(commandExists3, "commandExists");
function getExecutableCommand(editorType) {
  const commandConfig = editorCommands[editorType];
  const commands = process.platform === "win32" ? commandConfig.win32 : commandConfig.default;
  const availableCommand = commands.find((cmd) => commandExists3(cmd));
  if (!availableCommand) {
    throw new Error(
      `No available editor command found for ${editorType}. Tried: ${commands.join(", ")}. Please install one of these editors or set a different preferredEditor in settings.`
    );
  }
  return availableCommand;
}
__name(getExecutableCommand, "getExecutableCommand");
function getEditorCommand(preferredEditor) {
  if (preferredEditor) {
    return getExecutableCommand(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_react51.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 needsShell = process.platform === "win32" && (editorCommand2.endsWith(".cmd") || editorCommand2.endsWith(".bat"));
        const { status, error: error2 } = spawnSync5(editorCommand2, editorArgs, {
          stdio: "inherit",
          shell: needsShell
        });
        if (error2) throw error2;
        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);
var debugLogger98 = createDebugLogger("SUBAGENT_CREATION_SUMMARY");
function CreationSummary({
  state,
  onPrevious: _onPrevious,
  onCancel,
  config: config2
}) {
  const [saveError, setSaveError] = (0, import_react52.useState)(null);
  const [saveSuccess, setSaveSuccess] = (0, import_react52.useState)(false);
  const [warnings, setWarnings] = (0, import_react52.useState)([]);
  const launchEditor = useLaunchEditor();
  const truncateText2 = /* @__PURE__ */ __name((text, maxLength) => {
    if (text.length <= maxLength) return text;
    return text.substring(0, maxLength - 3) + "...";
  }, "truncateText");
  (0, import_react52.useEffect)(() => {
    const checkWarnings = /* @__PURE__ */ __name(async () => {
      if (!config2 || !state.generatedName) return;
      const allWarnings = [];
      try {
        const subagentManager = config2.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(
                t4(
                  'Name "{{name}}" already exists at {{level}} level - will overwrite existing subagent',
                  { name: state.generatedName, level: conflictLevel }
                )
              );
            } else if (targetLevel === "project") {
              allWarnings.push(
                t4(
                  'Name "{{name}}" exists at user level - project level will take precedence',
                  { name: state.generatedName }
                )
              );
            } else {
              allWarnings.push(
                t4(
                  'Name "{{name}}" exists at project level - existing subagent will take precedence',
                  { name: state.generatedName }
                )
              );
            }
          }
        }
      } catch (error2) {
        debugLogger98.warn("Error checking subagent name availability:", error2);
      }
      if (state.generatedDescription.length > 300) {
        allWarnings.push(
          t4("Description is over {{length}} characters", {
            length: state.generatedDescription.length.toString()
          })
        );
      }
      if (state.generatedSystemPrompt.length > 1e4) {
        allWarnings.push(
          t4("System prompt is over {{length}} characters", {
            length: state.generatedSystemPrompt.length.toString()
          })
        );
      }
      setWarnings(allWarnings);
    }, "checkWarnings");
    checkWarnings();
  }, [
    config2,
    state.generatedName,
    state.generatedDescription,
    state.generatedSystemPrompt,
    state.location
  ]);
  const toolsDisplay = state.selectedTools.length === 0 ? "*" : state.selectedTools.join(", ");
  const saveSubagent = (0, import_react52.useCallback)(async () => {
    if (!config2) {
      throw new Error("Configuration not available");
    }
    const subagentManager = config2.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, config2]);
  const showSuccessAndClose = (0, import_react52.useCallback)(() => {
    setSaveSuccess(true);
    setTimeout(() => {
      onCancel();
    }, 2e3);
  }, [onCancel]);
  const handleSave = (0, import_react52.useCallback)(async () => {
    setSaveError(null);
    try {
      await saveSubagent();
      showSuccessAndClose();
    } catch (error2) {
      setSaveError(
        error2 instanceof Error ? error2.message : "Unknown error occurred"
      );
    }
  }, [saveSubagent, showSuccessAndClose]);
  const handleEdit = (0, import_react52.useCallback)(async () => {
    setSaveError(null);
    try {
      const subagentManager = await saveSubagent();
      const subagentFilePath = subagentManager.getSubagentPath(
        state.generatedName,
        state.location
      );
      await launchEditor(subagentFilePath);
      showSuccessAndClose();
    } catch (error2) {
      setSaveError(
        t4("Failed to save and edit subagent: {{error}}", {
          error: error2 instanceof Error ? error2.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)(Text3, { bold: true, color: theme.status.success, children: t4("\u2705 Subagent Created Successfully!") }) }),
      /* @__PURE__ */ (0, import_jsx_runtime25.jsx)(Box_default, { children: /* @__PURE__ */ (0, import_jsx_runtime25.jsx)(Text3, { children: t4('Subagent "{{name}}" has been saved to {{level}} level.', {
        name: state.generatedName,
        level: state.location
      }) }) })
    ] });
  }
  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)(Text3, { color: theme.text.primary, children: t4("Name: ") }),
        /* @__PURE__ */ (0, import_jsx_runtime25.jsx)(Text3, { color: getColorForDisplay(state.color), children: state.generatedName })
      ] }),
      /* @__PURE__ */ (0, import_jsx_runtime25.jsxs)(Box_default, { children: [
        /* @__PURE__ */ (0, import_jsx_runtime25.jsx)(Text3, { color: theme.text.primary, children: t4("Location: ") }),
        /* @__PURE__ */ (0, import_jsx_runtime25.jsx)(Text3, { children: state.location === "project" ? t4("Project Level (.qwen/agents/)") : t4("User Level (~/.qwen/agents/)") })
      ] }),
      /* @__PURE__ */ (0, import_jsx_runtime25.jsxs)(Box_default, { children: [
        /* @__PURE__ */ (0, import_jsx_runtime25.jsx)(Text3, { color: theme.text.primary, children: t4("Tools: ") }),
        /* @__PURE__ */ (0, import_jsx_runtime25.jsx)(Text3, { children: toolsDisplay })
      ] }),
      shouldShowColor(state.color) && /* @__PURE__ */ (0, import_jsx_runtime25.jsxs)(Box_default, { children: [
        /* @__PURE__ */ (0, import_jsx_runtime25.jsx)(Text3, { color: theme.text.primary, children: t4("Color: ") }),
        /* @__PURE__ */ (0, import_jsx_runtime25.jsx)(Text3, { color: getColorForDisplay(state.color), children: state.color })
      ] }),
      /* @__PURE__ */ (0, import_jsx_runtime25.jsx)(Box_default, { marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime25.jsx)(Text3, { color: theme.text.primary, children: t4("Description:") }) }),
      /* @__PURE__ */ (0, import_jsx_runtime25.jsx)(Box_default, { padding: 1, paddingBottom: 0, children: /* @__PURE__ */ (0, import_jsx_runtime25.jsx)(Text3, { wrap: "wrap", children: truncateText2(state.generatedDescription, 250) }) }),
      /* @__PURE__ */ (0, import_jsx_runtime25.jsx)(Box_default, { marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime25.jsx)(Text3, { color: theme.text.primary, children: t4("System Prompt:") }) }),
      /* @__PURE__ */ (0, import_jsx_runtime25.jsx)(Box_default, { padding: 1, paddingBottom: 0, children: /* @__PURE__ */ (0, import_jsx_runtime25.jsx)(Text3, { wrap: "wrap", children: truncateText2(state.generatedSystemPrompt, 250) }) })
    ] }),
    saveError && /* @__PURE__ */ (0, import_jsx_runtime25.jsxs)(Box_default, { flexDirection: "column", children: [
      /* @__PURE__ */ (0, import_jsx_runtime25.jsx)(Text3, { bold: true, color: theme.status.error, children: t4("\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)(Text3, { 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)(Text3, { bold: true, color: theme.status.warning, children: t4("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)(Text3, { 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_react53 = __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: validate3
}) {
  const submit = (0, import_react53.useCallback)(() => {
    const value = initialText ? initialText.trim() : "";
    const error2 = validate3 ? validate3(value) : value.length === 0 ? "Please enter a value." : null;
    if (error2) {
      dispatch({ type: "SET_VALIDATION_ERRORS", errors: [error2] });
      return;
    }
    dispatch({ type: "SET_VALIDATION_ERRORS", errors: [] });
    onNext();
  }, [dispatch, onNext, validate3, 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)(Text3, { 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: config2
}) {
  const [state, dispatch] = (0, import_react54.useReducer)(wizardReducer, initialWizardState);
  const handleNext = (0, import_react54.useCallback)(() => {
    dispatch({ type: "GO_TO_NEXT_STEP" });
  }, []);
  const handlePrevious = (0, import_react54.useCallback)(() => {
    dispatch({ type: "GO_TO_PREVIOUS_STEP" });
  }, []);
  const handleCancel = (0, import_react54.useCallback)(() => {
    dispatch({ type: "RESET_WIZARD" });
    onClose();
  }, [onClose]);
  useKeypress(
    (key) => {
      if (key.name !== "escape") {
        return;
      }
      const kind2 = getStepKind(state.generationMethod, state.currentStep);
      if (kind2 === "LLM_DESC" && state.isGenerating) {
        return;
      }
      if (state.currentStep === WIZARD_STEPS.LOCATION_SELECTION) {
        handleCancel();
      } else {
        handlePrevious();
      }
    },
    { isActive: true }
  );
  const stepProps = (0, import_react54.useMemo)(
    () => ({
      state,
      dispatch,
      onNext: handleNext,
      onPrevious: handlePrevious,
      onCancel: handleCancel,
      config: config2
    }),
    [state, dispatch, handleNext, handlePrevious, handleCancel, config2]
  );
  const renderStepHeader = (0, import_react54.useCallback)(() => {
    const getStepHeaderText = /* @__PURE__ */ __name(() => {
      const kind2 = getStepKind(state.generationMethod, state.currentStep);
      const n3 = state.currentStep;
      switch (kind2) {
        case "LOCATION":
          return t4("Step {{n}}: Choose Location", { n: n3.toString() });
        case "GEN_METHOD":
          return t4("Step {{n}}: Choose Generation Method", { n: n3.toString() });
        case "LLM_DESC":
          return t4("Step {{n}}: Describe Your Subagent", { n: n3.toString() });
        case "MANUAL_NAME":
          return t4("Step {{n}}: Enter Subagent Name", { n: n3.toString() });
        case "MANUAL_PROMPT":
          return t4("Step {{n}}: Enter System Prompt", { n: n3.toString() });
        case "MANUAL_DESC":
          return t4("Step {{n}}: Enter Description", { n: n3.toString() });
        case "TOOLS":
          return t4("Step {{n}}: Select Tools", { n: n3.toString() });
        case "COLOR":
          return t4("Step {{n}}: Choose Background Color", { n: n3.toString() });
        case "FINAL":
          return t4("Step {{n}}: Confirm and Save", { n: n3.toString() });
        default:
          return t4("Unknown Step");
      }
    }, "getStepHeaderText");
    return /* @__PURE__ */ (0, import_jsx_runtime27.jsx)(Box_default, { children: /* @__PURE__ */ (0, import_jsx_runtime27.jsx)(Text3, { bold: true, children: getStepHeaderText() }) });
  }, [state.currentStep, state.generationMethod]);
  const renderDebugContent = (0, import_react54.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)(Text3, { color: theme.status.warning, bold: true, children: "Debug Info:" }),
      /* @__PURE__ */ (0, import_jsx_runtime27.jsxs)(Text3, { color: theme.text.secondary, children: [
        "Step: ",
        state.currentStep
      ] }),
      /* @__PURE__ */ (0, import_jsx_runtime27.jsxs)(Text3, { color: theme.text.secondary, children: [
        "Can Proceed: ",
        state.canProceed ? "Yes" : "No"
      ] }),
      /* @__PURE__ */ (0, import_jsx_runtime27.jsxs)(Text3, { color: theme.text.secondary, children: [
        "Generating: ",
        state.isGenerating ? "Yes" : "No"
      ] }),
      /* @__PURE__ */ (0, import_jsx_runtime27.jsxs)(Text3, { color: theme.text.secondary, children: [
        "Location: ",
        state.location
      ] }),
      /* @__PURE__ */ (0, import_jsx_runtime27.jsxs)(Text3, { color: theme.text.secondary, children: [
        "Method: ",
        state.generationMethod
      ] }),
      state.validationErrors.length > 0 && /* @__PURE__ */ (0, import_jsx_runtime27.jsxs)(Text3, { 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_react54.useCallback)(() => {
    const getNavigationInstructions = /* @__PURE__ */ __name(() => {
      const kind2 = getStepKind(state.generationMethod, state.currentStep);
      if (kind2 === "LLM_DESC" && state.isGenerating) {
        return t4("Esc to cancel");
      }
      if (getStepKind(state.generationMethod, state.currentStep) === "FINAL") {
        return t4("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 ? t4("\u2191\u2193 to navigate, ") : "";
      const escAction = state.currentStep === WIZARD_STEPS.LOCATION_SELECTION ? t4("cancel") : t4("go back");
      return t4("Press Enter to continue, {{navigation}}Esc to {{action}}", {
        navigation: navigationPart,
        action: escAction
      });
    }, "getNavigationInstructions");
    return /* @__PURE__ */ (0, import_jsx_runtime27.jsx)(Box_default, { children: /* @__PURE__ */ (0, import_jsx_runtime27.jsx)(Text3, { color: theme.text.secondary, children: getNavigationInstructions() }) });
  }, [state.currentStep, state.isGenerating, state.generationMethod]);
  const renderStepContent = (0, import_react54.useCallback)(() => {
    const kind2 = getStepKind(state.generationMethod, state.currentStep);
    switch (kind2) {
      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: t4("Enter a clear, unique name for this subagent."),
            placeholder: t4("e.g., Code Reviewer"),
            height: 1,
            initialText: state.generatedName,
            onChange: (text) => {
              const value = text;
              dispatch({ type: "SET_GENERATED_NAME", name: value });
            },
            validate: (text) => text.trim().length === 0 ? t4("Name cannot be empty.") : null
          },
          "manual-name"
        );
      case "MANUAL_PROMPT":
        return /* @__PURE__ */ (0, import_jsx_runtime27.jsx)(
          TextEntryStep,
          {
            state,
            dispatch,
            onNext: handleNext,
            description: t4(
              "Write the system prompt that defines this subagent's behavior. Be comprehensive for best results."
            ),
            placeholder: t4("e.g., You are an expert code reviewer..."),
            height: 10,
            initialText: state.generatedSystemPrompt,
            onChange: (text) => {
              dispatch({
                type: "SET_GENERATED_SYSTEM_PROMPT",
                systemPrompt: text
              });
            },
            validate: (text) => text.trim().length === 0 ? t4("System prompt cannot be empty.") : null
          },
          "manual-prompt"
        );
      case "MANUAL_DESC":
        return /* @__PURE__ */ (0, import_jsx_runtime27.jsx)(
          TextEntryStep,
          {
            state,
            dispatch,
            onNext: handleNext,
            description: t4(
              "Describe when and how this subagent should be used."
            ),
            placeholder: t4(
              "e.g., Reviews code for best practices and potential bugs."
            ),
            height: 6,
            initialText: state.generatedDescription,
            onChange: (text) => {
              dispatch({
                type: "SET_GENERATED_DESCRIPTION",
                description: text
              });
            },
            validate: (text) => text.trim().length === 0 ? t4("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: config2
          }
        );
      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.jsx)(Text3, { color: theme.status.error, children: t4("Invalid step: {{step}}", {
          step: state.currentStep.toString()
        }) }) });
    }
  }, [stepProps, state, config2, 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_react58 = __toESM(require_react(), 1);

// packages/cli/src/ui/components/subagents/manage/AgentSelectionStep.tsx
init_esbuild_shims();
var import_react55 = __toESM(require_react(), 1);
var import_jsx_runtime28 = __toESM(require_jsx_runtime(), 1);
var AgentSelectionStep = /* @__PURE__ */ __name(({
  availableAgents,
  onAgentSelect
}) => {
  const [navigation, setNavigation] = (0, import_react55.useState)({
    currentBlock: "project",
    projectIndex: 0,
    userIndex: 0,
    builtinIndex: 0,
    extensionIndex: 0
  });
  const projectAgents = (0, import_react55.useMemo)(
    () => availableAgents.filter((agent) => agent.level === "project"),
    [availableAgents]
  );
  const userAgents = (0, import_react55.useMemo)(
    () => availableAgents.filter((agent) => agent.level === "user"),
    [availableAgents]
  );
  const builtinAgents = (0, import_react55.useMemo)(
    () => availableAgents.filter((agent) => agent.level === "builtin"),
    [availableAgents]
  );
  const extensionAgents = (0, import_react55.useMemo)(
    () => availableAgents.filter((agent) => agent.level === "extension"),
    [availableAgents]
  );
  const projectNames = (0, import_react55.useMemo)(
    () => new Set(projectAgents.map((agent) => agent.name)),
    [projectAgents]
  );
  (0, import_react55.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" }));
    } else if (extensionAgents.length > 0) {
      setNavigation((prev) => ({ ...prev, currentBlock: "extension" }));
    }
  }, [projectAgents, userAgents, builtinAgents, extensionAgents]);
  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 if (extensionAgents.length > 0) {
              return {
                ...prev,
                currentBlock: "extension",
                extensionIndex: extensionAgents.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 if (extensionAgents.length > 0) {
              return {
                ...prev,
                currentBlock: "extension",
                extensionIndex: extensionAgents.length - 1
              };
            } else {
              return { ...prev, userIndex: userAgents.length - 1 };
            }
          } else if (prev.currentBlock === "builtin") {
            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 if (extensionAgents.length > 0) {
              return {
                ...prev,
                currentBlock: "extension",
                extensionIndex: extensionAgents.length - 1
              };
            } else {
              return { ...prev, builtinIndex: builtinAgents.length - 1 };
            }
          } else {
            if (prev.extensionIndex > 0) {
              return { ...prev, extensionIndex: prev.extensionIndex - 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 if (builtinAgents.length > 0) {
              return {
                ...prev,
                currentBlock: "builtin",
                builtinIndex: builtinAgents.length - 1
              };
            } else {
              return { ...prev, extensionIndex: extensionAgents.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 if (extensionAgents.length > 0) {
              return { ...prev, currentBlock: "extension", extensionIndex: 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 (extensionAgents.length > 0) {
              return { ...prev, currentBlock: "extension", extensionIndex: 0 };
            } else if (projectAgents.length > 0) {
              return { ...prev, currentBlock: "project", projectIndex: 0 };
            } else {
              return { ...prev, userIndex: 0 };
            }
          } else if (prev.currentBlock === "builtin") {
            if (prev.builtinIndex < builtinAgents.length - 1) {
              return { ...prev, builtinIndex: prev.builtinIndex + 1 };
            } else if (extensionAgents.length > 0) {
              return { ...prev, currentBlock: "extension", extensionIndex: 0 };
            } 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 (prev.extensionIndex < extensionAgents.length - 1) {
              return { ...prev, extensionIndex: prev.extensionIndex + 1 };
            } else if (projectAgents.length > 0) {
              return { ...prev, currentBlock: "project", projectIndex: 0 };
            } 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, extensionIndex: 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 if (navigation.currentBlock === "builtin") {
          globalIndex = projectAgents.length + userAgents.length + navigation.builtinIndex;
        } else {
          globalIndex = projectAgents.length + userAgents.length + builtinAgents.length + navigation.extensionIndex;
        }
        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)(Text3, { color: theme.text.secondary, children: t4("No subagents found.") }),
      /* @__PURE__ */ (0, import_jsx_runtime28.jsx)(Text3, { color: theme.text.secondary, children: t4("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)(Text3, { color: isSelected ? theme.text.accent : theme.text.primary, children: isSelected ? "\u25CF" : " " }) }),
      /* @__PURE__ */ (0, import_jsx_runtime28.jsxs)(Text3, { color: textColor, wrap: "truncate", children: [
        agent.name,
        agent.isBuiltin && /* @__PURE__ */ (0, import_jsx_runtime28.jsxs)(Text3, { color: isSelected ? theme.text.accent : theme.text.secondary, children: [
          " ",
          t4("(built-in)")
        ] }),
        agent.level === "user" && projectNames.has(agent.name) && /* @__PURE__ */ (0, import_jsx_runtime28.jsxs)(
          Text3,
          {
            color: isSelected ? theme.status.warning : theme.text.secondary,
            children: [
              " ",
              t4("(overridden by project level agent)")
            ]
          }
        )
      ] })
    ] }, `${agent.name}-${agent.level}`);
  }, "renderAgentItem");
  const enabledAgentsCount = projectAgents.length + userAgents.filter((agent) => !projectNames.has(agent.name)).length + builtinAgents.length + extensionAgents.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.jsx)(Text3, { color: theme.text.primary, bold: true, children: t4("Project Level ({{path}})", {
        path: 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.jsx)(Text3, { color: theme.text.primary, bold: true, children: t4("User Level ({{path}})", {
            path: 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",
        marginBottom: extensionAgents.length > 0 ? 1 : 0,
        children: [
          /* @__PURE__ */ (0, import_jsx_runtime28.jsx)(Text3, { color: theme.text.primary, bold: true, children: t4("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);
          }) })
        ]
      }
    ),
    extensionAgents.length > 0 && /* @__PURE__ */ (0, import_jsx_runtime28.jsxs)(Box_default, { flexDirection: "column", children: [
      /* @__PURE__ */ (0, import_jsx_runtime28.jsx)(Text3, { color: theme.text.primary, bold: true, children: t4("Extension Agents") }),
      /* @__PURE__ */ (0, import_jsx_runtime28.jsx)(Box_default, { marginTop: 1, flexDirection: "column", children: extensionAgents.map((agent, index) => {
        const isSelected = navigation.currentBlock === "extension" && navigation.extensionIndex === index;
        return renderAgentItem(agent, index, isSelected);
      }) })
    ] }),
    (projectAgents.length > 0 || userAgents.length > 0 || builtinAgents.length > 0 || extensionAgents.length > 0) && /* @__PURE__ */ (0, import_jsx_runtime28.jsx)(Box_default, { marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime28.jsx)(Text3, { color: theme.text.secondary, children: t4("Using: {{count}} agents", {
      count: enabledAgentsCount.toString()
    }) }) })
  ] });
}, "AgentSelectionStep");

// packages/cli/src/ui/components/subagents/manage/ActionSelectionStep.tsx
init_esbuild_shims();
var import_react56 = __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_react56.useState)(null);
  const allActions = [
    {
      key: "view",
      get label() {
        return t4("View Agent");
      },
      value: "view"
    },
    {
      key: "edit",
      get label() {
        return t4("Edit Agent");
      },
      value: "edit"
    },
    {
      key: "delete",
      get label() {
        return t4("Delete Agent");
      },
      value: "delete"
    },
    {
      key: "back",
      get label() {
        return t4("Back");
      },
      value: "back"
    }
  ];
  const isReadOnly = selectedAgent?.isBuiltin || selectedAgent?.level === "extension";
  const actions = isReadOnly ? 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)(Text3, { color: theme.status.error, children: t4("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)(Text3, { color: theme.text.primary, children: t4("File Path: ") }),
      /* @__PURE__ */ (0, import_jsx_runtime30.jsx)(Text3, { children: agent.filePath })
    ] }),
    /* @__PURE__ */ (0, import_jsx_runtime30.jsxs)(Box_default, { children: [
      /* @__PURE__ */ (0, import_jsx_runtime30.jsx)(Text3, { color: theme.text.primary, children: t4("Tools: ") }),
      /* @__PURE__ */ (0, import_jsx_runtime30.jsx)(Text3, { children: toolsDisplay })
    ] }),
    shouldShowColor(agent.color) && /* @__PURE__ */ (0, import_jsx_runtime30.jsxs)(Box_default, { children: [
      /* @__PURE__ */ (0, import_jsx_runtime30.jsx)(Text3, { color: theme.text.primary, children: t4("Color: ") }),
      /* @__PURE__ */ (0, import_jsx_runtime30.jsx)(Text3, { color: getColorForDisplay(agent.color), children: agent.color })
    ] }),
    /* @__PURE__ */ (0, import_jsx_runtime30.jsx)(Box_default, { marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime30.jsx)(Text3, { color: theme.text.primary, children: t4("Description:") }) }),
    /* @__PURE__ */ (0, import_jsx_runtime30.jsx)(Box_default, { padding: 1, paddingBottom: 0, children: /* @__PURE__ */ (0, import_jsx_runtime30.jsx)(Text3, { wrap: "wrap", children: agent.description }) }),
    /* @__PURE__ */ (0, import_jsx_runtime30.jsx)(Box_default, { marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime30.jsx)(Text3, { color: theme.text.primary, children: t4("System Prompt:") }) }),
    /* @__PURE__ */ (0, import_jsx_runtime30.jsx)(Box_default, { padding: 1, paddingBottom: 0, children: /* @__PURE__ */ (0, import_jsx_runtime30.jsx)(Text3, { wrap: "wrap", children: agent.systemPrompt }) })
  ] }) });
}, "AgentViewerStep");

// packages/cli/src/ui/components/subagents/manage/AgentEditStep.tsx
init_esbuild_shims();
var import_react57 = __toESM(require_react(), 1);
var import_jsx_runtime31 = __toESM(require_jsx_runtime(), 1);
var editOptions = [
  {
    id: "editor",
    get label() {
      return t4("Open in editor");
    }
  },
  {
    id: "tools",
    get label() {
      return t4("Edit tools");
    }
  },
  {
    id: "color",
    get label() {
      return t4("Edit color");
    }
  }
];
function EditOptionsStep({
  selectedAgent,
  onNavigateToStep
}) {
  const [selectedOption, setSelectedOption] = (0, import_react57.useState)("editor");
  const [error2, setError] = (0, import_react57.useState)(null);
  const launchEditor = useLaunchEditor();
  const handleHighlight = /* @__PURE__ */ __name((selectedValue) => {
    setSelectedOption(selectedValue);
  }, "handleHighlight");
  const handleSelect = (0, import_react57.useCallback)(
    async (selectedValue) => {
      if (!selectedAgent) return;
      setError(null);
      if (selectedValue === "editor") {
        try {
          if (!selectedAgent.filePath) {
            throw new Error("Agent has no file path");
          }
          await launchEditor(selectedAgent.filePath);
        } catch (err) {
          setError(
            t4("Failed to launch editor: {{error}}", {
              error: 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
      }
    ) }),
    error2 && /* @__PURE__ */ (0, import_jsx_runtime31.jsxs)(Box_default, { flexDirection: "column", children: [
      /* @__PURE__ */ (0, import_jsx_runtime31.jsx)(Text3, { bold: true, color: theme.status.error, children: t4("\u274C Error:") }),
      /* @__PURE__ */ (0, import_jsx_runtime31.jsx)(Box_default, { flexDirection: "column", padding: 1, paddingBottom: 0, children: /* @__PURE__ */ (0, import_jsx_runtime31.jsx)(Text3, { color: theme.status.error, wrap: "wrap", children: error2 }) })
    ] })
  ] });
}
__name(EditOptionsStep, "EditOptionsStep");

// packages/cli/src/ui/components/subagents/manage/AgentDeleteStep.tsx
init_esbuild_shims();
var import_jsx_runtime32 = __toESM(require_jsx_runtime(), 1);
var debugLogger99 = createDebugLogger("AGENT_DELETE_STEP");
function AgentDeleteStep({
  selectedAgent,
  onDelete,
  onNavigateBack
}) {
  useKeypress(
    async (key) => {
      if (!selectedAgent) return;
      if (key.name === "y" || key.name === "return") {
        try {
          await onDelete(selectedAgent);
        } catch (error2) {
          debugLogger99.error("Failed to delete agent:", error2);
        }
      } 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)(Text3, { color: theme.status.error, children: t4("No agent selected") }) });
  }
  return /* @__PURE__ */ (0, import_jsx_runtime32.jsx)(Box_default, { flexDirection: "column", gap: 1, children: /* @__PURE__ */ (0, import_jsx_runtime32.jsx)(Text3, { color: theme.status.error, children: t4('Are you sure you want to delete agent "{{name}}"?', {
    name: selectedAgent.name
  }) }) });
}
__name(AgentDeleteStep, "AgentDeleteStep");

// packages/cli/src/ui/components/subagents/manage/AgentsManagerDialog.tsx
var import_jsx_runtime33 = __toESM(require_jsx_runtime(), 1);
var debugLogger100 = createDebugLogger("AGENTS_MANAGER_DIALOG");
function AgentsManagerDialog({
  onClose,
  config: config2
}) {
  const [availableAgents, setAvailableAgents] = (0, import_react58.useState)([]);
  const [selectedAgentIndex, setSelectedAgentIndex] = (0, import_react58.useState)(-1);
  const [navigationStack, setNavigationStack] = (0, import_react58.useState)([
    MANAGEMENT_STEPS.AGENT_SELECTION
  ]);
  const selectedAgent = (0, import_react58.useMemo)(
    () => selectedAgentIndex >= 0 ? availableAgents[selectedAgentIndex] : null,
    [availableAgents, selectedAgentIndex]
  );
  const loadAgents = (0, import_react58.useCallback)(async () => {
    if (!config2) return;
    const manager = config2.getSubagentManager();
    const allAgents = await manager.listSubagents({ force: true });
    setAvailableAgents(allAgents);
  }, [config2]);
  (0, import_react58.useEffect)(() => {
    loadAgents();
  }, [loadAgents]);
  const getCurrentStep = (0, import_react58.useCallback)(
    () => navigationStack[navigationStack.length - 1] || MANAGEMENT_STEPS.AGENT_SELECTION,
    [navigationStack]
  );
  const handleSelectAgent = (0, import_react58.useCallback)((agentIndex) => {
    setSelectedAgentIndex(agentIndex);
    setNavigationStack((prev) => [...prev, MANAGEMENT_STEPS.ACTION_SELECTION]);
  }, []);
  const handleNavigateToStep = (0, import_react58.useCallback)((step) => {
    setNavigationStack((prev) => [...prev, step]);
  }, []);
  const handleNavigateBack = (0, import_react58.useCallback)(() => {
    setNavigationStack((prev) => {
      if (prev.length <= 1) {
        return prev;
      }
      return prev.slice(0, -1);
    });
  }, []);
  const handleDeleteAgent = (0, import_react58.useCallback)(
    async (agent) => {
      if (!config2) return;
      try {
        const subagentManager = config2.getSubagentManager();
        await subagentManager.deleteSubagent(
          agent.name,
          agent.level,
          agent.extensionName
        );
        await loadAgents();
        setNavigationStack([MANAGEMENT_STEPS.AGENT_SELECTION]);
        setSelectedAgentIndex(-1);
      } catch (error2) {
        debugLogger100.error("Failed to delete agent:", error2);
        throw error2;
      }
    },
    [config2, 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_react58.useMemo)(
    () => ({
      onNavigateToStep: handleNavigateToStep,
      onNavigateBack: handleNavigateBack
    }),
    [handleNavigateToStep, handleNavigateBack]
  );
  const renderStepHeader = (0, import_react58.useCallback)(() => {
    const currentStep = getCurrentStep();
    const getStepHeaderText = /* @__PURE__ */ __name(() => {
      switch (currentStep) {
        case MANAGEMENT_STEPS.AGENT_SELECTION:
          return t4("Agents");
        case MANAGEMENT_STEPS.ACTION_SELECTION:
          return t4("Choose Action");
        case MANAGEMENT_STEPS.AGENT_VIEWER:
          return selectedAgent?.name;
        case MANAGEMENT_STEPS.EDIT_OPTIONS:
          return t4("Edit {{name}}", { name: selectedAgent?.name || "" });
        case MANAGEMENT_STEPS.EDIT_TOOLS:
          return t4("Edit Tools: {{name}}", { name: selectedAgent?.name || "" });
        case MANAGEMENT_STEPS.EDIT_COLOR:
          return t4("Edit Color: {{name}}", { name: selectedAgent?.name || "" });
        case MANAGEMENT_STEPS.DELETE_CONFIRMATION:
          return t4("Delete {{name}}", { name: selectedAgent?.name || "" });
        default:
          return t4("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)(Text3, { bold: true, color: headerColor, children: getStepHeaderText() }) });
  }, [getCurrentStep, selectedAgent]);
  const renderStepFooter = (0, import_react58.useCallback)(() => {
    const currentStep = getCurrentStep();
    const getNavigationInstructions = /* @__PURE__ */ __name(() => {
      if (currentStep === MANAGEMENT_STEPS.AGENT_SELECTION) {
        if (availableAgents.length === 0) {
          return t4("Esc to close");
        }
        return t4("Enter to select, \u2191\u2193 to navigate, Esc to close");
      }
      if (currentStep === MANAGEMENT_STEPS.AGENT_VIEWER) {
        return t4("Esc to go back");
      }
      if (currentStep === MANAGEMENT_STEPS.DELETE_CONFIRMATION) {
        return t4("Enter to confirm, Esc to cancel");
      }
      return t4("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)(Text3, { color: theme.text.secondary, children: getNavigationInstructions() }) });
  }, [getCurrentStep, availableAgents]);
  const renderStepContent = (0, import_react58.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 && config2) {
                try {
                  const subagentManager = config2.getSubagentManager();
                  await subagentManager.updateSubagent(
                    selectedAgent.name,
                    { tools },
                    selectedAgent.level
                  );
                  await loadAgents();
                  handleNavigateBack();
                } catch (error2) {
                  debugLogger100.error("Failed to save agent changes:", error2);
                }
              }
            },
            config: config2
          }
        ) });
      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 && config2) {
                try {
                  const subagentManager = config2.getSubagentManager();
                  await subagentManager.updateSubagent(
                    selectedAgent.name,
                    { color },
                    selectedAgent.level
                  );
                  await loadAgents();
                  handleNavigateBack();
                } catch (error2) {
                  debugLogger100.error("Failed to save color changes:", error2);
                }
              }
            }
          }
        ) });
      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.jsx)(Text3, { color: theme.status.error, children: t4("Invalid step: {{step}}", { step: currentStep }) }) });
    }
  }, [
    getCurrentStep,
    availableAgents,
    selectedAgent,
    commonProps,
    config2,
    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_react60 = __toESM(require_react(), 1);

// packages/cli/src/ui/components/messages/ToolConfirmationMessage.tsx
init_esbuild_shims();
var import_react59 = __toESM(require_react(), 1);
var import_jsx_runtime34 = __toESM(require_jsx_runtime(), 1);
var ToolConfirmationMessage = /* @__PURE__ */ __name(({
  confirmationDetails,
  config: config2,
  isFocused = true,
  availableTerminalHeight,
  contentWidth,
  compactMode = false
}) => {
  const { onConfirm } = confirmationDetails;
  const settings = useSettings();
  const preferredEditor = settings.merged.general?.preferredEditor;
  const [ideClient, setIdeClient] = (0, import_react59.useState)(null);
  const [isDiffingEnabled, setIsDiffingEnabled] = (0, import_react59.useState)(false);
  (0, import_react59.useEffect)(() => {
    let isMounted = true;
    if (config2.getIdeMode()) {
      const getIdeClient = /* @__PURE__ */ __name(async () => {
        const client = await IdeClient.getInstance();
        if (isMounted) {
          setIdeClient(client);
          setIsDiffingEnabled(client?.isDiffingEnabled() ?? false);
        }
      }, "getIdeClient");
      getIdeClient();
    }
    return () => {
      isMounted = false;
    };
  }, [config2]);
  const handleConfirm = /* @__PURE__ */ __name(async (outcome) => {
    if (confirmationDetails.type === "edit") {
      if (config2.getIdeMode() && isDiffingEnabled) {
        const cliOutcome = outcome === ToolConfirmationOutcome.Cancel ? "rejected" : "accepted";
        await ideClient?.resolveDiffFromCli(
          confirmationDetails.filePath,
          cliOutcome
        );
      }
    }
    onConfirm(outcome);
  }, "handleConfirm");
  const isTrustedFolder = config2.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: t4("Yes, allow once"),
        value: ToolConfirmationOutcome.ProceedOnce
      },
      {
        key: "proceed-always",
        label: t4("Allow always"),
        value: ToolConfirmationOutcome.ProceedAlways
      },
      {
        key: "cancel",
        label: t4("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)(Text3, { wrap: "truncate", children: t4("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.jsxs)(Text3, { color: theme.text.primary, children: [
              t4("Modify in progress:"),
              " "
            ] }),
            /* @__PURE__ */ (0, import_jsx_runtime34.jsx)(Text3, { color: theme.status.success, children: t4("Save and close external editor to continue") })
          ]
        }
      );
    }
    question = t4("Apply this change?");
    options2.push({
      label: t4("Yes, allow once"),
      value: ToolConfirmationOutcome.ProceedOnce,
      key: "Yes, allow once"
    });
    if (isTrustedFolder) {
      options2.push({
        label: t4("Yes, allow always"),
        value: ToolConfirmationOutcome.ProceedAlways,
        key: "Yes, allow always"
      });
    }
    if ((!config2.getIdeMode() || !isDiffingEnabled) && preferredEditor) {
      options2.push({
        label: t4("Modify with external editor"),
        value: ToolConfirmationOutcome.ModifyWithEditor,
        key: "Modify with external editor"
      });
    }
    options2.push({
      label: t4("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(),
        contentWidth,
        settings
      }
    );
  } else if (confirmationDetails.type === "exec") {
    const executionProps = confirmationDetails;
    question = t4("Allow execution of: '{{command}}'?", {
      command: executionProps.rootCommand
    });
    options2.push({
      label: t4("Yes, allow once"),
      value: ToolConfirmationOutcome.ProceedOnce,
      key: "Yes, allow once"
    });
    if (isTrustedFolder) {
      options2.push({
        label: t4("Yes, allow always ..."),
        value: ToolConfirmationOutcome.ProceedAlways,
        key: "Yes, allow always ..."
      });
    }
    options2.push({
      label: t4("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(contentWidth, 1),
        children: /* @__PURE__ */ (0, import_jsx_runtime34.jsx)(Box_default, { children: /* @__PURE__ */ (0, import_jsx_runtime34.jsx)(Text3, { color: theme.text.link, children: executionProps.command }) })
      }
    ) }) });
  } else if (confirmationDetails.type === "plan") {
    const planProps = confirmationDetails;
    question = planProps.title;
    options2.push({
      key: "proceed-always",
      label: t4("Yes, and auto-accept edits"),
      value: ToolConfirmationOutcome.ProceedAlways
    });
    options2.push({
      key: "proceed-once",
      label: t4("Yes, and manually approve edits"),
      value: ToolConfirmationOutcome.ProceedOnce
    });
    options2.push({
      key: "cancel",
      label: t4("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(),
        contentWidth
      }
    ) });
  } else if (confirmationDetails.type === "info") {
    const infoProps = confirmationDetails;
    const displayUrls = infoProps.urls && !(infoProps.urls.length === 1 && infoProps.urls[0] === infoProps.prompt);
    question = t4("Do you want to proceed?");
    options2.push({
      label: t4("Yes, allow once"),
      value: ToolConfirmationOutcome.ProceedOnce,
      key: "Yes, allow once"
    });
    if (isTrustedFolder) {
      options2.push({
        label: t4("Yes, allow always"),
        value: ToolConfirmationOutcome.ProceedAlways,
        key: "Yes, allow always"
      });
    }
    options2.push({
      label: t4("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)(Text3, { color: theme.text.link, children: /* @__PURE__ */ (0, import_jsx_runtime34.jsx)(RenderInline, { text: infoProps.prompt, textColor: theme.text.link }) }),
      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)(Text3, { color: theme.text.primary, children: t4("URLs to fetch:") }),
        infoProps.urls.map((url2) => /* @__PURE__ */ (0, import_jsx_runtime34.jsxs)(Text3, { 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.jsx)(Text3, { color: theme.text.link, children: t4("MCP Server: {{server}}", { server: mcpProps.serverName }) }),
      /* @__PURE__ */ (0, import_jsx_runtime34.jsx)(Text3, { color: theme.text.link, children: t4("Tool: {{tool}}", { tool: mcpProps.toolName }) })
    ] });
    question = t4(
      'Allow execution of MCP tool "{{tool}}" from server "{{server}}"?',
      {
        tool: mcpProps.toolName,
        server: mcpProps.serverName
      }
    );
    options2.push({
      label: t4("Yes, allow once"),
      value: ToolConfirmationOutcome.ProceedOnce,
      key: "Yes, allow once"
    });
    if (isTrustedFolder) {
      options2.push({
        label: t4('Yes, always allow tool "{{tool}}" from server "{{server}}"', {
          tool: mcpProps.toolName,
          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: t4('Yes, always allow all tools from server "{{server}}"', {
          server: mcpProps.serverName
        }),
        value: ToolConfirmationOutcome.ProceedAlwaysServer,
        key: `Yes, always allow all tools from server "${mcpProps.serverName}"`
      });
    }
    options2.push({
      label: t4("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: contentWidth, 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)(Text3, { 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: config2
}) => {
  const [displayMode, setDisplayMode] = import_react60.default.useState("compact");
  const agentColor = (0, import_react60.useMemo)(() => {
    const colorOption = COLOR_OPTIONS.find(
      (option2) => option2.name === data.subagentColor
    );
    return colorOption?.value || theme.text.accent;
  }, [data.subagentColor]);
  const footerText = import_react60.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+e to show less, ctrl+f to show more.";
      }
      return "Press ctrl+e to show less.";
    }
    if (displayMode === "verbose") {
      return "Press ctrl+f to show less.";
    }
    return "";
  }, [displayMode, data]);
  useKeypress(
    (key) => {
      if (key.ctrl && key.name === "e") {
        setDisplayMode(
          (current) => current === "compact" ? "default" : "compact"
        );
      } else if (key.ctrl && key.name === "f") {
        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)(Text3, { 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)(Text3, { color: theme.text.secondary, children: [
            "+",
            data.toolCalls.length - 1,
            " more tool calls (ctrl+e 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,
            contentWidth: childWidth - 4,
            compactMode: true,
            config: config2
          }
        ) })
      ] }),
      data.status === "completed" && data.executionSummary && /* @__PURE__ */ (0, import_jsx_runtime35.jsx)(Box_default, { flexDirection: "row", marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime35.jsxs)(Text3, { 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)(Text3, { 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)(Text3, { 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: config2,
        isFocused: true,
        availableTerminalHeight: availableHeight,
        contentWidth: childWidth - 4,
        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)(Text3, { 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)(Text3, { color: theme.text.primary, children: "Task Detail: " }),
      shouldTruncate && displayMode === "default" && /* @__PURE__ */ (0, import_jsx_runtime35.jsxs)(Text3, { 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)(Text3, { 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)(Text3, { 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)(Text3, { 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)(Text3, { color: theme.text.primary, children: "Tools:" }),
      shouldTruncate && displayMode === "default" && /* @__PURE__ */ (0, import_jsx_runtime35.jsxs)(Text3, { 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_react60.default.useMemo(() => {
    const color = getStatusColor(toolCall.status);
    switch (toolCall.status) {
      case "executing":
        return /* @__PURE__ */ (0, import_jsx_runtime35.jsx)(Text3, { color, children: "\u22B7" });
      // Using same as ToolMessage
      case "awaiting_approval":
        return /* @__PURE__ */ (0, import_jsx_runtime35.jsx)(Text3, { color: theme.status.warning, children: "?" });
      case "success":
        return /* @__PURE__ */ (0, import_jsx_runtime35.jsx)(Text3, { color, children: "\u2713" });
      case "failed":
        return /* @__PURE__ */ (0, import_jsx_runtime35.jsx)(Text3, { color, bold: true, children: "x" });
      default:
        return /* @__PURE__ */ (0, import_jsx_runtime35.jsx)(Text3, { color, children: "o" });
    }
  }, [toolCall.status]);
  const description = import_react60.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_react60.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)(Text3, { wrap: "truncate-end", children: [
        /* @__PURE__ */ (0, import_jsx_runtime35.jsx)(Text3, { children: toolCall.name }),
        " ",
        /* @__PURE__ */ (0, import_jsx_runtime35.jsx)(Text3, { color: theme.text.secondary, children: description }),
        toolCall.error && /* @__PURE__ */ (0, import_jsx_runtime35.jsxs)(Text3, { 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)(Text3, { 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)(Text3, { 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)(Text3, { children: [
      "\u2022 ",
      /* @__PURE__ */ (0, import_jsx_runtime35.jsxs)(Text3, { children: [
        "Duration: ",
        fmtDuration(stats.totalDurationMs)
      ] })
    ] }),
    /* @__PURE__ */ (0, import_jsx_runtime35.jsxs)(Text3, { children: [
      "\u2022 ",
      /* @__PURE__ */ (0, import_jsx_runtime35.jsxs)(Text3, { children: [
        "Rounds: ",
        stats.rounds
      ] })
    ] }),
    /* @__PURE__ */ (0, import_jsx_runtime35.jsxs)(Text3, { children: [
      "\u2022 ",
      /* @__PURE__ */ (0, import_jsx_runtime35.jsxs)(Text3, { 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)(Text3, { 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)(Text3, { children: [
      "\u2022 ",
      /* @__PURE__ */ (0, import_jsx_runtime35.jsx)(Text3, { children: "Total Calls:" }),
      " ",
      executionSummary.totalToolCalls
    ] }),
    /* @__PURE__ */ (0, import_jsx_runtime35.jsxs)(Text3, { children: [
      "\u2022 ",
      /* @__PURE__ */ (0, import_jsx_runtime35.jsx)(Text3, { children: "Success Rate:" }),
      " ",
      /* @__PURE__ */ (0, import_jsx_runtime35.jsxs)(Text3, { color: theme.status.success, children: [
        executionSummary.successRate.toFixed(1),
        "%"
      ] }),
      " ",
      "(",
      /* @__PURE__ */ (0, import_jsx_runtime35.jsxs)(Text3, { color: theme.status.success, children: [
        executionSummary.successfulToolCalls,
        " success"
      ] }),
      ",",
      " ",
      /* @__PURE__ */ (0, import_jsx_runtime35.jsxs)(Text3, { 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)(Text3, { 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)(Text3, { 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)(Text3, { 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)(Text3, { color: theme.status.error, children: "Task Failed: " }),
    /* @__PURE__ */ (0, import_jsx_runtime35.jsx)(Text3, { 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)(Text3, { color: Colors.AccentGreen, wrap: "wrap", children: message }) }),
    /* @__PURE__ */ (0, import_jsx_runtime36.jsx)(
      MarkdownDisplay,
      {
        text: plan,
        isPending: false,
        availableTerminalHeight: availableHeight,
        contentWidth: childWidth
      }
    )
  ] });
}, "PlanSummaryDisplay");

// packages/cli/src/ui/components/ShellInputPrompt.tsx
init_esbuild_shims();
var import_react61 = __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_react61.useCallback)(
    (input) => {
      if (activeShellPtyId) {
        ShellExecutionService.writeToPty(activeShellPtyId, input);
      }
    },
    [activeShellPtyId]
  );
  const handleInput = (0, import_react61.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_react62.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 && "type" in resultDisplay && resultDisplay.type === "mcp_tool_progress") {
    const progress = resultDisplay;
    const msg = progress.message ?? `Progress: ${progress.progress}`;
    const totalStr = progress.total != null ? `/${progress.total}` : "";
    return {
      type: "string",
      data: `\u23F3 [${progress.progress}${totalStr}] ${msg}`
    };
  }
  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: config2 }) => /* @__PURE__ */ (0, import_jsx_runtime37.jsx)(
  AgentExecutionDisplay,
  {
    data,
    availableHeight,
    childWidth,
    config: config2
  }
), "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,
        contentWidth: 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)(Text3, { wrap: "wrap", color: theme.text.primary, children: displayData }) }) });
}, "StringResultRenderer");
var DiffResultRenderer = /* @__PURE__ */ __name(({ data, availableHeight, childWidth, settings }) => /* @__PURE__ */ (0, import_jsx_runtime37.jsx)(
  DiffRenderer,
  {
    diffContent: data.fileDiff,
    filename: data.fileName,
    availableTerminalHeight: availableHeight,
    contentWidth: childWidth,
    settings
  }
), "DiffResultRenderer");
var ToolMessage = /* @__PURE__ */ __name(({
  name: name3,
  description,
  resultDisplay,
  status,
  availableTerminalHeight,
  contentWidth,
  emphasis = "medium",
  renderOutputAsMarkdown = true,
  activeShellPtyId,
  embeddedShellFocused,
  ptyId,
  config: config2
}) => {
  const settings = useSettings();
  const isThisShellFocused = (name3 === SHELL_COMMAND_NAME || name3 === "Shell") && status === "Executing" /* Executing */ && ptyId === activeShellPtyId && embeddedShellFocused;
  const [lastUpdateTime, setLastUpdateTime] = import_react62.default.useState(null);
  const [userHasFocused, setUserHasFocused] = import_react62.default.useState(false);
  const [showFocusHint, setShowFocusHint] = import_react62.default.useState(false);
  import_react62.default.useEffect(() => {
    if (resultDisplay) {
      setLastUpdateTime(/* @__PURE__ */ new Date());
    }
  }, [resultDisplay]);
  import_react62.default.useEffect(() => {
    if (!lastUpdateTime) {
      return;
    }
    const timer = setTimeout(() => {
      setShowFocusHint(true);
    }, 5e3);
    return () => clearTimeout(timer);
  }, [lastUpdateTime]);
  import_react62.default.useEffect(() => {
    if (isThisShellFocused) {
      setUserHasFocused(true);
    }
  }, [isThisShellFocused]);
  const isThisShellFocusable = (name3 === SHELL_COMMAND_NAME || name3 === "Shell") && status === "Executing" /* Executing */ && config2?.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;
  const innerWidth = contentWidth - STATUS_INDICATOR_WIDTH;
  if (availableHeight) {
    renderOutputAsMarkdown = false;
  }
  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)(Text3, { 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: innerWidth
        }
      ),
      displayRenderer.type === "task" && config2 && /* @__PURE__ */ (0, import_jsx_runtime37.jsx)(
        SubagentExecutionRenderer,
        {
          data: displayRenderer.data,
          availableHeight,
          childWidth: innerWidth,
          config: config2
        }
      ),
      displayRenderer.type === "diff" && /* @__PURE__ */ (0, import_jsx_runtime37.jsx)(
        DiffResultRenderer,
        {
          data: displayRenderer.data,
          availableHeight,
          childWidth: innerWidth,
          settings
        }
      ),
      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: innerWidth
        }
      )
    ] }) }),
    isThisShellFocused && config2 && /* @__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)(Text3, { 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)(Text3, { color: theme.status.success, "aria-label": "Success:", children: TOOL_STATUS.SUCCESS }),
    status === "Confirming" /* Confirming */ && /* @__PURE__ */ (0, import_jsx_runtime37.jsx)(Text3, { color: statusColor, "aria-label": "Confirming:", children: TOOL_STATUS.CONFIRMING }),
    status === "Canceled" /* Canceled */ && /* @__PURE__ */ (0, import_jsx_runtime37.jsx)(Text3, { color: statusColor, "aria-label": "Canceled:", bold: true, children: TOOL_STATUS.CANCELED }),
    status === "Error" /* Error */ && /* @__PURE__ */ (0, import_jsx_runtime37.jsx)(Text3, { 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_react62.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)(
    Text3,
    {
      wrap: "truncate-end",
      strikethrough: status === "Canceled" /* Canceled */,
      children: [
        /* @__PURE__ */ (0, import_jsx_runtime37.jsx)(Text3, { color: nameColor, bold: true, children: name3 }),
        " ",
        /* @__PURE__ */ (0, import_jsx_runtime37.jsx)(Text3, { color: theme.text.secondary, children: description })
      ]
    }
  ) });
}, "ToolInfo");
var TrailingIndicator = /* @__PURE__ */ __name(() => /* @__PURE__ */ (0, import_jsx_runtime37.jsxs)(Text3, { color: theme.text.primary, wrap: "truncate", children: [
  " ",
  "\u2190"
] }), "TrailingIndicator");

// packages/cli/src/ui/contexts/ConfigContext.tsx
init_esbuild_shims();
var import_react63 = __toESM(require_react(), 1);
var ConfigContext = import_react63.default.createContext(void 0);
var useConfig = /* @__PURE__ */ __name(() => {
  const context2 = (0, import_react63.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,
  contentWidth,
  isFocused = true,
  activeShellPtyId,
  embeddedShellFocused
}) => {
  const isEmbeddedShellFocused = embeddedShellFocused && toolCalls.some(
    (t5) => t5.ptyId === activeShellPtyId && t5.status === "Executing" /* Executing */
  );
  const hasPending = !toolCalls.every(
    (t5) => t5.status === "Success" /* Success */
  );
  const config2 = useConfig();
  const isShellCommand = toolCalls.some(
    (t5) => t5.name === SHELL_COMMAND_NAME || t5.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 = contentWidth - 4;
  const toolAwaitingApproval = (0, import_react64.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: contentWidth,
      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,
              contentWidth: innerWidth,
              emphasis: isConfirming ? "high" : toolAwaitingApproval ? "low" : "medium",
              activeShellPtyId,
              embeddedShellFocused,
              config: config2
            }
          ) }),
          tool.status === "Confirming" /* Confirming */ && isConfirming && tool.confirmationDetails && /* @__PURE__ */ (0, import_jsx_runtime38.jsx)(
            ToolConfirmationMessage,
            {
              confirmationDetails: tool.confirmationDetails,
              config: config2,
              isFocused,
              availableTerminalHeight: availableTerminalHeightPerToolMessage,
              contentWidth: innerWidth
            }
          ),
          tool.outputFile && /* @__PURE__ */ (0, import_jsx_runtime38.jsx)(Box_default, { marginX: 1, children: /* @__PURE__ */ (0, import_jsx_runtime38.jsxs)(Text3, { 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,
  contentWidth
}) => {
  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,
      contentWidth: contentWidth - prefixWidth
    }
  ) });
}, "GeminiMessageContent");

// packages/cli/src/ui/components/messages/GeminiThoughtMessage.tsx
init_esbuild_shims();
var import_jsx_runtime40 = __toESM(require_jsx_runtime(), 1);
var GeminiThoughtMessage = /* @__PURE__ */ __name(({
  text,
  isPending,
  availableTerminalHeight,
  contentWidth
}) => {
  const prefix = "\u2726 ";
  const prefixWidth = prefix.length;
  return /* @__PURE__ */ (0, import_jsx_runtime40.jsxs)(Box_default, { flexDirection: "row", children: [
    /* @__PURE__ */ (0, import_jsx_runtime40.jsx)(Box_default, { width: prefixWidth, children: /* @__PURE__ */ (0, import_jsx_runtime40.jsx)(Text3, { color: theme.text.secondary, children: prefix }) }),
    /* @__PURE__ */ (0, import_jsx_runtime40.jsx)(Box_default, { flexGrow: 1, flexDirection: "column", children: /* @__PURE__ */ (0, import_jsx_runtime40.jsx)(
      MarkdownDisplay,
      {
        text,
        isPending,
        availableTerminalHeight,
        contentWidth: contentWidth - prefixWidth,
        textColor: theme.text.secondary
      }
    ) })
  ] });
}, "GeminiThoughtMessage");

// packages/cli/src/ui/components/messages/GeminiThoughtMessageContent.tsx
init_esbuild_shims();
var import_jsx_runtime41 = __toESM(require_jsx_runtime(), 1);
var GeminiThoughtMessageContent = /* @__PURE__ */ __name(({ text, isPending, availableTerminalHeight, contentWidth }) => {
  const originalPrefix = "\u2726 ";
  const prefixWidth = originalPrefix.length;
  return /* @__PURE__ */ (0, import_jsx_runtime41.jsx)(Box_default, { flexDirection: "column", paddingLeft: prefixWidth, children: /* @__PURE__ */ (0, import_jsx_runtime41.jsx)(
    MarkdownDisplay,
    {
      text,
      isPending,
      availableTerminalHeight,
      contentWidth: contentWidth - prefixWidth,
      textColor: theme.text.secondary
    }
  ) });
}, "GeminiThoughtMessageContent");

// packages/cli/src/ui/components/messages/CompressionMessage.tsx
init_esbuild_shims();
var import_jsx_runtime42 = __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 t4("Compressing chat history");
    }
    switch (compressionStatus) {
      case CompressionStatus.COMPRESSED:
        return t4(
          "Chat history compressed from {{originalTokens}} to {{newTokens}} tokens.",
          {
            originalTokens: String(originalTokens),
            newTokens: String(newTokens)
          }
        );
      case CompressionStatus.COMPRESSION_FAILED_INFLATED_TOKEN_COUNT:
        if (originalTokens < 5e4) {
          return t4("Compression was not beneficial for this history size.");
        }
        return t4(
          "Chat history compression did not reduce size. This may indicate issues with the compression prompt."
        );
      case CompressionStatus.COMPRESSION_FAILED_TOKEN_COUNT_ERROR:
        return t4(
          "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_runtime42.jsxs)(Box_default, { flexDirection: "row", children: [
    /* @__PURE__ */ (0, import_jsx_runtime42.jsx)(Box_default, { marginRight: 1, children: isPending ? /* @__PURE__ */ (0, import_jsx_runtime42.jsx)(build_default, { type: "dots" }) : /* @__PURE__ */ (0, import_jsx_runtime42.jsx)(Text3, { color: theme.text.accent, children: "\u2726" }) }),
    /* @__PURE__ */ (0, import_jsx_runtime42.jsx)(Box_default, { children: /* @__PURE__ */ (0, import_jsx_runtime42.jsx)(
      Text3,
      {
        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_runtime43 = __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_runtime43.jsx)(build_default, { type: "dots" });
    }
    return /* @__PURE__ */ (0, import_jsx_runtime43.jsx)(Text3, { color: Colors.AccentGreen, children: "\u2705" });
  }, "getIcon");
  return /* @__PURE__ */ (0, import_jsx_runtime43.jsxs)(Box_default, { flexDirection: "row", children: [
    /* @__PURE__ */ (0, import_jsx_runtime43.jsx)(Box_default, { marginRight: 1, children: getIcon() }),
    /* @__PURE__ */ (0, import_jsx_runtime43.jsx)(Box_default, { children: /* @__PURE__ */ (0, import_jsx_runtime43.jsx)(
      Text3,
      {
        color: summary.isPending ? Colors.AccentPurple : Colors.AccentGreen,
        children: getText3()
      }
    ) })
  ] });
}, "SummaryMessage");

// packages/cli/src/ui/components/messages/WarningMessage.tsx
init_esbuild_shims();
var import_jsx_runtime44 = __toESM(require_jsx_runtime(), 1);
var WarningMessage = /* @__PURE__ */ __name(({ text }) => {
  const prefix = "\u26A0 ";
  const prefixWidth = 3;
  return /* @__PURE__ */ (0, import_jsx_runtime44.jsxs)(Box_default, { flexDirection: "row", children: [
    /* @__PURE__ */ (0, import_jsx_runtime44.jsx)(Box_default, { width: prefixWidth, children: /* @__PURE__ */ (0, import_jsx_runtime44.jsx)(Text3, { color: Colors.AccentYellow, children: prefix }) }),
    /* @__PURE__ */ (0, import_jsx_runtime44.jsx)(Box_default, { flexGrow: 1, children: /* @__PURE__ */ (0, import_jsx_runtime44.jsx)(Text3, { wrap: "wrap", color: Colors.AccentYellow, children: /* @__PURE__ */ (0, import_jsx_runtime44.jsx)(RenderInline, { text, textColor: theme.status.warning }) }) })
  ] });
}, "WarningMessage");

// packages/cli/src/ui/components/messages/RetryCountdownMessage.tsx
init_esbuild_shims();
var import_jsx_runtime45 = __toESM(require_jsx_runtime(), 1);
var RetryCountdownMessage = /* @__PURE__ */ __name(({
  text
}) => {
  if (!text || text.trim() === "") {
    return null;
  }
  const prefix = "\u21BB ";
  const prefixWidth = prefix.length;
  return /* @__PURE__ */ (0, import_jsx_runtime45.jsxs)(Box_default, { flexDirection: "row", children: [
    /* @__PURE__ */ (0, import_jsx_runtime45.jsx)(Box_default, { width: prefixWidth, children: /* @__PURE__ */ (0, import_jsx_runtime45.jsx)(Text3, { color: theme.text.secondary, children: prefix }) }),
    /* @__PURE__ */ (0, import_jsx_runtime45.jsx)(Box_default, { flexGrow: 1, children: /* @__PURE__ */ (0, import_jsx_runtime45.jsx)(Text3, { wrap: "wrap", color: theme.text.secondary, children: text }) })
  ] });
}, "RetryCountdownMessage");

// packages/cli/src/ui/components/AboutBox.tsx
init_esbuild_shims();
var import_jsx_runtime46 = __toESM(require_jsx_runtime(), 1);
var AboutBox = /* @__PURE__ */ __name(({ width, ...props }) => {
  const fields = getSystemInfoFields(props);
  return /* @__PURE__ */ (0, import_jsx_runtime46.jsxs)(
    Box_default,
    {
      borderStyle: "round",
      borderColor: theme.border.default,
      flexDirection: "column",
      padding: 1,
      width,
      children: [
        /* @__PURE__ */ (0, import_jsx_runtime46.jsx)(Box_default, { marginBottom: 1, children: /* @__PURE__ */ (0, import_jsx_runtime46.jsx)(Text3, { bold: true, color: theme.text.accent, children: t4("Status") }) }),
        fields.map((field) => /* @__PURE__ */ (0, import_jsx_runtime46.jsxs)(
          Box_default,
          {
            flexDirection: "row",
            marginTop: field.label === t4("Auth") ? 1 : 0,
            children: [
              /* @__PURE__ */ (0, import_jsx_runtime46.jsx)(Box_default, { width: "35%", children: /* @__PURE__ */ (0, import_jsx_runtime46.jsx)(Text3, { bold: true, color: theme.text.link, children: field.label }) }),
              /* @__PURE__ */ (0, import_jsx_runtime46.jsx)(Box_default, { children: /* @__PURE__ */ (0, import_jsx_runtime46.jsx)(Text3, { color: theme.text.primary, children: field.value }) })
            ]
          },
          field.label
        ))
      ]
    }
  );
}, "AboutBox");

// packages/cli/src/ui/components/StatsDisplay.tsx
init_esbuild_shims();

// node_modules/ink-gradient/dist/index.js
init_esbuild_shims();
var import_react65 = __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_react65.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_default5 = Gradient;

// packages/cli/src/ui/contexts/SessionContext.tsx
init_esbuild_shims();
var import_react66 = __toESM(require_react(), 1);
var import_jsx_runtime47 = __toESM(require_jsx_runtime(), 1);
function areModelMetricsEqual(a2, b2) {
  if (a2.api.totalRequests !== b2.api.totalRequests || a2.api.totalErrors !== b2.api.totalErrors || a2.api.totalLatencyMs !== b2.api.totalLatencyMs) {
    return false;
  }
  if (a2.tokens.prompt !== b2.tokens.prompt || a2.tokens.candidates !== b2.tokens.candidates || a2.tokens.total !== b2.tokens.total || a2.tokens.cached !== b2.tokens.cached || a2.tokens.thoughts !== b2.tokens.thoughts || a2.tokens.tool !== b2.tokens.tool) {
    return false;
  }
  return true;
}
__name(areModelMetricsEqual, "areModelMetricsEqual");
function areToolCallStatsEqual(a2, b2) {
  if (a2.count !== b2.count || a2.success !== b2.success || a2.fail !== b2.fail || a2.durationMs !== b2.durationMs) {
    return false;
  }
  if (a2.decisions["accept" /* ACCEPT */] !== b2.decisions["accept" /* ACCEPT */] || a2.decisions["reject" /* REJECT */] !== b2.decisions["reject" /* REJECT */] || a2.decisions["modify" /* MODIFY */] !== b2.decisions["modify" /* MODIFY */] || a2.decisions["auto_accept" /* AUTO_ACCEPT */] !== b2.decisions["auto_accept" /* AUTO_ACCEPT */]) {
    return false;
  }
  return true;
}
__name(areToolCallStatsEqual, "areToolCallStatsEqual");
function areMetricsEqual(a2, b2) {
  if (a2 === b2) return true;
  if (!a2 || !b2) return false;
  if (a2.files.totalLinesAdded !== b2.files.totalLinesAdded || a2.files.totalLinesRemoved !== b2.files.totalLinesRemoved) {
    return false;
  }
  const toolsA = a2.tools;
  const toolsB = b2.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(a2.models);
  const modelsBKeys = Object.keys(b2.models);
  if (modelsAKeys.length !== modelsBKeys.length) return false;
  for (const key of modelsAKeys) {
    if (!b2.models[key] || !areModelMetricsEqual(a2.models[key], b2.models[key])) {
      return false;
    }
  }
  return true;
}
__name(areMetricsEqual, "areMetricsEqual");
var SessionStatsContext = (0, import_react66.createContext)(
  void 0
);
var createDefaultStats = /* @__PURE__ */ __name((sessionId = "") => ({
  sessionId,
  sessionStartTime: /* @__PURE__ */ new Date(),
  metrics: uiTelemetryService.getMetrics(),
  lastPromptTokenCount: 0,
  promptCount: 0
}), "createDefaultStats");
var SessionStatsProvider = /* @__PURE__ */ __name(({ sessionId, children }) => {
  const [stats, setStats] = (0, import_react66.useState)(
    () => createDefaultStats(sessionId ?? "")
  );
  (0, import_react66.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 startNewSession = (0, import_react66.useCallback)((sessionId2) => {
    setStats(() => ({
      ...createDefaultStats(sessionId2),
      lastPromptTokenCount: uiTelemetryService.getLastPromptTokenCount()
    }));
  }, []);
  const startNewPrompt = (0, import_react66.useCallback)(() => {
    setStats((prevState) => ({
      ...prevState,
      promptCount: prevState.promptCount + 1
    }));
  }, []);
  const getPromptCount = (0, import_react66.useCallback)(
    () => stats.promptCount,
    [stats.promptCount]
  );
  const value = (0, import_react66.useMemo)(
    () => ({
      stats,
      startNewSession,
      startNewPrompt,
      getPromptCount
    }),
    [stats, startNewSession, startNewPrompt, getPromptCount]
  );
  return /* @__PURE__ */ (0, import_jsx_runtime47.jsx)(SessionStatsContext.Provider, { value, children });
}, "SessionStatsProvider");
var useSessionStats = /* @__PURE__ */ __name(() => {
  const context2 = (0, import_react66.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/components/StatsDisplay.tsx
var import_jsx_runtime48 = __toESM(require_jsx_runtime(), 1);
var StatRow = /* @__PURE__ */ __name(({ title, children }) => /* @__PURE__ */ (0, import_jsx_runtime48.jsxs)(Box_default, { children: [
  /* @__PURE__ */ (0, import_jsx_runtime48.jsx)(Box_default, { width: 28, children: /* @__PURE__ */ (0, import_jsx_runtime48.jsx)(Text3, { color: theme.text.link, children: title }) }),
  /* @__PURE__ */ (0, import_jsx_runtime48.jsx)(Box_default, { flexGrow: 1, children })
] }), "StatRow");
var SubStatRow = /* @__PURE__ */ __name(({ title, children }) => /* @__PURE__ */ (0, import_jsx_runtime48.jsxs)(Box_default, { paddingLeft: 2, children: [
  /* @__PURE__ */ (0, import_jsx_runtime48.jsx)(Box_default, { width: 26, children: /* @__PURE__ */ (0, import_jsx_runtime48.jsxs)(Text3, { color: theme.text.secondary, children: [
    "\xBB ",
    title
  ] }) }),
  /* @__PURE__ */ (0, import_jsx_runtime48.jsx)(Box_default, { flexGrow: 1, children })
] }), "SubStatRow");
var Section = /* @__PURE__ */ __name(({ title, children }) => /* @__PURE__ */ (0, import_jsx_runtime48.jsxs)(Box_default, { flexDirection: "column", width: "100%", marginBottom: 1, children: [
  /* @__PURE__ */ (0, import_jsx_runtime48.jsx)(Text3, { 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_runtime48.jsxs)(Box_default, { flexDirection: "column", marginTop: 1, children: [
    /* @__PURE__ */ (0, import_jsx_runtime48.jsxs)(Box_default, { children: [
      /* @__PURE__ */ (0, import_jsx_runtime48.jsx)(Box_default, { width: nameWidth, children: /* @__PURE__ */ (0, import_jsx_runtime48.jsx)(Text3, { bold: true, color: theme.text.primary, children: t4("Model Usage") }) }),
      /* @__PURE__ */ (0, import_jsx_runtime48.jsx)(Box_default, { width: requestsWidth, justifyContent: "flex-end", children: /* @__PURE__ */ (0, import_jsx_runtime48.jsx)(Text3, { bold: true, color: theme.text.primary, children: t4("Reqs") }) }),
      /* @__PURE__ */ (0, import_jsx_runtime48.jsx)(Box_default, { width: inputTokensWidth, justifyContent: "flex-end", children: /* @__PURE__ */ (0, import_jsx_runtime48.jsx)(Text3, { bold: true, color: theme.text.primary, children: t4("Input Tokens") }) }),
      /* @__PURE__ */ (0, import_jsx_runtime48.jsx)(Box_default, { width: outputTokensWidth, justifyContent: "flex-end", children: /* @__PURE__ */ (0, import_jsx_runtime48.jsx)(Text3, { bold: true, color: theme.text.primary, children: t4("Output Tokens") }) })
    ] }),
    /* @__PURE__ */ (0, import_jsx_runtime48.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_runtime48.jsxs)(Box_default, { children: [
      /* @__PURE__ */ (0, import_jsx_runtime48.jsx)(Box_default, { width: nameWidth, children: /* @__PURE__ */ (0, import_jsx_runtime48.jsx)(Text3, { color: theme.text.primary, children: name3.replace("-001", "") }) }),
      /* @__PURE__ */ (0, import_jsx_runtime48.jsx)(Box_default, { width: requestsWidth, justifyContent: "flex-end", children: /* @__PURE__ */ (0, import_jsx_runtime48.jsx)(Text3, { color: theme.text.primary, children: modelMetrics.api.totalRequests }) }),
      /* @__PURE__ */ (0, import_jsx_runtime48.jsx)(Box_default, { width: inputTokensWidth, justifyContent: "flex-end", children: /* @__PURE__ */ (0, import_jsx_runtime48.jsx)(Text3, { color: theme.status.warning, children: modelMetrics.tokens.prompt.toLocaleString() }) }),
      /* @__PURE__ */ (0, import_jsx_runtime48.jsx)(Box_default, { width: outputTokensWidth, justifyContent: "flex-end", children: /* @__PURE__ */ (0, import_jsx_runtime48.jsx)(Text3, { color: theme.status.warning, children: modelMetrics.tokens.candidates.toLocaleString() }) })
    ] }, name3)),
    cacheEfficiency > 0 && /* @__PURE__ */ (0, import_jsx_runtime48.jsxs)(Box_default, { flexDirection: "column", marginTop: 1, children: [
      /* @__PURE__ */ (0, import_jsx_runtime48.jsxs)(Text3, { color: theme.text.primary, children: [
        /* @__PURE__ */ (0, import_jsx_runtime48.jsx)(Text3, { color: theme.status.success, children: t4("Savings Highlight:") }),
        " ",
        totalCachedTokens.toLocaleString(),
        " (",
        cacheEfficiency.toFixed(1),
        "%)",
        " ",
        t4("of input tokens were served from the cache, reducing costs.")
      ] }),
      /* @__PURE__ */ (0, import_jsx_runtime48.jsx)(Box_default, { height: 1 }),
      /* @__PURE__ */ (0, import_jsx_runtime48.jsxs)(Text3, { color: theme.text.secondary, children: [
        "\xBB ",
        t4("Tip: For a full token breakdown, run `/stats model`.")
      ] })
    ] })
  ] });
}, "ModelUsageTable");
var StatsDisplay = /* @__PURE__ */ __name(({
  duration: duration3,
  title,
  width
}) => {
  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_runtime48.jsx)(dist_default5, { colors: theme.ui.gradient, children: /* @__PURE__ */ (0, import_jsx_runtime48.jsx)(Text3, { bold: true, color: theme.text.primary, children: title }) }) : /* @__PURE__ */ (0, import_jsx_runtime48.jsx)(Text3, { bold: true, color: theme.text.accent, children: title });
    }
    return /* @__PURE__ */ (0, import_jsx_runtime48.jsx)(Text3, { bold: true, color: theme.text.accent, children: t4("Session Stats") });
  }, "renderTitle");
  return /* @__PURE__ */ (0, import_jsx_runtime48.jsxs)(
    Box_default,
    {
      borderStyle: "round",
      borderColor: theme.border.default,
      flexDirection: "column",
      paddingY: 1,
      paddingX: 2,
      width,
      children: [
        renderTitle(),
        /* @__PURE__ */ (0, import_jsx_runtime48.jsx)(Box_default, { height: 1 }),
        /* @__PURE__ */ (0, import_jsx_runtime48.jsxs)(Section, { title: t4("Interaction Summary"), children: [
          /* @__PURE__ */ (0, import_jsx_runtime48.jsx)(StatRow, { title: t4("Session ID:"), children: /* @__PURE__ */ (0, import_jsx_runtime48.jsx)(Text3, { color: theme.text.primary, children: stats.sessionId }) }),
          /* @__PURE__ */ (0, import_jsx_runtime48.jsx)(StatRow, { title: t4("Tool Calls:"), children: /* @__PURE__ */ (0, import_jsx_runtime48.jsxs)(Text3, { color: theme.text.primary, children: [
            tools.totalCalls,
            " (",
            " ",
            /* @__PURE__ */ (0, import_jsx_runtime48.jsxs)(Text3, { color: theme.status.success, children: [
              "\u2713 ",
              tools.totalSuccess
            ] }),
            " ",
            /* @__PURE__ */ (0, import_jsx_runtime48.jsxs)(Text3, { color: theme.status.error, children: [
              "x ",
              tools.totalFail
            ] }),
            " )"
          ] }) }),
          /* @__PURE__ */ (0, import_jsx_runtime48.jsx)(StatRow, { title: t4("Success Rate:"), children: /* @__PURE__ */ (0, import_jsx_runtime48.jsxs)(Text3, { color: successColor, children: [
            computed.successRate.toFixed(1),
            "%"
          ] }) }),
          computed.totalDecisions > 0 && /* @__PURE__ */ (0, import_jsx_runtime48.jsx)(StatRow, { title: t4("User Agreement:"), children: /* @__PURE__ */ (0, import_jsx_runtime48.jsxs)(Text3, { color: agreementColor, children: [
            computed.agreementRate.toFixed(1),
            "%",
            " ",
            /* @__PURE__ */ (0, import_jsx_runtime48.jsxs)(Text3, { color: theme.text.secondary, children: [
              "(",
              computed.totalDecisions,
              " ",
              t4("reviewed"),
              ")"
            ] })
          ] }) }),
          files && (files.totalLinesAdded > 0 || files.totalLinesRemoved > 0) && /* @__PURE__ */ (0, import_jsx_runtime48.jsx)(StatRow, { title: t4("Code Changes:"), children: /* @__PURE__ */ (0, import_jsx_runtime48.jsxs)(Text3, { color: theme.text.primary, children: [
            /* @__PURE__ */ (0, import_jsx_runtime48.jsxs)(Text3, { color: theme.status.success, children: [
              "+",
              files.totalLinesAdded
            ] }),
            " ",
            /* @__PURE__ */ (0, import_jsx_runtime48.jsxs)(Text3, { color: theme.status.error, children: [
              "-",
              files.totalLinesRemoved
            ] })
          ] }) })
        ] }),
        /* @__PURE__ */ (0, import_jsx_runtime48.jsxs)(Section, { title: t4("Performance"), children: [
          /* @__PURE__ */ (0, import_jsx_runtime48.jsx)(StatRow, { title: t4("Wall Time:"), children: /* @__PURE__ */ (0, import_jsx_runtime48.jsx)(Text3, { color: theme.text.primary, children: duration3 }) }),
          /* @__PURE__ */ (0, import_jsx_runtime48.jsx)(StatRow, { title: t4("Agent Active:"), children: /* @__PURE__ */ (0, import_jsx_runtime48.jsx)(Text3, { color: theme.text.primary, children: formatDuration(computed.agentActiveTime) }) }),
          /* @__PURE__ */ (0, import_jsx_runtime48.jsx)(SubStatRow, { title: t4("API Time:"), children: /* @__PURE__ */ (0, import_jsx_runtime48.jsxs)(Text3, { color: theme.text.primary, children: [
            formatDuration(computed.totalApiTime),
            " ",
            /* @__PURE__ */ (0, import_jsx_runtime48.jsxs)(Text3, { color: theme.text.secondary, children: [
              "(",
              computed.apiTimePercent.toFixed(1),
              "%)"
            ] })
          ] }) }),
          /* @__PURE__ */ (0, import_jsx_runtime48.jsx)(SubStatRow, { title: t4("Tool Time:"), children: /* @__PURE__ */ (0, import_jsx_runtime48.jsxs)(Text3, { color: theme.text.primary, children: [
            formatDuration(computed.totalToolTime),
            " ",
            /* @__PURE__ */ (0, import_jsx_runtime48.jsxs)(Text3, { color: theme.text.secondary, children: [
              "(",
              computed.toolTimePercent.toFixed(1),
              "%)"
            ] })
          ] }) })
        ] }),
        Object.keys(models).length > 0 && /* @__PURE__ */ (0, import_jsx_runtime48.jsx)(
          ModelUsageTable,
          {
            models,
            totalCachedTokens: computed.totalCachedTokens,
            cacheEfficiency: computed.cacheEfficiency
          }
        )
      ]
    }
  );
}, "StatsDisplay");

// packages/cli/src/ui/components/ModelStatsDisplay.tsx
init_esbuild_shims();
var import_jsx_runtime49 = __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_runtime49.jsxs)(Box_default, { children: [
  /* @__PURE__ */ (0, import_jsx_runtime49.jsx)(Box_default, { width: METRIC_COL_WIDTH, children: /* @__PURE__ */ (0, import_jsx_runtime49.jsx)(
    Text3,
    {
      bold: isSection,
      color: isSection ? theme.text.primary : theme.text.link,
      children: isSubtle ? `  \u21B3 ${title}` : title
    }
  ) }),
  values.map((value, index) => /* @__PURE__ */ (0, import_jsx_runtime49.jsx)(Box_default, { width: MODEL_COL_WIDTH, children: /* @__PURE__ */ (0, import_jsx_runtime49.jsx)(Text3, { color: theme.text.primary, children: value }) }, index))
] }), "StatRow");
var ModelStatsDisplay = /* @__PURE__ */ __name(({
  width
}) => {
  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_runtime49.jsx)(
      Box_default,
      {
        borderStyle: "round",
        borderColor: theme.border.default,
        paddingY: 1,
        paddingX: 2,
        width,
        children: /* @__PURE__ */ (0, import_jsx_runtime49.jsx)(Text3, { color: theme.text.primary, children: t4("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_runtime49.jsxs)(
    Box_default,
    {
      borderStyle: "round",
      borderColor: theme.border.default,
      flexDirection: "column",
      paddingY: 1,
      paddingX: 2,
      width,
      children: [
        /* @__PURE__ */ (0, import_jsx_runtime49.jsx)(Text3, { bold: true, color: theme.text.accent, children: t4("Model Stats For Nerds") }),
        /* @__PURE__ */ (0, import_jsx_runtime49.jsx)(Box_default, { height: 1 }),
        /* @__PURE__ */ (0, import_jsx_runtime49.jsxs)(Box_default, { children: [
          /* @__PURE__ */ (0, import_jsx_runtime49.jsx)(Box_default, { width: METRIC_COL_WIDTH, children: /* @__PURE__ */ (0, import_jsx_runtime49.jsx)(Text3, { bold: true, color: theme.text.primary, children: t4("Metric") }) }),
          modelNames.map((name3) => /* @__PURE__ */ (0, import_jsx_runtime49.jsx)(Box_default, { width: MODEL_COL_WIDTH, children: /* @__PURE__ */ (0, import_jsx_runtime49.jsx)(Text3, { bold: true, color: theme.text.primary, children: name3 }) }, name3))
        ] }),
        /* @__PURE__ */ (0, import_jsx_runtime49.jsx)(
          Box_default,
          {
            borderStyle: "single",
            borderBottom: true,
            borderTop: false,
            borderLeft: false,
            borderRight: false,
            borderColor: theme.border.default
          }
        ),
        /* @__PURE__ */ (0, import_jsx_runtime49.jsx)(StatRow2, { title: t4("API"), values: [], isSection: true }),
        /* @__PURE__ */ (0, import_jsx_runtime49.jsx)(
          StatRow2,
          {
            title: t4("Requests"),
            values: getModelValues((m3) => m3.api.totalRequests.toLocaleString())
          }
        ),
        /* @__PURE__ */ (0, import_jsx_runtime49.jsx)(
          StatRow2,
          {
            title: t4("Errors"),
            values: getModelValues((m3) => {
              const errorRate = calculateErrorRate(m3);
              return /* @__PURE__ */ (0, import_jsx_runtime49.jsxs)(
                Text3,
                {
                  color: m3.api.totalErrors > 0 ? theme.status.error : theme.text.primary,
                  children: [
                    m3.api.totalErrors.toLocaleString(),
                    " (",
                    errorRate.toFixed(1),
                    "%)"
                  ]
                }
              );
            })
          }
        ),
        /* @__PURE__ */ (0, import_jsx_runtime49.jsx)(
          StatRow2,
          {
            title: t4("Avg Latency"),
            values: getModelValues((m3) => {
              const avgLatency = calculateAverageLatency(m3);
              return formatDuration(avgLatency);
            })
          }
        ),
        /* @__PURE__ */ (0, import_jsx_runtime49.jsx)(Box_default, { height: 1 }),
        /* @__PURE__ */ (0, import_jsx_runtime49.jsx)(StatRow2, { title: t4("Tokens"), values: [], isSection: true }),
        /* @__PURE__ */ (0, import_jsx_runtime49.jsx)(
          StatRow2,
          {
            title: t4("Total"),
            values: getModelValues((m3) => /* @__PURE__ */ (0, import_jsx_runtime49.jsx)(Text3, { color: theme.status.warning, children: m3.tokens.total.toLocaleString() }))
          }
        ),
        /* @__PURE__ */ (0, import_jsx_runtime49.jsx)(
          StatRow2,
          {
            title: t4("Prompt"),
            isSubtle: true,
            values: getModelValues((m3) => m3.tokens.prompt.toLocaleString())
          }
        ),
        hasCached && /* @__PURE__ */ (0, import_jsx_runtime49.jsx)(
          StatRow2,
          {
            title: t4("Cached"),
            isSubtle: true,
            values: getModelValues((m3) => {
              const cacheHitRate = calculateCacheHitRate(m3);
              return /* @__PURE__ */ (0, import_jsx_runtime49.jsxs)(Text3, { color: theme.status.success, children: [
                m3.tokens.cached.toLocaleString(),
                " (",
                cacheHitRate.toFixed(1),
                "%)"
              ] });
            })
          }
        ),
        hasThoughts && /* @__PURE__ */ (0, import_jsx_runtime49.jsx)(
          StatRow2,
          {
            title: t4("Thoughts"),
            isSubtle: true,
            values: getModelValues((m3) => m3.tokens.thoughts.toLocaleString())
          }
        ),
        hasTool && /* @__PURE__ */ (0, import_jsx_runtime49.jsx)(
          StatRow2,
          {
            title: t4("Tool"),
            isSubtle: true,
            values: getModelValues((m3) => m3.tokens.tool.toLocaleString())
          }
        ),
        /* @__PURE__ */ (0, import_jsx_runtime49.jsx)(
          StatRow2,
          {
            title: t4("Output"),
            isSubtle: true,
            values: getModelValues((m3) => m3.tokens.candidates.toLocaleString())
          }
        )
      ]
    }
  );
}, "ModelStatsDisplay");

// packages/cli/src/ui/components/ToolStatsDisplay.tsx
init_esbuild_shims();
var import_jsx_runtime50 = __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_runtime50.jsxs)(Box_default, { children: [
    /* @__PURE__ */ (0, import_jsx_runtime50.jsx)(Box_default, { width: TOOL_NAME_COL_WIDTH, children: /* @__PURE__ */ (0, import_jsx_runtime50.jsx)(Text3, { color: theme.text.link, children: name3 }) }),
    /* @__PURE__ */ (0, import_jsx_runtime50.jsx)(Box_default, { width: CALLS_COL_WIDTH, justifyContent: "flex-end", children: /* @__PURE__ */ (0, import_jsx_runtime50.jsx)(Text3, { color: theme.text.primary, children: stats.count }) }),
    /* @__PURE__ */ (0, import_jsx_runtime50.jsx)(Box_default, { width: SUCCESS_RATE_COL_WIDTH, justifyContent: "flex-end", children: /* @__PURE__ */ (0, import_jsx_runtime50.jsxs)(Text3, { color: successColor, children: [
      successRate.toFixed(1),
      "%"
    ] }) }),
    /* @__PURE__ */ (0, import_jsx_runtime50.jsx)(Box_default, { width: AVG_DURATION_COL_WIDTH, justifyContent: "flex-end", children: /* @__PURE__ */ (0, import_jsx_runtime50.jsx)(Text3, { color: theme.text.primary, children: formatDuration(avgDuration) }) })
  ] });
}, "StatRow");
var ToolStatsDisplay = /* @__PURE__ */ __name(({
  width
}) => {
  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_runtime50.jsx)(
      Box_default,
      {
        borderStyle: "round",
        borderColor: theme.border.default,
        paddingY: 1,
        paddingX: 2,
        width,
        children: /* @__PURE__ */ (0, import_jsx_runtime50.jsx)(Text3, { color: theme.text.primary, children: t4("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_runtime50.jsxs)(
    Box_default,
    {
      borderStyle: "round",
      borderColor: theme.border.default,
      flexDirection: "column",
      paddingY: 1,
      paddingX: 2,
      width,
      children: [
        /* @__PURE__ */ (0, import_jsx_runtime50.jsx)(Text3, { bold: true, color: theme.text.accent, children: t4("Tool Stats For Nerds") }),
        /* @__PURE__ */ (0, import_jsx_runtime50.jsx)(Box_default, { height: 1 }),
        /* @__PURE__ */ (0, import_jsx_runtime50.jsxs)(Box_default, { children: [
          /* @__PURE__ */ (0, import_jsx_runtime50.jsx)(Box_default, { width: TOOL_NAME_COL_WIDTH, children: /* @__PURE__ */ (0, import_jsx_runtime50.jsx)(Text3, { bold: true, color: theme.text.primary, children: t4("Tool Name") }) }),
          /* @__PURE__ */ (0, import_jsx_runtime50.jsx)(Box_default, { width: CALLS_COL_WIDTH, justifyContent: "flex-end", children: /* @__PURE__ */ (0, import_jsx_runtime50.jsx)(Text3, { bold: true, color: theme.text.primary, children: t4("Calls") }) }),
          /* @__PURE__ */ (0, import_jsx_runtime50.jsx)(Box_default, { width: SUCCESS_RATE_COL_WIDTH, justifyContent: "flex-end", children: /* @__PURE__ */ (0, import_jsx_runtime50.jsx)(Text3, { bold: true, color: theme.text.primary, children: t4("Success Rate") }) }),
          /* @__PURE__ */ (0, import_jsx_runtime50.jsx)(Box_default, { width: AVG_DURATION_COL_WIDTH, justifyContent: "flex-end", children: /* @__PURE__ */ (0, import_jsx_runtime50.jsx)(Text3, { bold: true, color: theme.text.primary, children: t4("Avg Duration") }) })
        ] }),
        /* @__PURE__ */ (0, import_jsx_runtime50.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_runtime50.jsx)(StatRow3, { name: name3, stats: stats2 }, name3)),
        /* @__PURE__ */ (0, import_jsx_runtime50.jsx)(Box_default, { height: 1 }),
        /* @__PURE__ */ (0, import_jsx_runtime50.jsx)(Text3, { bold: true, color: theme.text.primary, children: t4("User Decision Summary") }),
        /* @__PURE__ */ (0, import_jsx_runtime50.jsxs)(Box_default, { children: [
          /* @__PURE__ */ (0, import_jsx_runtime50.jsx)(
            Box_default,
            {
              width: TOOL_NAME_COL_WIDTH + CALLS_COL_WIDTH + SUCCESS_RATE_COL_WIDTH,
              children: /* @__PURE__ */ (0, import_jsx_runtime50.jsx)(Text3, { color: theme.text.link, children: t4("Total Reviewed Suggestions:") })
            }
          ),
          /* @__PURE__ */ (0, import_jsx_runtime50.jsx)(Box_default, { width: AVG_DURATION_COL_WIDTH, justifyContent: "flex-end", children: /* @__PURE__ */ (0, import_jsx_runtime50.jsx)(Text3, { color: theme.text.primary, children: totalReviewed }) })
        ] }),
        /* @__PURE__ */ (0, import_jsx_runtime50.jsxs)(Box_default, { children: [
          /* @__PURE__ */ (0, import_jsx_runtime50.jsx)(
            Box_default,
            {
              width: TOOL_NAME_COL_WIDTH + CALLS_COL_WIDTH + SUCCESS_RATE_COL_WIDTH,
              children: /* @__PURE__ */ (0, import_jsx_runtime50.jsx)(Text3, { color: theme.text.primary, children: t4(" \xBB Accepted:") })
            }
          ),
          /* @__PURE__ */ (0, import_jsx_runtime50.jsx)(Box_default, { width: AVG_DURATION_COL_WIDTH, justifyContent: "flex-end", children: /* @__PURE__ */ (0, import_jsx_runtime50.jsx)(Text3, { color: theme.status.success, children: totalDecisions.accept }) })
        ] }),
        /* @__PURE__ */ (0, import_jsx_runtime50.jsxs)(Box_default, { children: [
          /* @__PURE__ */ (0, import_jsx_runtime50.jsx)(
            Box_default,
            {
              width: TOOL_NAME_COL_WIDTH + CALLS_COL_WIDTH + SUCCESS_RATE_COL_WIDTH,
              children: /* @__PURE__ */ (0, import_jsx_runtime50.jsx)(Text3, { color: theme.text.primary, children: t4(" \xBB Rejected:") })
            }
          ),
          /* @__PURE__ */ (0, import_jsx_runtime50.jsx)(Box_default, { width: AVG_DURATION_COL_WIDTH, justifyContent: "flex-end", children: /* @__PURE__ */ (0, import_jsx_runtime50.jsx)(Text3, { color: theme.status.error, children: totalDecisions.reject }) })
        ] }),
        /* @__PURE__ */ (0, import_jsx_runtime50.jsxs)(Box_default, { children: [
          /* @__PURE__ */ (0, import_jsx_runtime50.jsx)(
            Box_default,
            {
              width: TOOL_NAME_COL_WIDTH + CALLS_COL_WIDTH + SUCCESS_RATE_COL_WIDTH,
              children: /* @__PURE__ */ (0, import_jsx_runtime50.jsx)(Text3, { color: theme.text.primary, children: t4(" \xBB Modified:") })
            }
          ),
          /* @__PURE__ */ (0, import_jsx_runtime50.jsx)(Box_default, { width: AVG_DURATION_COL_WIDTH, justifyContent: "flex-end", children: /* @__PURE__ */ (0, import_jsx_runtime50.jsx)(Text3, { color: theme.status.warning, children: totalDecisions.modify }) })
        ] }),
        /* @__PURE__ */ (0, import_jsx_runtime50.jsx)(
          Box_default,
          {
            borderStyle: "single",
            borderBottom: true,
            borderTop: false,
            borderLeft: false,
            borderRight: false,
            borderColor: theme.border.default,
            width: "100%"
          }
        ),
        /* @__PURE__ */ (0, import_jsx_runtime50.jsxs)(Box_default, { children: [
          /* @__PURE__ */ (0, import_jsx_runtime50.jsx)(
            Box_default,
            {
              width: TOOL_NAME_COL_WIDTH + CALLS_COL_WIDTH + SUCCESS_RATE_COL_WIDTH,
              children: /* @__PURE__ */ (0, import_jsx_runtime50.jsx)(Text3, { color: theme.text.primary, children: t4(" Overall Agreement Rate:") })
            }
          ),
          /* @__PURE__ */ (0, import_jsx_runtime50.jsx)(Box_default, { width: AVG_DURATION_COL_WIDTH, justifyContent: "flex-end", children: /* @__PURE__ */ (0, import_jsx_runtime50.jsx)(Text3, { 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_runtime51 = __toESM(require_jsx_runtime(), 1);
var SessionSummaryDisplay = /* @__PURE__ */ __name(({
  duration: duration3,
  width
}) => {
  const config2 = useConfig();
  const { stats } = useSessionStats();
  const hasMessages = stats.promptCount > 0;
  const canResume = !!config2.getChatRecordingService();
  return /* @__PURE__ */ (0, import_jsx_runtime51.jsxs)(import_jsx_runtime51.Fragment, { children: [
    /* @__PURE__ */ (0, import_jsx_runtime51.jsx)(
      StatsDisplay,
      {
        title: t4("Agent powering down. Goodbye!"),
        duration: duration3,
        width
      }
    ),
    hasMessages && canResume && /* @__PURE__ */ (0, import_jsx_runtime51.jsx)(Box_default, { marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime51.jsxs)(Text3, { color: theme.text.secondary, children: [
      t4("To continue this session, run"),
      " ",
      /* @__PURE__ */ (0, import_jsx_runtime51.jsxs)(Text3, { color: theme.text.accent, children: [
        "qwen --resume ",
        stats.sessionId
      ] })
    ] }) })
  ] });
}, "SessionSummaryDisplay");

// packages/cli/src/ui/components/Help.tsx
init_esbuild_shims();
var import_jsx_runtime52 = __toESM(require_jsx_runtime(), 1);
var Help = /* @__PURE__ */ __name(({ commands, width }) => /* @__PURE__ */ (0, import_jsx_runtime52.jsxs)(
  Box_default,
  {
    flexDirection: "column",
    borderColor: theme.border.default,
    borderStyle: "round",
    padding: 1,
    width,
    children: [
      /* @__PURE__ */ (0, import_jsx_runtime52.jsx)(Text3, { bold: true, color: theme.text.primary, children: t4("Basics:") }),
      /* @__PURE__ */ (0, import_jsx_runtime52.jsxs)(Text3, { color: theme.text.primary, children: [
        /* @__PURE__ */ (0, import_jsx_runtime52.jsx)(Text3, { bold: true, color: theme.text.accent, children: t4("Add context") }),
        ":",
        " ",
        t4(
          "Use {{symbol}} to specify files for context (e.g., {{example}}) to target specific files or folders.",
          {
            symbol: t4("@"),
            example: t4("@src/myFile.ts")
          }
        )
      ] }),
      /* @__PURE__ */ (0, import_jsx_runtime52.jsxs)(Text3, { color: theme.text.primary, children: [
        /* @__PURE__ */ (0, import_jsx_runtime52.jsx)(Text3, { bold: true, color: theme.text.accent, children: t4("Shell mode") }),
        ":",
        " ",
        t4(
          "Execute shell commands via {{symbol}} (e.g., {{example1}}) or use natural language (e.g., {{example2}}).",
          {
            symbol: t4("!"),
            example1: t4("!npm run start"),
            example2: t4("start server")
          }
        )
      ] }),
      /* @__PURE__ */ (0, import_jsx_runtime52.jsx)(Box_default, { height: 1 }),
      /* @__PURE__ */ (0, import_jsx_runtime52.jsx)(Text3, { bold: true, color: theme.text.primary, children: t4("Commands:") }),
      commands.filter((command2) => command2.description && !command2.hidden).map((command2) => /* @__PURE__ */ (0, import_jsx_runtime52.jsxs)(Box_default, { flexDirection: "column", children: [
        /* @__PURE__ */ (0, import_jsx_runtime52.jsxs)(Text3, { color: theme.text.primary, children: [
          /* @__PURE__ */ (0, import_jsx_runtime52.jsxs)(Text3, { bold: true, color: theme.text.accent, children: [
            " ",
            formatCommandLabel(command2, "/")
          ] }),
          command2.kind === "mcp-prompt" /* MCP_PROMPT */ && /* @__PURE__ */ (0, import_jsx_runtime52.jsx)(Text3, { color: theme.text.secondary, children: " [MCP]" }),
          command2.description && " - " + command2.description
        ] }),
        command2.subCommands && command2.subCommands.filter((subCommand) => !subCommand.hidden).map((subCommand) => /* @__PURE__ */ (0, import_jsx_runtime52.jsxs)(Text3, { color: theme.text.primary, children: [
          /* @__PURE__ */ (0, import_jsx_runtime52.jsxs)(Text3, { bold: true, color: theme.text.accent, children: [
            "   ",
            formatCommandLabel(subCommand)
          ] }),
          subCommand.description && " - " + subCommand.description
        ] }, subCommand.name))
      ] }, command2.name)),
      /* @__PURE__ */ (0, import_jsx_runtime52.jsxs)(Text3, { color: theme.text.primary, children: [
        /* @__PURE__ */ (0, import_jsx_runtime52.jsxs)(Text3, { bold: true, color: theme.text.accent, children: [
          " ",
          "!",
          " "
        ] }),
        "- ",
        t4("shell command")
      ] }),
      /* @__PURE__ */ (0, import_jsx_runtime52.jsxs)(Text3, { color: theme.text.primary, children: [
        /* @__PURE__ */ (0, import_jsx_runtime52.jsx)(Text3, { color: theme.text.secondary, children: "[MCP]" }),
        " -",
        " ",
        t4("Model Context Protocol command (from external servers)")
      ] }),
      /* @__PURE__ */ (0, import_jsx_runtime52.jsx)(Box_default, { height: 1 }),
      /* @__PURE__ */ (0, import_jsx_runtime52.jsx)(Text3, { bold: true, color: theme.text.primary, children: t4("Keyboard Shortcuts:") }),
      /* @__PURE__ */ (0, import_jsx_runtime52.jsxs)(Text3, { color: theme.text.primary, children: [
        /* @__PURE__ */ (0, import_jsx_runtime52.jsx)(Text3, { bold: true, color: theme.text.accent, children: "Alt+Left/Right" }),
        " ",
        "- ",
        t4("Jump through words in the input")
      ] }),
      /* @__PURE__ */ (0, import_jsx_runtime52.jsxs)(Text3, { color: theme.text.primary, children: [
        /* @__PURE__ */ (0, import_jsx_runtime52.jsx)(Text3, { bold: true, color: theme.text.accent, children: "Ctrl+C" }),
        " ",
        "- ",
        t4("Close dialogs, cancel requests, or quit application")
      ] }),
      /* @__PURE__ */ (0, import_jsx_runtime52.jsxs)(Text3, { color: theme.text.primary, children: [
        /* @__PURE__ */ (0, import_jsx_runtime52.jsx)(Text3, { bold: true, color: theme.text.accent, children: process.platform === "win32" ? "Ctrl+Enter" : "Ctrl+J" }),
        " ",
        "-",
        " ",
        process.platform === "linux" ? t4("New line (Alt+Enter works for certain linux distros)") : t4("New line")
      ] }),
      /* @__PURE__ */ (0, import_jsx_runtime52.jsxs)(Text3, { color: theme.text.primary, children: [
        /* @__PURE__ */ (0, import_jsx_runtime52.jsx)(Text3, { bold: true, color: theme.text.accent, children: "Ctrl+L" }),
        " ",
        "- ",
        t4("Clear the screen")
      ] }),
      /* @__PURE__ */ (0, import_jsx_runtime52.jsxs)(Text3, { color: theme.text.primary, children: [
        /* @__PURE__ */ (0, import_jsx_runtime52.jsx)(Text3, { bold: true, color: theme.text.accent, children: process.platform === "darwin" ? "Ctrl+X / Meta+Enter" : "Ctrl+X" }),
        " ",
        "- ",
        t4("Open input in external editor")
      ] }),
      /* @__PURE__ */ (0, import_jsx_runtime52.jsxs)(Text3, { color: theme.text.primary, children: [
        /* @__PURE__ */ (0, import_jsx_runtime52.jsx)(Text3, { bold: true, color: theme.text.accent, children: "Enter" }),
        " ",
        "- ",
        t4("Send message")
      ] }),
      /* @__PURE__ */ (0, import_jsx_runtime52.jsxs)(Text3, { color: theme.text.primary, children: [
        /* @__PURE__ */ (0, import_jsx_runtime52.jsx)(Text3, { bold: true, color: theme.text.accent, children: "Esc" }),
        " ",
        "- ",
        t4("Cancel operation / Clear input (double press)")
      ] }),
      /* @__PURE__ */ (0, import_jsx_runtime52.jsxs)(Text3, { color: theme.text.primary, children: [
        /* @__PURE__ */ (0, import_jsx_runtime52.jsx)(Text3, { bold: true, color: theme.text.accent, children: process.platform === "win32" ? "Tab" : "Shift+Tab" }),
        " ",
        "- ",
        t4("Cycle approval modes")
      ] }),
      /* @__PURE__ */ (0, import_jsx_runtime52.jsxs)(Text3, { color: theme.text.primary, children: [
        /* @__PURE__ */ (0, import_jsx_runtime52.jsx)(Text3, { bold: true, color: theme.text.accent, children: "Up/Down" }),
        " ",
        "- ",
        t4("Cycle through your prompt history")
      ] }),
      /* @__PURE__ */ (0, import_jsx_runtime52.jsx)(Box_default, { height: 1 }),
      /* @__PURE__ */ (0, import_jsx_runtime52.jsx)(Text3, { color: theme.text.primary, children: t4("For a full list of shortcuts, see {{docPath}}", {
        docPath: t4("docs/keyboard-shortcuts.md")
      }) })
    ]
  }
), "Help");
function formatCommandLabel(command2, prefix = "") {
  const altNames = command2.altNames?.filter(Boolean);
  const baseLabel = `${prefix}${command2.name}`;
  if (!altNames || altNames.length === 0) {
    return baseLabel;
  }
  return `${baseLabel} (${altNames.join(", ")})`;
}
__name(formatCommandLabel, "formatCommandLabel");

// packages/cli/src/ui/components/views/ExtensionsList.tsx
init_esbuild_shims();
var import_jsx_runtime53 = __toESM(require_jsx_runtime(), 1);
var debugLogger101 = createDebugLogger("EXTENSIONS_LIST");
var ExtensionsList = /* @__PURE__ */ __name(() => {
  const { extensionsUpdateState, commandContext } = useUIState();
  const extensions = commandContext.services.config?.getExtensions() || [];
  if (extensions.length === 0) {
    return /* @__PURE__ */ (0, import_jsx_runtime53.jsx)(Text3, { children: "No extensions installed." });
  }
  return /* @__PURE__ */ (0, import_jsx_runtime53.jsxs)(Box_default, { flexDirection: "column", marginTop: 1, marginBottom: 1, children: [
    /* @__PURE__ */ (0, import_jsx_runtime53.jsx)(Text3, { children: "Installed extensions:" }),
    /* @__PURE__ */ (0, import_jsx_runtime53.jsx)(Box_default, { flexDirection: "column", paddingLeft: 2, children: extensions.map((ext2) => {
      const state = extensionsUpdateState.get(ext2.name);
      const isActive = ext2.isActive;
      const activeString = isActive ? "active" : "disabled";
      const activeColor = isActive ? "green" : "grey";
      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 */:
        case "updated" /* UPDATED */:
          stateColor = "green";
          break;
        default:
          debugLogger101.error(`Unhandled ExtensionUpdateState ${state}`);
          break;
      }
      return /* @__PURE__ */ (0, import_jsx_runtime53.jsxs)(Box_default, { flexDirection: "column", marginBottom: 1, children: [
        /* @__PURE__ */ (0, import_jsx_runtime53.jsxs)(Text3, { children: [
          /* @__PURE__ */ (0, import_jsx_runtime53.jsx)(Text3, { color: "cyan", children: `${ext2.name} (v${ext2.version})` }),
          /* @__PURE__ */ (0, import_jsx_runtime53.jsx)(Text3, { color: activeColor, children: ` - ${activeString}` }),
          /* @__PURE__ */ (0, import_jsx_runtime53.jsx)(Text3, { color: stateColor, children: ` (${stateText})` })
        ] }),
        ext2.resolvedSettings && ext2.resolvedSettings.length > 0 && /* @__PURE__ */ (0, import_jsx_runtime53.jsxs)(Box_default, { flexDirection: "column", paddingLeft: 2, children: [
          /* @__PURE__ */ (0, import_jsx_runtime53.jsx)(Text3, { children: "settings:" }),
          ext2.resolvedSettings.map((setting) => /* @__PURE__ */ (0, import_jsx_runtime53.jsxs)(Text3, { children: [
            "- ",
            setting.name,
            ": ",
            setting.value
          ] }, setting.name))
        ] })
      ] }, ext2.name);
    }) })
  ] });
}, "ExtensionsList");

// packages/cli/src/ui/components/views/SkillsList.tsx
init_esbuild_shims();
var import_jsx_runtime54 = __toESM(require_jsx_runtime(), 1);
var SkillsList = /* @__PURE__ */ __name(({ skills }) => /* @__PURE__ */ (0, import_jsx_runtime54.jsxs)(Box_default, { flexDirection: "column", marginBottom: 1, children: [
  /* @__PURE__ */ (0, import_jsx_runtime54.jsx)(Text3, { bold: true, color: theme.text.primary, children: t4("Available skills:") }),
  /* @__PURE__ */ (0, import_jsx_runtime54.jsx)(Box_default, { height: 1 }),
  skills.length > 0 ? skills.map((skill) => /* @__PURE__ */ (0, import_jsx_runtime54.jsxs)(Box_default, { flexDirection: "row", children: [
    /* @__PURE__ */ (0, import_jsx_runtime54.jsxs)(Text3, { color: theme.text.primary, children: [
      "  ",
      "- "
    ] }),
    /* @__PURE__ */ (0, import_jsx_runtime54.jsx)(Text3, { bold: true, color: theme.text.accent, children: skill.name })
  ] }, skill.name)) : /* @__PURE__ */ (0, import_jsx_runtime54.jsxs)(Text3, { color: theme.text.primary, children: [
    " ",
    t4("No skills available")
  ] })
] }), "SkillsList");

// packages/cli/src/ui/components/views/ToolsList.tsx
init_esbuild_shims();
var import_jsx_runtime55 = __toESM(require_jsx_runtime(), 1);
var ToolsList = /* @__PURE__ */ __name(({
  tools,
  showDescriptions,
  contentWidth
}) => /* @__PURE__ */ (0, import_jsx_runtime55.jsxs)(Box_default, { flexDirection: "column", children: [
  /* @__PURE__ */ (0, import_jsx_runtime55.jsx)(Text3, { bold: true, color: theme.text.primary, children: t4("Available Qwen Code CLI tools:") }),
  /* @__PURE__ */ (0, import_jsx_runtime55.jsx)(Box_default, { height: 1 }),
  tools.length > 0 ? tools.map((tool) => /* @__PURE__ */ (0, import_jsx_runtime55.jsxs)(Box_default, { flexDirection: "row", children: [
    /* @__PURE__ */ (0, import_jsx_runtime55.jsxs)(Text3, { color: theme.text.primary, children: [
      "  ",
      "- "
    ] }),
    /* @__PURE__ */ (0, import_jsx_runtime55.jsxs)(Box_default, { flexDirection: "column", children: [
      /* @__PURE__ */ (0, import_jsx_runtime55.jsxs)(Text3, { bold: true, color: theme.text.accent, children: [
        tool.displayName,
        showDescriptions ? ` (${tool.name})` : ""
      ] }),
      showDescriptions && tool.description && /* @__PURE__ */ (0, import_jsx_runtime55.jsx)(
        MarkdownDisplay,
        {
          contentWidth,
          text: tool.description,
          isPending: false
        }
      )
    ] })
  ] }, tool.name)) : /* @__PURE__ */ (0, import_jsx_runtime55.jsxs)(Text3, { color: theme.text.primary, children: [
    " ",
    t4("No tools available")
  ] })
] }), "ToolsList");

// packages/cli/src/ui/components/views/McpStatus.tsx
init_esbuild_shims();
var import_jsx_runtime56 = __toESM(require_jsx_runtime(), 1);
var McpStatus = /* @__PURE__ */ __name(({
  servers,
  tools,
  prompts: prompts3,
  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_runtime56.jsx)(Box_default, { flexDirection: "column", children: /* @__PURE__ */ (0, import_jsx_runtime56.jsx)(Text3, { children: t4("No MCP servers configured.") }) });
  }
  return /* @__PURE__ */ (0, import_jsx_runtime56.jsxs)(Box_default, { flexDirection: "column", children: [
    discoveryInProgress && /* @__PURE__ */ (0, import_jsx_runtime56.jsxs)(Box_default, { flexDirection: "column", marginBottom: 1, children: [
      /* @__PURE__ */ (0, import_jsx_runtime56.jsx)(Text3, { color: theme.status.warning, children: t4("\u23F3 MCP servers are starting up ({{count}} initializing)...", {
        count: String(connectingServers.length)
      }) }),
      /* @__PURE__ */ (0, import_jsx_runtime56.jsx)(Text3, { color: theme.text.primary, children: t4(
        "Note: First startup may take longer. Tool availability will update automatically."
      ) })
    ] }),
    /* @__PURE__ */ (0, import_jsx_runtime56.jsx)(Text3, { bold: true, children: t4("Configured MCP servers:") }),
    /* @__PURE__ */ (0, import_jsx_runtime56.jsx)(Box_default, { height: 1 }),
    serverNames.map((serverName) => {
      const server = servers[serverName];
      const serverTools = tools.filter(
        (tool) => tool.serverName === serverName
      );
      const serverPrompts = prompts3.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 = t4("Ready");
          statusColor = theme.status.success;
          break;
        case MCPServerStatus.CONNECTING:
          statusIndicator = "\u{1F504}";
          statusText = t4("Starting... (first startup may take longer)");
          statusColor = theme.status.warning;
          break;
        case MCPServerStatus.DISCONNECTED:
        default:
          statusIndicator = "\u{1F534}";
          statusText = t4("Disconnected");
          statusColor = theme.status.error;
          break;
      }
      let serverDisplayName = serverName;
      if (server.extensionName) {
        serverDisplayName += ` ${t4("(from {{extensionName}})", {
          extensionName: server.extensionName
        })}`;
      }
      const toolCount = serverTools.length;
      const promptCount = serverPrompts.length;
      const parts = [];
      if (toolCount > 0) {
        parts.push(
          toolCount === 1 ? t4("{{count}} tool", { count: String(toolCount) }) : t4("{{count}} tools", { count: String(toolCount) })
        );
      }
      if (promptCount > 0) {
        parts.push(
          promptCount === 1 ? t4("{{count}} prompt", { count: String(promptCount) }) : t4("{{count}} prompts", { count: String(promptCount) })
        );
      }
      const serverAuthStatus = authStatus[serverName];
      let authStatusNode = null;
      if (serverAuthStatus === "authenticated") {
        authStatusNode = /* @__PURE__ */ (0, import_jsx_runtime56.jsxs)(Text3, { children: [
          " (",
          t4("OAuth"),
          ")"
        ] });
      } else if (serverAuthStatus === "expired") {
        authStatusNode = /* @__PURE__ */ (0, import_jsx_runtime56.jsxs)(Text3, { color: theme.status.error, children: [
          " (",
          t4("OAuth expired"),
          ")"
        ] });
      } else if (serverAuthStatus === "unauthenticated") {
        authStatusNode = /* @__PURE__ */ (0, import_jsx_runtime56.jsxs)(Text3, { color: theme.status.warning, children: [
          " ",
          "(",
          t4("OAuth not authenticated"),
          ")"
        ] });
      }
      return /* @__PURE__ */ (0, import_jsx_runtime56.jsxs)(Box_default, { flexDirection: "column", marginBottom: 1, children: [
        /* @__PURE__ */ (0, import_jsx_runtime56.jsxs)(Box_default, { children: [
          /* @__PURE__ */ (0, import_jsx_runtime56.jsxs)(Text3, { color: statusColor, children: [
            statusIndicator,
            " "
          ] }),
          /* @__PURE__ */ (0, import_jsx_runtime56.jsx)(Text3, { bold: true, children: serverDisplayName }),
          /* @__PURE__ */ (0, import_jsx_runtime56.jsxs)(Text3, { children: [
            " - ",
            statusText,
            status === MCPServerStatus.CONNECTED && parts.length > 0 && ` (${parts.join(", ")})`
          ] }),
          authStatusNode
        ] }),
        status === MCPServerStatus.CONNECTING && /* @__PURE__ */ (0, import_jsx_runtime56.jsxs)(Text3, { children: [
          " (",
          t4("tools and prompts will appear when ready"),
          ")"
        ] }),
        status === MCPServerStatus.DISCONNECTED && toolCount > 0 && /* @__PURE__ */ (0, import_jsx_runtime56.jsxs)(Text3, { children: [
          "(",
          t4("{{count}} tools cached", { count: String(toolCount) }),
          ")"
        ] }),
        showDescriptions && server?.description && /* @__PURE__ */ (0, import_jsx_runtime56.jsx)(Text3, { color: theme.text.secondary, children: server.description.trim() }),
        serverTools.length > 0 && /* @__PURE__ */ (0, import_jsx_runtime56.jsxs)(Box_default, { flexDirection: "column", marginLeft: 2, children: [
          /* @__PURE__ */ (0, import_jsx_runtime56.jsx)(Text3, { color: theme.text.primary, children: t4("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_runtime56.jsxs)(Box_default, { flexDirection: "column", children: [
              /* @__PURE__ */ (0, import_jsx_runtime56.jsxs)(Text3, { children: [
                "- ",
                /* @__PURE__ */ (0, import_jsx_runtime56.jsx)(Text3, { color: theme.text.primary, children: tool.name })
              ] }),
              showDescriptions && tool.description && /* @__PURE__ */ (0, import_jsx_runtime56.jsx)(Box_default, { marginLeft: 2, children: /* @__PURE__ */ (0, import_jsx_runtime56.jsx)(Text3, { color: theme.text.secondary, children: tool.description.trim() }) }),
              schemaContent && /* @__PURE__ */ (0, import_jsx_runtime56.jsxs)(Box_default, { flexDirection: "column", marginLeft: 4, children: [
                /* @__PURE__ */ (0, import_jsx_runtime56.jsx)(Text3, { color: theme.text.secondary, children: t4("Parameters:") }),
                /* @__PURE__ */ (0, import_jsx_runtime56.jsx)(Text3, { color: theme.text.secondary, children: schemaContent })
              ] })
            ] }, tool.name);
          })
        ] }),
        serverPrompts.length > 0 && /* @__PURE__ */ (0, import_jsx_runtime56.jsxs)(Box_default, { flexDirection: "column", marginLeft: 2, children: [
          /* @__PURE__ */ (0, import_jsx_runtime56.jsx)(Text3, { color: theme.text.primary, children: t4("Prompts:") }),
          serverPrompts.map((prompt) => /* @__PURE__ */ (0, import_jsx_runtime56.jsxs)(Box_default, { flexDirection: "column", children: [
            /* @__PURE__ */ (0, import_jsx_runtime56.jsxs)(Text3, { children: [
              "- ",
              /* @__PURE__ */ (0, import_jsx_runtime56.jsx)(Text3, { color: theme.text.primary, children: prompt.name })
            ] }),
            showDescriptions && prompt.description && /* @__PURE__ */ (0, import_jsx_runtime56.jsx)(Box_default, { marginLeft: 2, children: /* @__PURE__ */ (0, import_jsx_runtime56.jsx)(Text3, { color: theme.text.primary, children: prompt.description.trim() }) })
          ] }, prompt.name))
        ] })
      ] }, serverName);
    }),
    blockedServers.map((server) => /* @__PURE__ */ (0, import_jsx_runtime56.jsxs)(Box_default, { marginBottom: 1, children: [
      /* @__PURE__ */ (0, import_jsx_runtime56.jsx)(Text3, { color: theme.status.error, children: "\u{1F534} " }),
      /* @__PURE__ */ (0, import_jsx_runtime56.jsxs)(Text3, { bold: true, children: [
        server.name,
        server.extensionName ? ` ${t4("(from {{extensionName}})", {
          extensionName: server.extensionName
        })}` : ""
      ] }),
      /* @__PURE__ */ (0, import_jsx_runtime56.jsxs)(Text3, { children: [
        " - ",
        t4("Blocked")
      ] })
    ] }, server.name)),
    showTips && /* @__PURE__ */ (0, import_jsx_runtime56.jsxs)(Box_default, { flexDirection: "column", marginTop: 1, children: [
      /* @__PURE__ */ (0, import_jsx_runtime56.jsx)(Text3, { color: theme.text.accent, children: t4("\u{1F4A1} Tips:") }),
      /* @__PURE__ */ (0, import_jsx_runtime56.jsxs)(Text3, { children: [
        "  ",
        "- ",
        t4("Use"),
        " ",
        /* @__PURE__ */ (0, import_jsx_runtime56.jsx)(Text3, { color: theme.text.accent, children: "/mcp desc" }),
        " ",
        t4("to show server and tool descriptions")
      ] }),
      /* @__PURE__ */ (0, import_jsx_runtime56.jsxs)(Text3, { children: [
        "  ",
        "- ",
        t4("Use"),
        " ",
        /* @__PURE__ */ (0, import_jsx_runtime56.jsx)(Text3, { color: theme.text.accent, children: "/mcp schema" }),
        " ",
        t4("to show tool parameter schemas")
      ] }),
      /* @__PURE__ */ (0, import_jsx_runtime56.jsxs)(Text3, { children: [
        "  ",
        "- ",
        t4("Use"),
        " ",
        /* @__PURE__ */ (0, import_jsx_runtime56.jsx)(Text3, { color: theme.text.accent, children: "/mcp nodesc" }),
        " ",
        t4("to hide descriptions")
      ] }),
      /* @__PURE__ */ (0, import_jsx_runtime56.jsxs)(Text3, { children: [
        "  ",
        "- ",
        t4("Use"),
        " ",
        /* @__PURE__ */ (0, import_jsx_runtime56.jsx)(Text3, { color: theme.text.accent, children: "/mcp auth <server-name>" }),
        " ",
        t4("to authenticate with OAuth-enabled servers")
      ] }),
      /* @__PURE__ */ (0, import_jsx_runtime56.jsxs)(Text3, { children: [
        "  ",
        "- ",
        t4("Press"),
        " ",
        /* @__PURE__ */ (0, import_jsx_runtime56.jsx)(Text3, { color: theme.text.accent, children: "Ctrl+T" }),
        " ",
        t4("to toggle tool descriptions on/off")
      ] })
    ] })
  ] });
}, "McpStatus");

// packages/cli/src/ui/components/messages/InsightProgressMessage.tsx
init_esbuild_shims();
var import_jsx_runtime57 = __toESM(require_jsx_runtime(), 1);
var InsightProgressMessage = /* @__PURE__ */ __name(({
  progress
}) => {
  const { stage, progress: percent, isComplete, error: error2 } = progress;
  const width = 30;
  const completedWidth = Math.round(percent / 100 * width);
  const remainingWidth = width - completedWidth;
  const bar = "\u2588".repeat(Math.max(0, completedWidth)) + "\u2591".repeat(Math.max(0, remainingWidth));
  if (error2) {
    return /* @__PURE__ */ (0, import_jsx_runtime57.jsxs)(Box_default, { flexDirection: "column", children: [
      /* @__PURE__ */ (0, import_jsx_runtime57.jsxs)(Text3, { color: theme.status.error, children: [
        "\u2715 ",
        stage
      ] }),
      /* @__PURE__ */ (0, import_jsx_runtime57.jsx)(Text3, { color: theme.text.secondary, children: error2 })
    ] });
  }
  if (isComplete) {
    return /* @__PURE__ */ (0, import_jsx_runtime57.jsx)(Box_default, { flexDirection: "row", children: /* @__PURE__ */ (0, import_jsx_runtime57.jsxs)(Text3, { color: theme.status.success, children: [
      "\u2713 ",
      stage
    ] }) });
  }
  return /* @__PURE__ */ (0, import_jsx_runtime57.jsxs)(Box_default, { flexDirection: "row", children: [
    /* @__PURE__ */ (0, import_jsx_runtime57.jsx)(Text3, { color: theme.text.accent, children: /* @__PURE__ */ (0, import_jsx_runtime57.jsx)(build_default, { type: "dots" }) }),
    /* @__PURE__ */ (0, import_jsx_runtime57.jsx)(Text3, { children: " " }),
    /* @__PURE__ */ (0, import_jsx_runtime57.jsxs)(Text3, { color: theme.text.secondary, children: [
      bar,
      " "
    ] }),
    /* @__PURE__ */ (0, import_jsx_runtime57.jsxs)(Text3, { color: theme.text.accent, children: [
      stage,
      progress.detail ? ` (${progress.detail})` : ""
    ] })
  ] });
}, "InsightProgressMessage");

// packages/cli/src/ui/components/HistoryItemDisplay.tsx
var import_jsx_runtime58 = __toESM(require_jsx_runtime(), 1);
var HistoryItemDisplayComponent = /* @__PURE__ */ __name(({
  item,
  availableTerminalHeight,
  terminalWidth,
  mainAreaWidth,
  isPending,
  commands,
  isFocused = true,
  activeShellPtyId,
  embeddedShellFocused,
  availableTerminalHeightGemini
}) => {
  const itemForDisplay = (0, import_react67.useMemo)(() => escapeAnsiCtrlCodes(item), [item]);
  const contentWidth = terminalWidth - 4;
  const boxWidth = mainAreaWidth || contentWidth;
  return /* @__PURE__ */ (0, import_jsx_runtime58.jsxs)(
    Box_default,
    {
      flexDirection: "column",
      marginLeft: 2,
      marginRight: 2,
      children: [
        itemForDisplay.type === "user" && /* @__PURE__ */ (0, import_jsx_runtime58.jsx)(UserMessage, { text: itemForDisplay.text }),
        itemForDisplay.type === "user_shell" && /* @__PURE__ */ (0, import_jsx_runtime58.jsx)(UserShellMessage, { text: itemForDisplay.text }),
        itemForDisplay.type === "gemini" && /* @__PURE__ */ (0, import_jsx_runtime58.jsx)(
          GeminiMessage,
          {
            text: itemForDisplay.text,
            isPending,
            availableTerminalHeight: availableTerminalHeightGemini ?? availableTerminalHeight,
            contentWidth
          }
        ),
        itemForDisplay.type === "gemini_content" && /* @__PURE__ */ (0, import_jsx_runtime58.jsx)(
          GeminiMessageContent,
          {
            text: itemForDisplay.text,
            isPending,
            availableTerminalHeight: availableTerminalHeightGemini ?? availableTerminalHeight,
            contentWidth
          }
        ),
        itemForDisplay.type === "gemini_thought" && /* @__PURE__ */ (0, import_jsx_runtime58.jsx)(
          GeminiThoughtMessage,
          {
            text: itemForDisplay.text,
            isPending,
            availableTerminalHeight: availableTerminalHeightGemini ?? availableTerminalHeight,
            contentWidth
          }
        ),
        itemForDisplay.type === "gemini_thought_content" && /* @__PURE__ */ (0, import_jsx_runtime58.jsx)(
          GeminiThoughtMessageContent,
          {
            text: itemForDisplay.text,
            isPending,
            availableTerminalHeight: availableTerminalHeightGemini ?? availableTerminalHeight,
            contentWidth
          }
        ),
        itemForDisplay.type === "info" && /* @__PURE__ */ (0, import_jsx_runtime58.jsx)(InfoMessage, { text: itemForDisplay.text }),
        itemForDisplay.type === "warning" && /* @__PURE__ */ (0, import_jsx_runtime58.jsx)(WarningMessage, { text: itemForDisplay.text }),
        itemForDisplay.type === "error" && /* @__PURE__ */ (0, import_jsx_runtime58.jsx)(ErrorMessage, { text: itemForDisplay.text }),
        itemForDisplay.type === "retry_countdown" && /* @__PURE__ */ (0, import_jsx_runtime58.jsx)(RetryCountdownMessage, { text: itemForDisplay.text }),
        itemForDisplay.type === "about" && /* @__PURE__ */ (0, import_jsx_runtime58.jsx)(AboutBox, { ...itemForDisplay.systemInfo, width: boxWidth }),
        itemForDisplay.type === "help" && commands && /* @__PURE__ */ (0, import_jsx_runtime58.jsx)(Help, { commands, width: boxWidth }),
        itemForDisplay.type === "stats" && /* @__PURE__ */ (0, import_jsx_runtime58.jsx)(StatsDisplay, { duration: itemForDisplay.duration, width: boxWidth }),
        itemForDisplay.type === "model_stats" && /* @__PURE__ */ (0, import_jsx_runtime58.jsx)(ModelStatsDisplay, { width: boxWidth }),
        itemForDisplay.type === "tool_stats" && /* @__PURE__ */ (0, import_jsx_runtime58.jsx)(ToolStatsDisplay, { width: boxWidth }),
        itemForDisplay.type === "quit" && /* @__PURE__ */ (0, import_jsx_runtime58.jsx)(
          SessionSummaryDisplay,
          {
            duration: itemForDisplay.duration,
            width: boxWidth
          }
        ),
        itemForDisplay.type === "tool_group" && /* @__PURE__ */ (0, import_jsx_runtime58.jsx)(
          ToolGroupMessage,
          {
            toolCalls: itemForDisplay.tools,
            groupId: itemForDisplay.id,
            availableTerminalHeight,
            contentWidth,
            isFocused,
            activeShellPtyId,
            embeddedShellFocused
          }
        ),
        itemForDisplay.type === "compression" && /* @__PURE__ */ (0, import_jsx_runtime58.jsx)(CompressionMessage, { compression: itemForDisplay.compression }),
        item.type === "summary" && /* @__PURE__ */ (0, import_jsx_runtime58.jsx)(SummaryMessage, { summary: item.summary }),
        itemForDisplay.type === "extensions_list" && /* @__PURE__ */ (0, import_jsx_runtime58.jsx)(ExtensionsList, {}),
        itemForDisplay.type === "tools_list" && /* @__PURE__ */ (0, import_jsx_runtime58.jsx)(
          ToolsList,
          {
            contentWidth,
            tools: itemForDisplay.tools,
            showDescriptions: itemForDisplay.showDescriptions
          }
        ),
        itemForDisplay.type === "skills_list" && /* @__PURE__ */ (0, import_jsx_runtime58.jsx)(SkillsList, { skills: itemForDisplay.skills }),
        itemForDisplay.type === "mcp_status" && /* @__PURE__ */ (0, import_jsx_runtime58.jsx)(McpStatus, { ...itemForDisplay, serverStatus: getMCPServerStatus }),
        itemForDisplay.type === "insight_progress" && /* @__PURE__ */ (0, import_jsx_runtime58.jsx)(InsightProgressMessage, { progress: itemForDisplay.progress })
      ]
    },
    itemForDisplay.id
  );
}, "HistoryItemDisplayComponent");

// packages/cli/src/ui/hooks/useTerminalSize.ts
init_esbuild_shims();
var import_react68 = __toESM(require_react(), 1);
function useTerminalSize() {
  const [size, setSize] = (0, import_react68.useState)({
    columns: process.stdout.columns || 80,
    rows: process.stdout.rows || 24
  });
  (0, import_react68.useEffect)(() => {
    function updateSize() {
      setSize({
        columns: process.stdout.columns || 80,
        rows: process.stdout.rows || 24
      });
    }
    __name(updateSize, "updateSize");
    process.stdout.on("resize", updateSize);
    return () => {
      process.stdout.off("resize", updateSize);
    };
  }, []);
  return size;
}
__name(useTerminalSize, "useTerminalSize");

// packages/cli/src/ui/components/QuittingDisplay.tsx
var import_jsx_runtime59 = __toESM(require_jsx_runtime(), 1);
var QuittingDisplay = /* @__PURE__ */ __name(() => {
  const uiState = useUIState();
  const { rows: terminalHeight, columns: terminalWidth } = useTerminalSize();
  const availableTerminalHeight = terminalHeight;
  const { mainAreaWidth } = uiState;
  if (!uiState.quittingMessages) {
    return null;
  }
  return /* @__PURE__ */ (0, import_jsx_runtime59.jsx)(Box_default, { flexDirection: "column", marginBottom: 1, children: uiState.quittingMessages.map((item) => /* @__PURE__ */ (0, import_jsx_runtime59.jsx)(
    HistoryItemDisplayComponent,
    {
      availableTerminalHeight: uiState.constrainHeight ? availableTerminalHeight : void 0,
      terminalWidth,
      mainAreaWidth,
      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_react69 = __toESM(require_react(), 1);
var AppContext2 = (0, import_react69.createContext)(null);
var useAppContext = /* @__PURE__ */ __name(() => {
  const context2 = (0, import_react69.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_runtime60 = __toESM(require_jsx_runtime(), 1);
var UpdateNotification = /* @__PURE__ */ __name(({ message }) => /* @__PURE__ */ (0, import_jsx_runtime60.jsx)(
  Box_default,
  {
    borderStyle: "round",
    borderColor: theme.status.warning,
    paddingX: 1,
    marginY: 1,
    children: /* @__PURE__ */ (0, import_jsx_runtime60.jsx)(Text3, { color: theme.status.warning, children: message })
  }
), "UpdateNotification");

// packages/cli/src/ui/components/Notifications.tsx
var import_jsx_runtime61 = __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 */;
  return /* @__PURE__ */ (0, import_jsx_runtime61.jsxs)(import_jsx_runtime61.Fragment, { children: [
    updateInfo && /* @__PURE__ */ (0, import_jsx_runtime61.jsx)(UpdateNotification, { message: updateInfo.message }),
    showStartupWarnings && /* @__PURE__ */ (0, import_jsx_runtime61.jsx)(
      Box_default,
      {
        borderStyle: "round",
        borderColor: theme.status.warning,
        paddingX: 1,
        marginY: 1,
        flexDirection: "column",
        children: startupWarnings.map((warning, index) => /* @__PURE__ */ (0, import_jsx_runtime61.jsx)(Text3, { color: theme.status.warning, children: warning }, index))
      }
    ),
    showInitError && /* @__PURE__ */ (0, import_jsx_runtime61.jsxs)(
      Box_default,
      {
        borderStyle: "round",
        borderColor: theme.status.error,
        paddingX: 1,
        marginBottom: 1,
        children: [
          /* @__PURE__ */ (0, import_jsx_runtime61.jsxs)(Text3, { color: theme.status.error, children: [
            "Initialization Error: ",
            initError
          ] }),
          /* @__PURE__ */ (0, import_jsx_runtime61.jsxs)(Text3, { 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_runtime62 = __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_runtime62.jsx)(Box_default, { children: /* @__PURE__ */ (0, import_jsx_runtime62.jsx)(Text3, { 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 = `
 \u2584\u2584\u2584\u2584\u2584\u2584  \u2584\u2584     \u2584\u2584 \u2584\u2584\u2584\u2584\u2584\u2584\u2584 \u2584\u2584\u2584    \u2584\u2584
\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
`;

// packages/cli/src/ui/components/Header.tsx
var import_jsx_runtime63 = __toESM(require_jsx_runtime(), 1);
function titleizeAuthType(value) {
  return value.split(/[-_]/g).filter(Boolean).map((part) => {
    if (part.toLowerCase() === "ai") {
      return "AI";
    }
    return part.charAt(0).toUpperCase() + part.slice(1);
  }).join(" ");
}
__name(titleizeAuthType, "titleizeAuthType");
function formatAuthType2(authType) {
  if (!authType) {
    return "Unknown";
  }
  switch (authType) {
    case AuthType2.QWEN_OAUTH:
      return "Qwen OAuth";
    case AuthType2.USE_OPENAI:
      return "OpenAI";
    case AuthType2.USE_GEMINI:
      return "Gemini";
    case AuthType2.USE_VERTEX_AI:
      return "Vertex AI";
    case AuthType2.USE_ANTHROPIC:
      return "Anthropic";
    default:
      return titleizeAuthType(String(authType));
  }
}
__name(formatAuthType2, "formatAuthType");
var Header2 = /* @__PURE__ */ __name(({
  customAsciiArt,
  version: version2,
  authType,
  model,
  workingDirectory
}) => {
  const { columns: terminalWidth } = useTerminalSize();
  const displayLogo = customAsciiArt ?? shortAsciiLogo;
  const logoWidth = getAsciiArtWidth(displayLogo);
  const formattedAuthType = formatAuthType2(authType);
  const containerMarginX = 2;
  const logoGap = 2;
  const infoPanelPaddingX = 1;
  const infoPanelBorderWidth = 2;
  const infoPanelChromeWidth = infoPanelBorderWidth + infoPanelPaddingX * 2;
  const minPathLength = 40;
  const minInfoPanelWidth = minPathLength + infoPanelChromeWidth;
  const availableTerminalWidth = Math.max(
    0,
    terminalWidth - containerMarginX * 2
  );
  const showLogo = availableTerminalWidth >= logoWidth + logoGap + minInfoPanelWidth;
  const maxInfoPanelWidth = 60;
  const availableInfoPanelWidth = showLogo ? Math.min(availableTerminalWidth - logoWidth - logoGap, maxInfoPanelWidth) : availableTerminalWidth;
  const maxPathLength = Math.max(
    0,
    availableInfoPanelWidth - infoPanelChromeWidth
  );
  const infoPanelContentWidth = Math.max(
    0,
    availableInfoPanelWidth - infoPanelChromeWidth
  );
  const authModelText = `${formattedAuthType} | ${model}`;
  const modelHintText = " (/model to change)";
  const showModelHint = infoPanelContentWidth > 0 && getCachedStringWidth(authModelText + modelHintText) <= infoPanelContentWidth;
  const tildeifiedPath = tildeifyPath(workingDirectory);
  const shortenedPath = shortenPath(tildeifiedPath, Math.max(3, maxPathLength));
  const displayPath = maxPathLength <= 0 ? "" : shortenedPath.length > maxPathLength ? shortenedPath.slice(0, maxPathLength) : shortenedPath;
  const gradientColors = theme.ui.gradient || [
    theme.text.secondary,
    theme.text.link,
    theme.text.accent
  ];
  return /* @__PURE__ */ (0, import_jsx_runtime63.jsxs)(
    Box_default,
    {
      flexDirection: "row",
      alignItems: "center",
      marginX: containerMarginX,
      width: availableTerminalWidth,
      children: [
        showLogo && /* @__PURE__ */ (0, import_jsx_runtime63.jsxs)(import_jsx_runtime63.Fragment, { children: [
          /* @__PURE__ */ (0, import_jsx_runtime63.jsx)(Box_default, { flexShrink: 0, children: /* @__PURE__ */ (0, import_jsx_runtime63.jsx)(dist_default5, { colors: gradientColors, children: /* @__PURE__ */ (0, import_jsx_runtime63.jsx)(Text3, { children: displayLogo }) }) }),
          /* @__PURE__ */ (0, import_jsx_runtime63.jsx)(Box_default, { width: logoGap })
        ] }),
        /* @__PURE__ */ (0, import_jsx_runtime63.jsxs)(
          Box_default,
          {
            flexDirection: "column",
            borderStyle: "round",
            borderColor: theme.border.default,
            paddingX: infoPanelPaddingX,
            flexGrow: showLogo ? 0 : 1,
            width: showLogo ? availableInfoPanelWidth : void 0,
            children: [
              /* @__PURE__ */ (0, import_jsx_runtime63.jsxs)(Text3, { children: [
                /* @__PURE__ */ (0, import_jsx_runtime63.jsx)(Text3, { bold: true, color: theme.text.accent, children: ">_ Qwen Code" }),
                /* @__PURE__ */ (0, import_jsx_runtime63.jsxs)(Text3, { color: theme.text.secondary, children: [
                  " (v",
                  version2,
                  ")"
                ] })
              ] }),
              /* @__PURE__ */ (0, import_jsx_runtime63.jsx)(Text3, { children: " " }),
              /* @__PURE__ */ (0, import_jsx_runtime63.jsxs)(Text3, { children: [
                /* @__PURE__ */ (0, import_jsx_runtime63.jsx)(Text3, { color: theme.text.secondary, children: authModelText }),
                showModelHint && /* @__PURE__ */ (0, import_jsx_runtime63.jsx)(Text3, { color: theme.text.secondary, children: modelHintText })
              ] }),
              /* @__PURE__ */ (0, import_jsx_runtime63.jsx)(Text3, { color: theme.text.secondary, children: displayPath })
            ]
          }
        )
      ]
    }
  );
}, "Header");

// packages/cli/src/ui/components/Tips.tsx
init_esbuild_shims();
var import_react70 = __toESM(require_react(), 1);
var import_jsx_runtime64 = __toESM(require_jsx_runtime(), 1);
var startupTips = [
  "Use /compress when the conversation gets long to summarize history and free up context.",
  "Start a fresh idea with /clear or /new; the previous session stays available in history.",
  "Use /bug to submit issues to the maintainers when something goes off.",
  "Switch auth type quickly with /auth.",
  "You can run any shell commands from Qwen Code using ! (e.g. !ls).",
  "Type / to open the command popup; Tab autocompletes slash commands and saved prompts.",
  "You can resume a previous conversation by running qwen --continue or qwen --resume.",
  process.platform === "win32" ? "You can switch permission mode quickly with Tab or /approval-mode." : "You can switch permission mode quickly with Shift+Tab or /approval-mode.",
  {
    text: "Try /insight to generate personalized insights from your chat history.",
    weight: 3
  }
];
function tipText(tip) {
  return typeof tip === "string" ? tip : tip.text;
}
__name(tipText, "tipText");
function tipWeight(tip) {
  return typeof tip === "string" ? 1 : tip.weight;
}
__name(tipWeight, "tipWeight");
function selectWeightedTip(tips) {
  const totalWeight = tips.reduce((sum, tip) => sum + tipWeight(tip), 0);
  let random2 = Math.random() * totalWeight;
  for (const tip of tips) {
    random2 -= tipWeight(tip);
    if (random2 <= 0) {
      return tipText(tip);
    }
  }
  return tipText(tips[tips.length - 1]);
}
__name(selectWeightedTip, "selectWeightedTip");
var Tips = /* @__PURE__ */ __name(() => {
  const selectedTip = (0, import_react70.useMemo)(() => selectWeightedTip(startupTips), []);
  return /* @__PURE__ */ (0, import_jsx_runtime64.jsx)(Box_default, { marginLeft: 2, marginRight: 2, children: /* @__PURE__ */ (0, import_jsx_runtime64.jsxs)(Text3, { color: theme.text.secondary, children: [
    t4("Tips: "),
    t4(selectedTip)
  ] }) });
}, "Tips");

// packages/cli/src/ui/components/AppHeader.tsx
var import_jsx_runtime65 = __toESM(require_jsx_runtime(), 1);
var AppHeader = /* @__PURE__ */ __name(({ version: version2 }) => {
  const settings = useSettings();
  const config2 = useConfig();
  const uiState = useUIState();
  const contentGeneratorConfig = config2.getContentGeneratorConfig();
  const authType = contentGeneratorConfig?.authType;
  const model = uiState.currentModel;
  const targetDir = config2.getTargetDir();
  const showBanner = !config2.getScreenReader();
  const showTips = !(settings.merged.ui?.hideTips || config2.getScreenReader());
  return /* @__PURE__ */ (0, import_jsx_runtime65.jsxs)(Box_default, { flexDirection: "column", children: [
    showBanner && /* @__PURE__ */ (0, import_jsx_runtime65.jsx)(
      Header2,
      {
        version: version2,
        authType,
        model,
        workingDirectory: targetDir
      }
    ),
    showTips && /* @__PURE__ */ (0, import_jsx_runtime65.jsx)(Tips, {})
  ] });
}, "AppHeader");

// packages/cli/src/ui/components/DebugModeNotification.tsx
init_esbuild_shims();
var import_jsx_runtime66 = __toESM(require_jsx_runtime(), 1);
var DebugModeNotification = /* @__PURE__ */ __name(() => {
  const config2 = useConfig();
  if (!config2.getDebugMode()) {
    return null;
  }
  const logPath = Storage.getDebugLogPath(config2.getSessionId());
  const isDegraded = isDebugLoggingDegraded();
  return /* @__PURE__ */ (0, import_jsx_runtime66.jsxs)(Box_default, { paddingX: 1, marginTop: 1, flexDirection: "column", children: [
    /* @__PURE__ */ (0, import_jsx_runtime66.jsx)(Text3, { color: theme.status.warning, children: "Debug mode enabled" }),
    /* @__PURE__ */ (0, import_jsx_runtime66.jsxs)(Text3, { dimColor: true, children: [
      "Logging to: ",
      logPath
    ] }),
    isDegraded && /* @__PURE__ */ (0, import_jsx_runtime66.jsx)(Text3, { dimColor: true, children: "Warning: Debug logging is degraded (write failures occurred)" })
  ] });
}, "DebugModeNotification");

// packages/cli/src/ui/components/MainContent.tsx
var import_jsx_runtime67 = __toESM(require_jsx_runtime(), 1);
var MAX_GEMINI_MESSAGE_LINES = 65536;
var MainContent = /* @__PURE__ */ __name(() => {
  const { version: version2 } = useAppContext();
  const uiState = useUIState();
  const {
    pendingHistoryItems,
    terminalWidth,
    mainAreaWidth,
    staticAreaMaxItemHeight,
    availableTerminalHeight
  } = uiState;
  return /* @__PURE__ */ (0, import_jsx_runtime67.jsxs)(import_jsx_runtime67.Fragment, { children: [
    /* @__PURE__ */ (0, import_jsx_runtime67.jsx)(
      Static,
      {
        items: [
          /* @__PURE__ */ (0, import_jsx_runtime67.jsx)(AppHeader, { version: version2 }, "app-header"),
          /* @__PURE__ */ (0, import_jsx_runtime67.jsx)(DebugModeNotification, {}, "debug-notification"),
          /* @__PURE__ */ (0, import_jsx_runtime67.jsx)(Notifications, {}, "notifications"),
          ...uiState.history.map((h3) => /* @__PURE__ */ (0, import_jsx_runtime67.jsx)(
            HistoryItemDisplayComponent,
            {
              terminalWidth,
              mainAreaWidth,
              availableTerminalHeight: staticAreaMaxItemHeight,
              availableTerminalHeightGemini: MAX_GEMINI_MESSAGE_LINES,
              item: h3,
              isPending: false,
              commands: uiState.slashCommands
            },
            h3.id
          ))
        ],
        children: (item) => item
      },
      `${uiState.historyRemountKey}-${uiState.currentModel}`
    ),
    /* @__PURE__ */ (0, import_jsx_runtime67.jsx)(OverflowProvider, { children: /* @__PURE__ */ (0, import_jsx_runtime67.jsxs)(Box_default, { flexDirection: "column", children: [
      pendingHistoryItems.map((item, i3) => /* @__PURE__ */ (0, import_jsx_runtime67.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
        },
        i3
      )),
      /* @__PURE__ */ (0, import_jsx_runtime67.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_runtime68 = __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 isInSandbox = !!process.env["SANDBOX"];
  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 = isInSandbox ? `Note: In sandbox environments, IDE integration requires manual setup on the host system. If you select Yes, you'll receive instructions on how to set this up.` : isExtensionPreInstalled ? `If you select Yes, the CLI will connect to your ${ideName ?? "editor"} and have access to your open files and display diffs directly.` : `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_runtime68.jsxs)(
    Box_default,
    {
      flexDirection: "column",
      borderStyle: "round",
      borderColor: theme.status.warning,
      padding: 1,
      width: "100%",
      marginLeft: 1,
      children: [
        /* @__PURE__ */ (0, import_jsx_runtime68.jsxs)(Box_default, { marginBottom: 1, flexDirection: "column", children: [
          /* @__PURE__ */ (0, import_jsx_runtime68.jsxs)(Text3, { children: [
            /* @__PURE__ */ (0, import_jsx_runtime68.jsx)(Text3, { color: theme.status.warning, children: "> " }),
            `Do you want to connect ${ideName ?? "your editor"} to Qwen Code?`
          ] }),
          /* @__PURE__ */ (0, import_jsx_runtime68.jsx)(Text3, { color: theme.text.secondary, children: installText })
        ] }),
        /* @__PURE__ */ (0, import_jsx_runtime68.jsx)(RadioButtonSelect, { items: OPTIONS, onSelect: onComplete })
      ]
    }
  );
}
__name(IdeIntegrationNudge, "IdeIntegrationNudge");

// packages/cli/src/ui/CommandFormatMigrationNudge.tsx
init_esbuild_shims();
var import_jsx_runtime69 = __toESM(require_jsx_runtime(), 1);
function CommandFormatMigrationNudge({
  tomlFiles,
  onComplete
}) {
  useKeypress(
    (key) => {
      if (key.name === "escape") {
        onComplete({
          userSelection: "no"
        });
      }
    },
    { isActive: true }
  );
  const OPTIONS = [
    {
      label: t4("Yes"),
      value: {
        userSelection: "yes"
      },
      key: "Yes"
    },
    {
      label: t4("No (esc)"),
      value: {
        userSelection: "no"
      },
      key: "No (esc)"
    }
  ];
  const count = tomlFiles.length;
  const fileList = count <= 3 ? tomlFiles.map((f5) => `  \u2022 ${f5}`).join("\n") : `  \u2022 ${tomlFiles.slice(0, 2).join("\n  \u2022 ")}
  \u2022 ${t4("... and {{count}} more", { count: String(count - 2) })}`;
  return /* @__PURE__ */ (0, import_jsx_runtime69.jsxs)(
    Box_default,
    {
      flexDirection: "column",
      borderStyle: "round",
      borderColor: theme.status.warning,
      padding: 1,
      width: "100%",
      marginLeft: 1,
      children: [
        /* @__PURE__ */ (0, import_jsx_runtime69.jsxs)(Box_default, { marginBottom: 1, flexDirection: "column", children: [
          /* @__PURE__ */ (0, import_jsx_runtime69.jsxs)(Text3, { children: [
            /* @__PURE__ */ (0, import_jsx_runtime69.jsx)(Text3, { color: theme.status.warning, children: "\u26A0\uFE0F  " }),
            /* @__PURE__ */ (0, import_jsx_runtime69.jsx)(Text3, { bold: true, children: t4("Command Format Migration") })
          ] }),
          /* @__PURE__ */ (0, import_jsx_runtime69.jsx)(Text3, { color: theme.text.secondary, children: count > 1 ? t4("Found {{count}} TOML command files:", { count: String(count) }) : t4("Found {{count}} TOML command file:", { count: String(count) }) }),
          /* @__PURE__ */ (0, import_jsx_runtime69.jsx)(Text3, { color: theme.text.secondary, children: fileList }),
          /* @__PURE__ */ (0, import_jsx_runtime69.jsx)(Text3, { children: "" }),
          /* @__PURE__ */ (0, import_jsx_runtime69.jsx)(Text3, { color: theme.text.secondary, children: t4(
            "The TOML format is deprecated. Would you like to migrate them to Markdown format?"
          ) }),
          /* @__PURE__ */ (0, import_jsx_runtime69.jsx)(Text3, { color: theme.text.secondary, children: t4("(Backups will be created and original files will be preserved)") })
        ] }),
        /* @__PURE__ */ (0, import_jsx_runtime69.jsx)(RadioButtonSelect, { items: OPTIONS, onSelect: onComplete })
      ]
    }
  );
}
__name(CommandFormatMigrationNudge, "CommandFormatMigrationNudge");

// packages/cli/src/ui/components/LoopDetectionConfirmation.tsx
init_esbuild_shims();
var import_jsx_runtime70 = __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_runtime70.jsx)(
    Box_default,
    {
      flexDirection: "column",
      borderStyle: "round",
      borderColor: theme.status.warning,
      width: "100%",
      marginLeft: 1,
      children: /* @__PURE__ */ (0, import_jsx_runtime70.jsxs)(Box_default, { paddingX: 1, paddingY: 0, flexDirection: "column", children: [
        /* @__PURE__ */ (0, import_jsx_runtime70.jsxs)(Box_default, { minHeight: 1, children: [
          /* @__PURE__ */ (0, import_jsx_runtime70.jsx)(Box_default, { minWidth: 3, children: /* @__PURE__ */ (0, import_jsx_runtime70.jsx)(Text3, { color: theme.status.warning, "aria-label": "Loop detected:", children: "?" }) }),
          /* @__PURE__ */ (0, import_jsx_runtime70.jsx)(Box_default, { children: /* @__PURE__ */ (0, import_jsx_runtime70.jsxs)(Text3, { wrap: "truncate-end", children: [
            /* @__PURE__ */ (0, import_jsx_runtime70.jsx)(Text3, { color: theme.text.primary, bold: true, children: "A potential loop was detected" }),
            " "
          ] }) })
        ] }),
        /* @__PURE__ */ (0, import_jsx_runtime70.jsx)(Box_default, { width: "100%", marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime70.jsxs)(Box_default, { flexDirection: "column", children: [
          /* @__PURE__ */ (0, import_jsx_runtime70.jsx)(Text3, { 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_runtime70.jsx)(Box_default, { marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime70.jsx)(RadioButtonSelect, { items: OPTIONS, onSelect: onComplete }) }),
          /* @__PURE__ */ (0, import_jsx_runtime70.jsx)(Box_default, { marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime70.jsx)(Text3, { 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_react71 = __toESM(require_react(), 1);
import * as process33 from "node:process";
import * as path106 from "node:path";

// packages/cli/src/utils/processUtils.ts
init_esbuild_shims();

// packages/cli/src/utils/cleanup.ts
init_esbuild_shims();
import { promises as fs96 } from "node:fs";
import { join as join43 } 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 (_2) {
    }
  }
  cleanupFunctions.length = 0;
}
__name(runExitCleanup, "runExitCleanup");
async function cleanupCheckpoints() {
  const storage = new Storage(process.cwd());
  const tempDir = storage.getProjectTempDir();
  const checkpointsDir = join43(tempDir, "checkpoints");
  try {
    await fs96.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_runtime71 = __toESM(require_jsx_runtime(), 1);
var FolderTrustDialog = /* @__PURE__ */ __name(({
  onSelect,
  isRestarting
}) => {
  (0, import_react71.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 = path106.basename(process33.cwd());
  const parentFolder = path106.basename(path106.dirname(process33.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_runtime71.jsxs)(Box_default, { flexDirection: "column", children: [
    /* @__PURE__ */ (0, import_jsx_runtime71.jsxs)(
      Box_default,
      {
        flexDirection: "column",
        borderStyle: "round",
        borderColor: theme.status.warning,
        padding: 1,
        width: "100%",
        marginLeft: 1,
        children: [
          /* @__PURE__ */ (0, import_jsx_runtime71.jsxs)(Box_default, { flexDirection: "column", marginBottom: 1, children: [
            /* @__PURE__ */ (0, import_jsx_runtime71.jsx)(Text3, { bold: true, color: theme.text.primary, children: "Do you trust this folder?" }),
            /* @__PURE__ */ (0, import_jsx_runtime71.jsx)(Text3, { 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_runtime71.jsx)(
            RadioButtonSelect,
            {
              items: options2,
              onSelect,
              isFocused: !isRestarting
            }
          )
        ]
      }
    ),
    isRestarting && /* @__PURE__ */ (0, import_jsx_runtime71.jsx)(Box_default, { marginLeft: 1, marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime71.jsx)(Text3, { 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_runtime72 = __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: t4("Yes, allow once"),
      value: ToolConfirmationOutcome.ProceedOnce,
      key: "Yes, allow once"
    },
    {
      label: t4("Yes, allow always for this session"),
      value: ToolConfirmationOutcome.ProceedAlways,
      key: "Yes, allow always for this session"
    },
    {
      label: t4("No (esc)"),
      value: ToolConfirmationOutcome.Cancel,
      key: "No (esc)"
    }
  ];
  return /* @__PURE__ */ (0, import_jsx_runtime72.jsxs)(
    Box_default,
    {
      flexDirection: "column",
      borderStyle: "round",
      borderColor: theme.status.warning,
      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)(Text3, { bold: true, color: theme.text.primary, children: t4("Shell Command Execution") }),
          /* @__PURE__ */ (0, import_jsx_runtime72.jsx)(Text3, { color: theme.text.primary, children: t4("A custom command wants to run the following shell commands:") }),
          /* @__PURE__ */ (0, import_jsx_runtime72.jsx)(
            Box_default,
            {
              flexDirection: "column",
              borderStyle: "round",
              borderColor: theme.border.default,
              paddingX: 1,
              marginTop: 1,
              children: commands.map((cmd) => /* @__PURE__ */ (0, import_jsx_runtime72.jsx)(Text3, { color: theme.text.link, children: /* @__PURE__ */ (0, import_jsx_runtime72.jsx)(RenderInline, { text: cmd }) }, cmd))
            }
          )
        ] }),
        /* @__PURE__ */ (0, import_jsx_runtime72.jsx)(Box_default, { marginBottom: 1, children: /* @__PURE__ */ (0, import_jsx_runtime72.jsx)(Text3, { color: theme.text.primary, children: t4("Do you want to proceed?") }) }),
        /* @__PURE__ */ (0, import_jsx_runtime72.jsx)(RadioButtonSelect, { items: options2, onSelect: handleSelect, isFocused: true })
      ]
    }
  );
}, "ShellConfirmationDialog");

// packages/cli/src/ui/components/ConsentPrompt.tsx
init_esbuild_shims();
var import_react72 = __toESM(require_react(), 1);
var import_jsx_runtime73 = __toESM(require_jsx_runtime(), 1);
var ConsentPrompt = /* @__PURE__ */ __name((props) => {
  const { prompt, onConfirm, terminalWidth } = props;
  return /* @__PURE__ */ (0, import_jsx_runtime73.jsxs)(
    Box_default,
    {
      borderStyle: "round",
      borderColor: theme.border.default,
      flexDirection: "column",
      paddingY: 1,
      paddingX: 2,
      children: [
        typeof prompt === "string" ? /* @__PURE__ */ (0, import_jsx_runtime73.jsx)(
          MarkdownDisplay,
          {
            isPending: true,
            text: prompt,
            contentWidth: terminalWidth
          }
        ) : prompt,
        /* @__PURE__ */ (0, import_jsx_runtime73.jsx)(Box_default, { marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime73.jsx)(
          RadioButtonSelect,
          {
            items: [
              { label: "Yes", value: true, key: "Yes" },
              { label: "No", value: false, key: "No" }
            ],
            onSelect: onConfirm
          }
        ) })
      ]
    }
  );
}, "ConsentPrompt");

// packages/cli/src/ui/components/SettingInputPrompt.tsx
init_esbuild_shims();
var import_react73 = __toESM(require_react(), 1);
var import_chalk7 = __toESM(require_source(), 1);
var import_jsx_runtime74 = __toESM(require_jsx_runtime(), 1);
var PasswordInput = /* @__PURE__ */ __name(({
  value,
  onChange,
  onSubmit,
  placeholder
}) => {
  useKeypress(
    (key) => {
      if (key.name === "return") {
        onSubmit();
        return;
      }
      if (key.name === "backspace" || key.name === "delete") {
        onChange(value.slice(0, -1));
        return;
      }
      if (key.ctrl && key.name === "u") {
        onChange("");
        return;
      }
      if (key.sequence && !key.ctrl && !key.meta && key.sequence.length === 1) {
        const charCode = key.sequence.charCodeAt(0);
        if (charCode >= 32 && charCode <= 126) {
          onChange(value + key.sequence);
        }
      }
    },
    { isActive: true }
  );
  const maskedValue = "*".repeat(value.length);
  const displayValue = maskedValue || "";
  const cursorChar = import_chalk7.default.inverse(" ");
  return /* @__PURE__ */ (0, import_jsx_runtime74.jsxs)(Box_default, { children: [
    /* @__PURE__ */ (0, import_jsx_runtime74.jsx)(Text3, { color: theme.text.accent, children: "> " }),
    value.length === 0 ? /* @__PURE__ */ (0, import_jsx_runtime74.jsxs)(Text3, { children: [
      cursorChar,
      /* @__PURE__ */ (0, import_jsx_runtime74.jsx)(Text3, { dimColor: true, children: placeholder.slice(1) })
    ] }) : /* @__PURE__ */ (0, import_jsx_runtime74.jsxs)(Text3, { children: [
      displayValue,
      cursorChar
    ] })
  ] });
}, "PasswordInput");
var SettingInputPrompt = /* @__PURE__ */ __name((props) => {
  const {
    settingName,
    settingDescription,
    sensitive,
    onSubmit,
    onCancel,
    terminalWidth
  } = props;
  const [value, setValue] = (0, import_react73.useState)("");
  useKeypress(
    (key) => {
      if (key.name === "escape") {
        onCancel();
      }
    },
    { isActive: true }
  );
  const handleSubmit = /* @__PURE__ */ __name(() => {
    if (value.trim()) {
      onSubmit(value);
    }
  }, "handleSubmit");
  return /* @__PURE__ */ (0, import_jsx_runtime74.jsxs)(
    Box_default,
    {
      borderStyle: "round",
      borderColor: theme.border.default,
      flexDirection: "column",
      paddingY: 1,
      paddingX: 2,
      children: [
        /* @__PURE__ */ (0, import_jsx_runtime74.jsx)(Text3, { bold: true, color: theme.text.accent, children: settingName }),
        /* @__PURE__ */ (0, import_jsx_runtime74.jsx)(Box_default, { marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime74.jsx)(Text3, { children: settingDescription }) }),
        /* @__PURE__ */ (0, import_jsx_runtime74.jsx)(Box_default, { marginTop: 1, flexDirection: "column", children: sensitive ? /* @__PURE__ */ (0, import_jsx_runtime74.jsx)(
          PasswordInput,
          {
            value,
            onChange: setValue,
            onSubmit: handleSubmit,
            placeholder: t4("Enter sensitive value...")
          }
        ) : /* @__PURE__ */ (0, import_jsx_runtime74.jsx)(
          TextInput,
          {
            value,
            onChange: setValue,
            onSubmit: handleSubmit,
            placeholder: t4("Enter value..."),
            inputWidth: Math.min(terminalWidth - 10, 60),
            isActive: true
          }
        ) }),
        /* @__PURE__ */ (0, import_jsx_runtime74.jsx)(Box_default, { marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime74.jsx)(Text3, { dimColor: true, children: t4("Press Enter to submit, Escape to cancel") }) })
      ]
    }
  );
}, "SettingInputPrompt");

// packages/cli/src/ui/components/PluginChoicePrompt.tsx
init_esbuild_shims();
var import_react74 = __toESM(require_react(), 1);
var import_jsx_runtime75 = __toESM(require_jsx_runtime(), 1);
var MAX_VISIBLE_ITEMS = 8;
var PluginChoicePrompt = /* @__PURE__ */ __name((props) => {
  const { marketplaceName, plugins, onSelect, onCancel } = props;
  const [selectedIndex, setSelectedIndex] = (0, import_react74.useState)(0);
  const prefixWidth = 2;
  const handleKeypress = (0, import_react74.useCallback)(
    (key) => {
      const { name: name3, sequence } = key;
      if (name3 === "escape") {
        onCancel();
        return;
      }
      if (name3 === "return") {
        const plugin = plugins[selectedIndex];
        if (plugin) {
          onSelect(plugin.name);
        }
        return;
      }
      if (name3 === "up" || sequence === "k") {
        setSelectedIndex((prev) => prev > 0 ? prev - 1 : plugins.length - 1);
        return;
      }
      if (name3 === "down" || sequence === "j") {
        setSelectedIndex((prev) => prev < plugins.length - 1 ? prev + 1 : 0);
        return;
      }
      const num = parseInt(sequence || "", 10);
      if (!isNaN(num) && num >= 1 && num <= plugins.length && num <= 9) {
        setSelectedIndex(num - 1);
        const plugin = plugins[num - 1];
        if (plugin) {
          onSelect(plugin.name);
        }
      }
    },
    [plugins, selectedIndex, onSelect, onCancel]
  );
  useKeypress(handleKeypress, { isActive: true });
  const { visiblePlugins, startIndex, hasMore, hasLess } = (0, import_react74.useMemo)(() => {
    const total = plugins.length;
    if (total <= MAX_VISIBLE_ITEMS) {
      return {
        visiblePlugins: plugins,
        startIndex: 0,
        hasMore: false,
        hasLess: false
      };
    }
    let start = 0;
    const halfWindow = Math.floor(MAX_VISIBLE_ITEMS / 2);
    if (selectedIndex <= halfWindow) {
      start = 0;
    } else if (selectedIndex >= total - halfWindow) {
      start = total - MAX_VISIBLE_ITEMS;
    } else {
      start = selectedIndex - halfWindow;
    }
    const end = Math.min(start + MAX_VISIBLE_ITEMS, total);
    return {
      visiblePlugins: plugins.slice(start, end),
      startIndex: start,
      hasLess: start > 0,
      hasMore: end < total
    };
  }, [plugins, selectedIndex]);
  return /* @__PURE__ */ (0, import_jsx_runtime75.jsxs)(
    Box_default,
    {
      borderStyle: "round",
      borderColor: theme.border.default,
      flexDirection: "column",
      paddingY: 1,
      paddingX: 2,
      width: "100%",
      children: [
        /* @__PURE__ */ (0, import_jsx_runtime75.jsx)(Text3, { bold: true, color: theme.text.accent, children: t4('Select a plugin from "{{name}}"', { name: marketplaceName }) }),
        /* @__PURE__ */ (0, import_jsx_runtime75.jsxs)(Box_default, { marginTop: 1, flexDirection: "column", children: [
          hasLess && /* @__PURE__ */ (0, import_jsx_runtime75.jsx)(Box_default, { children: /* @__PURE__ */ (0, import_jsx_runtime75.jsxs)(Text3, { dimColor: true, children: [
            " ",
            "\u2191 ",
            t4("{{count}} more above", { count: String(startIndex) })
          ] }) }),
          visiblePlugins.map((plugin, visibleIndex) => {
            const actualIndex = startIndex + visibleIndex;
            const isSelected = actualIndex === selectedIndex;
            const prefix = isSelected ? "\u276F " : "  ";
            return /* @__PURE__ */ (0, import_jsx_runtime75.jsxs)(Box_default, { flexDirection: "column", children: [
              /* @__PURE__ */ (0, import_jsx_runtime75.jsxs)(Box_default, { flexDirection: "row", children: [
                /* @__PURE__ */ (0, import_jsx_runtime75.jsx)(Text3, { color: isSelected ? theme.text.accent : void 0, children: prefix }),
                /* @__PURE__ */ (0, import_jsx_runtime75.jsx)(
                  Text3,
                  {
                    bold: isSelected,
                    color: isSelected ? theme.text.accent : void 0,
                    children: plugin.name
                  }
                )
              ] }),
              isSelected && plugin.description && /* @__PURE__ */ (0, import_jsx_runtime75.jsx)(Box_default, { marginLeft: prefixWidth, children: /* @__PURE__ */ (0, import_jsx_runtime75.jsx)(Text3, { color: theme.text.accent, children: plugin.description }) })
            ] }, plugin.name);
          }),
          hasMore && /* @__PURE__ */ (0, import_jsx_runtime75.jsx)(Box_default, { children: /* @__PURE__ */ (0, import_jsx_runtime75.jsxs)(Text3, { dimColor: true, children: [
            " ",
            "\u2193",
            " ",
            t4("{{count}} more below", {
              count: String(plugins.length - startIndex - MAX_VISIBLE_ITEMS)
            })
          ] }) })
        ] }),
        /* @__PURE__ */ (0, import_jsx_runtime75.jsxs)(Box_default, { marginTop: 1, flexDirection: "row", gap: 2, children: [
          /* @__PURE__ */ (0, import_jsx_runtime75.jsx)(Text3, { dimColor: true, children: t4("Use \u2191\u2193 or j/k to navigate, Enter to select, Escape to cancel") }),
          plugins.length > MAX_VISIBLE_ITEMS && /* @__PURE__ */ (0, import_jsx_runtime75.jsxs)(Text3, { dimColor: true, children: [
            "(",
            selectedIndex + 1,
            "/",
            plugins.length,
            ")"
          ] })
        ] })
      ]
    }
  );
}, "PluginChoicePrompt");

// packages/cli/src/ui/components/ThemeDialog.tsx
init_esbuild_shims();
var import_react75 = __toESM(require_react(), 1);

// packages/cli/src/utils/dialogScopeUtils.ts
init_esbuild_shims();

// packages/cli/src/utils/settingsUtils.ts
init_esbuild_shims();
import * as fs97 from "node:fs";
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, path125) {
  const [first2, ...rest] = path125;
  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 path125 = key.split(".");
  let value = getNestedValue(settings, path125);
  if (value !== void 0) {
    return value;
  }
  value = getNestedValue(mergedSettings, path125);
  if (value !== void 0) {
    return value;
  }
  return definition.default;
}
__name(getEffectiveValue, "getEffectiveValue");
var SETTINGS_DIALOG_ORDER = [
  // Workflow Control - most impactful setting
  "tools.approvalMode",
  // Localization - users often set this first
  "general.language",
  "general.outputLanguage",
  // Theme
  "ui.theme",
  // Editor/Shell Experience
  "general.vimMode",
  "tools.shell.enableInteractiveShell",
  // Display Preferences
  "general.preferredEditor",
  "ide.enabled",
  "ui.showLineNumbers",
  "ui.hideTips",
  "general.terminalBell",
  "ui.enableWelcomeBack",
  // Git Behavior
  "general.gitCoAuthor",
  // File Filtering
  "context.fileFiltering.respectGitIgnore",
  "context.fileFiltering.respectQwenIgnore",
  // System Settings - rarely changed
  "general.disableAutoUpdate",
  // Privacy
  "privacy.usageStatisticsEnabled"
];
function getDialogSettingKeys() {
  const dialogSettings = Object.values(getFlattenedSchema()).filter((definition) => definition.showInDialog === true).map((definition) => definition.key);
  return dialogSettings.sort((a2, b2) => {
    const indexA = SETTINGS_DIALOG_ORDER.indexOf(a2);
    const indexB = SETTINGS_DIALOG_ORDER.indexOf(b2);
    if (indexA !== -1 && indexB !== -1) {
      return indexA - indexB;
    }
    if (indexA !== -1) return -1;
    if (indexB !== -1) return 1;
    return 0;
  });
}
__name(getDialogSettingKeys, "getDialogSettingKeys");
function settingExistsInScope(key, scopeSettings) {
  const path125 = key.split(".");
  const value = getNestedValue(scopeSettings, path125);
  return value !== void 0;
}
__name(settingExistsInScope, "settingExistsInScope");
function setNestedValue(obj, path125, value) {
  const [first2, ...rest] = path125;
  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 path125 = key.split(".");
  const newSettings = JSON.parse(JSON.stringify(pendingSettings));
  setNestedValue(newSettings, path125, value);
  return newSettings;
}
__name(setPendingSettingValue, "setPendingSettingValue");
function setPendingSettingValueAny(key, value, pendingSettings) {
  const path125 = key.split(".");
  const newSettings = structuredClone(pendingSettings);
  setNestedValue(newSettings, path125, value);
  return newSettings;
}
__name(setPendingSettingValueAny, "setPendingSettingValueAny");
function getRestartRequiredFromModified(modifiedSettings) {
  return Array.from(modifiedSettings).filter((key) => requiresRestart(key));
}
__name(getRestartRequiredFromModified, "getRestartRequiredFromModified");
function saveModifiedSettings(modifiedSettings, pendingSettings, loadedSettings, scope) {
  modifiedSettings.forEach((settingKey) => {
    const path125 = settingKey.split(".");
    const value = getNestedValue(
      pendingSettings,
      path125
    );
    const existsInOriginalFile = settingExistsInScope(
      settingKey,
      loadedSettings.forScope(scope).settings
    );
    if (value === void 0) {
      if (existsInOriginalFile) {
        loadedSettings.setValue(scope, settingKey, void 0);
      }
      return;
    }
    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 (key === "general.outputLanguage" && isAutoLanguage(value)) {
    valueString = t4("Auto (detect from system)");
  } else if (definition?.type === "enum" && definition.options) {
    const option2 = definition.options?.find((option3) => option3.value === value);
    if (option2?.label) {
      valueString = t4(option2.label) || option2.label;
    } else {
      valueString = `${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");
function backupSettingsFile(filePath) {
  try {
    if (fs97.existsSync(filePath)) {
      const backupPath = `${filePath}.orig`;
      if (!fs97.existsSync(backupPath)) {
        fs97.renameSync(filePath, backupPath);
        return true;
      }
    }
  } catch (_e2) {
  }
  return false;
}
__name(backupSettingsFile, "backupSettingsFile");

// 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(SettingScope2).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_runtime76 = __toESM(require_jsx_runtime(), 1);
function ScopeSelector({
  onSelect,
  onHighlight,
  isFocused,
  initialScope
}) {
  const scopeItems = getScopeItems().map((item) => ({
    ...item,
    label: t4(item.label),
    key: item.value
  }));
  const initialIndex = scopeItems.findIndex(
    (item) => item.value === initialScope
  );
  const safeInitialIndex = initialIndex >= 0 ? initialIndex : 0;
  return /* @__PURE__ */ (0, import_jsx_runtime76.jsxs)(Box_default, { flexDirection: "column", children: [
    /* @__PURE__ */ (0, import_jsx_runtime76.jsxs)(Text3, { bold: isFocused, wrap: "truncate", children: [
      isFocused ? "> " : "  ",
      t4("Apply To")
    ] }),
    /* @__PURE__ */ (0, import_jsx_runtime76.jsx)(Box_default, { height: 1 }),
    /* @__PURE__ */ (0, import_jsx_runtime76.jsx)(
      RadioButtonSelect,
      {
        items: scopeItems,
        initialIndex: safeInitialIndex,
        onSelect,
        onHighlight,
        isFocused,
        showNumbers: isFocused
      }
    )
  ] });
}
__name(ScopeSelector, "ScopeSelector");

// packages/cli/src/ui/components/ThemeDialog.tsx
var import_jsx_runtime77 = __toESM(require_jsx_runtime(), 1);
function ThemeDialog({
  onSelect,
  onHighlight,
  settings,
  availableTerminalHeight,
  terminalWidth
}) {
  const [selectedScope, setSelectedScope] = (0, import_react75.useState)(
    "User" /* User */
  );
  const [highlightedThemeName, setHighlightedThemeName] = (0, import_react75.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((s5) => s5.charAt(0).toUpperCase() + s5.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_react75.useCallback)(
    (themeName) => {
      onSelect(themeName, selectedScope);
    },
    [onSelect, selectedScope]
  );
  const handleThemeHighlight = /* @__PURE__ */ __name((themeName) => {
    setHighlightedThemeName(themeName);
    onHighlight(themeName);
  }, "handleThemeHighlight");
  const handleScopeHighlight = (0, import_react75.useCallback)((scope) => {
    setSelectedScope(scope);
  }, []);
  const handleScopeSelect = (0, import_react75.useCallback)(
    (scope) => {
      onSelect(highlightedThemeName, scope);
    },
    [onSelect, highlightedThemeName]
  );
  const [mode, setMode] = (0, import_react75.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_runtime77.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_runtime77.jsxs)(Box_default, { flexDirection: "row", children: [
          /* @__PURE__ */ (0, import_jsx_runtime77.jsxs)(Box_default, { flexDirection: "column", width: "45%", paddingRight: 2, children: [
            /* @__PURE__ */ (0, import_jsx_runtime77.jsxs)(Text3, { bold: mode === "theme", wrap: "truncate", children: [
              mode === "theme" ? "> " : "  ",
              t4("Select Theme"),
              " ",
              /* @__PURE__ */ (0, import_jsx_runtime77.jsx)(Text3, { color: theme.text.secondary, children: otherScopeModifiedMessage })
            ] }),
            /* @__PURE__ */ (0, import_jsx_runtime77.jsx)(
              RadioButtonSelect,
              {
                items: themeItems,
                initialIndex: safeInitialThemeIndex,
                onSelect: handleThemeSelect,
                onHighlight: handleThemeHighlight,
                isFocused: mode === "theme",
                maxItemsToShow: 12,
                showScrollArrows: true,
                showNumbers: mode === "theme"
              }
            )
          ] }),
          /* @__PURE__ */ (0, import_jsx_runtime77.jsxs)(Box_default, { flexDirection: "column", width: "55%", paddingLeft: 2, children: [
            /* @__PURE__ */ (0, import_jsx_runtime77.jsx)(Text3, { bold: true, color: theme.text.primary, children: t4("Preview") }),
            (() => {
              const previewTheme = themeManager.getTheme(
                highlightedThemeName || DEFAULT_THEME.name
              ) || DEFAULT_THEME;
              return /* @__PURE__ */ (0, import_jsx_runtime77.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_runtime77.jsx)(Box_default, { marginTop: 1 }),
                    /* @__PURE__ */ (0, import_jsx_runtime77.jsx)(
                      DiffRenderer,
                      {
                        diffContent: `--- a/util.py
+++ b/util.py
@@ -1,2 +1,2 @@
- print("Hello, " + name)
+ print(f"Hello, {name}!")
`,
                        availableTerminalHeight: diffHeight,
                        contentWidth: colorizeCodeWidth,
                        theme: previewTheme,
                        settings
                      }
                    )
                  ]
                }
              );
            })()
          ] })
        ] }) : /* @__PURE__ */ (0, import_jsx_runtime77.jsx)(
          ScopeSelector,
          {
            onSelect: handleScopeSelect,
            onHighlight: handleScopeHighlight,
            isFocused: mode === "scope",
            initialScope: selectedScope
          }
        ),
        /* @__PURE__ */ (0, import_jsx_runtime77.jsx)(Box_default, { marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime77.jsx)(Text3, { color: theme.text.secondary, wrap: "truncate", children: mode === "theme" ? t4("(Use Enter to select, Tab to configure scope)") : t4("(Use Enter to apply scope, Tab to go back)") }) })
      ]
    }
  );
}
__name(ThemeDialog, "ThemeDialog");

// packages/cli/src/ui/components/SettingsDialog.tsx
init_esbuild_shims();
var import_react77 = __toESM(require_react(), 1);

// packages/cli/src/ui/contexts/VimModeContext.tsx
init_esbuild_shims();
var import_react76 = __toESM(require_react(), 1);
var import_jsx_runtime78 = __toESM(require_jsx_runtime(), 1);
var VimModeContext = (0, import_react76.createContext)(void 0);
var VimModeProvider = /* @__PURE__ */ __name(({
  children,
  settings
}) => {
  const initialVimEnabled = settings.merged.general?.vimMode ?? false;
  const [vimEnabled, setVimEnabled] = (0, import_react76.useState)(initialVimEnabled);
  const [vimMode, setVimMode] = (0, import_react76.useState)(
    initialVimEnabled ? "NORMAL" : "INSERT"
  );
  (0, import_react76.useEffect)(() => {
    const enabled = settings.merged.general?.vimMode ?? false;
    setVimEnabled(enabled);
    if (enabled) {
      setVimMode("NORMAL");
    }
  }, [settings.merged.general?.vimMode]);
  const toggleVimEnabled = (0, import_react76.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_runtime78.jsx)(VimModeContext.Provider, { value, children });
}, "VimModeProvider");
var useVimMode = /* @__PURE__ */ __name(() => {
  const context2 = (0, import_react76.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_chalk8 = __toESM(require_source(), 1);
var import_jsx_runtime79 = __toESM(require_jsx_runtime(), 1);
var debugLogger102 = createDebugLogger("SETTINGS_DIALOG");
var maxItemsToShow = 8;
function SettingsDialog({
  settings,
  onSelect,
  onRestartRequest,
  availableTerminalHeight,
  config: config2
}) {
  const { vimEnabled, toggleVimEnabled } = useVimMode();
  const [mode, setMode] = (0, import_react77.useState)("settings");
  const [selectedScope, setSelectedScope] = (0, import_react77.useState)(
    "User" /* User */
  );
  const [activeSettingIndex, setActiveSettingIndex] = (0, import_react77.useState)(0);
  const [scrollOffset, setScrollOffset] = (0, import_react77.useState)(0);
  const [pendingSettings, setPendingSettings] = (0, import_react77.useState)(
    () => (
      // Deep clone to avoid mutation
      structuredClone(settings.forScope(selectedScope).settings)
    )
  );
  const [modifiedSettings, setModifiedSettings] = (0, import_react77.useState)(
    /* @__PURE__ */ new Set()
  );
  const [globalPendingChanges, setGlobalPendingChanges] = (0, import_react77.useState)(/* @__PURE__ */ new Map());
  const [restartRequiredSettings, setRestartRequiredSettings] = (0, import_react77.useState)(/* @__PURE__ */ new Set());
  const showRestartPrompt = restartRequiredSettings.size > 0;
  (0, import_react77.useEffect)(() => {
    let updated = structuredClone(settings.forScope(selectedScope).settings);
    const newModified = /* @__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" || def2?.type === "enum" && (typeof value === "string" || typeof value === "number")) {
        updated = setPendingSettingValueAny(key, value, updated);
      }
      newModified.add(key);
    }
    setPendingSettings(updated);
    setModifiedSettings(newModified);
  }, [selectedScope, settings, globalPendingChanges]);
  const generateSettingsItems = /* @__PURE__ */ __name(() => {
    const settingKeys = getDialogSettingKeys();
    return settingKeys.map((key) => {
      const definition = getSettingDefinition(key);
      return {
        label: definition?.label ? t4(definition.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)
            );
          }
          if (!requiresRestart(key)) {
            const immediateSettings = /* @__PURE__ */ new Set([key]);
            const immediateSettingsObject = setPendingSettingValueAny(
              key,
              newValue,
              {}
            );
            debugLogger102.debug(
              `[DEBUG SettingsDialog] Saving ${key} immediately with value:`,
              newValue
            );
            saveModifiedSettings(
              immediateSettings,
              immediateSettingsObject,
              settings,
              selectedScope
            );
            if (key === "general.vimMode" && newValue !== vimEnabled) {
              toggleVimEnabled().catch((error2) => {
                debugLogger102.error("Failed to toggle vim mode:", error2);
              });
            }
            if (key === "tools.approvalMode" && settings.merged.tools?.approvalMode) {
              try {
                config2?.setApprovalMode(settings.merged.tools.approvalMode);
              } catch (error2) {
                debugLogger102.error(
                  "Failed to apply approval mode to current session:",
                  error2
                );
              }
            }
            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 {
            const immediateSettings = /* @__PURE__ */ new Set([key]);
            const immediateSettingsObject = setPendingSettingValueAny(
              key,
              newValue,
              {}
            );
            saveModifiedSettings(
              immediateSettings,
              immediateSettingsObject,
              settings,
              selectedScope
            );
            setRestartRequiredSettings((prev) => new Set(prev).add(key));
          }
        }, "toggle")
      };
    });
  }, "generateSettingsItems");
  const items = generateSettingsItems();
  const [editingKey, setEditingKey] = (0, import_react77.useState)(null);
  const [editBuffer, setEditBuffer] = (0, import_react77.useState)("");
  const [editCursorPos, setEditCursorPos] = (0, import_react77.useState)(0);
  const [cursorVisible, setCursorVisible] = (0, import_react77.useState)(true);
  (0, import_react77.useEffect)(() => {
    if (!editingKey) {
      setCursorVisible(true);
      return;
    }
    const id = setInterval(() => setCursorVisible((v2) => !v2), 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 {
      if (key === "general.outputLanguage") {
        const trimmed2 = editBuffer.trim();
        parsed = trimmed2 === "" ? "auto" : trimmed2;
      } else {
        parsed = editBuffer;
      }
    }
    setPendingSettings(
      (prev) => parsed === void 0 ? setPendingSettingValueAny(
        key,
        void 0,
        prev
      ) : setPendingSettingValueAny(key, parsed, prev)
    );
    if (!requiresRestart(key)) {
      const immediateSettings = /* @__PURE__ */ new Set([key]);
      const immediateSettingsObject = parsed === void 0 ? {} : 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 {
      const immediateSettings = /* @__PURE__ */ new Set([key]);
      const immediateSettingsObject = parsed === void 0 ? {} : setPendingSettingValueAny(key, parsed, {});
      saveModifiedSettings(
        immediateSettings,
        immediateSettingsObject,
        settings,
        selectedScope
      );
      if (key === "general.outputLanguage" && typeof parsed === "string") {
        updateOutputLanguageFile(parsed);
      }
      setRestartRequiredSettings((prev) => new Set(prev).add(key));
    }
    setEditingKey(null);
    setEditBuffer("");
    setEditCursorPos(0);
  }, "commitEdit");
  const handleScopeHighlight = /* @__PURE__ */ __name((scope) => {
    setSelectedScope(scope);
  }, "handleScopeHighlight");
  const handleScopeSelect = /* @__PURE__ */ __name((scope) => {
    handleScopeHighlight(scope);
    setMode("settings");
  }, "handleScopeSelect");
  const DIALOG_PADDING = 2;
  const SETTINGS_TITLE_HEIGHT = 2;
  const SCROLL_ARROWS_HEIGHT = 2;
  const BOTTOM_HELP_TEXT_HEIGHT = 1;
  const RESTART_PROMPT_HEIGHT = showRestartPrompt ? 1 : 0;
  let currentAvailableTerminalHeight = availableTerminalHeight ?? Number.MAX_SAFE_INTEGER;
  currentAvailableTerminalHeight -= 2;
  const totalFixedHeight = DIALOG_PADDING + SETTINGS_TITLE_HEIGHT + SCROLL_ARROWS_HEIGHT + BOTTOM_HELP_TEXT_HEIGHT + RESTART_PROMPT_HEIGHT;
  const availableHeightForSettings = Math.max(
    1,
    currentAvailableTerminalHeight - totalFixedHeight
  );
  const maxVisibleItems = Math.max(1, availableHeightForSettings);
  const effectiveMaxItemsToShow = availableTerminalHeight ? Math.min(maxVisibleItems, items.length) : maxItemsToShow;
  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") {
        setMode((prev) => prev === "settings" ? "scope" : "settings");
      }
      if (mode === "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((b2) => {
                const before = cpSlice(b2, 0, editCursorPos);
                const after = cpSlice(b2, editCursorPos);
                return before + pasted + after;
              });
              setEditCursorPos((pos2) => pos2 + cpLen(pasted));
            }
            return;
          }
          if (name3 === "backspace" || name3 === "delete") {
            if (name3 === "backspace" && editCursorPos > 0) {
              setEditBuffer((b2) => {
                const before = cpSlice(b2, 0, editCursorPos - 1);
                const after = cpSlice(b2, editCursorPos);
                return before + after;
              });
              setEditCursorPos((pos2) => pos2 - 1);
            } else if (name3 === "delete" && editCursorPos < cpLen(editBuffer)) {
              setEditBuffer((b2) => {
                const before = cpSlice(b2, 0, editCursorPos);
                const after = cpSlice(b2, 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?.value === "ui.theme") {
            if (name3 === "return") {
              onSelect("ui.theme", selectedScope);
            }
            return;
          }
          if (currentItem?.value === "general.preferredEditor") {
            if (name3 === "return") {
              onSelect("general.preferredEditor", selectedScope);
            }
            return;
          }
          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 {
                  config2?.setApprovalMode(settings.merged.tools.approvalMode);
                } catch (error2) {
                  debugLogger102.error(
                    "Failed to apply approval mode to current session:",
                    error2
                  );
                }
              }
              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;
                });
              }
              setRestartRequiredSettings(
                (prev) => new Set(prev).add(currentSetting.value)
              );
            }
          }
        }
      }
      if (showRestartPrompt && name3 === "r") {
        const restartRequiredSettings2 = getRestartRequiredFromModified(modifiedSettings);
        const restartRequiredSet = new Set(restartRequiredSettings2);
        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;
          });
        }
        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_runtime79.jsxs)(
    Box_default,
    {
      borderStyle: "round",
      borderColor: theme.border.default,
      flexDirection: "column",
      padding: 1,
      width: "100%",
      children: [
        mode === "settings" ? /* @__PURE__ */ (0, import_jsx_runtime79.jsxs)(Box_default, { flexDirection: "column", flexGrow: 1, children: [
          /* @__PURE__ */ (0, import_jsx_runtime79.jsxs)(Text3, { bold: mode === "settings", wrap: "truncate", children: [
            mode === "settings" ? "> " : "  ",
            t4("Settings")
          ] }),
          /* @__PURE__ */ (0, import_jsx_runtime79.jsx)(Box_default, { height: 1 }),
          showScrollUp && /* @__PURE__ */ (0, import_jsx_runtime79.jsx)(Text3, { color: theme.text.secondary, children: "\u25B2" }),
          visibleItems.map((item, idx) => {
            const isActive = mode === "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_chalk8.default.inverse(atCursor) + afterCursor;
              } else if (cursorVisible && editCursorPos >= cpLen(editBuffer)) {
                displayValue = editBuffer + import_chalk8.default.inverse(" ");
              } else {
                displayValue = editBuffer;
              }
            } else if (item.type === "number" || item.type === "string") {
              const path125 = item.value.split(".");
              const currentValue = getNestedValue(pendingSettings, path125);
              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_runtime79.jsxs)(Box_default, { flexDirection: "row", alignItems: "center", children: [
              /* @__PURE__ */ (0, import_jsx_runtime79.jsx)(Box_default, { minWidth: 2, flexShrink: 0, children: /* @__PURE__ */ (0, import_jsx_runtime79.jsx)(
                Text3,
                {
                  color: isActive ? theme.status.success : theme.text.secondary,
                  children: isActive ? "\u25CF" : ""
                }
              ) }),
              /* @__PURE__ */ (0, import_jsx_runtime79.jsx)(Box_default, { flexGrow: 1, flexShrink: 1, children: /* @__PURE__ */ (0, import_jsx_runtime79.jsxs)(
                Text3,
                {
                  color: isActive ? theme.status.success : theme.text.primary,
                  wrap: "truncate",
                  children: [
                    item.label,
                    scopeMessage && /* @__PURE__ */ (0, import_jsx_runtime79.jsxs)(Text3, { color: theme.text.secondary, children: [
                      " ",
                      scopeMessage
                    ] })
                  ]
                }
              ) }),
              /* @__PURE__ */ (0, import_jsx_runtime79.jsx)(Box_default, { marginLeft: 1, flexShrink: 0, children: /* @__PURE__ */ (0, import_jsx_runtime79.jsx)(
                Text3,
                {
                  color: isActive ? theme.status.success : shouldBeGreyedOut ? theme.text.secondary : theme.text.primary,
                  wrap: "truncate",
                  children: displayValue
                }
              ) })
            ] }, item.value);
          }),
          showScrollDown && /* @__PURE__ */ (0, import_jsx_runtime79.jsx)(Text3, { color: theme.text.secondary, children: "\u25BC" })
        ] }) : /* @__PURE__ */ (0, import_jsx_runtime79.jsx)(
          ScopeSelector,
          {
            onSelect: handleScopeSelect,
            onHighlight: handleScopeHighlight,
            isFocused: mode === "scope",
            initialScope: selectedScope
          }
        ),
        /* @__PURE__ */ (0, import_jsx_runtime79.jsx)(Box_default, { marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime79.jsx)(Text3, { color: theme.text.secondary, wrap: "truncate", children: mode === "settings" ? t4("(Use Enter to select, Tab to configure scope)") : t4("(Use Enter to apply scope, Tab to go back)") }) }),
        showRestartPrompt && /* @__PURE__ */ (0, import_jsx_runtime79.jsx)(Text3, { color: theme.status.warning, children: t4(
          "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_react79 = __toESM(require_react(), 1);

// node_modules/ink-link/dist/index.js
init_esbuild_shims();
var import_react78 = __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 = (x3, y2) => {
  if (typeof x3 !== "number") {
    throw new TypeError("The `x` argument is required");
  }
  if (typeof y2 !== "number") {
    return ESC3 + (x3 + 1) + "G";
  }
  return ESC3 + (y2 + 1) + ";" + (x3 + 1) + "H";
};
ansiEscapes.cursorMove = (x3, y2) => {
  if (typeof x3 !== "number") {
    throw new TypeError("The `x` argument is required");
  }
  let returnValue = "";
  if (x3 < 0) {
    returnValue += ESC3 + -x3 + "D";
  } else if (x3 > 0) {
    returnValue += ESC3 + x3 + "C";
  }
  if (y2 < 0) {
    returnValue += ESC3 + -y2 + "A";
  } else if (y2 > 0) {
    returnValue += ESC3 + y2 + "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 i3 = 0; i3 < count; i3++) {
    clear += ansiEscapes.eraseLine + (i3 < 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_react78.default.createElement(
    Transform,
    { transform: /* @__PURE__ */ __name((children2) => terminalLink(children2, url2, { fallback }), "transform") },
    import_react78.default.createElement(Text3, 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_default6 = Link;

// packages/cli/src/ui/components/QwenOAuthProgress.tsx
var import_qrcode_terminal = __toESM(require_main2(), 1);
var import_jsx_runtime80 = __toESM(require_jsx_runtime(), 1);
var debugLogger103 = createDebugLogger("QWEN_OAUTH_PROGRESS");
function QrCodeDisplay({
  verificationUrl,
  qrCodeData
}) {
  if (!qrCodeData) {
    return null;
  }
  return /* @__PURE__ */ (0, import_jsx_runtime80.jsxs)(
    Box_default,
    {
      borderStyle: "round",
      borderColor: Colors.AccentBlue,
      flexDirection: "column",
      padding: 1,
      width: "100%",
      children: [
        /* @__PURE__ */ (0, import_jsx_runtime80.jsx)(Text3, { bold: true, color: Colors.AccentBlue, children: t4("Qwen OAuth Authentication") }),
        /* @__PURE__ */ (0, import_jsx_runtime80.jsx)(Box_default, { marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime80.jsx)(Text3, { children: t4("Please visit this URL to authorize:") }) }),
        /* @__PURE__ */ (0, import_jsx_runtime80.jsx)(dist_default6, { url: verificationUrl, fallback: false, children: /* @__PURE__ */ (0, import_jsx_runtime80.jsx)(Text3, { color: Colors.AccentGreen, bold: true, children: verificationUrl }) }),
        /* @__PURE__ */ (0, import_jsx_runtime80.jsx)(Box_default, { marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime80.jsx)(Text3, { children: t4("Or scan the QR code below:") }) }),
        /* @__PURE__ */ (0, import_jsx_runtime80.jsx)(Box_default, { marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime80.jsx)(Text3, { 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_runtime80.jsxs)(
    Box_default,
    {
      borderStyle: "round",
      borderColor: Colors.AccentBlue,
      flexDirection: "column",
      padding: 1,
      width: "100%",
      children: [
        /* @__PURE__ */ (0, import_jsx_runtime80.jsx)(Box_default, { marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime80.jsxs)(Text3, { children: [
          /* @__PURE__ */ (0, import_jsx_runtime80.jsx)(build_default, { type: "dots" }),
          " ",
          t4("Waiting for authorization"),
          dots
        ] }) }),
        /* @__PURE__ */ (0, import_jsx_runtime80.jsxs)(Box_default, { marginTop: 1, justifyContent: "space-between", children: [
          /* @__PURE__ */ (0, import_jsx_runtime80.jsxs)(Text3, { color: Colors.Gray, children: [
            t4("Time remaining:"),
            " ",
            formatTime(timeRemaining)
          ] }),
          /* @__PURE__ */ (0, import_jsx_runtime80.jsx)(Text3, { color: Colors.AccentPurple, children: t4("(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_react79.useState)(defaultTimeout);
  const [dots, setDots] = (0, import_react79.useState)("");
  const [qrCodeData, setQrCodeData] = (0, import_react79.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_react79.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 (error2) {
        debugLogger103.error("Failed to generate QR code:", error2);
        setQrCodeData(null);
      }
    }, "generateQR");
    generateQR();
  }, [deviceAuth?.verification_uri_complete]);
  (0, import_react79.useEffect)(() => {
    const timer = setInterval(() => {
      setTimeRemaining((prev) => {
        if (prev <= 1) {
          onTimeout();
          return 0;
        }
        return prev - 1;
      });
    }, 1e3);
    return () => clearInterval(timer);
  }, [onTimeout]);
  (0, import_react79.useEffect)(() => {
    const dotsTimer = setInterval(() => {
      setDots((prev) => {
        if (prev.length >= 3) return "";
        return prev + ".";
      });
    }, 500);
    return () => clearInterval(dotsTimer);
  }, []);
  const qrCodeDisplay = (0, import_react79.useMemo)(() => {
    if (!deviceAuth?.verification_uri_complete) return null;
    return /* @__PURE__ */ (0, import_jsx_runtime80.jsx)(
      QrCodeDisplay,
      {
        verificationUrl: deviceAuth.verification_uri_complete,
        qrCodeData
      }
    );
  }, [deviceAuth?.verification_uri_complete, qrCodeData]);
  if (authStatus === "timeout") {
    return /* @__PURE__ */ (0, import_jsx_runtime80.jsxs)(
      Box_default,
      {
        borderStyle: "round",
        borderColor: Colors.AccentRed,
        flexDirection: "column",
        padding: 1,
        width: "100%",
        children: [
          /* @__PURE__ */ (0, import_jsx_runtime80.jsx)(Text3, { bold: true, color: Colors.AccentRed, children: t4("Qwen OAuth Authentication Timeout") }),
          /* @__PURE__ */ (0, import_jsx_runtime80.jsx)(Box_default, { marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime80.jsx)(Text3, { children: authMessage || t4(
            "OAuth token expired (over {{seconds}} seconds). Please select authentication method again.",
            {
              seconds: defaultTimeout.toString()
            }
          ) }) }),
          /* @__PURE__ */ (0, import_jsx_runtime80.jsx)(Box_default, { marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime80.jsx)(Text3, { color: Colors.Gray, children: t4("Press any key to return to authentication type selection.") }) })
        ]
      }
    );
  }
  if (authStatus === "error") {
    return /* @__PURE__ */ (0, import_jsx_runtime80.jsxs)(
      Box_default,
      {
        borderStyle: "round",
        borderColor: Colors.AccentRed,
        flexDirection: "column",
        padding: 1,
        width: "100%",
        children: [
          /* @__PURE__ */ (0, import_jsx_runtime80.jsx)(Text3, { bold: true, color: Colors.AccentRed, children: "Qwen OAuth Authentication Error" }),
          /* @__PURE__ */ (0, import_jsx_runtime80.jsx)(Box_default, { marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime80.jsx)(Text3, { children: authMessage || "An error occurred during authentication. Please try again." }) }),
          /* @__PURE__ */ (0, import_jsx_runtime80.jsx)(Box_default, { marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime80.jsx)(Text3, { color: Colors.Gray, children: "Press any key to return to authentication type selection." }) })
        ]
      }
    );
  }
  if (!deviceAuth) {
    return /* @__PURE__ */ (0, import_jsx_runtime80.jsxs)(
      Box_default,
      {
        borderStyle: "round",
        borderColor: Colors.Gray,
        flexDirection: "column",
        padding: 1,
        width: "100%",
        children: [
          /* @__PURE__ */ (0, import_jsx_runtime80.jsx)(Box_default, { children: /* @__PURE__ */ (0, import_jsx_runtime80.jsxs)(Text3, { children: [
            /* @__PURE__ */ (0, import_jsx_runtime80.jsx)(build_default, { type: "dots" }),
            t4("Waiting for Qwen OAuth authentication...")
          ] }) }),
          /* @__PURE__ */ (0, import_jsx_runtime80.jsxs)(Box_default, { marginTop: 1, justifyContent: "space-between", children: [
            /* @__PURE__ */ (0, import_jsx_runtime80.jsxs)(Text3, { color: Colors.Gray, children: [
              t4("Time remaining:"),
              " ",
              Math.floor(timeRemaining / 60),
              ":",
              (timeRemaining % 60).toString().padStart(2, "0")
            ] }),
            /* @__PURE__ */ (0, import_jsx_runtime80.jsx)(Text3, { color: Colors.AccentPurple, children: t4("(Press ESC or CTRL+C to cancel)") })
          ] })
        ]
      }
    );
  }
  return /* @__PURE__ */ (0, import_jsx_runtime80.jsxs)(Box_default, { flexDirection: "column", width: "100%", children: [
    qrCodeDisplay,
    /* @__PURE__ */ (0, import_jsx_runtime80.jsx)(StatusDisplay, { timeRemaining, dots })
  ] });
}
__name(QwenOAuthProgress, "QwenOAuthProgress");

// packages/cli/src/ui/auth/AuthDialog.tsx
init_esbuild_shims();
var import_react82 = __toESM(require_react(), 1);

// packages/cli/src/ui/components/ApiKeyInput.tsx
init_esbuild_shims();
var import_react80 = __toESM(require_react(), 1);
var import_jsx_runtime81 = __toESM(require_jsx_runtime(), 1);
var CODING_PLAN_API_KEY_URL = "https://bailian.console.aliyun.com/?tab=model#/efm/coding_plan";
var CODING_PLAN_INTL_API_KEY_URL = "https://modelstudio.console.alibabacloud.com/?tab=dashboard#/efm/coding_plan";
function ApiKeyInput({
  onSubmit,
  onCancel,
  region = "china" /* CHINA */
}) {
  const [apiKey, setApiKey] = (0, import_react80.useState)("");
  const [error2, setError] = (0, import_react80.useState)(null);
  const apiKeyUrl = region === "global" /* GLOBAL */ ? CODING_PLAN_INTL_API_KEY_URL : CODING_PLAN_API_KEY_URL;
  useKeypress(
    (key) => {
      if (key.name === "escape") {
        onCancel();
      } else if (key.name === "return") {
        const trimmedKey = apiKey.trim();
        if (!trimmedKey) {
          setError(t4("API key cannot be empty."));
          return;
        }
        onSubmit(trimmedKey);
      }
    },
    { isActive: true }
  );
  return /* @__PURE__ */ (0, import_jsx_runtime81.jsxs)(Box_default, { flexDirection: "column", children: [
    /* @__PURE__ */ (0, import_jsx_runtime81.jsx)(Box_default, { marginBottom: 1, children: /* @__PURE__ */ (0, import_jsx_runtime81.jsx)(Text3, { children: t4("Please enter your API key:") }) }),
    /* @__PURE__ */ (0, import_jsx_runtime81.jsx)(TextInput, { value: apiKey, onChange: setApiKey, placeholder: "sk-sp-..." }),
    error2 && /* @__PURE__ */ (0, import_jsx_runtime81.jsx)(Box_default, { marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime81.jsx)(Text3, { color: theme.status.error, children: error2 }) }),
    /* @__PURE__ */ (0, import_jsx_runtime81.jsx)(Box_default, { marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime81.jsx)(Text3, { children: t4("You can get your exclusive Coding Plan API-KEY here:") }) }),
    /* @__PURE__ */ (0, import_jsx_runtime81.jsx)(Box_default, { marginTop: 0, children: /* @__PURE__ */ (0, import_jsx_runtime81.jsx)(dist_default6, { url: apiKeyUrl, fallback: false, children: /* @__PURE__ */ (0, import_jsx_runtime81.jsx)(Text3, { color: theme.status.success, underline: true, children: apiKeyUrl }) }) }),
    /* @__PURE__ */ (0, import_jsx_runtime81.jsx)(Box_default, { marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime81.jsx)(Text3, { color: theme.text.secondary, children: t4("(Press Enter to submit, Escape to cancel)") }) })
  ] });
}
__name(ApiKeyInput, "ApiKeyInput");

// packages/cli/src/ui/contexts/UIActionsContext.tsx
init_esbuild_shims();
var import_react81 = __toESM(require_react(), 1);
var UIActionsContext = (0, import_react81.createContext)(null);
var useUIActions = /* @__PURE__ */ __name(() => {
  const context2 = (0, import_react81.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_runtime82 = __toESM(require_jsx_runtime(), 1);
var MODEL_PROVIDERS_DOCUMENTATION_URL = "https://qwenlm.github.io/qwen-code-docs/en/users/configuration/settings/#modelproviders";
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,
    handleCodingPlanSubmit,
    onAuthError
  } = useUIActions();
  const config2 = useConfig();
  const [errorMessage, setErrorMessage] = (0, import_react82.useState)(null);
  const [selectedIndex, setSelectedIndex] = (0, import_react82.useState)(null);
  const [viewLevel, setViewLevel] = (0, import_react82.useState)("main");
  const [apiKeySubModeIndex, setApiKeySubModeIndex] = (0, import_react82.useState)(0);
  const [region, setRegion] = (0, import_react82.useState)(
    "china" /* CHINA */
  );
  const mainItems = [
    {
      key: AuthType2.QWEN_OAUTH,
      label: t4("Qwen OAuth"),
      value: AuthType2.QWEN_OAUTH
    },
    {
      key: "API-KEY",
      label: t4("API-KEY"),
      value: "API-KEY"
    }
  ];
  const apiKeySubItems = [
    {
      key: "coding-plan",
      label: t4("Coding Plan (Bailian, China)"),
      value: "coding-plan"
    },
    {
      key: "coding-plan-intl",
      label: t4("Coding Plan (Bailian, Global/Intl)"),
      value: "coding-plan-intl"
    },
    {
      key: "custom",
      label: t4("Custom"),
      value: "custom"
    }
  ];
  const initialAuthIndex = Math.max(
    0,
    mainItems.findIndex((item) => {
      if (pendingAuthType) {
        return item.value === pendingAuthType;
      }
      const currentAuthType = config2.getAuthType();
      if (currentAuthType) {
        return item.value === currentAuthType;
      }
      const defaultAuthType = parseDefaultAuthType(
        process.env["QWEN_DEFAULT_AUTH_TYPE"]
      );
      if (defaultAuthType) {
        return item.value === defaultAuthType;
      }
      return item.value === AuthType2.QWEN_OAUTH;
    })
  );
  const hasApiKey = Boolean(config2.getContentGeneratorConfig()?.apiKey);
  const currentSelectedAuthType = selectedIndex !== null ? mainItems[selectedIndex]?.value : mainItems[initialAuthIndex]?.value;
  const handleMainSelect = /* @__PURE__ */ __name(async (value) => {
    setErrorMessage(null);
    onAuthError(null);
    if (value === "API-KEY") {
      setViewLevel("api-key-sub");
      return;
    }
    await onAuthSelect(value);
  }, "handleMainSelect");
  const handleApiKeySubSelect = /* @__PURE__ */ __name(async (subMode) => {
    setErrorMessage(null);
    onAuthError(null);
    if (subMode === "coding-plan") {
      setRegion("china" /* CHINA */);
      setViewLevel("api-key-input");
    } else if (subMode === "coding-plan-intl") {
      setRegion("global" /* GLOBAL */);
      setViewLevel("api-key-input");
    } else {
      setViewLevel("custom-info");
    }
  }, "handleApiKeySubSelect");
  const handleApiKeyInputSubmit = /* @__PURE__ */ __name(async (apiKey) => {
    setErrorMessage(null);
    if (!apiKey.trim()) {
      setErrorMessage(t4("API key cannot be empty."));
      return;
    }
    await handleCodingPlanSubmit(apiKey, region);
  }, "handleApiKeyInputSubmit");
  const handleGoBack = /* @__PURE__ */ __name(() => {
    setErrorMessage(null);
    onAuthError(null);
    if (viewLevel === "api-key-sub") {
      setViewLevel("main");
      setSelectedIndex(null);
    } else if (viewLevel === "api-key-input" || viewLevel === "custom-info") {
      setViewLevel("api-key-sub");
    }
  }, "handleGoBack");
  useKeypress(
    (key) => {
      if (key.name === "escape") {
        if (viewLevel === "api-key-sub") {
          handleGoBack();
          return;
        }
        if (viewLevel === "api-key-input" || viewLevel === "custom-info") {
          handleGoBack();
          return;
        }
        if (errorMessage) {
          return;
        }
        if (config2.getAuthType() === void 0) {
          setErrorMessage(
            t4(
              "You must select an auth method to proceed. Press Ctrl+C again to exit."
            )
          );
          return;
        }
        onAuthSelect(void 0);
      }
    },
    { isActive: true }
  );
  const renderMainView = /* @__PURE__ */ __name(() => /* @__PURE__ */ (0, import_jsx_runtime82.jsxs)(import_jsx_runtime82.Fragment, { children: [
    /* @__PURE__ */ (0, import_jsx_runtime82.jsx)(Box_default, { marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime82.jsx)(Text3, { children: t4("How would you like to authenticate for this project?") }) }),
    /* @__PURE__ */ (0, import_jsx_runtime82.jsx)(Box_default, { marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime82.jsx)(
      RadioButtonSelect,
      {
        items: mainItems,
        initialIndex: initialAuthIndex,
        onSelect: handleMainSelect,
        onHighlight: (value) => {
          const index = mainItems.findIndex((item) => item.value === value);
          setSelectedIndex(index);
        }
      }
    ) }),
    /* @__PURE__ */ (0, import_jsx_runtime82.jsx)(Box_default, { marginTop: 1, paddingLeft: 2, children: /* @__PURE__ */ (0, import_jsx_runtime82.jsx)(Text3, { color: theme.text.secondary, children: currentSelectedAuthType === AuthType2.QWEN_OAUTH ? t4("Login with QwenChat account to use daily free quota.") : t4("Use coding plan credentials or your own api-keys/providers.") }) })
  ] }), "renderMainView");
  const renderApiKeySubView = /* @__PURE__ */ __name(() => /* @__PURE__ */ (0, import_jsx_runtime82.jsxs)(import_jsx_runtime82.Fragment, { children: [
    /* @__PURE__ */ (0, import_jsx_runtime82.jsx)(Box_default, { marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime82.jsx)(Text3, { children: t4("Select API-KEY configuration mode:") }) }),
    /* @__PURE__ */ (0, import_jsx_runtime82.jsx)(Box_default, { marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime82.jsx)(
      RadioButtonSelect,
      {
        items: apiKeySubItems,
        initialIndex: apiKeySubModeIndex,
        onSelect: handleApiKeySubSelect,
        onHighlight: (value) => {
          const index = apiKeySubItems.findIndex(
            (item) => item.value === value
          );
          setApiKeySubModeIndex(index);
        }
      }
    ) }),
    /* @__PURE__ */ (0, import_jsx_runtime82.jsx)(Box_default, { marginTop: 1, paddingLeft: 2, children: /* @__PURE__ */ (0, import_jsx_runtime82.jsx)(Text3, { color: theme.text.secondary, children: apiKeySubItems[apiKeySubModeIndex]?.value === "custom" ? t4(
      "More instructions about configuring `modelProviders` manually."
    ) : t4(
      "Paste your api key of Bailian Coding Plan and you're all set!"
    ) }) }),
    /* @__PURE__ */ (0, import_jsx_runtime82.jsx)(Box_default, { marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime82.jsx)(Text3, { color: theme?.text?.secondary, children: t4("(Press Escape to go back)") }) })
  ] }), "renderApiKeySubView");
  const renderApiKeyInputView = /* @__PURE__ */ __name(() => /* @__PURE__ */ (0, import_jsx_runtime82.jsx)(Box_default, { marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime82.jsx)(
    ApiKeyInput,
    {
      onSubmit: handleApiKeyInputSubmit,
      onCancel: handleGoBack,
      region
    }
  ) }), "renderApiKeyInputView");
  const renderCustomInfoView = /* @__PURE__ */ __name(() => /* @__PURE__ */ (0, import_jsx_runtime82.jsxs)(import_jsx_runtime82.Fragment, { children: [
    /* @__PURE__ */ (0, import_jsx_runtime82.jsx)(Box_default, { marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime82.jsx)(Text3, { bold: true, children: t4("Custom API-KEY Configuration") }) }),
    /* @__PURE__ */ (0, import_jsx_runtime82.jsx)(Box_default, { marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime82.jsx)(Text3, { children: t4("For advanced users who want to configure models manually.") }) }),
    /* @__PURE__ */ (0, import_jsx_runtime82.jsx)(Box_default, { marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime82.jsx)(Text3, { children: t4("Please configure your models in settings.json:") }) }),
    /* @__PURE__ */ (0, import_jsx_runtime82.jsx)(Box_default, { marginTop: 1, paddingLeft: 2, children: /* @__PURE__ */ (0, import_jsx_runtime82.jsxs)(Text3, { color: theme.status.warning, children: [
      "1. ",
      t4("Set API key via environment variable (e.g., OPENAI_API_KEY)")
    ] }) }),
    /* @__PURE__ */ (0, import_jsx_runtime82.jsx)(Box_default, { marginTop: 0, paddingLeft: 2, children: /* @__PURE__ */ (0, import_jsx_runtime82.jsxs)(Text3, { color: theme.status.warning, children: [
      "2.",
      " ",
      t4(
        "Add model configuration to modelProviders['openai'] (or other auth types)"
      )
    ] }) }),
    /* @__PURE__ */ (0, import_jsx_runtime82.jsx)(Box_default, { marginTop: 0, paddingLeft: 2, children: /* @__PURE__ */ (0, import_jsx_runtime82.jsxs)(Text3, { color: theme.status.warning, children: [
      "3.",
      " ",
      t4(
        "Each provider needs: id, envKey (required), plus optional baseUrl, generationConfig"
      )
    ] }) }),
    /* @__PURE__ */ (0, import_jsx_runtime82.jsx)(Box_default, { marginTop: 0, paddingLeft: 2, children: /* @__PURE__ */ (0, import_jsx_runtime82.jsxs)(Text3, { color: theme.status.warning, children: [
      "4.",
      " ",
      t4(
        "Use /model command to select your preferred model from the configured list"
      )
    ] }) }),
    /* @__PURE__ */ (0, import_jsx_runtime82.jsx)(Box_default, { marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime82.jsx)(Text3, { color: theme?.text?.secondary, children: t4(
      "Supported auth types: openai, anthropic, gemini, vertex-ai, etc."
    ) }) }),
    /* @__PURE__ */ (0, import_jsx_runtime82.jsx)(Box_default, { marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime82.jsx)(Text3, { color: theme?.text?.secondary, underline: true, children: t4("More instructions please check:") }) }),
    /* @__PURE__ */ (0, import_jsx_runtime82.jsx)(Box_default, { marginTop: 0, children: /* @__PURE__ */ (0, import_jsx_runtime82.jsx)(dist_default6, { url: MODEL_PROVIDERS_DOCUMENTATION_URL, fallback: false, children: /* @__PURE__ */ (0, import_jsx_runtime82.jsx)(Text3, { color: theme.status.success, underline: true, children: MODEL_PROVIDERS_DOCUMENTATION_URL }) }) }),
    /* @__PURE__ */ (0, import_jsx_runtime82.jsx)(Box_default, { marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime82.jsx)(Text3, { color: theme?.text?.secondary, children: t4("(Press Escape to go back)") }) })
  ] }), "renderCustomInfoView");
  const getViewTitle = /* @__PURE__ */ __name(() => {
    switch (viewLevel) {
      case "main":
        return t4("Get started");
      case "api-key-sub":
        return t4("API-KEY Configuration");
      case "api-key-input":
        return t4("Coding Plan Setup");
      case "custom-info":
        return t4("Custom Configuration");
      default:
        return t4("Get started");
    }
  }, "getViewTitle");
  return /* @__PURE__ */ (0, import_jsx_runtime82.jsxs)(
    Box_default,
    {
      borderStyle: "round",
      borderColor: theme?.border?.default,
      flexDirection: "column",
      padding: 1,
      width: "100%",
      children: [
        /* @__PURE__ */ (0, import_jsx_runtime82.jsx)(Text3, { bold: true, children: getViewTitle() }),
        viewLevel === "main" && renderMainView(),
        viewLevel === "api-key-sub" && renderApiKeySubView(),
        viewLevel === "api-key-input" && renderApiKeyInputView(),
        viewLevel === "custom-info" && renderCustomInfoView(),
        (authError || errorMessage) && /* @__PURE__ */ (0, import_jsx_runtime82.jsx)(Box_default, { marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime82.jsx)(Text3, { color: theme.status.error, children: authError || errorMessage }) }),
        viewLevel === "main" && /* @__PURE__ */ (0, import_jsx_runtime82.jsxs)(import_jsx_runtime82.Fragment, { children: [
          /* @__PURE__ */ (0, import_jsx_runtime82.jsx)(Box_default, { marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime82.jsx)(Text3, { color: theme.text.accent, children: t4("(Use Enter to Set Auth)") }) }),
          hasApiKey && currentSelectedAuthType === AuthType2.QWEN_OAUTH && /* @__PURE__ */ (0, import_jsx_runtime82.jsx)(Box_default, { marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime82.jsx)(Text3, { color: theme?.text?.secondary, children: t4(
            "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_runtime82.jsx)(Box_default, { marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime82.jsx)(Text3, { children: t4("Terms of Services and Privacy Notice for Qwen Code") }) }),
          /* @__PURE__ */ (0, import_jsx_runtime82.jsx)(Box_default, { marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime82.jsx)(Text3, { color: theme.text.link, children: "https://qwenlm.github.io/qwen-code-docs/en/users/support/tos-privacy/" }) })
        ] })
      ]
    }
  );
}
__name(AuthDialog, "AuthDialog");

// packages/cli/src/ui/components/EditorSettingsDialog.tsx
init_esbuild_shims();
var import_react83 = __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_runtime83 = __toESM(require_jsx_runtime(), 1);
var debugLogger104 = createDebugLogger("EDITOR_SETTINGS_DIALOG");
function EditorSettingsDialog({
  onSelect,
  settings,
  onExit
}) {
  const [selectedScope, setSelectedScope] = (0, import_react83.useState)(
    "User" /* User */
  );
  const [mode, setMode] = (0, import_react83.useState)("editor");
  useKeypress(
    (key) => {
      if (key.name === "tab") {
        setMode((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) {
    debugLogger104.error(`Editor is not supported: ${currentPreference}`);
    editorIndex = 0;
  }
  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);
    setMode("editor");
  }, "handleScopeSelect");
  const handleScopeHighlight = /* @__PURE__ */ __name((scope) => {
    setSelectedScope(scope);
  }, "handleScopeHighlight");
  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_runtime83.jsxs)(
    Box_default,
    {
      borderStyle: "round",
      borderColor: theme.border.default,
      flexDirection: "row",
      padding: 1,
      width: "100%",
      children: [
        /* @__PURE__ */ (0, import_jsx_runtime83.jsxs)(Box_default, { flexDirection: "column", width: "45%", paddingRight: 2, children: [
          mode === "editor" ? /* @__PURE__ */ (0, import_jsx_runtime83.jsxs)(Box_default, { flexDirection: "column", children: [
            /* @__PURE__ */ (0, import_jsx_runtime83.jsxs)(Text3, { bold: mode === "editor", wrap: "truncate", children: [
              mode === "editor" ? "> " : "  ",
              t4("Select Editor"),
              " ",
              /* @__PURE__ */ (0, import_jsx_runtime83.jsx)(Text3, { color: theme.text.secondary, children: otherScopeModifiedMessage })
            ] }),
            /* @__PURE__ */ (0, import_jsx_runtime83.jsx)(Box_default, { height: 1 }),
            /* @__PURE__ */ (0, import_jsx_runtime83.jsx)(
              RadioButtonSelect,
              {
                items: editorItems.map((item) => ({
                  label: item.name,
                  value: item.type,
                  disabled: item.disabled,
                  key: item.type
                })),
                initialIndex: editorIndex,
                onSelect: handleEditorSelect,
                isFocused: mode === "editor"
              },
              selectedScope
            )
          ] }) : /* @__PURE__ */ (0, import_jsx_runtime83.jsx)(
            ScopeSelector,
            {
              onSelect: handleScopeSelect,
              onHighlight: handleScopeHighlight,
              isFocused: mode === "scope",
              initialScope: selectedScope
            }
          ),
          /* @__PURE__ */ (0, import_jsx_runtime83.jsx)(Box_default, { marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime83.jsx)(Text3, { color: theme.text.secondary, wrap: "truncate", children: mode === "editor" ? t4("(Use Enter to select, Tab to configure scope)") : t4("(Use Enter to apply scope, Tab to go back)") }) })
        ] }),
        /* @__PURE__ */ (0, import_jsx_runtime83.jsxs)(Box_default, { flexDirection: "column", width: "55%", paddingLeft: 2, children: [
          /* @__PURE__ */ (0, import_jsx_runtime83.jsx)(Text3, { bold: true, color: theme.text.primary, children: t4("Editor Preference") }),
          /* @__PURE__ */ (0, import_jsx_runtime83.jsxs)(Box_default, { flexDirection: "column", gap: 1, marginTop: 1, children: [
            /* @__PURE__ */ (0, import_jsx_runtime83.jsx)(Text3, { color: theme.text.secondary, children: t4(
              "These editors are currently supported. Please note that some editors cannot be used in sandbox mode."
            ) }),
            /* @__PURE__ */ (0, import_jsx_runtime83.jsxs)(Text3, { color: theme.text.secondary, children: [
              t4("Your preferred editor is:"),
              " ",
              /* @__PURE__ */ (0, import_jsx_runtime83.jsx)(
                Text3,
                {
                  color: mergedEditorName === "None" ? theme.status.error : theme.text.link,
                  bold: true,
                  children: mergedEditorName
                }
              ),
              "."
            ] })
          ] })
        ] })
      ]
    }
  );
}
__name(EditorSettingsDialog, "EditorSettingsDialog");

// packages/cli/src/ui/components/PermissionsModifyTrustDialog.tsx
init_esbuild_shims();

// packages/cli/src/ui/hooks/usePermissionsModifyTrust.ts
init_esbuild_shims();
var import_react84 = __toESM(require_react(), 1);
import * as process34 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 = process34.cwd();
  const [initialState2] = (0, import_react84.useState)(() => getInitialTrustState(settings, cwd7));
  const [currentTrustLevel] = (0, import_react84.useState)(
    initialState2.currentTrustLevel
  );
  const [pendingTrustLevel, setPendingTrustLevel] = (0, import_react84.useState)();
  const [isInheritedTrustFromParent] = (0, import_react84.useState)(
    initialState2.isInheritedTrustFromParent
  );
  const [isInheritedTrustFromIde] = (0, import_react84.useState)(
    initialState2.isInheritedTrustFromIde
  );
  const [needsRestart, setNeedsRestart] = (0, import_react84.useState)(false);
  const isFolderTrustEnabled2 = !!settings.merged.security?.folderTrust?.enabled;
  const updateTrustLevel = (0, import_react84.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_react84.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_runtime84 = __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_runtime84.jsxs)(import_jsx_runtime84.Fragment, { children: [
    /* @__PURE__ */ (0, import_jsx_runtime84.jsxs)(
      Box_default,
      {
        borderStyle: "round",
        borderColor: theme.border.default,
        flexDirection: "column",
        padding: 1,
        children: [
          /* @__PURE__ */ (0, import_jsx_runtime84.jsxs)(Box_default, { flexDirection: "column", paddingBottom: 1, children: [
            /* @__PURE__ */ (0, import_jsx_runtime84.jsxs)(Text3, { bold: true, children: [
              "> ",
              "Modify Trust Level"
            ] }),
            /* @__PURE__ */ (0, import_jsx_runtime84.jsx)(Box_default, { marginTop: 1 }),
            /* @__PURE__ */ (0, import_jsx_runtime84.jsxs)(Text3, { children: [
              "Folder: ",
              cwd7
            ] }),
            /* @__PURE__ */ (0, import_jsx_runtime84.jsxs)(Text3, { children: [
              "Current Level: ",
              /* @__PURE__ */ (0, import_jsx_runtime84.jsx)(Text3, { bold: true, children: currentTrustLevel || "Not Set" })
            ] }),
            isInheritedTrustFromParent && /* @__PURE__ */ (0, import_jsx_runtime84.jsx)(Text3, { 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_runtime84.jsx)(Text3, { 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_runtime84.jsx)(
            RadioButtonSelect,
            {
              items: TRUST_LEVEL_ITEMS,
              onSelect: updateTrustLevel,
              isFocused: true,
              initialIndex
            }
          ),
          /* @__PURE__ */ (0, import_jsx_runtime84.jsx)(Box_default, { marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime84.jsx)(Text3, { color: theme.text.secondary, children: "(Use Enter to select)" }) })
        ]
      }
    ),
    needsRestart && /* @__PURE__ */ (0, import_jsx_runtime84.jsx)(Box_default, { marginLeft: 1, marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime84.jsx)(Text3, { color: theme.status.warning, children: "To apply the trust changes, Qwen Code must be restarted. Press 'r' to restart CLI now." }) })
  ] });
}
__name(PermissionsModifyTrustDialog, "PermissionsModifyTrustDialog");

// packages/cli/src/ui/components/ModelDialog.tsx
init_esbuild_shims();
var import_react85 = __toESM(require_react(), 1);

// packages/cli/src/ui/components/shared/DescriptiveRadioButtonSelect.tsx
init_esbuild_shims();
var import_jsx_runtime85 = __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_runtime85.jsx)(
    BaseSelectionList,
    {
      items,
      initialIndex,
      onSelect,
      onHighlight,
      isFocused,
      showNumbers,
      showScrollArrows,
      maxItemsToShow: maxItemsToShow2,
      renderItem: (item, { titleColor }) => /* @__PURE__ */ (0, import_jsx_runtime85.jsxs)(Box_default, { flexDirection: "column", children: [
        /* @__PURE__ */ (0, import_jsx_runtime85.jsx)(Text3, { color: titleColor, children: item.title }),
        /* @__PURE__ */ (0, import_jsx_runtime85.jsx)(Text3, { color: theme.text.secondary, children: item.description })
      ] }, item.key)
    }
  );
}
__name(DescriptiveRadioButtonSelect, "DescriptiveRadioButtonSelect");

// packages/cli/src/ui/components/ModelDialog.tsx
var import_jsx_runtime86 = __toESM(require_jsx_runtime(), 1);
function formatSourceBadge(source2) {
  if (!source2) return void 0;
  switch (source2.kind) {
    case "cli":
      return source2.detail ? `CLI ${source2.detail}` : "CLI";
    case "env":
      return source2.envKey ? `ENV ${source2.envKey}` : "ENV";
    case "settings":
      return source2.settingsPath ? `Settings ${source2.settingsPath}` : "Settings";
    case "modelProviders": {
      const suffix = source2.authType && source2.modelId ? `${source2.authType}:${source2.modelId}` : source2.authType ? `${source2.authType}` : source2.modelId ? `${source2.modelId}` : "";
      return suffix ? `ModelProviders ${suffix}` : "ModelProviders";
    }
    case "default":
      return source2.detail ? `Default ${source2.detail}` : "Default";
    case "computed":
      return source2.detail ? `Computed ${source2.detail}` : "Computed";
    case "programmatic":
      return source2.detail ? `Programmatic ${source2.detail}` : "Programmatic";
    case "unknown":
    default:
      return void 0;
  }
}
__name(formatSourceBadge, "formatSourceBadge");
function readSourcesFromConfig(config2) {
  if (!config2) {
    return {};
  }
  const maybe = config2;
  return maybe.getContentGeneratorConfigSources?.() ?? {};
}
__name(readSourcesFromConfig, "readSourcesFromConfig");
function maskApiKey(apiKey) {
  if (!apiKey) return "(not set)";
  const trimmed2 = apiKey.trim();
  if (trimmed2.length === 0) return "(not set)";
  if (trimmed2.length <= 6) return "***";
  const head = trimmed2.slice(0, 3);
  const tail = trimmed2.slice(-4);
  return `${head}\u2026${tail}`;
}
__name(maskApiKey, "maskApiKey");
function persistModelSelection(settings, modelId) {
  const scope = getPersistScopeForModelSelection(settings);
  settings.setValue(scope, "model.name", modelId);
}
__name(persistModelSelection, "persistModelSelection");
function persistAuthTypeSelection(settings, authType) {
  const scope = getPersistScopeForModelSelection(settings);
  settings.setValue(scope, "security.auth.selectedType", authType);
}
__name(persistAuthTypeSelection, "persistAuthTypeSelection");
function handleModelSwitchSuccess({
  settings,
  uiState,
  after,
  effectiveAuthType,
  effectiveModelId,
  isRuntime
}) {
  persistModelSelection(settings, effectiveModelId);
  if (effectiveAuthType) {
    persistAuthTypeSelection(settings, effectiveAuthType);
  }
  const baseUrl = after?.baseUrl ?? t4("(default)");
  const maskedKey = maskApiKey(after?.apiKey);
  uiState?.historyManager.addItem(
    {
      type: "info",
      text: `authType: ${effectiveAuthType ?? "(none)"}
Using ${isRuntime ? "runtime " : ""}model: ${effectiveModelId}
Base URL: ${baseUrl}
API key: ${maskedKey}`
    },
    Date.now()
  );
}
__name(handleModelSwitchSuccess, "handleModelSwitchSuccess");
function ConfigRow({
  label,
  value,
  badge
}) {
  return /* @__PURE__ */ (0, import_jsx_runtime86.jsxs)(Box_default, { flexDirection: "column", children: [
    /* @__PURE__ */ (0, import_jsx_runtime86.jsxs)(Box_default, { children: [
      /* @__PURE__ */ (0, import_jsx_runtime86.jsx)(Box_default, { minWidth: 12, flexShrink: 0, children: /* @__PURE__ */ (0, import_jsx_runtime86.jsxs)(Text3, { color: theme.text.secondary, children: [
        label,
        ":"
      ] }) }),
      /* @__PURE__ */ (0, import_jsx_runtime86.jsx)(Box_default, { flexGrow: 1, flexDirection: "row", flexWrap: "wrap", children: /* @__PURE__ */ (0, import_jsx_runtime86.jsx)(Text3, { children: value }) })
    ] }),
    badge ? /* @__PURE__ */ (0, import_jsx_runtime86.jsxs)(Box_default, { children: [
      /* @__PURE__ */ (0, import_jsx_runtime86.jsx)(Box_default, { minWidth: 12, flexShrink: 0, children: /* @__PURE__ */ (0, import_jsx_runtime86.jsx)(Text3, { children: " " }) }),
      /* @__PURE__ */ (0, import_jsx_runtime86.jsx)(Box_default, { flexGrow: 1, children: /* @__PURE__ */ (0, import_jsx_runtime86.jsx)(Text3, { color: theme.text.secondary, children: badge }) })
    ] }) : null
  ] });
}
__name(ConfigRow, "ConfigRow");
function ModelDialog({ onClose }) {
  const config2 = (0, import_react85.useContext)(ConfigContext);
  const uiState = (0, import_react85.useContext)(UIStateContext);
  const settings = useSettings();
  const [errorMessage, setErrorMessage] = (0, import_react85.useState)(null);
  const authType = config2?.getAuthType();
  const effectiveConfig = config2?.getContentGeneratorConfig?.() ?? void 0;
  const sources = readSourcesFromConfig(config2);
  const availableModelEntries = (0, import_react85.useMemo)(() => {
    const allModels = config2 ? config2.getAllConfiguredModels() : [];
    const runtimeModels = allModels.filter((m3) => m3.isRuntimeModel);
    const registryModels = allModels.filter((m3) => !m3.isRuntimeModel);
    const modelsByAuthTypeMap = /* @__PURE__ */ new Map();
    for (const model of registryModels) {
      const authType2 = model.authType;
      if (!modelsByAuthTypeMap.has(authType2)) {
        modelsByAuthTypeMap.set(authType2, []);
      }
      modelsByAuthTypeMap.get(authType2).push(model);
    }
    const authTypeOrder = [
      AuthType2.QWEN_OAUTH,
      AuthType2.USE_OPENAI,
      AuthType2.USE_ANTHROPIC,
      AuthType2.USE_GEMINI,
      AuthType2.USE_VERTEX_AI
    ];
    const availableAuthTypes = new Set(modelsByAuthTypeMap.keys());
    const orderedAuthTypes = authTypeOrder.filter(
      (t5) => availableAuthTypes.has(t5)
    );
    const result = [];
    for (const runtimeModel of runtimeModels) {
      result.push({
        authType: runtimeModel.authType,
        model: runtimeModel,
        isRuntime: true,
        snapshotId: runtimeModel.runtimeSnapshotId
      });
    }
    for (const t5 of orderedAuthTypes) {
      for (const model of modelsByAuthTypeMap.get(t5) ?? []) {
        result.push({ authType: t5, model, isRuntime: false });
      }
    }
    return result;
  }, [config2]);
  const MODEL_OPTIONS = (0, import_react85.useMemo)(
    () => availableModelEntries.map(
      ({ authType: t22, model, isRuntime, snapshotId }) => {
        const value = isRuntime && snapshotId ? snapshotId : `${t22}::${model.id}`;
        const title = /* @__PURE__ */ (0, import_jsx_runtime86.jsxs)(Text3, { children: [
          /* @__PURE__ */ (0, import_jsx_runtime86.jsxs)(
            Text3,
            {
              bold: true,
              color: isRuntime ? theme.status.warning : theme.text.accent,
              children: [
                "[",
                t22,
                "]"
              ]
            }
          ),
          /* @__PURE__ */ (0, import_jsx_runtime86.jsx)(Text3, { children: ` ${model.label}` }),
          isRuntime && /* @__PURE__ */ (0, import_jsx_runtime86.jsx)(Text3, { color: theme.status.warning, children: " (Runtime)" })
        ] });
        let description = model.description || "";
        if (isRuntime) {
          description = description ? `${description} (Runtime)` : "Runtime model";
        }
        return {
          value,
          title,
          description,
          key: value
        };
      }
    ),
    [availableModelEntries]
  );
  const preferredModelId = config2?.getModel() || MAINLINE_CODER_MODEL;
  const activeRuntimeSnapshot = config2?.getActiveRuntimeModelSnapshot?.();
  const preferredKey = activeRuntimeSnapshot ? activeRuntimeSnapshot.id : authType ? `${authType}::${preferredModelId}` : "";
  useKeypress(
    (key) => {
      if (key.name === "escape") {
        onClose();
      }
    },
    { isActive: true }
  );
  const initialIndex = (0, import_react85.useMemo)(() => {
    const index = MODEL_OPTIONS.findIndex(
      (option2) => option2.value === preferredKey
    );
    return index === -1 ? 0 : index;
  }, [MODEL_OPTIONS, preferredKey]);
  const handleSelect = (0, import_react85.useCallback)(
    async (selected) => {
      setErrorMessage(null);
      let after;
      let effectiveAuthType;
      let effectiveModelId = selected;
      let isRuntime = false;
      if (!config2) {
        onClose();
        return;
      }
      try {
        isRuntime = selected.startsWith("$runtime|");
        let selectedAuthType;
        let modelId;
        if (isRuntime) {
          const parts = selected.split("|");
          if (parts.length >= 2 && parts[0] === "$runtime") {
            selectedAuthType = parts[1];
          } else {
            selectedAuthType = authType;
          }
          modelId = selected;
        } else {
          const sep9 = "::";
          const idx = selected.indexOf(sep9);
          selectedAuthType = idx >= 0 ? selected.slice(0, idx) : authType;
          modelId = idx >= 0 ? selected.slice(idx + sep9.length) : selected;
        }
        await config2.switchModel(
          selectedAuthType,
          modelId,
          selectedAuthType !== authType && selectedAuthType === AuthType2.QWEN_OAUTH ? { requireCachedCredentials: true } : void 0
        );
        if (!isRuntime) {
          const event = new ModelSlashCommandEvent(modelId);
          logModelSlashCommand(config2, event);
        }
        after = config2.getContentGeneratorConfig?.();
        effectiveAuthType = after?.authType ?? selectedAuthType ?? authType;
        effectiveModelId = after?.model ?? modelId;
      } catch (e4) {
        const baseErrorMessage = e4 instanceof Error ? e4.message : String(e4);
        const errorPrefix = isRuntime ? "Failed to switch to runtime model." : `Failed to switch model to '${effectiveModelId ?? selected}'.`;
        setErrorMessage(`${errorPrefix}

${baseErrorMessage}`);
        return;
      }
      handleModelSwitchSuccess({
        settings,
        uiState,
        after,
        effectiveAuthType,
        effectiveModelId,
        isRuntime
      });
      onClose();
    },
    [authType, config2, onClose, settings, uiState, setErrorMessage]
  );
  const hasModels = MODEL_OPTIONS.length > 0;
  return /* @__PURE__ */ (0, import_jsx_runtime86.jsxs)(
    Box_default,
    {
      borderStyle: "round",
      borderColor: theme.border.default,
      flexDirection: "column",
      padding: 1,
      width: "100%",
      children: [
        /* @__PURE__ */ (0, import_jsx_runtime86.jsx)(Text3, { bold: true, children: t4("Select Model") }),
        /* @__PURE__ */ (0, import_jsx_runtime86.jsxs)(Box_default, { marginTop: 1, flexDirection: "column", children: [
          /* @__PURE__ */ (0, import_jsx_runtime86.jsx)(Text3, { color: theme.text.secondary, children: t4("Current (effective) configuration") }),
          /* @__PURE__ */ (0, import_jsx_runtime86.jsxs)(Box_default, { flexDirection: "column", marginTop: 1, children: [
            /* @__PURE__ */ (0, import_jsx_runtime86.jsx)(ConfigRow, { label: "AuthType", value: authType }),
            /* @__PURE__ */ (0, import_jsx_runtime86.jsx)(
              ConfigRow,
              {
                label: "Model",
                value: effectiveConfig?.model ?? config2?.getModel?.() ?? "",
                badge: formatSourceBadge(sources["model"])
              }
            ),
            authType !== AuthType2.QWEN_OAUTH && /* @__PURE__ */ (0, import_jsx_runtime86.jsxs)(import_jsx_runtime86.Fragment, { children: [
              /* @__PURE__ */ (0, import_jsx_runtime86.jsx)(
                ConfigRow,
                {
                  label: "Base URL",
                  value: effectiveConfig?.baseUrl ?? t4("(default)"),
                  badge: formatSourceBadge(sources["baseUrl"])
                }
              ),
              /* @__PURE__ */ (0, import_jsx_runtime86.jsx)(
                ConfigRow,
                {
                  label: "API Key",
                  value: effectiveConfig?.apiKey ? t4("(set)") : t4("(not set)"),
                  badge: formatSourceBadge(sources["apiKey"])
                }
              )
            ] })
          ] })
        ] }),
        !hasModels ? /* @__PURE__ */ (0, import_jsx_runtime86.jsxs)(Box_default, { marginTop: 1, flexDirection: "column", children: [
          /* @__PURE__ */ (0, import_jsx_runtime86.jsx)(Text3, { color: theme.status.warning, children: t4(
            "No models available for the current authentication type ({{authType}}).",
            {
              authType: authType ? String(authType) : t4("(none)")
            }
          ) }),
          /* @__PURE__ */ (0, import_jsx_runtime86.jsx)(Box_default, { marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime86.jsx)(Text3, { color: theme.text.secondary, children: t4(
            "Please configure models in settings.modelProviders or use environment variables."
          ) }) })
        ] }) : /* @__PURE__ */ (0, import_jsx_runtime86.jsx)(Box_default, { marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime86.jsx)(
          DescriptiveRadioButtonSelect,
          {
            items: MODEL_OPTIONS,
            onSelect: handleSelect,
            initialIndex,
            showNumbers: true
          }
        ) }),
        errorMessage && /* @__PURE__ */ (0, import_jsx_runtime86.jsx)(Box_default, { marginTop: 1, flexDirection: "column", paddingX: 1, children: /* @__PURE__ */ (0, import_jsx_runtime86.jsxs)(Text3, { color: theme.status.error, wrap: "wrap", children: [
          "\u2715 ",
          errorMessage
        ] }) }),
        /* @__PURE__ */ (0, import_jsx_runtime86.jsx)(Box_default, { marginTop: 1, flexDirection: "column", children: /* @__PURE__ */ (0, import_jsx_runtime86.jsx)(Text3, { color: theme.text.secondary, children: t4("(Press Esc to close)") }) })
      ]
    }
  );
}
__name(ModelDialog, "ModelDialog");

// packages/cli/src/ui/components/ApprovalModeDialog.tsx
init_esbuild_shims();
var import_react86 = __toESM(require_react(), 1);
var import_jsx_runtime87 = __toESM(require_jsx_runtime(), 1);
var formatModeDescription = /* @__PURE__ */ __name((mode) => {
  switch (mode) {
    case ApprovalMode.PLAN:
      return t4("Analyze only, do not modify files or execute commands");
    case ApprovalMode.DEFAULT:
      return t4("Require approval for file edits or shell commands");
    case ApprovalMode.AUTO_EDIT:
      return t4("Automatically approve file edits");
    case ApprovalMode.YOLO:
      return t4("Automatically approve all tools");
    default:
      return t4("{{mode}} mode", { mode });
  }
}, "formatModeDescription");
function ApprovalModeDialog({
  onSelect,
  settings,
  currentMode,
  availableTerminalHeight: _availableTerminalHeight
}) {
  const [selectedScope, setSelectedScope] = (0, import_react86.useState)(
    "User" /* User */
  );
  const [highlightedMode, setHighlightedMode] = (0, import_react86.useState)(
    currentMode || ApprovalMode.DEFAULT
  );
  const modeItems = APPROVAL_MODES.map((mode2) => ({
    label: `${mode2} - ${formatModeDescription(mode2)}`,
    value: mode2,
    key: mode2
  }));
  const initialModeIndex = modeItems.findIndex(
    (item) => item.value === highlightedMode
  );
  const safeInitialModeIndex = initialModeIndex >= 0 ? initialModeIndex : 0;
  const handleModeSelect = (0, import_react86.useCallback)(
    (mode2) => {
      onSelect(mode2, selectedScope);
    },
    [onSelect, selectedScope]
  );
  const handleModeHighlight = /* @__PURE__ */ __name((mode2) => {
    setHighlightedMode(mode2);
  }, "handleModeHighlight");
  const handleScopeHighlight = (0, import_react86.useCallback)((scope) => {
    setSelectedScope(scope);
  }, []);
  const handleScopeSelect = (0, import_react86.useCallback)((scope) => {
    setSelectedScope(scope);
    setMode("mode");
  }, []);
  const [mode, setMode] = (0, import_react86.useState)("mode");
  useKeypress(
    (key) => {
      if (key.name === "tab") {
        setMode((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_runtime87.jsxs)(
    Box_default,
    {
      borderStyle: "round",
      borderColor: theme.border.default,
      flexDirection: "column",
      padding: 1,
      width: "100%",
      children: [
        mode === "mode" ? /* @__PURE__ */ (0, import_jsx_runtime87.jsxs)(Box_default, { flexDirection: "column", flexGrow: 1, children: [
          /* @__PURE__ */ (0, import_jsx_runtime87.jsxs)(Text3, { bold: mode === "mode", wrap: "truncate", children: [
            mode === "mode" ? "> " : "  ",
            t4("Approval Mode"),
            " ",
            /* @__PURE__ */ (0, import_jsx_runtime87.jsx)(Text3, { color: theme.text.secondary, children: otherScopeModifiedMessage })
          ] }),
          /* @__PURE__ */ (0, import_jsx_runtime87.jsx)(Box_default, { height: 1 }),
          /* @__PURE__ */ (0, import_jsx_runtime87.jsx)(
            RadioButtonSelect,
            {
              items: modeItems,
              initialIndex: safeInitialModeIndex,
              onSelect: handleModeSelect,
              onHighlight: handleModeHighlight,
              isFocused: mode === "mode",
              maxItemsToShow: 10,
              showScrollArrows: false,
              showNumbers: mode === "mode"
            }
          ),
          showWorkspacePriorityWarning && /* @__PURE__ */ (0, import_jsx_runtime87.jsx)(Box_default, { marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime87.jsxs)(Text3, { color: theme.status.warning, wrap: "wrap", children: [
            "\u26A0",
            " ",
            t4(
              "Workspace approval mode exists and takes priority. User-level change will have no effect."
            )
          ] }) })
        ] }) : /* @__PURE__ */ (0, import_jsx_runtime87.jsx)(
          ScopeSelector,
          {
            onSelect: handleScopeSelect,
            onHighlight: handleScopeHighlight,
            isFocused: mode === "scope",
            initialScope: selectedScope
          }
        ),
        /* @__PURE__ */ (0, import_jsx_runtime87.jsx)(Box_default, { marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime87.jsx)(Text3, { color: theme.text.secondary, wrap: "truncate", children: mode === "mode" ? t4("(Use Enter to select, Tab to configure scope)") : t4("(Use Enter to apply scope, Tab to go back)") }) })
      ]
    }
  );
}
__name(ApprovalModeDialog, "ApprovalModeDialog");

// packages/cli/src/ui/components/DialogManager.tsx
import process35 from "node:process";

// packages/cli/src/ui/components/IdeTrustChangeDialog.tsx
init_esbuild_shims();
var import_jsx_runtime88 = __toESM(require_jsx_runtime(), 1);
var debugLogger105 = createDebugLogger("IDE_TRUST_DIALOG");
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") {
    debugLogger105.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_runtime88.jsx)(Box_default, { borderStyle: "round", borderColor: theme.status.warning, paddingX: 1, children: /* @__PURE__ */ (0, import_jsx_runtime88.jsxs)(Text3, { 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_runtime89 = __toESM(require_jsx_runtime(), 1);
function WelcomeBackDialog({
  welcomeBackInfo,
  onSelect,
  onClose
}) {
  useKeypress(
    (key) => {
      if (key.name === "escape") {
        onClose();
      }
    },
    { isActive: true }
  );
  const options2 = [
    {
      key: "restart",
      label: t4("Start new chat session"),
      value: "restart"
    },
    {
      key: "continue",
      label: t4("Continue previous conversation"),
      value: "continue"
    }
  ];
  const {
    timeAgo,
    goalContent,
    totalTasks = 0,
    doneCount = 0,
    inProgressCount = 0,
    pendingTasks = []
  } = welcomeBackInfo;
  return /* @__PURE__ */ (0, import_jsx_runtime89.jsxs)(
    Box_default,
    {
      flexDirection: "column",
      borderStyle: "round",
      borderColor: Colors.AccentBlue,
      padding: 1,
      width: "100%",
      marginLeft: 1,
      children: [
        /* @__PURE__ */ (0, import_jsx_runtime89.jsx)(Box_default, { flexDirection: "column", marginBottom: 1, children: /* @__PURE__ */ (0, import_jsx_runtime89.jsx)(Text3, { color: Colors.AccentBlue, bold: true, children: t4("\u{1F44B} Welcome back! (Last updated: {{timeAgo}})", {
          timeAgo: timeAgo || ""
        }) }) }),
        goalContent && /* @__PURE__ */ (0, import_jsx_runtime89.jsxs)(Box_default, { flexDirection: "column", marginBottom: 1, children: [
          /* @__PURE__ */ (0, import_jsx_runtime89.jsx)(Text3, { color: Colors.Foreground, bold: true, children: t4("\u{1F3AF} Overall Goal:") }),
          /* @__PURE__ */ (0, import_jsx_runtime89.jsx)(Box_default, { marginTop: 1, paddingLeft: 2, children: /* @__PURE__ */ (0, import_jsx_runtime89.jsx)(Text3, { color: Colors.Gray, children: goalContent }) })
        ] }),
        totalTasks > 0 && /* @__PURE__ */ (0, import_jsx_runtime89.jsxs)(Box_default, { flexDirection: "column", marginBottom: 1, children: [
          /* @__PURE__ */ (0, import_jsx_runtime89.jsxs)(Text3, { color: Colors.Foreground, bold: true, children: [
            "\u{1F4CB} ",
            t4("Current Plan:")
          ] }),
          /* @__PURE__ */ (0, import_jsx_runtime89.jsx)(Box_default, { marginTop: 1, paddingLeft: 2, children: /* @__PURE__ */ (0, import_jsx_runtime89.jsxs)(Text3, { color: Colors.Gray, children: [
            t4("Progress: {{done}}/{{total}} tasks completed", {
              done: String(doneCount),
              total: String(totalTasks)
            }),
            inProgressCount > 0 && t4(", {{inProgress}} in progress", {
              inProgress: String(inProgressCount)
            })
          ] }) }),
          pendingTasks.length > 0 && /* @__PURE__ */ (0, import_jsx_runtime89.jsxs)(Box_default, { flexDirection: "column", marginTop: 1, paddingLeft: 2, children: [
            /* @__PURE__ */ (0, import_jsx_runtime89.jsx)(Text3, { color: Colors.Foreground, bold: true, children: t4("Pending Tasks:") }),
            pendingTasks.map((task, index) => /* @__PURE__ */ (0, import_jsx_runtime89.jsxs)(Text3, { color: Colors.Gray, children: [
              "\u2022 ",
              task
            ] }, index))
          ] })
        ] }),
        /* @__PURE__ */ (0, import_jsx_runtime89.jsxs)(Box_default, { flexDirection: "column", marginTop: 1, children: [
          /* @__PURE__ */ (0, import_jsx_runtime89.jsx)(Text3, { bold: true, children: t4("What would you like to do?") }),
          /* @__PURE__ */ (0, import_jsx_runtime89.jsx)(Text3, { children: t4("Choose how to proceed with your session:") })
        ] }),
        /* @__PURE__ */ (0, import_jsx_runtime89.jsx)(Box_default, { marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime89.jsx)(RadioButtonSelect, { items: options2, onSelect, isFocused: true }) })
      ]
    }
  );
}
__name(WelcomeBackDialog, "WelcomeBackDialog");

// packages/cli/src/ui/components/SessionPicker.tsx
init_esbuild_shims();

// packages/cli/src/ui/hooks/useSessionPicker.ts
init_esbuild_shims();
var import_react87 = __toESM(require_react(), 1);

// packages/cli/src/ui/utils/sessionPickerUtils.ts
init_esbuild_shims();
var SESSION_PAGE_SIZE = 20;
function truncateText(text, maxWidth) {
  const firstLine = text.split(/\r?\n/, 1)[0];
  if (firstLine.length <= maxWidth) {
    return firstLine;
  }
  if (maxWidth <= 3) {
    return firstLine.slice(0, maxWidth);
  }
  return firstLine.slice(0, maxWidth - 3) + "...";
}
__name(truncateText, "truncateText");
function filterSessions(sessions, filterByBranch, currentBranch) {
  return sessions.filter((session) => {
    if (filterByBranch && currentBranch) {
      return session.gitBranch === currentBranch;
    }
    return true;
  });
}
__name(filterSessions, "filterSessions");
function formatMessageCount(count) {
  return count === 1 ? "1 message" : `${count} messages`;
}
__name(formatMessageCount, "formatMessageCount");

// packages/cli/src/ui/hooks/useSessionPicker.ts
function useSessionPicker({
  sessionService,
  currentBranch,
  onSelect,
  onCancel,
  maxVisibleItems,
  centerSelection = false,
  isActive = true
}) {
  const [selectedIndex, setSelectedIndex] = (0, import_react87.useState)(0);
  const [sessionState, setSessionState] = (0, import_react87.useState)({
    sessions: [],
    hasMore: true,
    nextCursor: void 0
  });
  const [filterByBranch, setFilterByBranch] = (0, import_react87.useState)(false);
  const [isLoading, setIsLoading] = (0, import_react87.useState)(true);
  const [followScrollOffset, setFollowScrollOffset] = (0, import_react87.useState)(0);
  const isLoadingMoreRef = (0, import_react87.useRef)(false);
  const filteredSessions = (0, import_react87.useMemo)(
    () => filterSessions(sessionState.sessions, filterByBranch, currentBranch),
    [sessionState.sessions, filterByBranch, currentBranch]
  );
  const scrollOffset = (0, import_react87.useMemo)(() => {
    if (centerSelection) {
      if (filteredSessions.length <= maxVisibleItems) {
        return 0;
      }
      const halfVisible = Math.floor(maxVisibleItems / 2);
      let offset = selectedIndex - halfVisible;
      offset = Math.max(0, offset);
      offset = Math.min(filteredSessions.length - maxVisibleItems, offset);
      return offset;
    }
    return followScrollOffset;
  }, [
    centerSelection,
    filteredSessions.length,
    followScrollOffset,
    maxVisibleItems,
    selectedIndex
  ]);
  const visibleSessions = (0, import_react87.useMemo)(
    () => filteredSessions.slice(scrollOffset, scrollOffset + maxVisibleItems),
    [filteredSessions, maxVisibleItems, scrollOffset]
  );
  const showScrollUp = scrollOffset > 0;
  const showScrollDown = scrollOffset + maxVisibleItems < filteredSessions.length;
  (0, import_react87.useEffect)(() => {
    if (!sessionService) {
      return;
    }
    const loadInitialSessions = /* @__PURE__ */ __name(async () => {
      try {
        const result = await sessionService.listSessions({
          size: SESSION_PAGE_SIZE
        });
        setSessionState({
          sessions: result.items,
          hasMore: result.hasMore,
          nextCursor: result.nextCursor
        });
      } finally {
        setIsLoading(false);
      }
    }, "loadInitialSessions");
    void loadInitialSessions();
  }, [sessionService]);
  const loadMoreSessions = (0, import_react87.useCallback)(async () => {
    if (!sessionService || !sessionState.hasMore || isLoadingMoreRef.current) {
      return;
    }
    isLoadingMoreRef.current = true;
    try {
      const result = await sessionService.listSessions({
        size: SESSION_PAGE_SIZE,
        cursor: sessionState.nextCursor
      });
      setSessionState((prev) => ({
        sessions: [...prev.sessions, ...result.items],
        hasMore: result.hasMore && result.nextCursor !== void 0,
        nextCursor: result.nextCursor
      }));
    } finally {
      isLoadingMoreRef.current = false;
    }
  }, [sessionService, sessionState.hasMore, sessionState.nextCursor]);
  (0, import_react87.useEffect)(() => {
    setSelectedIndex(0);
    setFollowScrollOffset(0);
  }, [filterByBranch]);
  (0, import_react87.useEffect)(() => {
    if (selectedIndex >= filteredSessions.length && filteredSessions.length > 0) {
      setSelectedIndex(filteredSessions.length - 1);
    }
  }, [filteredSessions.length, selectedIndex]);
  (0, import_react87.useEffect)(() => {
    if (isLoading || !sessionState.hasMore || isLoadingMoreRef.current || !centerSelection) {
      return;
    }
    const sentinelVisible = scrollOffset + maxVisibleItems >= filteredSessions.length;
    const shouldLoadMore = filteredSessions.length === 0 || sentinelVisible;
    if (shouldLoadMore) {
      void loadMoreSessions();
    }
  }, [
    centerSelection,
    filteredSessions.length,
    isLoading,
    loadMoreSessions,
    maxVisibleItems,
    scrollOffset,
    sessionState.hasMore
  ]);
  useKeypress(
    (key) => {
      const { name: name3, sequence, ctrl } = key;
      if (name3 === "escape" || ctrl && name3 === "c") {
        onCancel();
        return;
      }
      if (name3 === "return") {
        const session = filteredSessions[selectedIndex];
        if (session) {
          onSelect(session.sessionId);
        }
        return;
      }
      if (name3 === "up" || name3 === "k") {
        setSelectedIndex((prev) => {
          const newIndex = Math.max(0, prev - 1);
          if (!centerSelection && newIndex < followScrollOffset) {
            setFollowScrollOffset(newIndex);
          }
          return newIndex;
        });
        return;
      }
      if (name3 === "down" || name3 === "j") {
        if (filteredSessions.length === 0) {
          return;
        }
        setSelectedIndex((prev) => {
          const newIndex = Math.min(filteredSessions.length - 1, prev + 1);
          if (!centerSelection && newIndex >= followScrollOffset + maxVisibleItems) {
            setFollowScrollOffset(newIndex - maxVisibleItems + 1);
          }
          if (!centerSelection && newIndex >= filteredSessions.length - 3) {
            void loadMoreSessions();
          }
          return newIndex;
        });
        return;
      }
      if (sequence === "b" || sequence === "B") {
        if (currentBranch) {
          setFilterByBranch((prev) => !prev);
        }
      }
    },
    { isActive }
  );
  return {
    selectedIndex,
    sessionState,
    filteredSessions,
    filterByBranch,
    isLoading,
    scrollOffset,
    visibleSessions,
    showScrollUp,
    showScrollDown,
    loadMoreSessions
  };
}
__name(useSessionPicker, "useSessionPicker");

// packages/cli/src/ui/components/SessionPicker.tsx
var import_jsx_runtime90 = __toESM(require_jsx_runtime(), 1);
var PREFIX_CHARS = {
  selected: "\u203A ",
  scrollUp: "\u2191 ",
  scrollDown: "\u2193 ",
  normal: "  "
};
function SessionListItemView({
  session,
  isSelected,
  isFirst,
  isLast,
  showScrollUp,
  showScrollDown,
  maxPromptWidth,
  prefixChars = PREFIX_CHARS,
  boldSelectedPrefix = true
}) {
  const timeAgo = formatRelativeTime(session.mtime);
  const messageText = formatMessageCount(session.messageCount);
  const showUpIndicator = isFirst && showScrollUp;
  const showDownIndicator = isLast && showScrollDown;
  const prefix = isSelected ? prefixChars.selected : showUpIndicator ? prefixChars.scrollUp : showDownIndicator ? prefixChars.scrollDown : prefixChars.normal;
  const promptText = session.prompt || "(empty prompt)";
  const truncatedPrompt = truncateText(promptText, maxPromptWidth);
  return /* @__PURE__ */ (0, import_jsx_runtime90.jsxs)(Box_default, { flexDirection: "column", marginBottom: isLast ? 0 : 1, children: [
    /* @__PURE__ */ (0, import_jsx_runtime90.jsxs)(Box_default, { children: [
      /* @__PURE__ */ (0, import_jsx_runtime90.jsx)(
        Text3,
        {
          color: isSelected ? theme.text.accent : showUpIndicator || showDownIndicator ? theme.text.secondary : void 0,
          bold: isSelected && boldSelectedPrefix,
          children: prefix
        }
      ),
      /* @__PURE__ */ (0, import_jsx_runtime90.jsx)(
        Text3,
        {
          color: isSelected ? theme.text.accent : theme.text.primary,
          bold: isSelected,
          children: truncatedPrompt
        }
      )
    ] }),
    /* @__PURE__ */ (0, import_jsx_runtime90.jsx)(Box_default, { paddingLeft: 2, children: /* @__PURE__ */ (0, import_jsx_runtime90.jsxs)(Text3, { color: theme.text.secondary, children: [
      timeAgo,
      " \xB7 ",
      messageText,
      session.gitBranch && ` \xB7 ${session.gitBranch}`
    ] }) })
  ] });
}
__name(SessionListItemView, "SessionListItemView");
function SessionPicker(props) {
  const {
    sessionService,
    onSelect,
    onCancel,
    currentBranch,
    centerSelection = true
  } = props;
  const { columns: width, rows: height } = useTerminalSize();
  const boxWidth = width - 4;
  const reservedLines = 6;
  const itemHeight = 3;
  const maxVisibleItems = Math.max(
    1,
    Math.floor((height - reservedLines) / itemHeight)
  );
  const picker = useSessionPicker({
    sessionService,
    currentBranch,
    onSelect,
    onCancel,
    maxVisibleItems,
    centerSelection,
    isActive: true
  });
  return /* @__PURE__ */ (0, import_jsx_runtime90.jsx)(
    Box_default,
    {
      flexDirection: "column",
      width: boxWidth,
      height: height - 1,
      overflow: "hidden",
      children: /* @__PURE__ */ (0, import_jsx_runtime90.jsxs)(
        Box_default,
        {
          flexDirection: "column",
          borderStyle: "round",
          borderColor: theme.border.default,
          width: boxWidth,
          height: height - 1,
          overflow: "hidden",
          children: [
            /* @__PURE__ */ (0, import_jsx_runtime90.jsxs)(Box_default, { paddingX: 1, children: [
              /* @__PURE__ */ (0, import_jsx_runtime90.jsx)(Text3, { bold: true, color: theme.text.primary, children: t4("Resume Session") }),
              picker.filterByBranch && currentBranch && /* @__PURE__ */ (0, import_jsx_runtime90.jsxs)(Text3, { color: theme.text.secondary, children: [
                " ",
                t4("(branch: {{branch}})", { branch: currentBranch })
              ] })
            ] }),
            /* @__PURE__ */ (0, import_jsx_runtime90.jsx)(Box_default, { children: /* @__PURE__ */ (0, import_jsx_runtime90.jsx)(Text3, { color: theme.border.default, children: "\u2500".repeat(boxWidth - 2) }) }),
            /* @__PURE__ */ (0, import_jsx_runtime90.jsx)(Box_default, { flexDirection: "column", flexGrow: 1, paddingX: 1, overflow: "hidden", children: !sessionService || picker.isLoading ? /* @__PURE__ */ (0, import_jsx_runtime90.jsx)(Box_default, { paddingY: 1, justifyContent: "center", children: /* @__PURE__ */ (0, import_jsx_runtime90.jsx)(Text3, { color: theme.text.secondary, children: t4("Loading sessions...") }) }) : picker.filteredSessions.length === 0 ? /* @__PURE__ */ (0, import_jsx_runtime90.jsx)(Box_default, { paddingY: 1, justifyContent: "center", children: /* @__PURE__ */ (0, import_jsx_runtime90.jsx)(Text3, { color: theme.text.secondary, children: picker.filterByBranch ? t4('No sessions found for branch "{{branch}}"', {
              branch: currentBranch ?? ""
            }) : t4("No sessions found") }) }) : picker.visibleSessions.map((session, visibleIndex) => {
              const actualIndex = picker.scrollOffset + visibleIndex;
              return /* @__PURE__ */ (0, import_jsx_runtime90.jsx)(
                SessionListItemView,
                {
                  session,
                  isSelected: actualIndex === picker.selectedIndex,
                  isFirst: visibleIndex === 0,
                  isLast: visibleIndex === picker.visibleSessions.length - 1,
                  showScrollUp: picker.showScrollUp,
                  showScrollDown: picker.showScrollDown,
                  maxPromptWidth: boxWidth - 6,
                  prefixChars: PREFIX_CHARS,
                  boldSelectedPrefix: false
                },
                session.sessionId
              );
            }) }),
            /* @__PURE__ */ (0, import_jsx_runtime90.jsx)(Box_default, { children: /* @__PURE__ */ (0, import_jsx_runtime90.jsx)(Text3, { color: theme.border.default, children: "\u2500".repeat(boxWidth - 2) }) }),
            /* @__PURE__ */ (0, import_jsx_runtime90.jsx)(Box_default, { paddingX: 1, children: /* @__PURE__ */ (0, import_jsx_runtime90.jsxs)(Box_default, { flexDirection: "row", children: [
              currentBranch && /* @__PURE__ */ (0, import_jsx_runtime90.jsxs)(Text3, { color: theme.text.secondary, children: [
                /* @__PURE__ */ (0, import_jsx_runtime90.jsx)(
                  Text3,
                  {
                    bold: picker.filterByBranch,
                    color: picker.filterByBranch ? theme.text.accent : void 0,
                    children: "B"
                  }
                ),
                t4(" to toggle branch"),
                " \xB7"
              ] }),
              /* @__PURE__ */ (0, import_jsx_runtime90.jsx)(Text3, { color: theme.text.secondary, children: t4("\u2191\u2193 to navigate \xB7 Esc to cancel") })
            ] }) })
          ]
        }
      )
    }
  );
}
__name(SessionPicker, "SessionPicker");

// packages/cli/src/ui/components/DialogManager.tsx
var import_jsx_runtime91 = __toESM(require_jsx_runtime(), 1);
var DialogManager = /* @__PURE__ */ __name(({
  addItem,
  terminalWidth
}) => {
  const config2 = useConfig();
  const settings = useSettings();
  const uiState = useUIState();
  const uiActions = useUIActions();
  const { constrainHeight, terminalHeight, staticExtraHeight, mainAreaWidth } = uiState;
  if (uiState.showWelcomeBackDialog && uiState.welcomeBackInfo?.hasHistory) {
    return /* @__PURE__ */ (0, import_jsx_runtime91.jsx)(
      WelcomeBackDialog,
      {
        welcomeBackInfo: uiState.welcomeBackInfo,
        onSelect: uiActions.handleWelcomeBackSelection,
        onClose: uiActions.handleWelcomeBackClose
      }
    );
  }
  if (uiState.showIdeRestartPrompt) {
    return /* @__PURE__ */ (0, import_jsx_runtime91.jsx)(IdeTrustChangeDialog, { reason: uiState.ideTrustRestartReason });
  }
  if (uiState.shouldShowIdePrompt) {
    return /* @__PURE__ */ (0, import_jsx_runtime91.jsx)(
      IdeIntegrationNudge,
      {
        ide: uiState.currentIDE,
        onComplete: uiActions.handleIdePromptComplete
      }
    );
  }
  if (uiState.shouldShowCommandMigrationNudge) {
    return /* @__PURE__ */ (0, import_jsx_runtime91.jsx)(
      CommandFormatMigrationNudge,
      {
        tomlFiles: uiState.commandMigrationTomlFiles,
        onComplete: uiActions.handleCommandMigrationComplete
      }
    );
  }
  if (uiState.isFolderTrustDialogOpen) {
    return /* @__PURE__ */ (0, import_jsx_runtime91.jsx)(
      FolderTrustDialog,
      {
        onSelect: uiActions.handleFolderTrustSelect,
        isRestarting: uiState.isRestarting
      }
    );
  }
  if (uiState.shellConfirmationRequest) {
    return /* @__PURE__ */ (0, import_jsx_runtime91.jsx)(ShellConfirmationDialog, { request: uiState.shellConfirmationRequest });
  }
  if (uiState.loopDetectionConfirmationRequest) {
    return /* @__PURE__ */ (0, import_jsx_runtime91.jsx)(
      LoopDetectionConfirmation,
      {
        onComplete: uiState.loopDetectionConfirmationRequest.onComplete
      }
    );
  }
  if (uiState.confirmationRequest) {
    return /* @__PURE__ */ (0, import_jsx_runtime91.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_runtime91.jsx)(
      ConsentPrompt,
      {
        prompt: request4.prompt,
        onConfirm: request4.onConfirm,
        terminalWidth
      }
    );
  }
  if (uiState.codingPlanUpdateRequest) {
    return /* @__PURE__ */ (0, import_jsx_runtime91.jsx)(
      ConsentPrompt,
      {
        prompt: uiState.codingPlanUpdateRequest.prompt,
        onConfirm: uiState.codingPlanUpdateRequest.onConfirm,
        terminalWidth
      }
    );
  }
  if (uiState.settingInputRequests.length > 0) {
    const request4 = uiState.settingInputRequests[0];
    return /* @__PURE__ */ (0, import_jsx_runtime91.jsx)(
      SettingInputPrompt,
      {
        settingName: request4.settingName,
        settingDescription: request4.settingDescription,
        sensitive: request4.sensitive,
        onSubmit: request4.onSubmit,
        onCancel: request4.onCancel,
        terminalWidth
      },
      request4.settingName
    );
  }
  if (uiState.pluginChoiceRequests.length > 0) {
    const request4 = uiState.pluginChoiceRequests[0];
    return /* @__PURE__ */ (0, import_jsx_runtime91.jsx)(
      PluginChoicePrompt,
      {
        marketplaceName: request4.marketplaceName,
        plugins: request4.plugins,
        onSelect: request4.onSelect,
        onCancel: request4.onCancel,
        terminalWidth
      },
      request4.marketplaceName
    );
  }
  if (uiState.isThemeDialogOpen) {
    return /* @__PURE__ */ (0, import_jsx_runtime91.jsxs)(Box_default, { flexDirection: "column", children: [
      uiState.themeError && /* @__PURE__ */ (0, import_jsx_runtime91.jsx)(Box_default, { marginBottom: 1, children: /* @__PURE__ */ (0, import_jsx_runtime91.jsx)(Text3, { color: theme.status.error, children: uiState.themeError }) }),
      /* @__PURE__ */ (0, import_jsx_runtime91.jsx)(
        ThemeDialog,
        {
          onSelect: uiActions.handleThemeSelect,
          onHighlight: uiActions.handleThemeHighlight,
          settings,
          availableTerminalHeight: constrainHeight ? terminalHeight - staticExtraHeight : void 0,
          terminalWidth: mainAreaWidth
        }
      )
    ] });
  }
  if (uiState.isEditorDialogOpen) {
    return /* @__PURE__ */ (0, import_jsx_runtime91.jsxs)(Box_default, { flexDirection: "column", children: [
      uiState.editorError && /* @__PURE__ */ (0, import_jsx_runtime91.jsx)(Box_default, { marginBottom: 1, children: /* @__PURE__ */ (0, import_jsx_runtime91.jsx)(Text3, { color: theme.status.error, children: uiState.editorError }) }),
      /* @__PURE__ */ (0, import_jsx_runtime91.jsx)(
        EditorSettingsDialog,
        {
          onSelect: uiActions.handleEditorSelect,
          settings,
          onExit: uiActions.exitEditorDialog
        }
      )
    ] });
  }
  if (uiState.isSettingsDialogOpen) {
    return /* @__PURE__ */ (0, import_jsx_runtime91.jsx)(Box_default, { flexDirection: "column", children: /* @__PURE__ */ (0, import_jsx_runtime91.jsx)(
      SettingsDialog,
      {
        settings,
        onSelect: (settingName) => {
          if (settingName === "ui.theme") {
            uiActions.openThemeDialog();
            return;
          }
          if (settingName === "general.preferredEditor") {
            uiActions.openEditorDialog();
            return;
          }
          uiActions.closeSettingsDialog();
        },
        onRestartRequest: () => process35.exit(0),
        availableTerminalHeight: terminalHeight - staticExtraHeight,
        config: config2
      }
    ) });
  }
  if (uiState.isApprovalModeDialogOpen) {
    const currentMode = config2.getApprovalMode();
    return /* @__PURE__ */ (0, import_jsx_runtime91.jsx)(Box_default, { flexDirection: "column", children: /* @__PURE__ */ (0, import_jsx_runtime91.jsx)(
      ApprovalModeDialog,
      {
        settings,
        currentMode,
        onSelect: uiActions.handleApprovalModeSelect,
        availableTerminalHeight: constrainHeight ? terminalHeight - staticExtraHeight : void 0
      }
    ) });
  }
  if (uiState.isModelDialogOpen) {
    return /* @__PURE__ */ (0, import_jsx_runtime91.jsx)(ModelDialog, { onClose: uiActions.closeModelDialog });
  }
  if (uiState.isAuthDialogOpen || uiState.authError) {
    return /* @__PURE__ */ (0, import_jsx_runtime91.jsx)(Box_default, { flexDirection: "column", children: /* @__PURE__ */ (0, import_jsx_runtime91.jsx)(AuthDialog, {}) });
  }
  if (uiState.isAuthenticating) {
    if (uiState.pendingAuthType === AuthType2.QWEN_OAUTH) {
      return /* @__PURE__ */ (0, import_jsx_runtime91.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.isPermissionsDialogOpen) {
    return /* @__PURE__ */ (0, import_jsx_runtime91.jsx)(
      PermissionsModifyTrustDialog,
      {
        onExit: uiActions.closePermissionsDialog,
        addItem
      }
    );
  }
  if (uiState.isSubagentCreateDialogOpen) {
    return /* @__PURE__ */ (0, import_jsx_runtime91.jsx)(
      AgentCreationWizard,
      {
        onClose: uiActions.closeSubagentCreateDialog,
        config: config2
      }
    );
  }
  if (uiState.isAgentsManagerDialogOpen) {
    return /* @__PURE__ */ (0, import_jsx_runtime91.jsx)(
      AgentsManagerDialog,
      {
        onClose: uiActions.closeAgentsManagerDialog,
        config: config2
      }
    );
  }
  if (uiState.isResumeDialogOpen) {
    return /* @__PURE__ */ (0, import_jsx_runtime91.jsx)(
      SessionPicker,
      {
        sessionService: config2.getSessionService(),
        currentBranch: uiState.branchName,
        onSelect: uiActions.handleResume,
        onCancel: uiActions.closeResumeDialog
      }
    );
  }
  return null;
}, "DialogManager");

// packages/cli/src/ui/components/Composer.tsx
init_esbuild_shims();
var import_react99 = __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_runtime92 = __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 */ ? t4("(esc to cancel, {{time}})", {
    time: elapsedTime < 60 ? `${elapsedTime}s` : formatDuration(elapsedTime * 1e3)
  }) : null;
  return /* @__PURE__ */ (0, import_jsx_runtime92.jsxs)(Box_default, { paddingLeft: 0, flexDirection: "column", children: [
    /* @__PURE__ */ (0, import_jsx_runtime92.jsxs)(
      Box_default,
      {
        width: "100%",
        flexDirection: isNarrow ? "column" : "row",
        alignItems: isNarrow ? "flex-start" : "center",
        children: [
          /* @__PURE__ */ (0, import_jsx_runtime92.jsxs)(Box_default, { children: [
            /* @__PURE__ */ (0, import_jsx_runtime92.jsx)(Box_default, { marginRight: 1, children: /* @__PURE__ */ (0, import_jsx_runtime92.jsx)(
              GeminiRespondingSpinner,
              {
                nonRespondingDisplay: streamingState === "waiting_for_confirmation" /* WaitingForConfirmation */ ? "\u280F" : ""
              }
            ) }),
            primaryText && /* @__PURE__ */ (0, import_jsx_runtime92.jsx)(Text3, { color: theme.text.accent, wrap: "truncate-end", children: primaryText }),
            !isNarrow && cancelAndTimerContent && /* @__PURE__ */ (0, import_jsx_runtime92.jsxs)(Text3, { color: theme.text.secondary, children: [
              " ",
              cancelAndTimerContent
            ] })
          ] }),
          !isNarrow && /* @__PURE__ */ (0, import_jsx_runtime92.jsx)(Box_default, { flexGrow: 1 }),
          !isNarrow && rightContent && /* @__PURE__ */ (0, import_jsx_runtime92.jsx)(Box_default, { children: rightContent })
        ]
      }
    ),
    isNarrow && cancelAndTimerContent && /* @__PURE__ */ (0, import_jsx_runtime92.jsx)(Box_default, { children: /* @__PURE__ */ (0, import_jsx_runtime92.jsx)(Text3, { color: theme.text.secondary, children: cancelAndTimerContent }) }),
    isNarrow && rightContent && /* @__PURE__ */ (0, import_jsx_runtime92.jsx)(Box_default, { children: rightContent })
  ] });
}, "LoadingIndicator");

// packages/cli/src/ui/components/InputPrompt.tsx
init_esbuild_shims();
var import_react97 = __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_react88 = __toESM(require_react(), 1);
var import_jsx_runtime93 = __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_runtime93.jsx)(Text3, { 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_runtime93.jsxs)(Text3, { color: textColor, wrap: "wrap", children: [
    before,
    match2 ? match2.split(/(\s+)/).map((part, index) => /* @__PURE__ */ (0, import_jsx_runtime93.jsx)(
      Text3,
      {
        color: theme.background.primary,
        backgroundColor: theme.text.primary,
        children: part
      },
      `match-${index}`
    )) : null,
    after
  ] });
}, "_PrepareLabel");
var PrepareLabel = import_react88.default.memo(_PrepareLabel);

// packages/cli/src/ui/components/SuggestionsDisplay.tsx
var import_jsx_runtime94 = __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_runtime94.jsx)(Box_default, { width, children: /* @__PURE__ */ (0, import_jsx_runtime94.jsx)(Text3, { 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((s5) => s5.label + (s5.commandKind === "mcp-prompt" /* MCP_PROMPT */ ? " [MCP]" : ""), "getFullLabel");
  const maxLabelLength = Math.max(
    ...suggestions.map((s5) => getFullLabel(s5).length)
  );
  const commandColumnWidth = mode === "slash" ? Math.min(maxLabelLength, Math.floor(width * 0.5)) : 0;
  return /* @__PURE__ */ (0, import_jsx_runtime94.jsxs)(Box_default, { flexDirection: "column", width, children: [
    scrollOffset > 0 && /* @__PURE__ */ (0, import_jsx_runtime94.jsx)(Text3, { 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 displayLabel = suggestion.label ?? suggestion.value;
      const isLong = displayLabel.length >= MAX_WIDTH;
      const labelElement = /* @__PURE__ */ (0, import_jsx_runtime94.jsx)(
        PrepareLabel,
        {
          label: displayLabel,
          matchedIndex: suggestion.matchedIndex,
          userInput,
          textColor,
          isExpanded
        }
      );
      return /* @__PURE__ */ (0, import_jsx_runtime94.jsxs)(Box_default, { flexDirection: "row", children: [
        /* @__PURE__ */ (0, import_jsx_runtime94.jsx)(
          Box_default,
          {
            ...mode === "slash" ? { width: commandColumnWidth, flexShrink: 0 } : { flexShrink: 1 },
            children: /* @__PURE__ */ (0, import_jsx_runtime94.jsxs)(Box_default, { children: [
              labelElement,
              suggestion.commandKind === "mcp-prompt" /* MCP_PROMPT */ && /* @__PURE__ */ (0, import_jsx_runtime94.jsx)(Text3, { color: textColor, children: " [MCP]" })
            ] })
          }
        ),
        suggestion.description && /* @__PURE__ */ (0, import_jsx_runtime94.jsx)(Box_default, { flexGrow: 1, paddingLeft: 2, children: /* @__PURE__ */ (0, import_jsx_runtime94.jsx)(Text3, { color: textColor, wrap: "truncate", children: suggestion.description }) }),
        isActive && isLong && /* @__PURE__ */ (0, import_jsx_runtime94.jsx)(Box_default, { children: /* @__PURE__ */ (0, import_jsx_runtime94.jsx)(Text3, { color: Colors.Gray, children: isExpanded ? " \u2190 " : " \u2192 " }) })
      ] }, `${suggestion.value}-${originalIndex}`);
    }),
    endIndex < suggestions.length && /* @__PURE__ */ (0, import_jsx_runtime94.jsx)(Text3, { color: "gray", children: "\u25BC" }),
    suggestions.length > MAX_SUGGESTIONS_TO_SHOW && /* @__PURE__ */ (0, import_jsx_runtime94.jsxs)(Text3, { color: "gray", children: [
      "(",
      activeIndex + 1,
      "/",
      suggestions.length,
      ")"
    ] })
  ] });
}
__name(SuggestionsDisplay, "SuggestionsDisplay");

// packages/cli/src/ui/hooks/useInputHistory.ts
init_esbuild_shims();
var import_react89 = __toESM(require_react(), 1);
function useInputHistory({
  userMessages,
  onSubmit,
  isActive,
  currentQuery,
  onChange
}) {
  const [historyIndex, setHistoryIndex] = (0, import_react89.useState)(-1);
  const [originalQueryBeforeNav, setOriginalQueryBeforeNav] = (0, import_react89.useState)("");
  const resetHistoryNav = (0, import_react89.useCallback)(() => {
    setHistoryIndex(-1);
    setOriginalQueryBeforeNav("");
  }, []);
  const handleSubmit = (0, import_react89.useCallback)(
    (value) => {
      const trimmedValue = value.trim();
      if (trimmedValue) {
        onSubmit(trimmedValue);
      }
      resetHistoryNav();
    },
    [onSubmit, resetHistoryNav]
  );
  const navigateUp = (0, import_react89.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_react89.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_chalk9 = __toESM(require_source(), 1);

// packages/cli/src/ui/hooks/useShellHistory.ts
init_esbuild_shims();
var import_react90 = __toESM(require_react(), 1);
import * as fs98 from "node:fs/promises";
import * as path107 from "node:path";
var MAX_HISTORY_LENGTH2 = 100;
var debugLogger106 = createDebugLogger("SHELL_HISTORY");
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 fs98.readFile(filePath, "utf-8");
    const result = [];
    let cur = "";
    for (const raw2 of text.split(/\r?\n/)) {
      if (!raw2.trim()) continue;
      const line = raw2;
      const m3 = cur.match(/(\\+)$/);
      if (m3 && m3[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 [];
    debugLogger106.error("Error reading history:", err);
    return [];
  }
}
__name(readHistoryFile, "readHistoryFile");
async function writeHistoryFile(filePath, history) {
  try {
    await fs98.mkdir(path107.dirname(filePath), { recursive: true });
    await fs98.writeFile(filePath, history.join("\n"));
  } catch (error2) {
    debugLogger106.error("Error writing shell history:", error2);
  }
}
__name(writeHistoryFile, "writeHistoryFile");
function useShellHistory(projectRoot, storage) {
  const [history, setHistory] = (0, import_react90.useState)([]);
  const [historyIndex, setHistoryIndex] = (0, import_react90.useState)(-1);
  const [historyFilePath, setHistoryFilePath] = (0, import_react90.useState)(null);
  (0, import_react90.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_react90.useCallback)(
    (command2) => {
      if (!command2.trim() || !historyFilePath) {
        return;
      }
      const newHistory = [command2, ...history.filter((c4) => c4 !== command2)].slice(0, MAX_HISTORY_LENGTH2).filter(Boolean);
      setHistory(newHistory);
      writeHistoryFile(historyFilePath, [...newHistory].reverse());
      setHistoryIndex(-1);
    },
    [history, historyFilePath]
  );
  const getPreviousCommand = (0, import_react90.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_react90.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_react90.useCallback)(() => {
    setHistoryIndex(-1);
  }, []);
  return {
    history,
    addCommandToHistory,
    getPreviousCommand,
    getNextCommand,
    resetHistoryPosition
  };
}
__name(useShellHistory, "useShellHistory");

// packages/cli/src/ui/hooks/useReverseSearchCompletion.tsx
init_esbuild_shims();
var import_react92 = __toESM(require_react(), 1);

// packages/cli/src/ui/hooks/useCompletion.ts
init_esbuild_shims();
var import_react91 = __toESM(require_react(), 1);
function useCompletion() {
  const [suggestions, setSuggestions] = (0, import_react91.useState)([]);
  const [activeSuggestionIndex, setActiveSuggestionIndex] = (0, import_react91.useState)(-1);
  const [visibleStartIndex, setVisibleStartIndex] = (0, import_react91.useState)(0);
  const [showSuggestions, setShowSuggestions] = (0, import_react91.useState)(false);
  const [isLoadingSuggestions, setIsLoadingSuggestions] = (0, import_react91.useState)(false);
  const [isPerfectMatch, setIsPerfectMatch] = (0, import_react91.useState)(false);
  const resetCompletionState = (0, import_react91.useCallback)(() => {
    setSuggestions([]);
    setActiveSuggestionIndex(-1);
    setVisibleStartIndex(0);
    setShowSuggestions(false);
    setIsLoadingSuggestions(false);
    setIsPerfectMatch(false);
  }, []);
  const navigateUp = (0, import_react91.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_react91.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_react92.useState)(value);
  (0, import_react92.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_react92.useRef)("");
  const prevMatchesRef = (0, import_react92.useRef)([]);
  (0, import_react92.useEffect)(() => {
    if (reverseSearchActive) {
      prevQueryRef.current = "";
      prevMatchesRef.current = [];
    }
  }, [reverseSearchActive]);
  (0, import_react92.useEffect)(() => {
    prevQueryRef.current = "";
    prevMatchesRef.current = [];
  }, [history]);
  const searchHistory = (0, import_react92.useCallback)(
    (query, items) => {
      const out = [];
      for (let i3 = 0; i3 < items.length; i3++) {
        const cmd = items[i3];
        const idx = cmd.toLowerCase().indexOf(query);
        if (idx !== -1) {
          out.push({ label: cmd, value: cmd, matchedIndex: idx });
        }
      }
      return out;
    },
    []
  );
  const matches = (0, import_react92.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((m3) => m3.value) : history;
    return searchHistory(query, source2);
  }, [debouncedQuery, history, reverseSearchActive, searchHistory]);
  (0, import_react92.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_react92.useCallback)(
    (i3) => {
      if (i3 < 0 || i3 >= suggestions.length) return;
      buffer.setText(suggestions[i3].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_react95 = __toESM(require_react(), 1);

// packages/cli/src/ui/hooks/useAtCompletion.ts
init_esbuild_shims();
var import_react93 = __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: config2,
    cwd: cwd7,
    setSuggestions,
    setIsLoadingSuggestions
  } = props;
  const [state, dispatch] = (0, import_react93.useReducer)(atCompletionReducer, initialState);
  const fileSearch = (0, import_react93.useRef)(null);
  const searchAbortController = (0, import_react93.useRef)(null);
  const slowSearchTimer = (0, import_react93.useRef)(null);
  (0, import_react93.useEffect)(() => {
    setSuggestions(state.suggestions);
  }, [state.suggestions, setSuggestions]);
  (0, import_react93.useEffect)(() => {
    setIsLoadingSuggestions(state.isLoading);
  }, [state.isLoading, setIsLoadingSuggestions]);
  (0, import_react93.useEffect)(() => {
    dispatch({ type: "RESET" });
  }, [cwd7, config2]);
  (0, import_react93.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_react93.useEffect)(() => {
    const initialize = /* @__PURE__ */ __name(async () => {
      try {
        const searcher = FileSearchFactory.create({
          projectRoot: cwd7,
          ignoreDirs: [],
          useGitignore: config2?.getFileFilteringOptions()?.respectGitIgnore ?? true,
          useQwenignore: config2?.getFileFilteringOptions()?.respectQwenIgnore ?? true,
          cache: true,
          cacheTtl: 30,
          // 30 seconds
          enableRecursiveFileSearch: config2?.getEnableRecursiveFileSearch() ?? true,
          // Use enableFuzzySearch with !== false to default to true when undefined.
          enableFuzzySearch: config2?.getFileFilteringEnableFuzzySearch() !== false
        });
        await searcher.initialize();
        fileSearch.current = searcher;
        dispatch({ type: "INITIALIZE_SUCCESS" });
        if (state.pattern !== null) {
          dispatch({ type: "SEARCH", payload: state.pattern });
        }
      } catch (_2) {
        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((p2) => ({
          label: p2,
          value: escapePath(p2)
        }));
        dispatch({ type: "SEARCH_SUCCESS", payload: suggestions });
      } catch (error2) {
        if (!(error2 instanceof Error && error2.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, config2, cwd7]);
}
__name(useAtCompletion, "useAtCompletion");

// packages/cli/src/ui/hooks/useSlashCompletion.ts
init_esbuild_shims();
var import_react94 = __toESM(require_react(), 1);
init_fzf_es();
var debugLogger107 = createDebugLogger("SLASH_COMPLETION");
function logErrorSafely(error2, context2) {
  if (error2 instanceof Error) {
    debugLogger107.error(`[${context2}]`, error2);
  } else {
    debugLogger107.error(`[${context2}] Non-error thrown:`, error2);
  }
}
__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_react94.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((p2) => p2);
    let commandPathParts = rawParts;
    let partial2 = "";
    if (!hasTrailingSpace && rawParts.length > 0) {
      partial2 = 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, partial2) && cmd.subCommands
      );
      if (exactMatchAsParent) {
        leafCommand = exactMatchAsParent;
        currentLevel = exactMatchAsParent.subCommands;
        partial2 = "";
      }
    }
    const depth = commandPathParts.length;
    const isArgumentCompletion = !!(leafCommand?.completion && (hasTrailingSpace || rawParts.length > depth && depth > 0 && partial2 !== ""));
    return {
      hasTrailingSpace,
      commandPathParts,
      partial: partial2,
      currentLevel,
      leafCommand,
      exactMatchAsParent,
      isArgumentCompletion
    };
  }, [query, slashCommands]);
}
__name(useCommandParser, "useCommandParser");
function useCommandSuggestions(parserResult, commandContext, getFzfForCommands, getPrefixSuggestions) {
  const [suggestions, setSuggestions] = (0, import_react94.useState)([]);
  const [isLoading, setIsLoading] = (0, import_react94.useState)(false);
  (0, import_react94.useEffect)(() => {
    const abortController = new AbortController();
    const { signal } = abortController;
    const {
      isArgumentCompletion,
      leafCommand,
      commandPathParts,
      partial: partial2,
      currentLevel
    } = parserResult;
    if (isArgumentCompletion) {
      const fetchAndSetSuggestions = /* @__PURE__ */ __name(async () => {
        if (signal.aborted) return;
        if (!leafCommand?.completion) {
          debugLogger107.warn(
            "Attempted argument completion without completion function"
          );
          return;
        }
        setIsLoading(true);
        try {
          const rawParts = [...commandPathParts];
          if (partial2) rawParts.push(partial2);
          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((item) => toSuggestion(item)).filter((suggestion) => !!suggestion);
            setSuggestions(finalSuggestions);
            setIsLoading(false);
          }
        } catch (error2) {
          if (!signal.aborted) {
            logErrorSafely(error2, "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 (partial2 === "") {
          potentialSuggestions = commandsToSearch.filter(
            (cmd) => cmd.description && !cmd.hidden
          );
        } else {
          const fzfInstance = getFzfForCommands(commandsToSearch);
          if (fzfInstance) {
            try {
              const fzfResults = await fzfInstance.fzf.find(partial2);
              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 (error2) {
              logErrorSafely(
                error2,
                "Fuzzy search - falling back to prefix matching"
              );
              potentialSuggestions = getPrefixSuggestions(
                commandsToSearch,
                partial2
              );
            }
          } else {
            potentialSuggestions = getPrefixSuggestions(
              commandsToSearch,
              partial2
            );
          }
        }
        if (!signal.aborted) {
          const finalSuggestions = potentialSuggestions.map((cmd) => ({
            label: formatSlashCommandLabel(cmd),
            value: cmd.name,
            description: cmd.description,
            commandKind: cmd.kind
          }));
          setSuggestions(finalSuggestions);
        }
      }, "performFuzzySearch");
      performFuzzySearch().catch((error2) => {
        logErrorSafely(error2, "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 toSuggestion(item) {
  if (typeof item === "string") {
    return { label: item, value: item };
  }
  if (!item.value) {
    return null;
  }
  return {
    label: item.label ?? item.value,
    value: item.value,
    description: item.description
  };
}
__name(toSuggestion, "toSuggestion");
function useCompletionPositions(query, parserResult) {
  return (0, import_react94.useMemo)(() => {
    if (!query) {
      return { start: -1, end: -1 };
    }
    const { hasTrailingSpace, partial: partial2, exactMatchAsParent } = parserResult;
    if (hasTrailingSpace || exactMatchAsParent) {
      return { start: query.length, end: query.length };
    } else if (partial2) {
      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 - partial2.length, end: query.length };
      }
    } else {
      return { start: 1, end: query.length };
    }
  }, [query, parserResult]);
}
__name(useCompletionPositions, "useCompletionPositions");
function usePerfectMatch(parserResult) {
  return (0, import_react94.useMemo)(() => {
    const { hasTrailingSpace, partial: partial2, leafCommand, currentLevel } = parserResult;
    if (hasTrailingSpace) {
      return { isPerfectMatch: false };
    }
    if (leafCommand && partial2 === "" && leafCommand.action) {
      return { isPerfectMatch: true };
    }
    if (currentLevel) {
      const perfectMatch = currentLevel.find(
        (cmd) => matchesCommand(cmd, partial2) && 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_react94.useState)(-1);
  const [completionEnd, setCompletionEnd] = (0, import_react94.useState)(-1);
  const fzfInstanceCache = (0, import_react94.useMemo)(
    () => /* @__PURE__ */ new WeakMap(),
    []
  );
  const getFzfForCommands = (0, import_react94.useMemo)(
    () => (commands) => {
      if (!commands || commands.length === 0) {
        return null;
      }
      const cached2 = fzfInstanceCache.get(commands);
      if (cached2) {
        return cached2;
      }
      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 (error2) {
        logErrorSafely(error2, "FZF instance creation");
        return null;
      }
    },
    [fzfInstanceCache]
  );
  const getPrefixSuggestions = (0, import_react94.useMemo)(
    () => (commands, partial2) => commands.filter(
      (cmd) => cmd.description && !cmd.hidden && (cmd.name.toLowerCase().startsWith(partial2.toLowerCase()) || cmd.altNames?.some(
        (alt) => alt.toLowerCase().startsWith(partial2.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_react94.useEffect)(() => {
    if (!enabled) {
      setSuggestions([]);
      setIsLoadingSuggestions(false);
      setIsPerfectMatch(false);
      setCompletionStart(-1);
      setCompletionEnd(-1);
    }
  }, [enabled, setSuggestions, setIsLoadingSuggestions, setIsPerfectMatch]);
  (0, import_react94.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");
function formatSlashCommandLabel(command2) {
  const baseLabel = command2.name;
  const altNames = command2.altNames?.filter(Boolean);
  if (!altNames || altNames.length === 0) {
    return baseLabel;
  }
  return `${baseLabel} (${altNames.join(", ")})`;
}
__name(formatSlashCommandLabel, "formatSlashCommandLabel");

// packages/cli/src/ui/hooks/useCommandCompletion.tsx
function useCommandCompletion(buffer, dirs, cwd7, slashCommands, commandContext, reverseSearchActive = false, config2, active = true) {
  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_react95.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 i3 = cursorCol - 1; i3 >= 0; i3--) {
      const char = codePoints[i3];
      if (char === " ") {
        let backslashCount = 0;
        for (let j2 = i3 - 1; j2 >= 0 && codePoints[j2] === "\\"; j2--) {
          backslashCount++;
        }
        if (backslashCount % 2 === 0) {
          break;
        }
      } else if (char === "@") {
        let end = codePoints.length;
        for (let i4 = cursorCol; i4 < codePoints.length; i4++) {
          if (codePoints[i4] === " ") {
            let backslashCount = 0;
            for (let j2 = i4 - 1; j2 >= 0 && codePoints[j2] === "\\"; j2--) {
              backslashCount++;
            }
            if (backslashCount % 2 === 0) {
              end = i4;
              break;
            }
          }
        }
        const pathStart = i3 + 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: config2,
    cwd: cwd7,
    setSuggestions,
    setIsLoadingSuggestions
  });
  const slashCompletionRange = useSlashCompletion({
    enabled: completionMode === "SLASH" /* SLASH */,
    query,
    slashCommands,
    commandContext,
    setSuggestions,
    setIsLoadingSuggestions,
    setIsPerfectMatch
  });
  (0, import_react95.useEffect)(() => {
    setActiveSuggestionIndex(suggestions.length > 0 ? 0 : -1);
    setVisibleStartIndex(0);
  }, [suggestions, setActiveSuggestionIndex, setVisibleStartIndex]);
  (0, import_react95.useEffect)(() => {
    if (completionMode === "IDLE" /* IDLE */ || reverseSearchActive || !active) {
      resetCompletionState();
      return;
    }
    setShowSuggestions(isLoadingSuggestions || suggestions.length > 0);
  }, [
    completionMode,
    suggestions.length,
    isLoadingSuggestions,
    reverseSearchActive,
    active,
    resetCompletionState,
    setShowSuggestions
  ]);
  const handleAutocomplete = (0, import_react95.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/components/InputPrompt.tsx
import * as path108 from "node:path";

// packages/cli/src/ui/contexts/ShellFocusContext.tsx
init_esbuild_shims();
var import_react96 = __toESM(require_react(), 1);
var ShellFocusContext = (0, import_react96.createContext)(true);
var useShellFocusState = /* @__PURE__ */ __name(() => (0, import_react96.useContext)(ShellFocusContext), "useShellFocusState");

// packages/cli/src/ui/FeedbackDialog.tsx
init_esbuild_shims();
var import_jsx_runtime95 = __toESM(require_jsx_runtime(), 1);
var FEEDBACK_OPTIONS = {
  GOOD: 1,
  BAD: 2,
  FINE: 3,
  DISMISS: 0
};
var FEEDBACK_OPTION_KEYS = {
  [FEEDBACK_OPTIONS.GOOD]: "1",
  [FEEDBACK_OPTIONS.BAD]: "2",
  [FEEDBACK_OPTIONS.FINE]: "3",
  [FEEDBACK_OPTIONS.DISMISS]: "0"
};
var FEEDBACK_DIALOG_KEYS = ["1", "2", "3", "0"];
var FeedbackDialog = /* @__PURE__ */ __name(() => {
  const uiState = useUIState();
  const uiActions = useUIActions();
  useKeypress(
    (key) => {
      if (key.name === FEEDBACK_OPTION_KEYS[FEEDBACK_OPTIONS.BAD]) {
        uiActions.submitFeedback(FEEDBACK_OPTIONS.BAD);
      } else if (key.name === FEEDBACK_OPTION_KEYS[FEEDBACK_OPTIONS.FINE]) {
        uiActions.submitFeedback(FEEDBACK_OPTIONS.FINE);
      } else if (key.name === FEEDBACK_OPTION_KEYS[FEEDBACK_OPTIONS.GOOD]) {
        uiActions.submitFeedback(FEEDBACK_OPTIONS.GOOD);
      } else if (key.name === FEEDBACK_OPTION_KEYS[FEEDBACK_OPTIONS.DISMISS]) {
        uiActions.submitFeedback(FEEDBACK_OPTIONS.DISMISS);
      } else {
        uiActions.temporaryCloseFeedbackDialog();
      }
    },
    { isActive: uiState.isFeedbackDialogOpen }
  );
  return /* @__PURE__ */ (0, import_jsx_runtime95.jsxs)(Box_default, { flexDirection: "column", marginY: 1, children: [
    /* @__PURE__ */ (0, import_jsx_runtime95.jsxs)(Box_default, { children: [
      /* @__PURE__ */ (0, import_jsx_runtime95.jsx)(Text3, { color: "cyan", children: "\u25CF " }),
      /* @__PURE__ */ (0, import_jsx_runtime95.jsx)(Text3, { bold: true, children: t4("How is Qwen doing this session? (optional)") })
    ] }),
    /* @__PURE__ */ (0, import_jsx_runtime95.jsxs)(Box_default, { marginTop: 1, children: [
      /* @__PURE__ */ (0, import_jsx_runtime95.jsxs)(Text3, { color: "cyan", children: [
        FEEDBACK_OPTION_KEYS[FEEDBACK_OPTIONS.GOOD],
        ":",
        " "
      ] }),
      /* @__PURE__ */ (0, import_jsx_runtime95.jsx)(Text3, { children: t4("Good") }),
      /* @__PURE__ */ (0, import_jsx_runtime95.jsx)(Text3, { children: " " }),
      /* @__PURE__ */ (0, import_jsx_runtime95.jsxs)(Text3, { color: "cyan", children: [
        FEEDBACK_OPTION_KEYS[FEEDBACK_OPTIONS.BAD],
        ": "
      ] }),
      /* @__PURE__ */ (0, import_jsx_runtime95.jsx)(Text3, { children: t4("Bad") }),
      /* @__PURE__ */ (0, import_jsx_runtime95.jsx)(Text3, { children: " " }),
      /* @__PURE__ */ (0, import_jsx_runtime95.jsxs)(Text3, { color: "cyan", children: [
        FEEDBACK_OPTION_KEYS[FEEDBACK_OPTIONS.FINE],
        ":",
        " "
      ] }),
      /* @__PURE__ */ (0, import_jsx_runtime95.jsx)(Text3, { children: t4("Fine") }),
      /* @__PURE__ */ (0, import_jsx_runtime95.jsx)(Text3, { children: " " }),
      /* @__PURE__ */ (0, import_jsx_runtime95.jsxs)(Text3, { color: "cyan", children: [
        FEEDBACK_OPTION_KEYS[FEEDBACK_OPTIONS.DISMISS],
        ":",
        " "
      ] }),
      /* @__PURE__ */ (0, import_jsx_runtime95.jsx)(Text3, { children: t4("Dismiss") }),
      /* @__PURE__ */ (0, import_jsx_runtime95.jsx)(Text3, { children: " " })
    ] })
  ] });
}, "FeedbackDialog");

// packages/cli/src/ui/components/InputPrompt.tsx
var import_jsx_runtime96 = __toESM(require_jsx_runtime(), 1);
var debugLogger108 = createDebugLogger("INPUT_PROMPT");
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 LARGE_PASTE_CHAR_THRESHOLD = 1e3;
var LARGE_PASTE_LINE_THRESHOLD = 10;
var InputPrompt = /* @__PURE__ */ __name(({
  buffer,
  onSubmit,
  userMessages,
  onClearScreen,
  config: config2,
  slashCommands,
  commandContext,
  placeholder,
  focus = true,
  suggestionsWidth,
  shellModeActive,
  setShellModeActive,
  approvalMode,
  onEscapePromptChange,
  onToggleShortcuts,
  showShortcuts,
  onSuggestionsVisibilityChange,
  vimHandleInput,
  isEmbeddedShellFocused
}) => {
  const isShellFocused = useShellFocusState();
  const uiState = useUIState();
  const uiActions = useUIActions();
  const { pasteWorkaround } = useKeypressContext();
  const [justNavigatedHistory, setJustNavigatedHistory] = (0, import_react97.useState)(false);
  const [escPressCount, setEscPressCount] = (0, import_react97.useState)(0);
  const [showEscapePrompt, setShowEscapePrompt] = (0, import_react97.useState)(false);
  const escapeTimerRef = (0, import_react97.useRef)(null);
  const [recentPasteTime, setRecentPasteTime] = (0, import_react97.useState)(null);
  const pasteTimeoutRef = (0, import_react97.useRef)(null);
  const [attachments, setAttachments] = (0, import_react97.useState)([]);
  const [isAttachmentMode, setIsAttachmentMode] = (0, import_react97.useState)(false);
  const [selectedAttachmentIndex, setSelectedAttachmentIndex] = (0, import_react97.useState)(-1);
  const [pendingPastes, setPendingPastes] = (0, import_react97.useState)(
    /* @__PURE__ */ new Map()
  );
  const activePlaceholderIds = (0, import_react97.useRef)(/* @__PURE__ */ new Map());
  const parsePlaceholder = (0, import_react97.useCallback)(
    (placeholder2) => {
      const match2 = placeholder2.match(
        /^\[Pasted Content (\d+) chars\](?: #(\d+))?$/
      );
      if (!match2) return null;
      const charCount = parseInt(match2[1], 10);
      const id = match2[2] ? parseInt(match2[2], 10) : 1;
      return { charCount, id };
    },
    []
  );
  const freePlaceholderId = (0, import_react97.useCallback)((charCount, id) => {
    const activeIds = activePlaceholderIds.current.get(charCount);
    if (activeIds) {
      activeIds.delete(id);
      if (activeIds.size === 0) {
        activePlaceholderIds.current.delete(charCount);
      }
    }
  }, []);
  const [dirs, setDirs] = (0, import_react97.useState)(
    config2.getWorkspaceContext().getDirectories()
  );
  const dirsChanged = config2.getWorkspaceContext().getDirectories();
  (0, import_react97.useEffect)(() => {
    if (dirs.length !== dirsChanged.length) {
      setDirs(dirsChanged);
    }
  }, [dirs.length, dirsChanged]);
  const [reverseSearchActive, setReverseSearchActive] = (0, import_react97.useState)(false);
  const [commandSearchActive, setCommandSearchActive] = (0, import_react97.useState)(false);
  const [textBeforeReverseSearch, setTextBeforeReverseSearch] = (0, import_react97.useState)("");
  const [cursorPosition, setCursorPosition] = (0, import_react97.useState)([
    0,
    0
  ]);
  const [expandedSuggestionIndex, setExpandedSuggestionIndex] = (0, import_react97.useState)(-1);
  const shellHistory = useShellHistory(config2.getProjectRoot());
  const shellHistoryData = shellHistory.history;
  const completion3 = useCommandCompletion(
    buffer,
    dirs,
    config2.getTargetDir(),
    slashCommands,
    commandContext,
    reverseSearchActive,
    config2,
    // Suppress completion when history navigation just occurred
    !justNavigatedHistory
  );
  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_react97.useCallback)(() => {
    if (escapeTimerRef.current) {
      clearTimeout(escapeTimerRef.current);
      escapeTimerRef.current = null;
    }
    setEscPressCount(0);
    setShowEscapePrompt(false);
  }, []);
  (0, import_react97.useEffect)(() => {
    if (onEscapePromptChange) {
      onEscapePromptChange(showEscapePrompt);
    }
  }, [showEscapePrompt, onEscapePromptChange]);
  const nextLargePastePlaceholder = (0, import_react97.useCallback)((charCount) => {
    const activeIds = activePlaceholderIds.current.get(charCount) || /* @__PURE__ */ new Set();
    let id = 1;
    while (activeIds.has(id)) {
      id++;
    }
    activeIds.add(id);
    activePlaceholderIds.current.set(charCount, activeIds);
    const base = `[Pasted Content ${charCount} chars]`;
    return id === 1 ? base : `${base} #${id}`;
  }, []);
  (0, import_react97.useEffect)(
    () => () => {
      if (escapeTimerRef.current) {
        clearTimeout(escapeTimerRef.current);
      }
      if (pasteTimeoutRef.current) {
        clearTimeout(pasteTimeoutRef.current);
      }
    },
    []
  );
  const handleSubmitAndClear = (0, import_react97.useCallback)(
    (submittedValue) => {
      let finalValue = submittedValue;
      if (pendingPastes.size > 0) {
        const placeholders = Array.from(pendingPastes.keys()).sort(
          (a2, b2) => b2.length - a2.length
        );
        const escapedPlaceholders = placeholders.map(
          (placeholderValue) => placeholderValue.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")
        );
        const placeholderRegex = new RegExp(escapedPlaceholders.join("|"), "g");
        finalValue = finalValue.replace(
          placeholderRegex,
          (matchedPlaceholder) => pendingPastes.get(matchedPlaceholder) ?? matchedPlaceholder
        );
        setPendingPastes(/* @__PURE__ */ new Map());
        activePlaceholderIds.current.clear();
      }
      if (shellModeActive) {
        shellHistory.addCommandToHistory(finalValue);
      }
      if (attachments.length > 0) {
        const attachmentRefs = attachments.map((att) => `@${path108.relative(config2.getTargetDir(), att.path)}`).join(" ");
        finalValue = `${attachmentRefs}

${finalValue.trim()}`;
      }
      buffer.setText("");
      onSubmit(finalValue);
      setAttachments([]);
      setIsAttachmentMode(false);
      setSelectedAttachmentIndex(-1);
      resetCompletionState();
      resetReverseSearchCompletionState();
    },
    [
      onSubmit,
      buffer,
      resetCompletionState,
      shellModeActive,
      shellHistory,
      resetReverseSearchCompletionState,
      attachments,
      config2,
      pendingPastes
    ]
  );
  const customSetTextAndResetCompletionSignal = (0, import_react97.useCallback)(
    (newText) => {
      buffer.setText(newText);
      setJustNavigatedHistory(true);
    },
    [buffer, setJustNavigatedHistory]
  );
  const inputHistory = useInputHistory({
    userMessages,
    onSubmit: handleSubmitAndClear,
    // History navigation (Ctrl+P/N) now always works since completion navigation
    // only uses arrow keys. Only disable in shell mode.
    isActive: !shellModeActive,
    currentQuery: buffer.text,
    onChange: customSetTextAndResetCompletionSignal
  });
  (0, import_react97.useEffect)(() => {
    if (justNavigatedHistory) {
      resetCompletionState();
      resetReverseSearchCompletionState();
      resetCommandSearchCompletionState();
      setExpandedSuggestionIndex(-1);
      setJustNavigatedHistory(false);
    }
  }, [
    justNavigatedHistory,
    buffer.text,
    resetCompletionState,
    setJustNavigatedHistory,
    resetReverseSearchCompletionState,
    resetCommandSearchCompletionState
  ]);
  const handleClipboardImage = (0, import_react97.useCallback)(async (validated = false) => {
    try {
      const hasImage = validated || await clipboardHasImage();
      if (hasImage) {
        const imagePath = await saveClipboardImage(Storage.getGlobalTempDir());
        if (imagePath) {
          cleanupOldClipboardImages(Storage.getGlobalTempDir()).catch(() => {
          });
          const filename = path108.basename(imagePath);
          const newAttachment = {
            id: String(Date.now()),
            path: imagePath,
            filename
          };
          setAttachments((prev) => [...prev, newAttachment]);
        }
      }
    } catch (error2) {
      debugLogger108.error("Error handling clipboard image:", error2);
    }
  }, []);
  const handleAttachmentDelete = (0, import_react97.useCallback)((index) => {
    setAttachments((prev) => {
      const newList = prev.filter((_2, i3) => i3 !== index);
      if (newList.length === 0) {
        setIsAttachmentMode(false);
        setSelectedAttachmentIndex(-1);
      } else {
        setSelectedAttachmentIndex(Math.min(index, newList.length - 1));
      }
      return newList;
    });
  }, []);
  const handleInput = (0, import_react97.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);
        const pasted = key.sequence.replace(/\r\n/g, "\n").replace(/\r/g, "\n");
        const charCount = [...pasted].length;
        const lineCount = pasted.split("\n").length;
        if (key.pasteImage) {
          handleClipboardImage(true);
        } else if (charCount > LARGE_PASTE_CHAR_THRESHOLD || lineCount > LARGE_PASTE_LINE_THRESHOLD) {
          const placeholder2 = nextLargePastePlaceholder(charCount);
          setPendingPastes((prev) => {
            const next = new Map(prev);
            next.set(placeholder2, pasted);
            return next;
          });
          buffer.insert(placeholder2, { paste: false });
        } else {
          buffer.handleInput(key);
        }
        return;
      }
      if (vimHandleInput && vimHandleInput(key)) {
        return;
      }
      if (uiState.isFeedbackDialogOpen) {
        if (FEEDBACK_DIALOG_KEYS.includes(key.name)) {
          return;
        } else {
          uiActions.temporaryCloseFeedbackDialog();
        }
      }
      if (key.name !== "escape") {
        if (escPressCount > 0 || showEscapePrompt) {
          resetEscapeState();
        }
      }
      if (key.sequence === "!" && buffer.text === "" && !completion3.showSuggestions) {
        if (showShortcuts && onToggleShortcuts) {
          onToggleShortcuts();
        }
        setShellModeActive(!shellModeActive);
        buffer.setText("");
        return;
      }
      if (key.sequence === "?" && buffer.text === "" && !completion3.showSuggestions && onToggleShortcuts) {
        onToggleShortcuts();
        return;
      }
      if (showShortcuts && onToggleShortcuts) {
        onToggleShortcuts();
      }
      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 (isAttachmentMode && attachments.length > 0) {
        if (key.name === "left") {
          setSelectedAttachmentIndex((i3) => Math.max(0, i3 - 1));
          return;
        }
        if (key.name === "right") {
          setSelectedAttachmentIndex(
            (i3) => Math.min(attachments.length - 1, i3 + 1)
          );
          return;
        }
        if (keyMatchers["navigationDown" /* NAVIGATION_DOWN */](key)) {
          setIsAttachmentMode(false);
          setSelectedAttachmentIndex(-1);
          return;
        }
        if (key.name === "backspace" || key.name === "delete") {
          handleAttachmentDelete(selectedAttachmentIndex);
          return;
        }
        if (key.name === "return" || key.name === "escape") {
          setIsAttachmentMode(false);
          setSelectedAttachmentIndex(-1);
          return;
        }
        setIsAttachmentMode(false);
        setSelectedAttachmentIndex(-1);
      }
      if (!isAttachmentMode && attachments.length > 0 && !shellModeActive && !reverseSearchActive && !commandSearchActive && buffer.visualCursor[0] === 0 && buffer.visualScrollRow === 0 && keyMatchers["navigationUp" /* NAVIGATION_UP */](key)) {
        setIsAttachmentMode(true);
        setSelectedAttachmentIndex(attachments.length - 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 (pasteWorkaround && 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;
      }
      if (key.name === "backspace" || key.sequence === "\x7F" || key.ctrl && key.name === "h") {
        const text = buffer.text;
        const [row, col] = buffer.cursor;
        let offset = 0;
        for (let i3 = 0; i3 < row; i3++) {
          offset += buffer.lines[i3].length + 1;
        }
        offset += col;
        let placeholderDeleted = false;
        for (const placeholder2 of pendingPastes.keys()) {
          const placeholderStart = offset - placeholder2.length;
          if (placeholderStart >= 0 && text.slice(placeholderStart, offset) === placeholder2) {
            buffer.replaceRangeByOffset(placeholderStart, offset, "");
            setPendingPastes((prev) => {
              const next = new Map(prev);
              next.delete(placeholder2);
              return next;
            });
            const parsed = parsePlaceholder(placeholder2);
            if (parsed) {
              freePlaceholderId(parsed.charCount, parsed.id);
            }
            placeholderDeleted = true;
            break;
          }
        }
        if (!placeholderDeleted) {
          buffer.backspace();
        }
        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,
      onToggleShortcuts,
      showShortcuts,
      uiState,
      isAttachmentMode,
      attachments,
      selectedAttachmentIndex,
      handleAttachmentDelete,
      uiActions,
      pasteWorkaround,
      nextLargePastePlaceholder,
      pendingPastes,
      parsePlaceholder,
      freePlaceholderId
    ]
  );
  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;
  (0, import_react97.useEffect)(() => {
    if (onSuggestionsVisibilityChange) {
      onSuggestionsVisibilityChange(shouldShowSuggestions);
    }
  }, [shouldShowSuggestions, onSuggestionsVisibilityChange]);
  const showAutoAcceptStyling = !shellModeActive && approvalMode === ApprovalMode.AUTO_EDIT;
  const showYoloStyling = !shellModeActive && approvalMode === ApprovalMode.YOLO;
  let statusColor;
  let statusText = "";
  if (shellModeActive) {
    statusColor = theme.ui.symbol;
    statusText = t4("Shell mode");
  } else if (showYoloStyling) {
    statusColor = theme.status.errorDim;
    statusText = t4("YOLO mode");
  } else if (showAutoAcceptStyling) {
    statusColor = theme.status.warningDim;
    statusText = t4("Accepting edits");
  }
  const borderColor = isShellFocused && !isEmbeddedShellFocused ? statusColor ?? theme.border.focused : theme.border.default;
  return /* @__PURE__ */ (0, import_jsx_runtime96.jsxs)(import_jsx_runtime96.Fragment, { children: [
    attachments.length > 0 && /* @__PURE__ */ (0, import_jsx_runtime96.jsxs)(Box_default, { marginLeft: 2, marginBottom: 0, children: [
      /* @__PURE__ */ (0, import_jsx_runtime96.jsx)(Text3, { color: theme.text.secondary, children: t4("Attachments: ") }),
      attachments.map((att, idx) => /* @__PURE__ */ (0, import_jsx_runtime96.jsxs)(
        Text3,
        {
          color: isAttachmentMode && idx === selectedAttachmentIndex ? theme.status.success : theme.text.secondary,
          children: [
            "[",
            att.filename,
            "]",
            idx < attachments.length - 1 ? " " : ""
          ]
        },
        att.id
      ))
    ] }),
    /* @__PURE__ */ (0, import_jsx_runtime96.jsxs)(
      Box_default,
      {
        borderStyle: "single",
        borderTop: true,
        borderBottom: true,
        borderLeft: false,
        borderRight: false,
        borderColor,
        children: [
          /* @__PURE__ */ (0, import_jsx_runtime96.jsxs)(
            Text3,
            {
              color: statusColor ?? theme.text.accent,
              "aria-label": statusText || void 0,
              children: [
                shellModeActive ? reverseSearchActive ? /* @__PURE__ */ (0, import_jsx_runtime96.jsxs)(
                  Text3,
                  {
                    color: theme.text.link,
                    "aria-label": SCREEN_READER_USER_PREFIX,
                    children: [
                      "(r:)",
                      " "
                    ]
                  }
                ) : "!" : commandSearchActive ? /* @__PURE__ */ (0, import_jsx_runtime96.jsx)(Text3, { color: theme.text.accent, children: "(r:) " }) : showYoloStyling ? "*" : ">",
                " "
              ]
            }
          ),
          /* @__PURE__ */ (0, import_jsx_runtime96.jsx)(Box_default, { flexGrow: 1, flexDirection: "column", children: buffer.text.length === 0 && placeholder ? showCursor ? /* @__PURE__ */ (0, import_jsx_runtime96.jsxs)(Text3, { children: [
            import_chalk9.default.inverse(placeholder.slice(0, 1)),
            /* @__PURE__ */ (0, import_jsx_runtime96.jsx)(Text3, { color: theme.text.secondary, children: placeholder.slice(1) })
          ] }) : /* @__PURE__ */ (0, import_jsx_runtime96.jsx)(Text3, { 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_chalk9.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_runtime96.jsx)(Text3, { color, children: display }, `token-${segIdx}`)
              );
            });
            if (isOnCursorLine && cursorVisualColAbsolute === cpLen(lineText)) {
              renderedLine.push(
                /* @__PURE__ */ (0, import_jsx_runtime96.jsx)(Text3, { children: showCursor ? import_chalk9.default.inverse(" ") + "\u200B" : " \u200B" }, `cursor-end-${cursorVisualColAbsolute}`)
              );
            }
            return /* @__PURE__ */ (0, import_jsx_runtime96.jsx)(Box_default, { height: 1, children: /* @__PURE__ */ (0, import_jsx_runtime96.jsx)(Text3, { children: renderedLine }) }, `line-${visualIdxInRenderedSet}`);
          }) })
        ]
      }
    ),
    shouldShowSuggestions && /* @__PURE__ */ (0, import_jsx_runtime96.jsx)(Box_default, { marginLeft: 2, marginRight: 2, children: /* @__PURE__ */ (0, import_jsx_runtime96.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
      }
    ) }),
    attachments.length > 0 && !shouldShowSuggestions && /* @__PURE__ */ (0, import_jsx_runtime96.jsx)(Box_default, { marginLeft: 2, marginRight: 2, children: /* @__PURE__ */ (0, import_jsx_runtime96.jsx)(Text3, { color: theme.text.secondary, children: isAttachmentMode ? t4("\u2190 \u2192 select, Delete to remove, \u2193 to exit") : t4("\u2191 to manage attachments") }) })
  ] });
}, "InputPrompt");

// packages/cli/src/ui/components/Footer.tsx
init_esbuild_shims();

// packages/cli/src/ui/components/ContextUsageDisplay.tsx
init_esbuild_shims();
var import_jsx_runtime97 = __toESM(require_jsx_runtime(), 1);
var ContextUsageDisplay = /* @__PURE__ */ __name(({
  promptTokenCount,
  terminalWidth,
  contextWindowSize
}) => {
  if (promptTokenCount === 0) {
    return null;
  }
  const percentage = promptTokenCount / contextWindowSize;
  const percentageUsed = (percentage * 100).toFixed(1);
  const label = terminalWidth < 100 ? "% used" : "% context used";
  return /* @__PURE__ */ (0, import_jsx_runtime97.jsxs)(Text3, { color: theme.text.secondary, children: [
    percentageUsed,
    label
  ] });
}, "ContextUsageDisplay");

// packages/cli/src/ui/components/AutoAcceptIndicator.tsx
init_esbuild_shims();
var import_jsx_runtime98 = __toESM(require_jsx_runtime(), 1);
var AutoAcceptIndicator = /* @__PURE__ */ __name(({
  approvalMode
}) => {
  let textColor = "";
  let textContent2 = "";
  let subText = "";
  const cycleText = process.platform === "win32" ? ` ${t4("(tab to cycle)")}` : ` ${t4("(shift + tab to cycle)")}`;
  switch (approvalMode) {
    case ApprovalMode.PLAN:
      textColor = theme.status.success;
      textContent2 = t4("plan mode");
      subText = cycleText;
      break;
    case ApprovalMode.AUTO_EDIT:
      textColor = theme.status.warning;
      textContent2 = t4("auto-accept edits");
      subText = cycleText;
      break;
    case ApprovalMode.YOLO:
      textColor = theme.status.error;
      textContent2 = t4("YOLO mode");
      subText = cycleText;
      break;
    case ApprovalMode.DEFAULT:
    default:
      break;
  }
  return /* @__PURE__ */ (0, import_jsx_runtime98.jsx)(Box_default, { children: /* @__PURE__ */ (0, import_jsx_runtime98.jsxs)(Text3, { color: textColor, children: [
    textContent2,
    subText && /* @__PURE__ */ (0, import_jsx_runtime98.jsx)(Text3, { color: theme.text.secondary, children: subText })
  ] }) });
}, "AutoAcceptIndicator");

// packages/cli/src/ui/components/ShellModeIndicator.tsx
init_esbuild_shims();
var import_jsx_runtime99 = __toESM(require_jsx_runtime(), 1);
var ShellModeIndicator = /* @__PURE__ */ __name(() => /* @__PURE__ */ (0, import_jsx_runtime99.jsx)(Box_default, { children: /* @__PURE__ */ (0, import_jsx_runtime99.jsxs)(Text3, { color: theme.ui.symbol, children: [
  "shell mode enabled",
  /* @__PURE__ */ (0, import_jsx_runtime99.jsx)(Text3, { color: theme.text.secondary, children: " (esc to disable)" })
] }) }), "ShellModeIndicator");

// packages/cli/src/ui/components/Footer.tsx
var import_jsx_runtime100 = __toESM(require_jsx_runtime(), 1);
var Footer = /* @__PURE__ */ __name(() => {
  const uiState = useUIState();
  const config2 = useConfig();
  const { vimEnabled, vimMode } = useVimMode();
  const { promptTokenCount, showAutoAcceptIndicator } = {
    promptTokenCount: uiState.sessionStats.lastPromptTokenCount,
    showAutoAcceptIndicator: uiState.showAutoAcceptIndicator
  };
  const { columns: terminalWidth } = useTerminalSize();
  const isNarrow = isNarrowWidth(terminalWidth);
  const sandboxEnv = process.env["SANDBOX"];
  const sandboxInfo = sandboxEnv ? sandboxEnv === "sandbox-exec" ? "seatbelt" : sandboxEnv.startsWith("qwen-code") ? "docker" : sandboxEnv : null;
  const debugMode = config2.getDebugMode();
  const contextWindowSize = config2.getContentGeneratorConfig()?.contextWindowSize;
  const leftContent = uiState.ctrlCPressedOnce ? /* @__PURE__ */ (0, import_jsx_runtime100.jsx)(Text3, { color: theme.status.warning, children: t4("Press Ctrl+C again to exit.") }) : uiState.ctrlDPressedOnce ? /* @__PURE__ */ (0, import_jsx_runtime100.jsx)(Text3, { color: theme.status.warning, children: t4("Press Ctrl+D again to exit.") }) : uiState.showEscapePrompt ? /* @__PURE__ */ (0, import_jsx_runtime100.jsx)(Text3, { color: theme.text.secondary, children: t4("Press Esc again to clear.") }) : vimEnabled && vimMode === "INSERT" ? /* @__PURE__ */ (0, import_jsx_runtime100.jsx)(Text3, { color: theme.text.secondary, children: "-- INSERT --" }) : uiState.shellModeActive ? /* @__PURE__ */ (0, import_jsx_runtime100.jsx)(ShellModeIndicator, {}) : showAutoAcceptIndicator !== void 0 && showAutoAcceptIndicator !== ApprovalMode.DEFAULT ? /* @__PURE__ */ (0, import_jsx_runtime100.jsx)(AutoAcceptIndicator, { approvalMode: showAutoAcceptIndicator }) : /* @__PURE__ */ (0, import_jsx_runtime100.jsx)(Text3, { color: theme.text.secondary, children: t4("? for shortcuts") });
  const rightItems = [];
  if (sandboxInfo) {
    rightItems.push({
      key: "sandbox",
      node: /* @__PURE__ */ (0, import_jsx_runtime100.jsxs)(Text3, { color: theme.status.success, children: [
        "\u{1F512} ",
        sandboxInfo
      ] })
    });
  }
  if (debugMode) {
    rightItems.push({
      key: "debug",
      node: /* @__PURE__ */ (0, import_jsx_runtime100.jsx)(Text3, { color: theme.status.warning, children: "Debug Mode" })
    });
  }
  if (promptTokenCount > 0 && contextWindowSize) {
    rightItems.push({
      key: "context",
      node: /* @__PURE__ */ (0, import_jsx_runtime100.jsx)(Text3, { color: theme.text.accent, children: /* @__PURE__ */ (0, import_jsx_runtime100.jsx)(
        ContextUsageDisplay,
        {
          promptTokenCount,
          terminalWidth,
          contextWindowSize
        }
      ) })
    });
  }
  return /* @__PURE__ */ (0, import_jsx_runtime100.jsxs)(
    Box_default,
    {
      justifyContent: "space-between",
      width: "100%",
      flexDirection: "row",
      alignItems: "center",
      children: [
        /* @__PURE__ */ (0, import_jsx_runtime100.jsx)(
          Box_default,
          {
            marginLeft: 2,
            justifyContent: "flex-start",
            flexDirection: isNarrow ? "column" : "row",
            alignItems: isNarrow ? "flex-start" : "center",
            children: leftContent
          }
        ),
        /* @__PURE__ */ (0, import_jsx_runtime100.jsx)(Box_default, { alignItems: "center", justifyContent: "flex-end", marginRight: 2, children: rightItems.map(({ key, node }, index) => /* @__PURE__ */ (0, import_jsx_runtime100.jsxs)(Box_default, { alignItems: "center", children: [
          index > 0 && /* @__PURE__ */ (0, import_jsx_runtime100.jsx)(Text3, { color: theme.text.secondary, children: " | " }),
          node
        ] }, key)) })
      ]
    }
  );
}, "Footer");

// packages/cli/src/ui/components/QueuedMessageDisplay.tsx
init_esbuild_shims();
var import_jsx_runtime101 = __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_runtime101.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_runtime101.jsx)(Box_default, { paddingLeft: 2, width: "100%", children: /* @__PURE__ */ (0, import_jsx_runtime101.jsx)(Text3, { dimColor: true, wrap: "truncate", children: preview }) }, index);
    }),
    messageQueue.length > MAX_DISPLAYED_QUEUED_MESSAGES && /* @__PURE__ */ (0, import_jsx_runtime101.jsx)(Box_default, { paddingLeft: 2, children: /* @__PURE__ */ (0, import_jsx_runtime101.jsxs)(Text3, { dimColor: true, children: [
      "... (+",
      messageQueue.length - MAX_DISPLAYED_QUEUED_MESSAGES,
      " more)"
    ] }) })
  ] });
}, "QueuedMessageDisplay");

// packages/cli/src/ui/components/KeyboardShortcuts.tsx
init_esbuild_shims();
var import_jsx_runtime102 = __toESM(require_jsx_runtime(), 1);
var getNewlineKey = /* @__PURE__ */ __name(() => process.platform === "win32" ? "ctrl+enter" : "ctrl+j", "getNewlineKey");
var getPasteKey = /* @__PURE__ */ __name(() => {
  if (process.platform === "win32") return "alt+v";
  return process.platform === "darwin" ? "cmd+v" : "ctrl+v";
}, "getPasteKey");
var getExternalEditorKey = /* @__PURE__ */ __name(() => process.platform === "darwin" ? "ctrl+x" : "ctrl+x", "getExternalEditorKey");
var getShortcuts = /* @__PURE__ */ __name(() => [
  { key: "!", description: t4("for shell mode") },
  { key: "/", description: t4("for commands") },
  { key: "@", description: t4("for file paths") },
  { key: "esc esc", description: t4("to clear input") },
  {
    key: process.platform === "win32" ? "tab" : "shift+tab",
    description: t4("to cycle approvals")
  },
  { key: "ctrl+c", description: t4("to quit") },
  { key: getNewlineKey(), description: t4("for newline") + " \u23CE" },
  { key: "ctrl+l", description: t4("to clear screen") },
  { key: "ctrl+r", description: t4("to search history") },
  { key: getPasteKey(), description: t4("to paste images") },
  { key: getExternalEditorKey(), description: t4("for external editor") }
], "getShortcuts");
var ShortcutItem = /* @__PURE__ */ __name(({ shortcut }) => /* @__PURE__ */ (0, import_jsx_runtime102.jsxs)(Text3, { color: theme.text.secondary, children: [
  /* @__PURE__ */ (0, import_jsx_runtime102.jsx)(Text3, { color: theme.text.accent, children: shortcut.key }),
  " ",
  shortcut.description
] }), "ShortcutItem");
var COLUMN_GAP = 4;
var MARGIN_LEFT = 2;
var MARGIN_RIGHT = 2;
var COLUMN_SPLITS = {
  3: [3, 4, 4],
  2: [6, 5],
  1: [11]
};
var KeyboardShortcuts = /* @__PURE__ */ __name(() => {
  const { columns: terminalWidth } = useTerminalSize();
  const shortcuts = getShortcuts();
  const getShortcutWidth = /* @__PURE__ */ __name((shortcut) => shortcut.key.length + 1 + shortcut.description.length, "getShortcutWidth");
  const calculateLayoutWidth = /* @__PURE__ */ __name((splits2) => {
    let startIndex2 = 0;
    let totalWidth = 0;
    splits2.forEach((count, colIndex) => {
      const columnItems = shortcuts.slice(startIndex2, startIndex2 + count);
      const columnWidth = Math.max(...columnItems.map(getShortcutWidth));
      totalWidth += columnWidth;
      if (colIndex < splits2.length - 1) {
        totalWidth += COLUMN_GAP;
      }
      startIndex2 += count;
    });
    return totalWidth;
  }, "calculateLayoutWidth");
  const availableWidth = terminalWidth - MARGIN_LEFT - MARGIN_RIGHT;
  const width3Col = calculateLayoutWidth(COLUMN_SPLITS[3]);
  const width2Col = calculateLayoutWidth(COLUMN_SPLITS[2]);
  const numColumns = availableWidth >= width3Col ? 3 : availableWidth >= width2Col ? 2 : 1;
  const splits = COLUMN_SPLITS[numColumns];
  const columns = [];
  let startIndex = 0;
  for (const count of splits) {
    columns.push(shortcuts.slice(startIndex, startIndex + count));
    startIndex += count;
  }
  return /* @__PURE__ */ (0, import_jsx_runtime102.jsx)(
    Box_default,
    {
      flexDirection: "row",
      marginLeft: MARGIN_LEFT,
      marginRight: MARGIN_RIGHT,
      children: columns.map((column, colIndex) => /* @__PURE__ */ (0, import_jsx_runtime102.jsx)(
        Box_default,
        {
          flexDirection: "column",
          marginRight: colIndex < numColumns - 1 ? COLUMN_GAP : 0,
          children: column.map((shortcut) => /* @__PURE__ */ (0, import_jsx_runtime102.jsx)(ShortcutItem, { shortcut }, shortcut.key))
        },
        colIndex
      ))
    }
  );
}, "KeyboardShortcuts");

// packages/cli/src/ui/components/ConfigInitDisplay.tsx
init_esbuild_shims();
var import_react98 = __toESM(require_react(), 1);
var import_jsx_runtime103 = __toESM(require_jsx_runtime(), 1);
var ConfigInitDisplay = /* @__PURE__ */ __name(() => {
  const config2 = useConfig();
  const [message, setMessage] = (0, import_react98.useState)(t4("Initializing..."));
  (0, import_react98.useEffect)(() => {
    const onChange = /* @__PURE__ */ __name((clients) => {
      if (!clients || clients.size === 0) {
        setMessage(t4("Initializing..."));
        return;
      }
      let connected = 0;
      for (const client of clients.values()) {
        if (client.getStatus() === MCPServerStatus.CONNECTED) {
          connected++;
        }
      }
      setMessage(
        t4("Connecting to MCP servers... ({{connected}}/{{total}})", {
          connected: String(connected),
          total: String(clients.size)
        })
      );
    }, "onChange");
    appEvents.on("mcp-client-update", onChange);
    return () => {
      appEvents.off("mcp-client-update", onChange);
    };
  }, [config2]);
  return /* @__PURE__ */ (0, import_jsx_runtime103.jsx)(Box_default, { marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime103.jsxs)(Text3, { children: [
    /* @__PURE__ */ (0, import_jsx_runtime103.jsx)(GeminiSpinner, {}),
    " ",
    /* @__PURE__ */ (0, import_jsx_runtime103.jsx)(Text3, { color: theme.text.primary, children: message })
  ] }) });
}, "ConfigInitDisplay");

// packages/cli/src/ui/components/Composer.tsx
var import_jsx_runtime104 = __toESM(require_jsx_runtime(), 1);
var Composer = /* @__PURE__ */ __name(() => {
  const config2 = useConfig();
  const isScreenReaderEnabled = use_is_screen_reader_enabled_default();
  const uiState = useUIState();
  const uiActions = useUIActions();
  const { vimEnabled } = useVimMode();
  const { showAutoAcceptIndicator } = uiState;
  const [showShortcuts, setShowShortcuts] = (0, import_react99.useState)(false);
  const handleToggleShortcuts = (0, import_react99.useCallback)(() => {
    setShowShortcuts((prev) => !prev);
  }, []);
  const [showSuggestions, setShowSuggestions] = (0, import_react99.useState)(false);
  const handleSuggestionsVisibilityChange = (0, import_react99.useCallback)(
    (visible) => {
      setShowSuggestions(visible);
      uiActions.onSuggestionsVisibilityChange(visible);
    },
    [uiActions]
  );
  return /* @__PURE__ */ (0, import_jsx_runtime104.jsxs)(Box_default, { flexDirection: "column", marginTop: 1, children: [
    !uiState.embeddedShellFocused && /* @__PURE__ */ (0, import_jsx_runtime104.jsx)(
      LoadingIndicator,
      {
        thought: uiState.streamingState === "waiting_for_confirmation" /* WaitingForConfirmation */ || config2.getAccessibility()?.enableLoadingPhrases === false ? void 0 : uiState.thought,
        currentLoadingPhrase: config2.getAccessibility()?.enableLoadingPhrases === false ? void 0 : uiState.currentLoadingPhrase,
        elapsedTime: uiState.elapsedTime
      }
    ),
    !uiState.isConfigInitialized && /* @__PURE__ */ (0, import_jsx_runtime104.jsx)(ConfigInitDisplay, {}),
    /* @__PURE__ */ (0, import_jsx_runtime104.jsx)(QueuedMessageDisplay, { messageQueue: uiState.messageQueue }),
    uiState.isFeedbackDialogOpen && /* @__PURE__ */ (0, import_jsx_runtime104.jsx)(FeedbackDialog, {}),
    uiState.isInputActive && /* @__PURE__ */ (0, import_jsx_runtime104.jsx)(
      InputPrompt,
      {
        buffer: uiState.buffer,
        inputWidth: uiState.inputWidth,
        suggestionsWidth: uiState.suggestionsWidth,
        onSubmit: uiActions.handleFinalSubmit,
        userMessages: uiState.userMessages,
        onClearScreen: uiActions.handleClearScreen,
        config: config2,
        slashCommands: uiState.slashCommands,
        commandContext: uiState.commandContext,
        shellModeActive: uiState.shellModeActive,
        setShellModeActive: uiActions.setShellModeActive,
        approvalMode: showAutoAcceptIndicator,
        onEscapePromptChange: uiActions.onEscapePromptChange,
        onToggleShortcuts: handleToggleShortcuts,
        showShortcuts,
        onSuggestionsVisibilityChange: handleSuggestionsVisibilityChange,
        focus: true,
        vimHandleInput: uiActions.vimHandleInput,
        isEmbeddedShellFocused: uiState.embeddedShellFocused,
        placeholder: vimEnabled ? "  " + t4("Press 'i' for INSERT mode and 'Esc' for NORMAL mode.") : "  " + t4("Type your message or @path/to/file")
      }
    ),
    !showSuggestions && (showShortcuts ? /* @__PURE__ */ (0, import_jsx_runtime104.jsx)(KeyboardShortcuts, {}) : !isScreenReaderEnabled && /* @__PURE__ */ (0, import_jsx_runtime104.jsx)(Footer, {}))
  ] });
}, "Composer");

// packages/cli/src/ui/components/ExitWarning.tsx
init_esbuild_shims();
var import_jsx_runtime105 = __toESM(require_jsx_runtime(), 1);
var ExitWarning = /* @__PURE__ */ __name(() => {
  const uiState = useUIState();
  return /* @__PURE__ */ (0, import_jsx_runtime105.jsxs)(import_jsx_runtime105.Fragment, { children: [
    uiState.dialogsVisible && uiState.ctrlCPressedOnce && /* @__PURE__ */ (0, import_jsx_runtime105.jsx)(Box_default, { marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime105.jsx)(Text3, { color: theme.status.warning, children: "Press Ctrl+C again to exit." }) }),
    uiState.dialogsVisible && uiState.ctrlDPressedOnce && /* @__PURE__ */ (0, import_jsx_runtime105.jsx)(Box_default, { marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime105.jsx)(Text3, { color: theme.status.warning, children: "Press Ctrl+D again to exit." }) })
  ] });
}, "ExitWarning");

// packages/cli/src/ui/layouts/ScreenReaderAppLayout.tsx
var import_jsx_runtime106 = __toESM(require_jsx_runtime(), 1);
var ScreenReaderAppLayout = /* @__PURE__ */ __name(() => {
  const uiState = useUIState();
  return /* @__PURE__ */ (0, import_jsx_runtime106.jsxs)(Box_default, { flexDirection: "column", width: "90%", height: "100%", children: [
    /* @__PURE__ */ (0, import_jsx_runtime106.jsx)(Notifications, {}),
    /* @__PURE__ */ (0, import_jsx_runtime106.jsx)(Footer, {}),
    /* @__PURE__ */ (0, import_jsx_runtime106.jsx)(Box_default, { flexGrow: 1, overflow: "hidden", children: /* @__PURE__ */ (0, import_jsx_runtime106.jsx)(MainContent, {}) }),
    uiState.dialogsVisible ? /* @__PURE__ */ (0, import_jsx_runtime106.jsx)(Box_default, { marginX: 2, flexDirection: "column", width: uiState.mainAreaWidth, children: /* @__PURE__ */ (0, import_jsx_runtime106.jsx)(
      DialogManager,
      {
        terminalWidth: uiState.terminalWidth,
        addItem: uiState.historyManager.addItem
      }
    ) }) : /* @__PURE__ */ (0, import_jsx_runtime106.jsx)(Composer, {}),
    /* @__PURE__ */ (0, import_jsx_runtime106.jsx)(ExitWarning, {})
  ] });
}, "ScreenReaderAppLayout");

// packages/cli/src/ui/layouts/DefaultAppLayout.tsx
init_esbuild_shims();
var import_jsx_runtime107 = __toESM(require_jsx_runtime(), 1);
var DefaultAppLayout = /* @__PURE__ */ __name(() => {
  const uiState = useUIState();
  const { columns: terminalWidth } = useTerminalSize();
  return /* @__PURE__ */ (0, import_jsx_runtime107.jsxs)(Box_default, { flexDirection: "column", width: terminalWidth, children: [
    /* @__PURE__ */ (0, import_jsx_runtime107.jsx)(MainContent, {}),
    /* @__PURE__ */ (0, import_jsx_runtime107.jsxs)(Box_default, { flexDirection: "column", ref: uiState.mainControlsRef, children: [
      uiState.dialogsVisible ? /* @__PURE__ */ (0, import_jsx_runtime107.jsx)(Box_default, { marginX: 2, flexDirection: "column", width: uiState.mainAreaWidth, children: /* @__PURE__ */ (0, import_jsx_runtime107.jsx)(
        DialogManager,
        {
          terminalWidth: uiState.terminalWidth,
          addItem: uiState.historyManager.addItem
        }
      ) }) : /* @__PURE__ */ (0, import_jsx_runtime107.jsx)(Composer, {}),
      /* @__PURE__ */ (0, import_jsx_runtime107.jsx)(ExitWarning, {})
    ] })
  ] });
}, "DefaultAppLayout");

// packages/cli/src/ui/App.tsx
var import_jsx_runtime108 = __toESM(require_jsx_runtime(), 1);
var App2 = /* @__PURE__ */ __name(() => {
  const uiState = useUIState();
  const isScreenReaderEnabled = use_is_screen_reader_enabled_default();
  if (uiState.quittingMessages) {
    return /* @__PURE__ */ (0, import_jsx_runtime108.jsx)(QuittingDisplay, {});
  }
  return /* @__PURE__ */ (0, import_jsx_runtime108.jsx)(StreamingContext.Provider, { value: uiState.streamingState, children: isScreenReaderEnabled ? /* @__PURE__ */ (0, import_jsx_runtime108.jsx)(ScreenReaderAppLayout, {}) : /* @__PURE__ */ (0, import_jsx_runtime108.jsx)(DefaultAppLayout, {}) });
}, "App");

// packages/cli/src/ui/utils/resumeHistoryUtils.ts
init_esbuild_shims();
import * as path109 from "node:path";
function extractTextFromParts(parts) {
  if (!parts) return "";
  const textParts = [];
  for (const part of parts) {
    if ("text" in part && part.text) {
      if (!("thought" in part && part.thought)) {
        textParts.push(part.text);
      }
    }
  }
  return textParts.join("\n");
}
__name(extractTextFromParts, "extractTextFromParts");
function extractThoughtTextFromParts(parts) {
  if (!parts) return "";
  const thoughtParts = [];
  for (const part of parts) {
    if ("text" in part && part.text && "thought" in part && part.thought) {
      thoughtParts.push(part.text);
    }
  }
  return thoughtParts.join("\n");
}
__name(extractThoughtTextFromParts, "extractThoughtTextFromParts");
function extractFunctionCalls(parts) {
  if (!parts) return [];
  const calls = [];
  for (const part of parts) {
    if ("functionCall" in part && part.functionCall) {
      const fc = part.functionCall;
      calls.push({
        id: fc.id || `call-${calls.length}`,
        name: fc.name || "unknown",
        args: fc.args || {}
      });
    }
  }
  return calls;
}
__name(extractFunctionCalls, "extractFunctionCalls");
function getTool(config2, name3) {
  const toolRegistry = config2.getToolRegistry();
  return toolRegistry.getTool(name3);
}
__name(getTool, "getTool");
function formatToolDescription(tool, args) {
  try {
    const invocation = tool.build(args);
    return invocation.getDescription();
  } catch {
    return "";
  }
}
__name(formatToolDescription, "formatToolDescription");
function restoreHistoryItem(raw2) {
  if (!raw2 || typeof raw2 !== "object") {
    return;
  }
  const clone4 = { ...raw2 };
  if ("timestamp" in clone4) {
    const ts = clone4["timestamp"];
    if (typeof ts === "string" || typeof ts === "number") {
      clone4["timestamp"] = new Date(ts);
    }
  }
  if (typeof clone4["type"] !== "string") {
    return;
  }
  return clone4;
}
__name(restoreHistoryItem, "restoreHistoryItem");
function convertToHistoryItems(conversation, config2) {
  const items = [];
  const pendingAtCommands = [];
  let atCommandCounter = 0;
  const pendingToolCalls = /* @__PURE__ */ new Map();
  let currentToolGroup = [];
  const buildAtCommandDisplays = /* @__PURE__ */ __name((payload) => {
    if (payload.status === "error") {
      atCommandCounter += 1;
      const filesLabel = payload.filesRead?.length ? payload.filesRead.join(", ") : "files";
      return [
        {
          callId: `at-command-${atCommandCounter}`,
          name: "Read File(s)",
          description: "Error attempting to read files",
          status: "Error" /* Error */,
          resultDisplay: payload.message || `Error reading files (${filesLabel})`,
          confirmationDetails: void 0
        }
      ];
    }
    if (!payload.filesRead?.length) {
      atCommandCounter += 1;
      return [
        {
          callId: `at-command-${atCommandCounter}`,
          name: "Read File",
          description: "Read File(s)",
          status: "Success" /* Success */,
          resultDisplay: void 0,
          confirmationDetails: void 0
        }
      ];
    }
    return payload.filesRead.map((filePath) => {
      atCommandCounter += 1;
      const isDir = filePath.endsWith("/");
      return {
        callId: `at-command-${atCommandCounter}`,
        name: isDir ? "Read Directory" : "Read File",
        description: isDir ? `Read directory ${path109.basename(filePath)}` : `Read file ${path109.basename(filePath)}`,
        status: "Success" /* Success */,
        resultDisplay: void 0,
        confirmationDetails: void 0
      };
    });
  }, "buildAtCommandDisplays");
  for (const record2 of conversation.messages) {
    if (record2.type === "system") {
      if (record2.subtype === "slash_command") {
        if (currentToolGroup.length > 0) {
          items.push({
            type: "tool_group",
            tools: [...currentToolGroup]
          });
          currentToolGroup = [];
        }
        const payload = record2.systemPayload;
        if (!payload) continue;
        if (payload.phase === "invocation" && payload.rawCommand) {
          items.push({ type: "user", text: payload.rawCommand });
        }
        if (payload.phase === "result") {
          const outputs = payload.outputHistoryItems ?? [];
          for (const raw2 of outputs) {
            const restored = restoreHistoryItem(raw2);
            if (restored) {
              items.push(restored);
            }
          }
        }
      }
      if (record2.subtype === "at_command") {
        const payload = record2.systemPayload;
        if (!payload) continue;
        pendingAtCommands.push(payload);
      }
      continue;
    }
    switch (record2.type) {
      case "user": {
        if (pendingAtCommands.length > 0) {
          if (currentToolGroup.length > 0) {
            items.push({
              type: "tool_group",
              tools: [...currentToolGroup]
            });
            currentToolGroup = [];
          }
          const payload = pendingAtCommands.shift();
          const text2 = payload.userText || extractTextFromParts(record2.message?.parts);
          if (text2) {
            items.push({ type: "user", text: text2 });
          }
          const toolDisplays = buildAtCommandDisplays(payload);
          if (toolDisplays.length > 0) {
            items.push({
              type: "tool_group",
              tools: toolDisplays
            });
          }
          break;
        }
        if (currentToolGroup.length > 0) {
          items.push({
            type: "tool_group",
            tools: [...currentToolGroup]
          });
          currentToolGroup = [];
        }
        const text = extractTextFromParts(record2.message?.parts);
        if (text) {
          items.push({ type: "user", text });
        }
        break;
      }
      case "assistant": {
        const parts = record2.message?.parts;
        const thoughtText = !config2.getContentGenerator().useSummarizedThinking() ? extractThoughtTextFromParts(parts) : "";
        const text = extractTextFromParts(parts);
        const functionCalls = extractFunctionCalls(parts);
        if (thoughtText) {
          if (currentToolGroup.length > 0) {
            items.push({
              type: "tool_group",
              tools: [...currentToolGroup]
            });
            currentToolGroup = [];
          }
          items.push({ type: "gemini_thought", text: thoughtText });
        }
        if (text) {
          if (currentToolGroup.length > 0) {
            items.push({
              type: "tool_group",
              tools: [...currentToolGroup]
            });
            currentToolGroup = [];
          }
          items.push({ type: "gemini", text });
        }
        for (const fc of functionCalls) {
          const tool = getTool(config2, fc.name);
          pendingToolCalls.set(fc.id, { name: fc.name, args: fc.args });
          currentToolGroup.push({
            callId: fc.id,
            name: tool?.displayName || fc.name,
            description: tool ? formatToolDescription(tool, fc.args) : "",
            resultDisplay: void 0,
            status: "Success" /* Success */,
            // Will be updated by tool_result
            confirmationDetails: void 0
          });
        }
        break;
      }
      case "tool_result": {
        if (record2.toolCallResult) {
          const callId = record2.toolCallResult.callId;
          const toolCall = currentToolGroup.find((t5) => t5.callId === callId);
          if (toolCall) {
            const rawDisplay = record2.toolCallResult.resultDisplay;
            toolCall.resultDisplay = rawDisplay;
            const rawStatus = record2.toolCallResult["status"];
            toolCall.status = rawStatus === "error" ? "Error" /* Error */ : "Success" /* Success */;
          }
          pendingToolCalls.delete(callId || "");
        }
        break;
      }
      default:
        break;
    }
  }
  if (pendingAtCommands.length > 0) {
    for (const payload of pendingAtCommands) {
      if (currentToolGroup.length > 0) {
        items.push({
          type: "tool_group",
          tools: [...currentToolGroup]
        });
        currentToolGroup = [];
      }
      const text = payload.userText;
      if (text) {
        items.push({ type: "user", text });
      }
      const toolDisplays = buildAtCommandDisplays(payload);
      if (toolDisplays.length > 0) {
        items.push({
          type: "tool_group",
          tools: toolDisplays
        });
      }
    }
  }
  if (currentToolGroup.length > 0) {
    items.push({
      type: "tool_group",
      tools: currentToolGroup
    });
  }
  return items;
}
__name(convertToHistoryItems, "convertToHistoryItems");
function buildResumedHistoryItems(sessionData, config2, baseTimestamp = Date.now()) {
  const items = [];
  let idCounter = 1;
  const getNextId = /* @__PURE__ */ __name(() => baseTimestamp + idCounter++, "getNextId");
  const historyItems = convertToHistoryItems(sessionData.conversation, config2);
  for (const item of historyItems) {
    items.push({
      ...item,
      id: getNextId()
    });
  }
  return items;
}
__name(buildResumedHistoryItems, "buildResumedHistoryItems");

// packages/cli/src/ui/AppContainer.tsx
import process49 from "node:process";

// packages/cli/src/ui/hooks/useMemoryMonitor.ts
init_esbuild_shims();
var import_react100 = __toESM(require_react(), 1);
import process36 from "node:process";
var MEMORY_WARNING_THRESHOLD = 7 * 1024 * 1024 * 1024;
var MEMORY_CHECK_INTERVAL = 60 * 1e3;
var useMemoryMonitor = /* @__PURE__ */ __name(({ addItem }) => {
  (0, import_react100.useEffect)(() => {
    const intervalId = setInterval(() => {
      const usage2 = process36.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_react101 = __toESM(require_react(), 1);
import process37 from "node:process";
var useThemeCommand = /* @__PURE__ */ __name((loadedSettings, setThemeError, addItem, initialThemeError) => {
  const [isThemeDialogOpen, setIsThemeDialogOpen] = (0, import_react101.useState)(!!initialThemeError);
  const openThemeDialog = (0, import_react101.useCallback)(() => {
    if (process37.env["NO_COLOR"]) {
      addItem(
        {
          type: "info" /* INFO */,
          text: t4(
            "Theme configuration unavailable due to NO_COLOR env variable."
          )
        },
        Date.now()
      );
      return;
    }
    setIsThemeDialogOpen(true);
  }, [addItem]);
  const applyTheme = (0, import_react101.useCallback)(
    (themeName) => {
      if (!themeManager.setActiveTheme(themeName)) {
        setIsThemeDialogOpen(true);
        setThemeError(
          t4('Theme "{{themeName}}" not found.', {
            themeName: themeName ?? ""
          })
        );
      } else {
        setThemeError(null);
      }
    },
    [setThemeError]
  );
  const handleThemeHighlight = (0, import_react101.useCallback)(
    (themeName) => {
      applyTheme(themeName);
    },
    [applyTheme]
  );
  const handleThemeSelect = (0, import_react101.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(
            t4('Theme "{{themeName}}" not found in selected scope.', {
              themeName: themeName ?? ""
            })
          );
          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/hooks/useFeedbackDialog.ts
init_esbuild_shims();
var import_react102 = __toESM(require_react(), 1);
import * as fs99 from "node:fs";
var import_strip_json_comments3 = __toESM(require_strip_json_comments(), 1);
var FEEDBACK_SHOW_PROBABILITY = 0.25;
var MIN_TOOL_CALLS = 10;
var MIN_USER_MESSAGES = 5;
var FEEDBACK_COOLDOWN_HOURS = 24;
var debugLogger109 = createDebugLogger("FEEDBACK_DIALOG");
var lastMessageIsAIResponse = /* @__PURE__ */ __name((history) => history.length > 0 && history[history.length - 1].type === "gemini" /* GEMINI */, "lastMessageIsAIResponse");
var getFeedbackLastShownTimestampFromFile = /* @__PURE__ */ __name(() => {
  try {
    if (fs99.existsSync(USER_SETTINGS_PATH)) {
      const content = fs99.readFileSync(USER_SETTINGS_PATH, "utf-8");
      const settings = JSON.parse((0, import_strip_json_comments3.default)(content));
      return settings?.ui?.feedbackLastShownTimestamp ?? 0;
    }
  } catch (error2) {
    if (isNodeError(error2) && error2.code !== "ENOENT") {
      debugLogger109.warn(
        "Failed to read feedbackLastShownTimestamp from settings file:",
        error2
      );
    }
  }
  return 0;
}, "getFeedbackLastShownTimestampFromFile");
var shouldShowFeedbackBasedOnFatigue = /* @__PURE__ */ __name(() => {
  const feedbackLastShownTimestamp = getFeedbackLastShownTimestampFromFile();
  const now = Date.now();
  const timeSinceLastShown = now - feedbackLastShownTimestamp;
  const cooldownMs = FEEDBACK_COOLDOWN_HOURS * 60 * 60 * 1e3;
  return timeSinceLastShown >= cooldownMs;
}, "shouldShowFeedbackBasedOnFatigue");
var meetsMinimumSessionRequirements = /* @__PURE__ */ __name((sessionStats) => {
  const toolCallsCount = sessionStats.metrics.tools.totalCalls;
  const userMessagesCount = sessionStats.promptCount;
  return toolCallsCount > MIN_TOOL_CALLS || userMessagesCount > MIN_USER_MESSAGES;
}, "meetsMinimumSessionRequirements");
var useFeedbackDialog = /* @__PURE__ */ __name(({
  config: config2,
  settings,
  streamingState,
  history,
  sessionStats
}) => {
  const [isFeedbackDialogOpen, setIsFeedbackDialogOpen] = (0, import_react102.useState)(false);
  const [isFeedbackDismissedTemporarily, setIsFeedbackDismissedTemporarily] = (0, import_react102.useState)(false);
  const openFeedbackDialog = (0, import_react102.useCallback)(() => {
    setIsFeedbackDialogOpen(true);
  }, []);
  const closeFeedbackDialog = (0, import_react102.useCallback)(
    () => setIsFeedbackDialogOpen(false),
    []
  );
  const temporaryCloseFeedbackDialog = (0, import_react102.useCallback)(() => {
    setIsFeedbackDialogOpen(false);
    setIsFeedbackDismissedTemporarily(true);
  }, []);
  const submitFeedback = (0, import_react102.useCallback)(
    (rating) => {
      if (rating >= FEEDBACK_OPTIONS.GOOD && rating <= FEEDBACK_OPTIONS.FINE) {
        const feedbackEvent = new UserFeedbackEvent(
          sessionStats.sessionId,
          rating,
          config2.getModel(),
          config2.getApprovalMode()
        );
        logUserFeedback(config2, feedbackEvent);
      }
      settings.setValue(
        "User" /* User */,
        "ui.feedbackLastShownTimestamp",
        Date.now()
      );
      closeFeedbackDialog();
    },
    [closeFeedbackDialog, sessionStats.sessionId, config2, settings]
  );
  (0, import_react102.useEffect)(() => {
    const checkAndShowFeedback = /* @__PURE__ */ __name(() => {
      if (streamingState === "idle" /* Idle */ && history.length > 0) {
        if (config2.getAuthType() !== AuthType2.QWEN_OAUTH || !config2.getUsageStatisticsEnabled() || settings.merged.ui?.enableUserFeedback === false || !lastMessageIsAIResponse(history) || Math.random() > FEEDBACK_SHOW_PROBABILITY || !meetsMinimumSessionRequirements(sessionStats) || isFeedbackDismissedTemporarily) {
          return;
        }
        if (shouldShowFeedbackBasedOnFatigue()) {
          openFeedbackDialog();
        }
      }
    }, "checkAndShowFeedback");
    checkAndShowFeedback();
  }, [
    streamingState,
    history,
    sessionStats,
    isFeedbackDialogOpen,
    isFeedbackDismissedTemporarily,
    openFeedbackDialog,
    settings.merged.ui?.enableUserFeedback,
    config2
  ]);
  (0, import_react102.useEffect)(() => {
    if (streamingState === "responding" /* Responding */ && isFeedbackDismissedTemporarily) {
      setIsFeedbackDismissedTemporarily(false);
    }
  }, [streamingState, isFeedbackDismissedTemporarily]);
  return {
    isFeedbackDialogOpen,
    openFeedbackDialog,
    closeFeedbackDialog,
    temporaryCloseFeedbackDialog,
    submitFeedback
  };
}, "useFeedbackDialog");

// packages/cli/src/ui/auth/useAuth.ts
init_esbuild_shims();
var import_react104 = __toESM(require_react(), 1);

// packages/cli/src/ui/hooks/useQwenAuth.ts
init_esbuild_shims();
var import_react103 = __toESM(require_react(), 1);
var useQwenAuth = /* @__PURE__ */ __name((pendingAuthType, isAuthenticating) => {
  const [qwenAuthState, setQwenAuthState] = (0, import_react103.useState)({
    deviceAuth: null,
    authStatus: "idle",
    authMessage: null
  });
  const isQwenAuth = pendingAuthType === AuthType2.QWEN_OAUTH;
  (0, import_react103.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_react103.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, config2, addItem, onAuthChange) => {
  const unAuthenticated = config2.getAuthType() === void 0;
  const [authState, setAuthState] = (0, import_react104.useState)(
    unAuthenticated ? "updating" /* Updating */ : "unauthenticated" /* Unauthenticated */
  );
  const [authError, setAuthError] = (0, import_react104.useState)(null);
  const [isAuthenticating, setIsAuthenticating] = (0, import_react104.useState)(false);
  const [isAuthDialogOpen, setIsAuthDialogOpen] = (0, import_react104.useState)(unAuthenticated);
  const [pendingAuthType, setPendingAuthType] = (0, import_react104.useState)(
    void 0
  );
  const { qwenAuthState, cancelQwenAuth } = useQwenAuth(
    pendingAuthType,
    isAuthenticating
  );
  const onAuthError = (0, import_react104.useCallback)(
    (error2) => {
      setAuthError(error2);
      if (error2) {
        setAuthState("updating" /* Updating */);
        setIsAuthDialogOpen(true);
      }
    },
    [setAuthError, setAuthState]
  );
  const handleAuthFailure = (0, import_react104.useCallback)(
    (error2) => {
      setIsAuthenticating(false);
      const errorMessage = t4("Failed to authenticate. Message: {{message}}", {
        message: getErrorMessage(error2)
      });
      onAuthError(errorMessage);
      if (pendingAuthType) {
        const authEvent = new AuthEvent(
          pendingAuthType,
          "manual",
          "error",
          errorMessage
        );
        logAuth(config2, authEvent);
      }
    },
    [onAuthError, pendingAuthType, config2]
  );
  const handleAuthSuccess = (0, import_react104.useCallback)(
    async (authType, credentials) => {
      try {
        const authTypeScope = getPersistScopeForModelSelection(settings);
        settings.setValue(
          authTypeScope,
          "security.auth.selectedType",
          authType
        );
        const contentGeneratorConfig = config2.getContentGeneratorConfig();
        if (contentGeneratorConfig?.model) {
          settings.setValue(
            authTypeScope,
            "model.name",
            contentGeneratorConfig.model
          );
        }
        if (authType !== AuthType2.QWEN_OAUTH && credentials) {
          if (credentials?.apiKey != null) {
            settings.setValue(
              authTypeScope,
              "security.auth.apiKey",
              credentials.apiKey
            );
          }
          if (credentials?.baseUrl != null) {
            settings.setValue(
              authTypeScope,
              "security.auth.baseUrl",
              credentials.baseUrl
            );
          }
        }
      } catch (error2) {
        handleAuthFailure(error2);
        return;
      }
      setAuthError(null);
      setAuthState("authenticated" /* Authenticated */);
      setPendingAuthType(void 0);
      setIsAuthDialogOpen(false);
      setIsAuthenticating(false);
      onAuthChange?.();
      addItem(
        {
          type: "info" /* INFO */,
          text: t4("Authenticated successfully with {{authType}} credentials.", {
            authType
          })
        },
        Date.now()
      );
      const authEvent = new AuthEvent(authType, "manual", "success");
      logAuth(config2, authEvent);
    },
    [settings, handleAuthFailure, config2, addItem, onAuthChange]
  );
  const performAuth = (0, import_react104.useCallback)(
    async (authType, credentials) => {
      try {
        await config2.refreshAuth(authType);
        handleAuthSuccess(authType, credentials);
      } catch (e4) {
        handleAuthFailure(e4);
      }
    },
    [config2, handleAuthSuccess, handleAuthFailure]
  );
  const isProviderManagedModel = (0, import_react104.useCallback)(
    (authType, modelId) => {
      if (!modelId) {
        return false;
      }
      const modelProviders = settings.merged.modelProviders;
      if (!modelProviders) {
        return false;
      }
      const providerModels = modelProviders[authType];
      if (!Array.isArray(providerModels)) {
        return false;
      }
      return providerModels.some(
        (providerModel) => providerModel.id === modelId
      );
    },
    [settings]
  );
  const handleAuthSelect = (0, import_react104.useCallback)(
    async (authType, credentials) => {
      if (!authType) {
        setIsAuthDialogOpen(false);
        setAuthError(null);
        return;
      }
      if (authType === AuthType2.USE_OPENAI && credentials?.model && isProviderManagedModel(authType, credentials.model)) {
        onAuthError(
          t4(
            'Model "{{modelName}}" is managed via settings.modelProviders. Please complete the fields in settings, or use another model id.',
            { modelName: credentials.model }
          )
        );
        return;
      }
      setPendingAuthType(authType);
      setAuthError(null);
      setIsAuthDialogOpen(false);
      setIsAuthenticating(true);
      if (authType === AuthType2.USE_OPENAI) {
        if (credentials) {
          const settingsGenerationConfig = settings.merged.model?.generationConfig;
          config2.updateCredentials(
            {
              apiKey: credentials.apiKey,
              baseUrl: credentials.baseUrl,
              model: credentials.model
            },
            settingsGenerationConfig
          );
          await performAuth(authType, credentials);
        }
        return;
      }
      await performAuth(authType);
    },
    [
      config2,
      performAuth,
      isProviderManagedModel,
      onAuthError,
      settings.merged.model?.generationConfig
    ]
  );
  const openAuthDialog = (0, import_react104.useCallback)(() => {
    setIsAuthDialogOpen(true);
  }, []);
  const cancelAuthentication = (0, import_react104.useCallback)(() => {
    if (isAuthenticating && pendingAuthType === AuthType2.QWEN_OAUTH) {
      cancelQwenAuth();
    }
    if (isAuthenticating && pendingAuthType) {
      const authEvent = new AuthEvent(pendingAuthType, "manual", "cancelled");
      logAuth(config2, authEvent);
    }
    setIsAuthenticating(false);
    setIsAuthDialogOpen(true);
    setAuthError(null);
  }, [isAuthenticating, pendingAuthType, cancelQwenAuth, config2]);
  const handleCodingPlanSubmit = (0, import_react104.useCallback)(
    async (apiKey, region = "china" /* CHINA */) => {
      try {
        setIsAuthenticating(true);
        setAuthError(null);
        const { template, version: version2, regionName } = getCodingPlanConfig(region);
        const persistScope = getPersistScopeForModelSelection(settings);
        const settingsFile = settings.forScope(persistScope);
        backupSettingsFile(settingsFile.path);
        settings.setValue(persistScope, `env.${CODING_PLAN_ENV_KEY}`, apiKey);
        process.env[CODING_PLAN_ENV_KEY] = apiKey;
        const newConfigs = template.map(
          (templateConfig) => ({
            ...templateConfig,
            envKey: CODING_PLAN_ENV_KEY
          })
        );
        const existingConfigs = settings.merged.modelProviders?.[AuthType2.USE_OPENAI] || [];
        const nonCodingPlanConfigs = existingConfigs.filter(
          (existing) => !isCodingPlanConfig(existing.baseUrl, existing.envKey)
        );
        const updatedConfigs = [...newConfigs, ...nonCodingPlanConfigs];
        settings.setValue(
          persistScope,
          `modelProviders.${AuthType2.USE_OPENAI}`,
          updatedConfigs
        );
        settings.setValue(
          persistScope,
          "security.auth.selectedType",
          AuthType2.USE_OPENAI
        );
        settings.setValue(persistScope, "codingPlan.region", region);
        settings.setValue(persistScope, "codingPlan.version", version2);
        if (updatedConfigs.length > 0 && updatedConfigs[0]?.id) {
          settings.setValue(persistScope, "model.name", updatedConfigs[0].id);
        }
        const updatedModelProviders = {
          ...settings.merged.modelProviders,
          [AuthType2.USE_OPENAI]: updatedConfigs
        };
        config2.reloadModelProvidersConfig(updatedModelProviders);
        await config2.refreshAuth(AuthType2.USE_OPENAI);
        setAuthError(null);
        setAuthState("authenticated" /* Authenticated */);
        setIsAuthDialogOpen(false);
        setIsAuthenticating(false);
        onAuthChange?.();
        addItem(
          {
            type: "info" /* INFO */,
            text: t4(
              "Authenticated successfully with {{region}}. API key and model configs saved to settings.json (backed up).",
              { region: regionName }
            )
          },
          Date.now()
        );
        const authEvent = new AuthEvent(
          AuthType2.USE_OPENAI,
          "coding-plan",
          "success"
        );
        logAuth(config2, authEvent);
      } catch (error2) {
        handleAuthFailure(error2);
      }
    },
    [settings, config2, handleAuthFailure, addItem, onAuthChange]
  );
  (0, import_react104.useEffect)(() => {
    const defaultAuthType = process.env["QWEN_DEFAULT_AUTH_TYPE"];
    if (defaultAuthType && ![
      AuthType2.QWEN_OAUTH,
      AuthType2.USE_OPENAI,
      AuthType2.USE_ANTHROPIC,
      AuthType2.USE_GEMINI,
      AuthType2.USE_VERTEX_AI
    ].includes(defaultAuthType)) {
      onAuthError(
        t4(
          'Invalid QWEN_DEFAULT_AUTH_TYPE value: "{{value}}". Valid values are: {{validValues}}',
          {
            value: defaultAuthType,
            validValues: [
              AuthType2.QWEN_OAUTH,
              AuthType2.USE_OPENAI,
              AuthType2.USE_ANTHROPIC,
              AuthType2.USE_GEMINI,
              AuthType2.USE_VERTEX_AI
            ].join(", ")
          }
        )
      );
    }
  }, [onAuthError]);
  return {
    authState,
    setAuthState,
    authError,
    onAuthError,
    isAuthDialogOpen,
    isAuthenticating,
    pendingAuthType,
    qwenAuthState,
    handleAuthSelect,
    handleCodingPlanSubmit,
    openAuthDialog,
    cancelAuthentication
  };
}, "useAuthCommand");

// packages/cli/src/ui/hooks/useEditorSettings.ts
init_esbuild_shims();
var import_react105 = __toESM(require_react(), 1);
var useEditorSettings = /* @__PURE__ */ __name((loadedSettings, setEditorError, addItem) => {
  const [isEditorDialogOpen, setIsEditorDialogOpen] = (0, import_react105.useState)(false);
  const openEditorDialog = (0, import_react105.useCallback)(() => {
    setIsEditorDialogOpen(true);
  }, []);
  const handleEditorSelect = (0, import_react105.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 (error2) {
        setEditorError(`Failed to set editor preference: ${error2}`);
      }
    },
    [loadedSettings, setEditorError, addItem]
  );
  const exitEditorDialog = (0, import_react105.useCallback)(() => {
    setIsEditorDialogOpen(false);
  }, []);
  return {
    isEditorDialogOpen,
    openEditorDialog,
    handleEditorSelect,
    exitEditorDialog
  };
}, "useEditorSettings");

// packages/cli/src/ui/hooks/useSettingsCommand.ts
init_esbuild_shims();
var import_react106 = __toESM(require_react(), 1);
function useSettingsCommand() {
  const [isSettingsDialogOpen, setIsSettingsDialogOpen] = (0, import_react106.useState)(false);
  const openSettingsDialog = (0, import_react106.useCallback)(() => {
    setIsSettingsDialogOpen(true);
  }, []);
  const closeSettingsDialog = (0, import_react106.useCallback)(() => {
    setIsSettingsDialogOpen(false);
  }, []);
  return {
    isSettingsDialogOpen,
    openSettingsDialog,
    closeSettingsDialog
  };
}
__name(useSettingsCommand, "useSettingsCommand");

// packages/cli/src/ui/hooks/useModelCommand.ts
init_esbuild_shims();
var import_react107 = __toESM(require_react(), 1);
var useModelCommand = /* @__PURE__ */ __name(() => {
  const [isModelDialogOpen, setIsModelDialogOpen] = (0, import_react107.useState)(false);
  const openModelDialog = (0, import_react107.useCallback)(() => {
    setIsModelDialogOpen(true);
  }, []);
  const closeModelDialog = (0, import_react107.useCallback)(() => {
    setIsModelDialogOpen(false);
  }, []);
  return {
    isModelDialogOpen,
    openModelDialog,
    closeModelDialog
  };
}, "useModelCommand");

// packages/cli/src/ui/hooks/useApprovalModeCommand.ts
init_esbuild_shims();
var import_react108 = __toESM(require_react(), 1);
var useApprovalModeCommand = /* @__PURE__ */ __name((loadedSettings, config2) => {
  const [isApprovalModeDialogOpen, setIsApprovalModeDialogOpen] = (0, import_react108.useState)(false);
  const openApprovalModeDialog = (0, import_react108.useCallback)(() => {
    setIsApprovalModeDialogOpen(true);
  }, []);
  const handleApprovalModeSelect = (0, import_react108.useCallback)(
    (mode, scope) => {
      try {
        if (!mode) {
          setIsApprovalModeDialogOpen(false);
          return;
        }
        loadedSettings.setValue(scope, "tools.approvalMode", mode);
        config2.setApprovalMode(
          loadedSettings.merged.tools?.approvalMode ?? mode
        );
      } finally {
        setIsApprovalModeDialogOpen(false);
      }
    },
    [config2, loadedSettings]
  );
  return {
    isApprovalModeDialogOpen,
    openApprovalModeDialog,
    handleApprovalModeSelect
  };
}, "useApprovalModeCommand");

// packages/cli/src/ui/hooks/useResumeCommand.ts
init_esbuild_shims();
var import_react109 = __toESM(require_react(), 1);
function useResumeCommand(options2) {
  const [isResumeDialogOpen, setIsResumeDialogOpen] = (0, import_react109.useState)(false);
  const openResumeDialog = (0, import_react109.useCallback)(() => {
    setIsResumeDialogOpen(true);
  }, []);
  const closeResumeDialog = (0, import_react109.useCallback)(() => {
    setIsResumeDialogOpen(false);
  }, []);
  const { config: config2, historyManager, startNewSession, remount } = options2 ?? {};
  const handleResume = (0, import_react109.useCallback)(
    async (sessionId) => {
      if (!config2 || !historyManager || !startNewSession) {
        return;
      }
      closeResumeDialog();
      const cwd7 = config2.getTargetDir();
      const sessionService = new SessionService(cwd7);
      const sessionData = await sessionService.loadSession(sessionId);
      if (!sessionData) {
        return;
      }
      startNewSession(sessionId);
      const uiHistoryItems = buildResumedHistoryItems(sessionData, config2);
      historyManager.clearItems();
      historyManager.loadHistory(uiHistoryItems);
      config2.startNewSession(sessionId, sessionData);
      await config2.getGeminiClient()?.initialize?.();
      remount?.();
    },
    [closeResumeDialog, config2, historyManager, startNewSession, remount]
  );
  return {
    isResumeDialogOpen,
    openResumeDialog,
    closeResumeDialog,
    handleResume
  };
}
__name(useResumeCommand, "useResumeCommand");

// packages/cli/src/ui/hooks/slashCommandProcessor.ts
init_esbuild_shims();
var import_react110 = __toESM(require_react(), 1);

// packages/cli/node_modules/@google/genai/dist/node/index.mjs
init_esbuild_shims();
var import_google_auth_library4 = __toESM(require_src44(), 1);
init_wrapper();
var Outcome2;
(function(Outcome3) {
  Outcome3["OUTCOME_UNSPECIFIED"] = "OUTCOME_UNSPECIFIED";
  Outcome3["OUTCOME_OK"] = "OUTCOME_OK";
  Outcome3["OUTCOME_FAILED"] = "OUTCOME_FAILED";
  Outcome3["OUTCOME_DEADLINE_EXCEEDED"] = "OUTCOME_DEADLINE_EXCEEDED";
})(Outcome2 || (Outcome2 = {}));
var Language2;
(function(Language3) {
  Language3["LANGUAGE_UNSPECIFIED"] = "LANGUAGE_UNSPECIFIED";
  Language3["PYTHON"] = "PYTHON";
})(Language2 || (Language2 = {}));
var FunctionResponseScheduling2;
(function(FunctionResponseScheduling3) {
  FunctionResponseScheduling3["SCHEDULING_UNSPECIFIED"] = "SCHEDULING_UNSPECIFIED";
  FunctionResponseScheduling3["SILENT"] = "SILENT";
  FunctionResponseScheduling3["WHEN_IDLE"] = "WHEN_IDLE";
  FunctionResponseScheduling3["INTERRUPT"] = "INTERRUPT";
})(FunctionResponseScheduling2 || (FunctionResponseScheduling2 = {}));
var Type2;
(function(Type3) {
  Type3["TYPE_UNSPECIFIED"] = "TYPE_UNSPECIFIED";
  Type3["STRING"] = "STRING";
  Type3["NUMBER"] = "NUMBER";
  Type3["INTEGER"] = "INTEGER";
  Type3["BOOLEAN"] = "BOOLEAN";
  Type3["ARRAY"] = "ARRAY";
  Type3["OBJECT"] = "OBJECT";
  Type3["NULL"] = "NULL";
})(Type2 || (Type2 = {}));
var Mode2;
(function(Mode3) {
  Mode3["MODE_UNSPECIFIED"] = "MODE_UNSPECIFIED";
  Mode3["MODE_DYNAMIC"] = "MODE_DYNAMIC";
})(Mode2 || (Mode2 = {}));
var ApiSpec2;
(function(ApiSpec3) {
  ApiSpec3["API_SPEC_UNSPECIFIED"] = "API_SPEC_UNSPECIFIED";
  ApiSpec3["SIMPLE_SEARCH"] = "SIMPLE_SEARCH";
  ApiSpec3["ELASTIC_SEARCH"] = "ELASTIC_SEARCH";
})(ApiSpec2 || (ApiSpec2 = {}));
var AuthType3;
(function(AuthType4) {
  AuthType4["AUTH_TYPE_UNSPECIFIED"] = "AUTH_TYPE_UNSPECIFIED";
  AuthType4["NO_AUTH"] = "NO_AUTH";
  AuthType4["API_KEY_AUTH"] = "API_KEY_AUTH";
  AuthType4["HTTP_BASIC_AUTH"] = "HTTP_BASIC_AUTH";
  AuthType4["GOOGLE_SERVICE_ACCOUNT_AUTH"] = "GOOGLE_SERVICE_ACCOUNT_AUTH";
  AuthType4["OAUTH"] = "OAUTH";
  AuthType4["OIDC_AUTH"] = "OIDC_AUTH";
})(AuthType3 || (AuthType3 = {}));
var HttpElementLocation2;
(function(HttpElementLocation3) {
  HttpElementLocation3["HTTP_IN_UNSPECIFIED"] = "HTTP_IN_UNSPECIFIED";
  HttpElementLocation3["HTTP_IN_QUERY"] = "HTTP_IN_QUERY";
  HttpElementLocation3["HTTP_IN_HEADER"] = "HTTP_IN_HEADER";
  HttpElementLocation3["HTTP_IN_PATH"] = "HTTP_IN_PATH";
  HttpElementLocation3["HTTP_IN_BODY"] = "HTTP_IN_BODY";
  HttpElementLocation3["HTTP_IN_COOKIE"] = "HTTP_IN_COOKIE";
})(HttpElementLocation2 || (HttpElementLocation2 = {}));
var PhishBlockThreshold2;
(function(PhishBlockThreshold3) {
  PhishBlockThreshold3["PHISH_BLOCK_THRESHOLD_UNSPECIFIED"] = "PHISH_BLOCK_THRESHOLD_UNSPECIFIED";
  PhishBlockThreshold3["BLOCK_LOW_AND_ABOVE"] = "BLOCK_LOW_AND_ABOVE";
  PhishBlockThreshold3["BLOCK_MEDIUM_AND_ABOVE"] = "BLOCK_MEDIUM_AND_ABOVE";
  PhishBlockThreshold3["BLOCK_HIGH_AND_ABOVE"] = "BLOCK_HIGH_AND_ABOVE";
  PhishBlockThreshold3["BLOCK_HIGHER_AND_ABOVE"] = "BLOCK_HIGHER_AND_ABOVE";
  PhishBlockThreshold3["BLOCK_VERY_HIGH_AND_ABOVE"] = "BLOCK_VERY_HIGH_AND_ABOVE";
  PhishBlockThreshold3["BLOCK_ONLY_EXTREMELY_HIGH"] = "BLOCK_ONLY_EXTREMELY_HIGH";
})(PhishBlockThreshold2 || (PhishBlockThreshold2 = {}));
var ThinkingLevel2;
(function(ThinkingLevel3) {
  ThinkingLevel3["THINKING_LEVEL_UNSPECIFIED"] = "THINKING_LEVEL_UNSPECIFIED";
  ThinkingLevel3["LOW"] = "LOW";
  ThinkingLevel3["HIGH"] = "HIGH";
})(ThinkingLevel2 || (ThinkingLevel2 = {}));
var HarmCategory2;
(function(HarmCategory3) {
  HarmCategory3["HARM_CATEGORY_UNSPECIFIED"] = "HARM_CATEGORY_UNSPECIFIED";
  HarmCategory3["HARM_CATEGORY_HARASSMENT"] = "HARM_CATEGORY_HARASSMENT";
  HarmCategory3["HARM_CATEGORY_HATE_SPEECH"] = "HARM_CATEGORY_HATE_SPEECH";
  HarmCategory3["HARM_CATEGORY_SEXUALLY_EXPLICIT"] = "HARM_CATEGORY_SEXUALLY_EXPLICIT";
  HarmCategory3["HARM_CATEGORY_DANGEROUS_CONTENT"] = "HARM_CATEGORY_DANGEROUS_CONTENT";
  HarmCategory3["HARM_CATEGORY_CIVIC_INTEGRITY"] = "HARM_CATEGORY_CIVIC_INTEGRITY";
  HarmCategory3["HARM_CATEGORY_IMAGE_HATE"] = "HARM_CATEGORY_IMAGE_HATE";
  HarmCategory3["HARM_CATEGORY_IMAGE_DANGEROUS_CONTENT"] = "HARM_CATEGORY_IMAGE_DANGEROUS_CONTENT";
  HarmCategory3["HARM_CATEGORY_IMAGE_HARASSMENT"] = "HARM_CATEGORY_IMAGE_HARASSMENT";
  HarmCategory3["HARM_CATEGORY_IMAGE_SEXUALLY_EXPLICIT"] = "HARM_CATEGORY_IMAGE_SEXUALLY_EXPLICIT";
  HarmCategory3["HARM_CATEGORY_JAILBREAK"] = "HARM_CATEGORY_JAILBREAK";
})(HarmCategory2 || (HarmCategory2 = {}));
var HarmBlockMethod2;
(function(HarmBlockMethod3) {
  HarmBlockMethod3["HARM_BLOCK_METHOD_UNSPECIFIED"] = "HARM_BLOCK_METHOD_UNSPECIFIED";
  HarmBlockMethod3["SEVERITY"] = "SEVERITY";
  HarmBlockMethod3["PROBABILITY"] = "PROBABILITY";
})(HarmBlockMethod2 || (HarmBlockMethod2 = {}));
var HarmBlockThreshold2;
(function(HarmBlockThreshold3) {
  HarmBlockThreshold3["HARM_BLOCK_THRESHOLD_UNSPECIFIED"] = "HARM_BLOCK_THRESHOLD_UNSPECIFIED";
  HarmBlockThreshold3["BLOCK_LOW_AND_ABOVE"] = "BLOCK_LOW_AND_ABOVE";
  HarmBlockThreshold3["BLOCK_MEDIUM_AND_ABOVE"] = "BLOCK_MEDIUM_AND_ABOVE";
  HarmBlockThreshold3["BLOCK_ONLY_HIGH"] = "BLOCK_ONLY_HIGH";
  HarmBlockThreshold3["BLOCK_NONE"] = "BLOCK_NONE";
  HarmBlockThreshold3["OFF"] = "OFF";
})(HarmBlockThreshold2 || (HarmBlockThreshold2 = {}));
var FinishReason2;
(function(FinishReason3) {
  FinishReason3["FINISH_REASON_UNSPECIFIED"] = "FINISH_REASON_UNSPECIFIED";
  FinishReason3["STOP"] = "STOP";
  FinishReason3["MAX_TOKENS"] = "MAX_TOKENS";
  FinishReason3["SAFETY"] = "SAFETY";
  FinishReason3["RECITATION"] = "RECITATION";
  FinishReason3["LANGUAGE"] = "LANGUAGE";
  FinishReason3["OTHER"] = "OTHER";
  FinishReason3["BLOCKLIST"] = "BLOCKLIST";
  FinishReason3["PROHIBITED_CONTENT"] = "PROHIBITED_CONTENT";
  FinishReason3["SPII"] = "SPII";
  FinishReason3["MALFORMED_FUNCTION_CALL"] = "MALFORMED_FUNCTION_CALL";
  FinishReason3["IMAGE_SAFETY"] = "IMAGE_SAFETY";
  FinishReason3["UNEXPECTED_TOOL_CALL"] = "UNEXPECTED_TOOL_CALL";
  FinishReason3["IMAGE_PROHIBITED_CONTENT"] = "IMAGE_PROHIBITED_CONTENT";
  FinishReason3["NO_IMAGE"] = "NO_IMAGE";
})(FinishReason2 || (FinishReason2 = {}));
var HarmProbability2;
(function(HarmProbability3) {
  HarmProbability3["HARM_PROBABILITY_UNSPECIFIED"] = "HARM_PROBABILITY_UNSPECIFIED";
  HarmProbability3["NEGLIGIBLE"] = "NEGLIGIBLE";
  HarmProbability3["LOW"] = "LOW";
  HarmProbability3["MEDIUM"] = "MEDIUM";
  HarmProbability3["HIGH"] = "HIGH";
})(HarmProbability2 || (HarmProbability2 = {}));
var HarmSeverity2;
(function(HarmSeverity3) {
  HarmSeverity3["HARM_SEVERITY_UNSPECIFIED"] = "HARM_SEVERITY_UNSPECIFIED";
  HarmSeverity3["HARM_SEVERITY_NEGLIGIBLE"] = "HARM_SEVERITY_NEGLIGIBLE";
  HarmSeverity3["HARM_SEVERITY_LOW"] = "HARM_SEVERITY_LOW";
  HarmSeverity3["HARM_SEVERITY_MEDIUM"] = "HARM_SEVERITY_MEDIUM";
  HarmSeverity3["HARM_SEVERITY_HIGH"] = "HARM_SEVERITY_HIGH";
})(HarmSeverity2 || (HarmSeverity2 = {}));
var UrlRetrievalStatus2;
(function(UrlRetrievalStatus3) {
  UrlRetrievalStatus3["URL_RETRIEVAL_STATUS_UNSPECIFIED"] = "URL_RETRIEVAL_STATUS_UNSPECIFIED";
  UrlRetrievalStatus3["URL_RETRIEVAL_STATUS_SUCCESS"] = "URL_RETRIEVAL_STATUS_SUCCESS";
  UrlRetrievalStatus3["URL_RETRIEVAL_STATUS_ERROR"] = "URL_RETRIEVAL_STATUS_ERROR";
  UrlRetrievalStatus3["URL_RETRIEVAL_STATUS_PAYWALL"] = "URL_RETRIEVAL_STATUS_PAYWALL";
  UrlRetrievalStatus3["URL_RETRIEVAL_STATUS_UNSAFE"] = "URL_RETRIEVAL_STATUS_UNSAFE";
})(UrlRetrievalStatus2 || (UrlRetrievalStatus2 = {}));
var BlockedReason2;
(function(BlockedReason3) {
  BlockedReason3["BLOCKED_REASON_UNSPECIFIED"] = "BLOCKED_REASON_UNSPECIFIED";
  BlockedReason3["SAFETY"] = "SAFETY";
  BlockedReason3["OTHER"] = "OTHER";
  BlockedReason3["BLOCKLIST"] = "BLOCKLIST";
  BlockedReason3["PROHIBITED_CONTENT"] = "PROHIBITED_CONTENT";
  BlockedReason3["IMAGE_SAFETY"] = "IMAGE_SAFETY";
  BlockedReason3["MODEL_ARMOR"] = "MODEL_ARMOR";
  BlockedReason3["JAILBREAK"] = "JAILBREAK";
})(BlockedReason2 || (BlockedReason2 = {}));
var TrafficType2;
(function(TrafficType3) {
  TrafficType3["TRAFFIC_TYPE_UNSPECIFIED"] = "TRAFFIC_TYPE_UNSPECIFIED";
  TrafficType3["ON_DEMAND"] = "ON_DEMAND";
  TrafficType3["PROVISIONED_THROUGHPUT"] = "PROVISIONED_THROUGHPUT";
})(TrafficType2 || (TrafficType2 = {}));
var Modality2;
(function(Modality3) {
  Modality3["MODALITY_UNSPECIFIED"] = "MODALITY_UNSPECIFIED";
  Modality3["TEXT"] = "TEXT";
  Modality3["IMAGE"] = "IMAGE";
  Modality3["AUDIO"] = "AUDIO";
})(Modality2 || (Modality2 = {}));
var MediaResolution2;
(function(MediaResolution3) {
  MediaResolution3["MEDIA_RESOLUTION_UNSPECIFIED"] = "MEDIA_RESOLUTION_UNSPECIFIED";
  MediaResolution3["MEDIA_RESOLUTION_LOW"] = "MEDIA_RESOLUTION_LOW";
  MediaResolution3["MEDIA_RESOLUTION_MEDIUM"] = "MEDIA_RESOLUTION_MEDIUM";
  MediaResolution3["MEDIA_RESOLUTION_HIGH"] = "MEDIA_RESOLUTION_HIGH";
})(MediaResolution2 || (MediaResolution2 = {}));
var TuningMode2;
(function(TuningMode3) {
  TuningMode3["TUNING_MODE_UNSPECIFIED"] = "TUNING_MODE_UNSPECIFIED";
  TuningMode3["TUNING_MODE_FULL"] = "TUNING_MODE_FULL";
  TuningMode3["TUNING_MODE_PEFT_ADAPTER"] = "TUNING_MODE_PEFT_ADAPTER";
})(TuningMode2 || (TuningMode2 = {}));
var AdapterSize2;
(function(AdapterSize3) {
  AdapterSize3["ADAPTER_SIZE_UNSPECIFIED"] = "ADAPTER_SIZE_UNSPECIFIED";
  AdapterSize3["ADAPTER_SIZE_ONE"] = "ADAPTER_SIZE_ONE";
  AdapterSize3["ADAPTER_SIZE_TWO"] = "ADAPTER_SIZE_TWO";
  AdapterSize3["ADAPTER_SIZE_FOUR"] = "ADAPTER_SIZE_FOUR";
  AdapterSize3["ADAPTER_SIZE_EIGHT"] = "ADAPTER_SIZE_EIGHT";
  AdapterSize3["ADAPTER_SIZE_SIXTEEN"] = "ADAPTER_SIZE_SIXTEEN";
  AdapterSize3["ADAPTER_SIZE_THIRTY_TWO"] = "ADAPTER_SIZE_THIRTY_TWO";
})(AdapterSize2 || (AdapterSize2 = {}));
var JobState2;
(function(JobState3) {
  JobState3["JOB_STATE_UNSPECIFIED"] = "JOB_STATE_UNSPECIFIED";
  JobState3["JOB_STATE_QUEUED"] = "JOB_STATE_QUEUED";
  JobState3["JOB_STATE_PENDING"] = "JOB_STATE_PENDING";
  JobState3["JOB_STATE_RUNNING"] = "JOB_STATE_RUNNING";
  JobState3["JOB_STATE_SUCCEEDED"] = "JOB_STATE_SUCCEEDED";
  JobState3["JOB_STATE_FAILED"] = "JOB_STATE_FAILED";
  JobState3["JOB_STATE_CANCELLING"] = "JOB_STATE_CANCELLING";
  JobState3["JOB_STATE_CANCELLED"] = "JOB_STATE_CANCELLED";
  JobState3["JOB_STATE_PAUSED"] = "JOB_STATE_PAUSED";
  JobState3["JOB_STATE_EXPIRED"] = "JOB_STATE_EXPIRED";
  JobState3["JOB_STATE_UPDATING"] = "JOB_STATE_UPDATING";
  JobState3["JOB_STATE_PARTIALLY_SUCCEEDED"] = "JOB_STATE_PARTIALLY_SUCCEEDED";
})(JobState2 || (JobState2 = {}));
var TuningTask2;
(function(TuningTask3) {
  TuningTask3["TUNING_TASK_UNSPECIFIED"] = "TUNING_TASK_UNSPECIFIED";
  TuningTask3["TUNING_TASK_I2V"] = "TUNING_TASK_I2V";
  TuningTask3["TUNING_TASK_T2V"] = "TUNING_TASK_T2V";
  TuningTask3["TUNING_TASK_R2V"] = "TUNING_TASK_R2V";
})(TuningTask2 || (TuningTask2 = {}));
var PartMediaResolutionLevel2;
(function(PartMediaResolutionLevel3) {
  PartMediaResolutionLevel3["MEDIA_RESOLUTION_UNSPECIFIED"] = "MEDIA_RESOLUTION_UNSPECIFIED";
  PartMediaResolutionLevel3["MEDIA_RESOLUTION_LOW"] = "MEDIA_RESOLUTION_LOW";
  PartMediaResolutionLevel3["MEDIA_RESOLUTION_MEDIUM"] = "MEDIA_RESOLUTION_MEDIUM";
  PartMediaResolutionLevel3["MEDIA_RESOLUTION_HIGH"] = "MEDIA_RESOLUTION_HIGH";
})(PartMediaResolutionLevel2 || (PartMediaResolutionLevel2 = {}));
var FeatureSelectionPreference2;
(function(FeatureSelectionPreference3) {
  FeatureSelectionPreference3["FEATURE_SELECTION_PREFERENCE_UNSPECIFIED"] = "FEATURE_SELECTION_PREFERENCE_UNSPECIFIED";
  FeatureSelectionPreference3["PRIORITIZE_QUALITY"] = "PRIORITIZE_QUALITY";
  FeatureSelectionPreference3["BALANCED"] = "BALANCED";
  FeatureSelectionPreference3["PRIORITIZE_COST"] = "PRIORITIZE_COST";
})(FeatureSelectionPreference2 || (FeatureSelectionPreference2 = {}));
var Behavior2;
(function(Behavior3) {
  Behavior3["UNSPECIFIED"] = "UNSPECIFIED";
  Behavior3["BLOCKING"] = "BLOCKING";
  Behavior3["NON_BLOCKING"] = "NON_BLOCKING";
})(Behavior2 || (Behavior2 = {}));
var DynamicRetrievalConfigMode2;
(function(DynamicRetrievalConfigMode3) {
  DynamicRetrievalConfigMode3["MODE_UNSPECIFIED"] = "MODE_UNSPECIFIED";
  DynamicRetrievalConfigMode3["MODE_DYNAMIC"] = "MODE_DYNAMIC";
})(DynamicRetrievalConfigMode2 || (DynamicRetrievalConfigMode2 = {}));
var Environment2;
(function(Environment3) {
  Environment3["ENVIRONMENT_UNSPECIFIED"] = "ENVIRONMENT_UNSPECIFIED";
  Environment3["ENVIRONMENT_BROWSER"] = "ENVIRONMENT_BROWSER";
})(Environment2 || (Environment2 = {}));
var FunctionCallingConfigMode2;
(function(FunctionCallingConfigMode3) {
  FunctionCallingConfigMode3["MODE_UNSPECIFIED"] = "MODE_UNSPECIFIED";
  FunctionCallingConfigMode3["AUTO"] = "AUTO";
  FunctionCallingConfigMode3["ANY"] = "ANY";
  FunctionCallingConfigMode3["NONE"] = "NONE";
  FunctionCallingConfigMode3["VALIDATED"] = "VALIDATED";
})(FunctionCallingConfigMode2 || (FunctionCallingConfigMode2 = {}));
var SafetyFilterLevel2;
(function(SafetyFilterLevel3) {
  SafetyFilterLevel3["BLOCK_LOW_AND_ABOVE"] = "BLOCK_LOW_AND_ABOVE";
  SafetyFilterLevel3["BLOCK_MEDIUM_AND_ABOVE"] = "BLOCK_MEDIUM_AND_ABOVE";
  SafetyFilterLevel3["BLOCK_ONLY_HIGH"] = "BLOCK_ONLY_HIGH";
  SafetyFilterLevel3["BLOCK_NONE"] = "BLOCK_NONE";
})(SafetyFilterLevel2 || (SafetyFilterLevel2 = {}));
var PersonGeneration2;
(function(PersonGeneration3) {
  PersonGeneration3["DONT_ALLOW"] = "DONT_ALLOW";
  PersonGeneration3["ALLOW_ADULT"] = "ALLOW_ADULT";
  PersonGeneration3["ALLOW_ALL"] = "ALLOW_ALL";
})(PersonGeneration2 || (PersonGeneration2 = {}));
var ImagePromptLanguage2;
(function(ImagePromptLanguage3) {
  ImagePromptLanguage3["auto"] = "auto";
  ImagePromptLanguage3["en"] = "en";
  ImagePromptLanguage3["ja"] = "ja";
  ImagePromptLanguage3["ko"] = "ko";
  ImagePromptLanguage3["hi"] = "hi";
  ImagePromptLanguage3["zh"] = "zh";
  ImagePromptLanguage3["pt"] = "pt";
  ImagePromptLanguage3["es"] = "es";
})(ImagePromptLanguage2 || (ImagePromptLanguage2 = {}));
var MaskReferenceMode2;
(function(MaskReferenceMode3) {
  MaskReferenceMode3["MASK_MODE_DEFAULT"] = "MASK_MODE_DEFAULT";
  MaskReferenceMode3["MASK_MODE_USER_PROVIDED"] = "MASK_MODE_USER_PROVIDED";
  MaskReferenceMode3["MASK_MODE_BACKGROUND"] = "MASK_MODE_BACKGROUND";
  MaskReferenceMode3["MASK_MODE_FOREGROUND"] = "MASK_MODE_FOREGROUND";
  MaskReferenceMode3["MASK_MODE_SEMANTIC"] = "MASK_MODE_SEMANTIC";
})(MaskReferenceMode2 || (MaskReferenceMode2 = {}));
var ControlReferenceType2;
(function(ControlReferenceType3) {
  ControlReferenceType3["CONTROL_TYPE_DEFAULT"] = "CONTROL_TYPE_DEFAULT";
  ControlReferenceType3["CONTROL_TYPE_CANNY"] = "CONTROL_TYPE_CANNY";
  ControlReferenceType3["CONTROL_TYPE_SCRIBBLE"] = "CONTROL_TYPE_SCRIBBLE";
  ControlReferenceType3["CONTROL_TYPE_FACE_MESH"] = "CONTROL_TYPE_FACE_MESH";
})(ControlReferenceType2 || (ControlReferenceType2 = {}));
var SubjectReferenceType2;
(function(SubjectReferenceType3) {
  SubjectReferenceType3["SUBJECT_TYPE_DEFAULT"] = "SUBJECT_TYPE_DEFAULT";
  SubjectReferenceType3["SUBJECT_TYPE_PERSON"] = "SUBJECT_TYPE_PERSON";
  SubjectReferenceType3["SUBJECT_TYPE_ANIMAL"] = "SUBJECT_TYPE_ANIMAL";
  SubjectReferenceType3["SUBJECT_TYPE_PRODUCT"] = "SUBJECT_TYPE_PRODUCT";
})(SubjectReferenceType2 || (SubjectReferenceType2 = {}));
var EditMode2;
(function(EditMode3) {
  EditMode3["EDIT_MODE_DEFAULT"] = "EDIT_MODE_DEFAULT";
  EditMode3["EDIT_MODE_INPAINT_REMOVAL"] = "EDIT_MODE_INPAINT_REMOVAL";
  EditMode3["EDIT_MODE_INPAINT_INSERTION"] = "EDIT_MODE_INPAINT_INSERTION";
  EditMode3["EDIT_MODE_OUTPAINT"] = "EDIT_MODE_OUTPAINT";
  EditMode3["EDIT_MODE_CONTROLLED_EDITING"] = "EDIT_MODE_CONTROLLED_EDITING";
  EditMode3["EDIT_MODE_STYLE"] = "EDIT_MODE_STYLE";
  EditMode3["EDIT_MODE_BGSWAP"] = "EDIT_MODE_BGSWAP";
  EditMode3["EDIT_MODE_PRODUCT_IMAGE"] = "EDIT_MODE_PRODUCT_IMAGE";
})(EditMode2 || (EditMode2 = {}));
var SegmentMode2;
(function(SegmentMode3) {
  SegmentMode3["FOREGROUND"] = "FOREGROUND";
  SegmentMode3["BACKGROUND"] = "BACKGROUND";
  SegmentMode3["PROMPT"] = "PROMPT";
  SegmentMode3["SEMANTIC"] = "SEMANTIC";
  SegmentMode3["INTERACTIVE"] = "INTERACTIVE";
})(SegmentMode2 || (SegmentMode2 = {}));
var VideoGenerationReferenceType2;
(function(VideoGenerationReferenceType3) {
  VideoGenerationReferenceType3["ASSET"] = "ASSET";
  VideoGenerationReferenceType3["STYLE"] = "STYLE";
})(VideoGenerationReferenceType2 || (VideoGenerationReferenceType2 = {}));
var VideoGenerationMaskMode2;
(function(VideoGenerationMaskMode3) {
  VideoGenerationMaskMode3["INSERT"] = "INSERT";
  VideoGenerationMaskMode3["REMOVE"] = "REMOVE";
  VideoGenerationMaskMode3["REMOVE_STATIC"] = "REMOVE_STATIC";
  VideoGenerationMaskMode3["OUTPAINT"] = "OUTPAINT";
})(VideoGenerationMaskMode2 || (VideoGenerationMaskMode2 = {}));
var VideoCompressionQuality2;
(function(VideoCompressionQuality3) {
  VideoCompressionQuality3["OPTIMIZED"] = "OPTIMIZED";
  VideoCompressionQuality3["LOSSLESS"] = "LOSSLESS";
})(VideoCompressionQuality2 || (VideoCompressionQuality2 = {}));
var TuningMethod2;
(function(TuningMethod3) {
  TuningMethod3["SUPERVISED_FINE_TUNING"] = "SUPERVISED_FINE_TUNING";
  TuningMethod3["PREFERENCE_TUNING"] = "PREFERENCE_TUNING";
})(TuningMethod2 || (TuningMethod2 = {}));
var DocumentState2;
(function(DocumentState3) {
  DocumentState3["STATE_UNSPECIFIED"] = "STATE_UNSPECIFIED";
  DocumentState3["STATE_PENDING"] = "STATE_PENDING";
  DocumentState3["STATE_ACTIVE"] = "STATE_ACTIVE";
  DocumentState3["STATE_FAILED"] = "STATE_FAILED";
})(DocumentState2 || (DocumentState2 = {}));
var FileState2;
(function(FileState3) {
  FileState3["STATE_UNSPECIFIED"] = "STATE_UNSPECIFIED";
  FileState3["PROCESSING"] = "PROCESSING";
  FileState3["ACTIVE"] = "ACTIVE";
  FileState3["FAILED"] = "FAILED";
})(FileState2 || (FileState2 = {}));
var FileSource2;
(function(FileSource3) {
  FileSource3["SOURCE_UNSPECIFIED"] = "SOURCE_UNSPECIFIED";
  FileSource3["UPLOADED"] = "UPLOADED";
  FileSource3["GENERATED"] = "GENERATED";
})(FileSource2 || (FileSource2 = {}));
var TurnCompleteReason2;
(function(TurnCompleteReason3) {
  TurnCompleteReason3["TURN_COMPLETE_REASON_UNSPECIFIED"] = "TURN_COMPLETE_REASON_UNSPECIFIED";
  TurnCompleteReason3["MALFORMED_FUNCTION_CALL"] = "MALFORMED_FUNCTION_CALL";
  TurnCompleteReason3["RESPONSE_REJECTED"] = "RESPONSE_REJECTED";
  TurnCompleteReason3["NEED_MORE_INPUT"] = "NEED_MORE_INPUT";
})(TurnCompleteReason2 || (TurnCompleteReason2 = {}));
var MediaModality2;
(function(MediaModality3) {
  MediaModality3["MODALITY_UNSPECIFIED"] = "MODALITY_UNSPECIFIED";
  MediaModality3["TEXT"] = "TEXT";
  MediaModality3["IMAGE"] = "IMAGE";
  MediaModality3["VIDEO"] = "VIDEO";
  MediaModality3["AUDIO"] = "AUDIO";
  MediaModality3["DOCUMENT"] = "DOCUMENT";
})(MediaModality2 || (MediaModality2 = {}));
var StartSensitivity2;
(function(StartSensitivity3) {
  StartSensitivity3["START_SENSITIVITY_UNSPECIFIED"] = "START_SENSITIVITY_UNSPECIFIED";
  StartSensitivity3["START_SENSITIVITY_HIGH"] = "START_SENSITIVITY_HIGH";
  StartSensitivity3["START_SENSITIVITY_LOW"] = "START_SENSITIVITY_LOW";
})(StartSensitivity2 || (StartSensitivity2 = {}));
var EndSensitivity2;
(function(EndSensitivity3) {
  EndSensitivity3["END_SENSITIVITY_UNSPECIFIED"] = "END_SENSITIVITY_UNSPECIFIED";
  EndSensitivity3["END_SENSITIVITY_HIGH"] = "END_SENSITIVITY_HIGH";
  EndSensitivity3["END_SENSITIVITY_LOW"] = "END_SENSITIVITY_LOW";
})(EndSensitivity2 || (EndSensitivity2 = {}));
var ActivityHandling2;
(function(ActivityHandling3) {
  ActivityHandling3["ACTIVITY_HANDLING_UNSPECIFIED"] = "ACTIVITY_HANDLING_UNSPECIFIED";
  ActivityHandling3["START_OF_ACTIVITY_INTERRUPTS"] = "START_OF_ACTIVITY_INTERRUPTS";
  ActivityHandling3["NO_INTERRUPTION"] = "NO_INTERRUPTION";
})(ActivityHandling2 || (ActivityHandling2 = {}));
var TurnCoverage2;
(function(TurnCoverage3) {
  TurnCoverage3["TURN_COVERAGE_UNSPECIFIED"] = "TURN_COVERAGE_UNSPECIFIED";
  TurnCoverage3["TURN_INCLUDES_ONLY_ACTIVITY"] = "TURN_INCLUDES_ONLY_ACTIVITY";
  TurnCoverage3["TURN_INCLUDES_ALL_INPUT"] = "TURN_INCLUDES_ALL_INPUT";
})(TurnCoverage2 || (TurnCoverage2 = {}));
var Scale2;
(function(Scale3) {
  Scale3["SCALE_UNSPECIFIED"] = "SCALE_UNSPECIFIED";
  Scale3["C_MAJOR_A_MINOR"] = "C_MAJOR_A_MINOR";
  Scale3["D_FLAT_MAJOR_B_FLAT_MINOR"] = "D_FLAT_MAJOR_B_FLAT_MINOR";
  Scale3["D_MAJOR_B_MINOR"] = "D_MAJOR_B_MINOR";
  Scale3["E_FLAT_MAJOR_C_MINOR"] = "E_FLAT_MAJOR_C_MINOR";
  Scale3["E_MAJOR_D_FLAT_MINOR"] = "E_MAJOR_D_FLAT_MINOR";
  Scale3["F_MAJOR_D_MINOR"] = "F_MAJOR_D_MINOR";
  Scale3["G_FLAT_MAJOR_E_FLAT_MINOR"] = "G_FLAT_MAJOR_E_FLAT_MINOR";
  Scale3["G_MAJOR_E_MINOR"] = "G_MAJOR_E_MINOR";
  Scale3["A_FLAT_MAJOR_F_MINOR"] = "A_FLAT_MAJOR_F_MINOR";
  Scale3["A_MAJOR_G_FLAT_MINOR"] = "A_MAJOR_G_FLAT_MINOR";
  Scale3["B_FLAT_MAJOR_G_MINOR"] = "B_FLAT_MAJOR_G_MINOR";
  Scale3["B_MAJOR_A_FLAT_MINOR"] = "B_MAJOR_A_FLAT_MINOR";
})(Scale2 || (Scale2 = {}));
var MusicGenerationMode2;
(function(MusicGenerationMode3) {
  MusicGenerationMode3["MUSIC_GENERATION_MODE_UNSPECIFIED"] = "MUSIC_GENERATION_MODE_UNSPECIFIED";
  MusicGenerationMode3["QUALITY"] = "QUALITY";
  MusicGenerationMode3["DIVERSITY"] = "DIVERSITY";
  MusicGenerationMode3["VOCALIZATION"] = "VOCALIZATION";
})(MusicGenerationMode2 || (MusicGenerationMode2 = {}));
var LiveMusicPlaybackControl2;
(function(LiveMusicPlaybackControl3) {
  LiveMusicPlaybackControl3["PLAYBACK_CONTROL_UNSPECIFIED"] = "PLAYBACK_CONTROL_UNSPECIFIED";
  LiveMusicPlaybackControl3["PLAY"] = "PLAY";
  LiveMusicPlaybackControl3["PAUSE"] = "PAUSE";
  LiveMusicPlaybackControl3["STOP"] = "STOP";
  LiveMusicPlaybackControl3["RESET_CONTEXT"] = "RESET_CONTEXT";
})(LiveMusicPlaybackControl2 || (LiveMusicPlaybackControl2 = {}));
var PagedItem2;
(function(PagedItem3) {
  PagedItem3["PAGED_ITEM_BATCH_JOBS"] = "batchJobs";
  PagedItem3["PAGED_ITEM_MODELS"] = "models";
  PagedItem3["PAGED_ITEM_TUNING_JOBS"] = "tuningJobs";
  PagedItem3["PAGED_ITEM_FILES"] = "files";
  PagedItem3["PAGED_ITEM_CACHED_CONTENTS"] = "cachedContents";
  PagedItem3["PAGED_ITEM_FILE_SEARCH_STORES"] = "fileSearchStores";
  PagedItem3["PAGED_ITEM_DOCUMENTS"] = "documents";
})(PagedItem2 || (PagedItem2 = {}));
var SDK_VERSION2 = "1.30.0";
var LIBRARY_LABEL2 = `google-genai-sdk/${SDK_VERSION2}`;
var MAX_CHUNK_SIZE2 = 1024 * 1024 * 8;

// packages/cli/src/services/McpPromptLoader.ts
init_esbuild_shims();
var McpPromptLoader = class {
  constructor(config2) {
    this.config = config2;
  }
  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 prompts3 = getMCPServerPrompts(this.config, serverName) || [];
      for (const prompt of prompts3) {
        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((_2) => `"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"]}`
                };
              }
              const firstMessage = result.messages?.[0];
              const content = firstMessage?.content;
              if (content?.type !== "text") {
                return {
                  type: "message",
                  messageType: "error",
                  content: "Received an empty or invalid prompt response from the server."
                };
              }
              return {
                type: "submit_prompt",
                content: JSON.stringify(content.text)
              };
            } catch (error2) {
              return {
                type: "message",
                messageType: "error",
                content: `Error: ${getErrorMessage(error2)}`
              };
            }
          }, "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 i3 = 0; i3 < unfilledArgs.length; i3++) {
        if (positionalArgs.length > i3) {
          promptInputs[unfilledArgs[i3].name] = positionalArgs[i3];
        } else {
          missingArgs.push(unfilledArgs[i3].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/ui/hooks/slashCommandProcessor.ts
var debugLogger110 = createDebugLogger("SLASH_COMMAND_PROCESSOR");
function serializeHistoryItemForRecording(item) {
  const clone4 = { ...item };
  if ("timestamp" in clone4 && clone4["timestamp"] instanceof Date) {
    clone4["timestamp"] = clone4["timestamp"].toISOString();
  }
  return clone4;
}
__name(serializeHistoryItemForRecording, "serializeHistoryItemForRecording");
var SLASH_COMMANDS_SKIP_RECORDING = /* @__PURE__ */ new Set([
  "quit",
  "exit",
  "clear",
  "reset",
  "new",
  "resume"
]);
var useSlashCommandProcessor = /* @__PURE__ */ __name((config2, settings, addItem, clearItems, loadHistory, refreshStatic, toggleVimEnabled, isProcessing, setIsProcessing, setGeminiMdFileCount, actions, extensionsUpdateState, isConfigInitialized, logger6) => {
  const { stats: sessionStats, startNewSession } = useSessionStats();
  const [commands, setCommands] = (0, import_react110.useState)([]);
  const [reloadTrigger, setReloadTrigger] = (0, import_react110.useState)(0);
  const reloadCommands = (0, import_react110.useCallback)(() => {
    setReloadTrigger((v2) => v2 + 1);
  }, []);
  const [shellConfirmationRequest, setShellConfirmationRequest] = (0, import_react110.useState)(null);
  const [confirmationRequest, setConfirmationRequest] = (0, import_react110.useState)(null);
  const [sessionShellAllowlist, setSessionShellAllowlist] = (0, import_react110.useState)(
    /* @__PURE__ */ new Set()
  );
  const gitService = (0, import_react110.useMemo)(() => {
    if (!config2?.getProjectRoot()) {
      return;
    }
    return new GitService(config2.getProjectRoot(), config2.storage);
  }, [config2]);
  const [pendingItem, setPendingItem] = (0, import_react110.useState)(
    null
  );
  const abortControllerRef = (0, import_react110.useRef)(null);
  const cancelSlashCommand = (0, import_react110.useCallback)(() => {
    if (!abortControllerRef.current) {
      return;
    }
    abortControllerRef.current.abort();
    addItem(
      {
        type: "info" /* INFO */,
        text: "Command cancelled."
      },
      Date.now()
    );
    setPendingItem(null);
    setIsProcessing(false);
  }, [addItem, setIsProcessing]);
  useKeypress(
    (key) => {
      if (key.name === "escape") {
        cancelSlashCommand();
      }
    },
    { isActive: isProcessing }
  );
  const pendingHistoryItems = (0, import_react110.useMemo)(() => {
    const items = [];
    if (pendingItem != null) {
      items.push(pendingItem);
    }
    return items;
  }, [pendingItem]);
  const addMessage = (0, import_react110.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 === "compression" /* COMPRESSION */) {
        historyItemContent = {
          type: "compression",
          compression: message.compression
        };
      } else if (message.type === "summary" /* SUMMARY */) {
        historyItemContent = {
          type: "summary",
          summary: message.summary
        };
      } else if (message.type === "insight_progress" /* INSIGHT_PROGRESS */) {
        historyItemContent = {
          type: "insight_progress",
          progress: message.progress
        };
      } else {
        historyItemContent = {
          type: message.type,
          text: message.content
        };
      }
      addItem(historyItemContent, message.timestamp.getTime());
    },
    [addItem]
  );
  const commandContext = (0, import_react110.useMemo)(
    () => ({
      services: {
        config: config2,
        settings,
        git: gitService,
        logger: logger6
      },
      ui: {
        addItem,
        clear: /* @__PURE__ */ __name(() => {
          clearItems();
          clearScreen2();
          refreshStatic();
        }, "clear"),
        loadHistory,
        setDebugMessage: actions.setDebugMessage,
        pendingItem,
        setPendingItem,
        toggleVimEnabled,
        setGeminiMdFileCount,
        reloadCommands,
        extensionsUpdateState,
        dispatchExtensionStateUpdate: actions.dispatchExtensionStateUpdate,
        addConfirmUpdateExtensionRequest: actions.addConfirmUpdateExtensionRequest
      },
      session: {
        stats: sessionStats,
        sessionShellAllowlist,
        startNewSession
      }
    }),
    [
      config2,
      settings,
      gitService,
      logger6,
      loadHistory,
      addItem,
      clearItems,
      refreshStatic,
      sessionStats,
      startNewSession,
      actions,
      pendingItem,
      setPendingItem,
      toggleVimEnabled,
      sessionShellAllowlist,
      setGeminiMdFileCount,
      reloadCommands,
      extensionsUpdateState
    ]
  );
  (0, import_react110.useEffect)(() => {
    if (!config2) {
      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);
      })();
    };
  }, [config2, reloadCommands]);
  (0, import_react110.useEffect)(() => {
    const controller = new AbortController();
    const load = /* @__PURE__ */ __name(async () => {
      const loaders = [
        new McpPromptLoader(config2),
        new BuiltinCommandLoader(config2),
        new FileCommandLoader(config2)
      ];
      const commandService = await CommandService.create(
        loaders,
        controller.signal
      );
      setCommands(commandService.getCommands());
    }, "load");
    load();
    return () => {
      controller.abort();
    };
  }, [config2, reloadTrigger, isConfigInitialized]);
  const handleSlashCommand2 = (0, import_react110.useCallback)(
    async (rawQuery, oneTimeShellAllowlist, overwriteConfirmed) => {
      if (typeof rawQuery !== "string") {
        return false;
      }
      const trimmed2 = rawQuery.trim();
      if (!trimmed2.startsWith("/") && !trimmed2.startsWith("?")) {
        return false;
      }
      const recordedItems = [];
      const recordItem = /* @__PURE__ */ __name((item) => {
        recordedItems.push(item);
      }, "recordItem");
      const addItemWithRecording = /* @__PURE__ */ __name((item, timestamp) => {
        recordItem(item);
        return addItem(item, timestamp);
      }, "addItemWithRecording");
      setIsProcessing(true);
      const abortController = new AbortController();
      abortControllerRef.current = abortController;
      const userMessageTimestamp = Date.now();
      addItemWithRecording(
        { 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,
              ui: {
                ...commandContext.ui,
                addItem: addItemWithRecording
              },
              invocation: {
                raw: trimmed2,
                name: commandToExecute.name,
                args
              },
              overwriteConfirmed,
              abortSignal: abortController.signal
            };
            if (oneTimeShellAllowlist && oneTimeShellAllowlist.size > 0) {
              fullCommandContext.session = {
                ...fullCommandContext.session,
                sessionShellAllowlist: /* @__PURE__ */ new Set([
                  ...fullCommandContext.session.sessionShellAllowlist,
                  ...oneTimeShellAllowlist
                ])
              };
            }
            const abortPromise = new Promise((resolve30) => {
              abortController.signal.addEventListener(
                "abort",
                () => resolve30(void 0),
                { once: true }
              );
            });
            const result = await Promise.race([
              commandToExecute.action(fullCommandContext, args),
              abortPromise
            ]);
            if (abortController.signal.aborted) {
              return { type: "handled" };
            }
            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 "resume":
                      actions.openResumeDialog();
                      return { type: "handled" };
                    case "help":
                      return { type: "handled" };
                    default: {
                      const unhandled = result.dialog;
                      throw new Error(
                        `Unhandled slash command result: ${unhandled}`
                      );
                    }
                  }
                case "load_history": {
                  config2?.getGeminiClient()?.setHistory(result.clientHistory);
                  config2?.getGeminiClient()?.stripThoughtsFromHistory();
                  fullCommandContext.ui.clear();
                  result.history.forEach((item, index) => {
                    fullCommandContext.ui.addItem(item, index);
                  });
                  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((resolve30) => {
                    setShellConfirmationRequest({
                      commands: result.commandsToConfirm,
                      onConfirm: /* @__PURE__ */ __name((resolvedOutcome, resolvedApprovedCommands) => {
                        setShellConfirmationRequest(null);
                        resolve30({
                          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((resolve30) => {
                    setConfirmationRequest({
                      prompt: result.prompt,
                      onConfirm: /* @__PURE__ */ __name((resolvedConfirmed) => {
                        setConfirmationRequest(null);
                        resolve30({ confirmed: resolvedConfirmed });
                      }, "onConfirm")
                    });
                  });
                  if (!confirmed) {
                    addItemWithRecording(
                      {
                        type: "info" /* INFO */,
                        text: "Operation cancelled."
                      },
                      Date.now()
                    );
                    return { type: "handled" };
                  }
                  return await handleSlashCommand2(
                    result.originalInvocation.raw,
                    void 0,
                    true
                  );
                }
                case "stream_messages": {
                  throw new Error(
                    "stream_messages result type is not supported in interactive mode"
                  );
                }
                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 (e4) {
        if (abortController.signal.aborted) {
          return { type: "handled" };
        }
        hasError = true;
        if (config2) {
          const event = makeSlashCommandEvent({
            command: resolvedCommandPath[0],
            subcommand,
            status: SlashCommandStatus.ERROR
          });
          logSlashCommand(config2, event);
        }
        addItemWithRecording(
          {
            type: "error" /* ERROR */,
            text: e4 instanceof Error ? e4.message : String(e4)
          },
          Date.now()
        );
        return { type: "handled" };
      } finally {
        if (config2?.getChatRecordingService) {
          const chatRecorder = config2.getChatRecordingService();
          const primaryCommand = resolvedCommandPath[0] || trimmed2.replace(/^[/?]/, "").split(/\s+/)[0] || trimmed2;
          const shouldRecord = !SLASH_COMMANDS_SKIP_RECORDING.has(primaryCommand);
          try {
            if (shouldRecord) {
              chatRecorder?.recordSlashCommand({
                phase: "invocation",
                rawCommand: trimmed2
              });
              const outputItems = recordedItems.filter((item) => item.type !== "user").map(serializeHistoryItemForRecording);
              chatRecorder?.recordSlashCommand({
                phase: "result",
                rawCommand: trimmed2,
                outputHistoryItems: outputItems
              });
            }
          } catch (recordError) {
            debugLogger110.error(
              "[slashCommand] Failed to record slash command:",
              recordError
            );
          }
        }
        if (config2 && resolvedCommandPath[0] && !hasError) {
          const event = makeSlashCommandEvent({
            command: resolvedCommandPath[0],
            subcommand,
            status: SlashCommandStatus.SUCCESS
          });
          logSlashCommand(config2, event);
        }
        setIsProcessing(false);
      }
    },
    [
      config2,
      addItem,
      actions,
      commands,
      commandContext,
      addMessage,
      setShellConfirmationRequest,
      setSessionShellAllowlist,
      setIsProcessing,
      setConfirmationRequest
    ]
  );
  return {
    handleSlashCommand: handleSlashCommand2,
    slashCommands: commands,
    pendingHistoryItems,
    commandContext,
    shellConfirmationRequest,
    confirmationRequest
  };
}, "useSlashCommandProcessor");

// packages/cli/src/ui/AppContainer.tsx
import * as fs109 from "node:fs";
import { basename as basename24 } 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_react111 = __toESM(require_react(), 1);
var useLogger = /* @__PURE__ */ __name((storage, sessionId) => {
  const [logger6, setLogger] = (0, import_react111.useState)(null);
  (0, import_react111.useEffect)(() => {
    if (!sessionId) {
      return;
    }
    const newLogger = new Logger(sessionId, storage);
    newLogger.initialize().then(() => {
      setLogger(newLogger);
    }).catch(() => {
    });
  }, [storage, sessionId]);
  return logger6;
}, "useLogger");

// packages/cli/src/ui/hooks/useGeminiStream.ts
init_esbuild_shims();
var import_react115 = __toESM(require_react(), 1);

// packages/cli/src/ui/hooks/shellCommandProcessor.ts
init_esbuild_shims();
var import_react112 = __toESM(require_react(), 1);
import crypto13 from "node:crypto";
import path110 from "node:path";
import os36 from "node:os";
import fs100 from "node:fs";
var OUTPUT_UPDATE_INTERVAL_MS2 = 1e3;
var MAX_OUTPUT_LENGTH = 1e4;
var debugLogger111 = createDebugLogger("SHELL_COMMAND_PROCESSOR");
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, config2, geminiClient, setShellInputFocused, terminalWidth, terminalHeight) => {
  const [activeShellPtyId, setActiveShellPtyId] = (0, import_react112.useState)(null);
  const handleShellCommand = (0, import_react112.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 isWindows9 = os36.platform() === "win32";
      const targetDir = config2.getTargetDir();
      let commandToExecute = rawQuery;
      let pwdFilePath;
      if (!isWindows9) {
        let command2 = rawQuery.trim();
        const pwdFileName = `shell_pwd_${crypto13.randomBytes(6).toString("hex")}.tmp`;
        pwdFilePath = path110.join(os36.tmpdir(), pwdFileName);
        if (!command2.endsWith(";") && !command2.endsWith("&")) {
          command2 += ";";
        }
        commandToExecute = `{ ${command2} }; __code=$?; pwd > "${pwdFilePath}"; exit $__code`;
      }
      const executeCommand = /* @__PURE__ */ __name(async (resolve30) => {
        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 = {
            ...config2.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 (config2.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,
            config2.getShouldUseNodePtyShell(),
            shellExecutionConfig
          );
          debugLogger111.debug(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 && fs100.existsSync(pwdFilePath)) {
              const finalPwd = fs100.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 && fs100.existsSync(pwdFilePath)) {
              fs100.unlinkSync(pwdFilePath);
            }
            setActiveShellPtyId(null);
            setShellInputFocused(false);
            resolve30();
          });
        } 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 && fs100.existsSync(pwdFilePath)) {
            fs100.unlinkSync(pwdFilePath);
          }
          setActiveShellPtyId(null);
          setShellInputFocused(false);
          resolve30();
        }
      }, "executeCommand");
      const execPromise = new Promise((resolve30) => {
        executeCommand(resolve30);
      });
      onExec(execPromise);
      return true;
    },
    [
      config2,
      onDebugMessage,
      addItemToHistory,
      setPendingHistoryItem,
      onExec,
      geminiClient,
      setShellInputFocused,
      terminalHeight,
      terminalWidth
    ]
  );
  return { handleShellCommand, activeShellPtyId };
}, "useShellCommandProcessor");

// 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);
var debugLogger112 = createDebugLogger("REACT_TOOL_SCHEDULER");
function useReactToolScheduler(onComplete, config2, 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({
      config: config2,
      chatRecordingService: config2.getChatRecordingService(),
      outputUpdateHandler,
      onAllToolCallsComplete: allToolCallsCompleteHandler,
      onToolCallsUpdate: toolCallsUpdateHandler,
      getPreferredEditor,
      onEditorClose
    }),
    [
      config2,
      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;
      debugLogger112.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 fs101 } from "node:fs";
import path111 from "node:path";
var debugLogger113 = createDebugLogger("GEMINI_STREAM");
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");
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, config2, settings, onDebugMessage, handleSlashCommand2, shellModeActive, getPreferredEditor, onAuthError, performMemoryRefresh, modelSwitchedFromQuotaError, setModelSwitchedFromQuotaError, onEditorClose, onCancelSubmit, setShellInputFocused, terminalWidth, terminalHeight) => {
  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 [pendingRetryErrorItem, setPendingRetryErrorItem] = (0, import_react115.useState)(null);
  const [
    pendingRetryCountdownItem,
    pendingRetryCountdownItemRef,
    setPendingRetryCountdownItem
  ] = useStateAndRef(null);
  const retryCountdownTimerRef = (0, import_react115.useRef)(
    null
  );
  const processedMemoryToolsRef = (0, import_react115.useRef)(/* @__PURE__ */ new Set());
  const {
    startNewPrompt,
    getPromptCount,
    stats: sessionStates
  } = useSessionStats();
  const storage = config2.storage;
  const logger6 = useLogger(storage, sessionStates.sessionId);
  const gitService = (0, import_react115.useMemo)(() => {
    if (!config2.getProjectRoot()) {
      return;
    }
    return new GitService(config2.getProjectRoot(), storage);
  }, [config2, storage]);
  const [toolCalls, scheduleToolCalls, markToolsAsSubmitted] = useReactToolScheduler(
    async (completedToolCallsFromScheduler) => {
      if (completedToolCallsFromScheduler.length > 0) {
        addItem(
          mapToDisplay(
            completedToolCallsFromScheduler
          ),
          Date.now()
        );
        await handleCompletedTools(
          completedToolCallsFromScheduler
        );
      }
    },
    config2,
    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 stopRetryCountdownTimer = (0, import_react115.useCallback)(() => {
    if (retryCountdownTimerRef.current) {
      clearInterval(retryCountdownTimerRef.current);
      retryCountdownTimerRef.current = null;
    }
  }, []);
  const clearRetryCountdown = (0, import_react115.useCallback)(() => {
    stopRetryCountdownTimer();
    setPendingRetryErrorItem(null);
    setPendingRetryCountdownItem(null);
  }, [setPendingRetryCountdownItem, stopRetryCountdownTimer]);
  const startRetryCountdown = (0, import_react115.useCallback)(
    (retryInfo) => {
      stopRetryCountdownTimer();
      const startTime = Date.now();
      const { message, attempt, maxRetries, delayMs } = retryInfo;
      const retryReasonText = message ?? t4("Rate limit exceeded. Please wait and try again.");
      setPendingRetryErrorItem({
        type: "error" /* ERROR */,
        text: retryReasonText
      });
      const updateCountdown = /* @__PURE__ */ __name(() => {
        const elapsedMs = Date.now() - startTime;
        const remainingMs = Math.max(0, delayMs - elapsedMs);
        const remainingSec = Math.ceil(remainingMs / 1e3);
        setPendingRetryCountdownItem({
          type: "retry_countdown",
          text: t4(
            "Retrying in {{seconds}} seconds\u2026 (attempt {{attempt}}/{{maxRetries}})",
            {
              seconds: String(remainingSec),
              attempt: String(attempt),
              maxRetries: String(maxRetries)
            }
          )
        });
        if (remainingMs <= 0) {
          stopRetryCountdownTimer();
        }
      }, "updateCountdown");
      updateCountdown();
      retryCountdownTimerRef.current = setInterval(updateCountdown, 1e3);
    },
    [setPendingRetryCountdownItem, stopRetryCountdownTimer]
  );
  (0, import_react115.useEffect)(() => () => stopRetryCountdownTimer(), [stopRetryCountdownTimer]);
  const onExec = (0, import_react115.useCallback)(async (done) => {
    setIsResponding(true);
    await done;
    setIsResponding(false);
  }, []);
  const { handleShellCommand, activeShellPtyId } = useShellCommandProcessor(
    addItem,
    setPendingHistoryItem,
    onExec,
    onDebugMessage,
    config2,
    geminiClient,
    setShellInputFocused,
    terminalWidth,
    terminalHeight
  );
  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 (config2.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(
          config2,
          new ConversationFinishedEvent(config2.getApprovalMode(), turnCount)
        );
      }
    }
  }, [streamingState, config2, 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 = config2.getSessionId() + "########" + getPromptCount();
    const cancellationEvent = new ApiCancelEvent(
      config2.getModel(),
      prompt_id,
      config2.getContentGeneratorConfig()?.authType
    );
    logApiCancel(config2, cancellationEvent);
    if (pendingHistoryItemRef.current) {
      addItem(pendingHistoryItemRef.current, Date.now());
    }
    addItem(
      {
        type: "info" /* INFO */,
        text: "Request cancelled."
      },
      Date.now()
    );
    setPendingHistoryItem(null);
    clearRetryCountdown();
    onCancelSubmit();
    setIsResponding(false);
    setShellInputFocused(false);
  }, [
    streamingState,
    addItem,
    setPendingHistoryItem,
    onCancelSubmit,
    pendingHistoryItemRef,
    setShellInputFocused,
    clearRetryCountdown,
    config2,
    getPromptCount
  ]);
  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(`Received user query (${trimmedQuery.length} chars)`);
        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 };
        }
        localQueryToSendToGemini = trimmedQuery;
        addItem(
          { type: "user" /* USER */, text: trimmedQuery },
          userMessageTimestamp
        );
        if (isAtCommand(trimmedQuery)) {
          const atCommandResult = await handleAtCommand({
            query: trimmedQuery,
            config: config2,
            onDebugMessage,
            messageId: userMessageTimestamp,
            signal: abortSignal,
            addItem
          });
          if (!atCommandResult.shouldProceed) {
            return { queryToSend: null, shouldProceed: false };
          }
          localQueryToSendToGemini = atCommandResult.processedQuery;
        }
      } 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 };
    },
    [
      config2,
      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 mergeThought = (0, import_react115.useCallback)(
    (incoming) => {
      setThought((prev) => {
        if (!prev) {
          return incoming;
        }
        const subject = incoming.subject || prev.subject;
        const description = `${prev.description ?? ""}${incoming.description ?? ""}`;
        return { subject, description };
      });
    },
    [setThought]
  );
  const handleThoughtEvent = (0, import_react115.useCallback)(
    (eventValue, currentThoughtBuffer, userMessageTimestamp) => {
      if (turnCancelledRef.current) {
        return "";
      }
      const thoughtText = eventValue.description ?? "";
      if (!thoughtText) {
        return currentThoughtBuffer;
      }
      let newThoughtBuffer = currentThoughtBuffer + thoughtText;
      const pendingType = pendingHistoryItemRef.current?.type;
      const isPendingThought = pendingType === "gemini_thought" || pendingType === "gemini_thought_content";
      if (!isPendingThought) {
        if (pendingHistoryItemRef.current) {
          addItem(pendingHistoryItemRef.current, userMessageTimestamp);
        }
        setPendingHistoryItem({ type: "gemini_thought", text: "" });
      }
      const splitPoint = findLastSafeSplitPoint(newThoughtBuffer);
      const nextPendingType = isPendingThought && pendingType === "gemini_thought_content" ? "gemini_thought_content" : "gemini_thought";
      if (splitPoint === newThoughtBuffer.length) {
        setPendingHistoryItem({
          type: nextPendingType,
          text: newThoughtBuffer
        });
      } else {
        const beforeText = newThoughtBuffer.substring(0, splitPoint);
        const afterText = newThoughtBuffer.substring(splitPoint);
        addItem(
          {
            type: nextPendingType,
            text: beforeText
          },
          userMessageTimestamp
        );
        setPendingHistoryItem({
          type: "gemini_thought_content",
          text: afterText
        });
        newThoughtBuffer = afterText;
      }
      mergeThought(eventValue);
      return newThoughtBuffer;
    },
    [addItem, pendingHistoryItemRef, setPendingHistoryItem, mergeThought]
  );
  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
      );
      clearRetryCountdown();
      setIsResponding(false);
      setThought(null);
    },
    [
      addItem,
      pendingHistoryItemRef,
      setPendingHistoryItem,
      setThought,
      clearRetryCountdown
    ]
  );
  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,
            config2.getContentGeneratorConfig()?.authType
          )
        },
        userMessageTimestamp
      );
      clearRetryCountdown();
      setThought(null);
    },
    [
      addItem,
      pendingHistoryItemRef,
      setPendingHistoryItem,
      config2,
      setThought,
      clearRetryCountdown
    ]
  );
  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 = {
        [FinishReason2.FINISH_REASON_UNSPECIFIED]: void 0,
        [FinishReason2.STOP]: void 0,
        [FinishReason2.MAX_TOKENS]: "Response truncated due to token limits.",
        [FinishReason2.SAFETY]: "Response stopped due to safety reasons.",
        [FinishReason2.RECITATION]: "Response stopped due to recitation policy.",
        [FinishReason2.LANGUAGE]: "Response stopped due to unsupported language.",
        [FinishReason2.BLOCKLIST]: "Response stopped due to forbidden terms.",
        [FinishReason2.PROHIBITED_CONTENT]: "Response stopped due to prohibited content.",
        [FinishReason2.SPII]: "Response stopped due to sensitive personally identifiable information.",
        [FinishReason2.OTHER]: "Response stopped for other reasons.",
        [FinishReason2.MALFORMED_FUNCTION_CALL]: "Response stopped due to malformed function call.",
        [FinishReason2.IMAGE_SAFETY]: "Response stopped due to image safety violations.",
        [FinishReason2.UNEXPECTED_TOOL_CALL]: "Response stopped due to unexpected tool call.",
        [FinishReason2.IMAGE_PROHIBITED_CONTENT]: "Response stopped due to image prohibited content.",
        [FinishReason2.NO_IMAGE]: "Response stopped due to no image."
      };
      const message = finishReasonMessages[finishReason];
      if (message) {
        addItem(
          {
            type: "info",
            text: `\u26A0\uFE0F  ${message}`
          },
          userMessageTimestamp
        );
      }
      clearRetryCountdown();
    },
    [addItem, clearRetryCountdown]
  );
  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 ${config2.getModel()}. A compressed context will be sent for future messages (compressed from: ${eventValue?.originalTokenCount ?? "unknown"} to ${eventValue?.newTokenCount ?? "unknown"} tokens).`
        },
        Date.now()
      );
    },
    [addItem, config2, pendingHistoryItemRef, setPendingHistoryItem]
  );
  const handleMaxSessionTurnsEvent = (0, import_react115.useCallback)(
    () => addItem(
      {
        type: "info",
        text: `The session has reached the maximum number of turns: ${config2.getMaxSessionTurns()}. Please update this limit in your setting.json file.`
      },
      Date.now()
    ),
    [addItem, config2]
  );
  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") {
        config2.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()
        );
      }
    },
    [config2, addItem]
  );
  const handleLoopDetectedEvent = (0, import_react115.useCallback)(() => {
    setLoopDetectionConfirmationRequest({
      onComplete: handleLoopDetectionConfirmation
    });
  }, [handleLoopDetectionConfirmation]);
  const processGeminiStreamEvents = (0, import_react115.useCallback)(
    async (stream2, userMessageTimestamp, signal) => {
      let geminiMessageBuffer = "";
      let thoughtBuffer = "";
      const toolCallRequests = [];
      for await (const event of stream2) {
        switch (event.type) {
          case GeminiEventType.Thought:
            if (event.value.subject) {
              setThought(event.value);
            } else {
              thoughtBuffer = handleThoughtEvent(
                event.value,
                thoughtBuffer,
                userMessageTimestamp
              );
            }
            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:
            if (pendingHistoryItemRef.current) {
              setPendingHistoryItem(null);
            }
            if (event.retryInfo) {
              startRetryCountdown(event.retryInfo);
            } else if (!pendingRetryCountdownItemRef.current) {
              clearRetryCountdown();
            }
            break;
          default: {
            const unreachable = event;
            return unreachable;
          }
        }
      }
      if (toolCallRequests.length > 0) {
        scheduleToolCalls(toolCallRequests, signal);
      }
      return 0 /* Completed */;
    },
    [
      handleContentEvent,
      handleThoughtEvent,
      handleUserCancelledEvent,
      handleErrorEvent,
      scheduleToolCalls,
      handleChatCompressionEvent,
      handleFinishedEvent,
      handleMaxSessionTurnsEvent,
      handleSessionTokenLimitExceededEvent,
      handleCitationEvent,
      startRetryCountdown,
      clearRetryCountdown,
      setThought,
      pendingHistoryItemRef,
      setPendingHistoryItem,
      pendingRetryCountdownItemRef
    ]
  );
  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);
      }
      abortControllerRef.current = new AbortController();
      const abortSignal = abortControllerRef.current.signal;
      turnCancelledRef.current = false;
      if (!prompt_id) {
        prompt_id = config2.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;
        }
        if (!options2?.isContinuation) {
          const formatCheck = checkImageFormatsSupport(queryToSend);
          if (formatCheck.hasUnsupportedFormats) {
            addItem(
              {
                type: "info" /* INFO */,
                text: getUnsupportedImageFormatWarning()
              },
              userMessageTimestamp
            );
          }
        }
        const finalQueryToSend = queryToSend;
        if (!options2?.isContinuation) {
          startNewPrompt();
          if (typeof queryToSend === "string") {
            logUserPrompt(
              config2,
              new UserPromptEvent(
                queryToSend.length,
                prompt_id,
                config2.getContentGeneratorConfig()?.authType,
                queryToSend
              )
            );
          }
          setThought(null);
        }
        setIsResponding(true);
        setInitError(null);
        try {
          const stream2 = geminiClient.sendMessageStream(
            finalQueryToSend,
            abortSignal,
            prompt_id,
            options2
          );
          const processingStatus = await processGeminiStreamEvents(
            stream2,
            userMessageTimestamp,
            abortSignal
          );
          if (processingStatus === 1 /* UserCancelled */) {
            isSubmittingQueryRef.current = false;
            return;
          }
          if (pendingHistoryItemRef.current) {
            addItem(pendingHistoryItemRef.current, userMessageTimestamp);
            setPendingHistoryItem(null);
          }
          if (loopDetectedRef.current) {
            loopDetectedRef.current = false;
            handleLoopDetectedEvent();
          }
        } catch (error2) {
          if (error2 instanceof UnauthorizedError) {
            onAuthError("Session expired or is unauthorized.");
          } else if (!isNodeError(error2) || error2.name !== "AbortError") {
            addItem(
              {
                type: "error" /* ERROR */,
                text: parseAndFormatApiError(
                  getErrorMessage(error2) || "Unknown error",
                  config2.getContentGeneratorConfig()?.authType
                )
              },
              userMessageTimestamp
            );
          }
        } finally {
          setIsResponding(false);
          isSubmittingQueryRef.current = false;
        }
      });
    },
    [
      streamingState,
      setModelSwitchedFromQuotaError,
      prepareQueryForGemini,
      processGeminiStreamEvents,
      pendingHistoryItemRef,
      addItem,
      setPendingHistoryItem,
      setInitError,
      geminiClient,
      onAuthError,
      config2,
      startNewPrompt,
      getPromptCount,
      handleLoopDetectedEvent
    ]
  );
  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 (error2) {
              debugLogger113.error(
                `Failed to auto-approve tool call ${call.request.callId}:`,
                error2
              );
            }
          }
        }
      }
    },
    [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(
        (t5) => t5.request.isClientInitiated
      );
      if (clientTools.length > 0) {
        markToolsAsSubmitted(clientTools.map((t5) => t5.request.callId));
      }
      const newSuccessfulMemorySaves = completedAndReadyToSubmitTools.filter(
        (t5) => t5.request.name === "save_memory" && t5.status === "success" && !processedMemoryToolsRef.current.has(t5.request.callId)
      );
      if (newSuccessfulMemorySaves.length > 0) {
        void performMemoryRefresh();
        newSuccessfulMemorySaves.forEach(
          (t5) => processedMemoryToolsRef.current.add(t5.request.callId)
        );
      }
      const geminiTools = completedAndReadyToSubmitTools.filter(
        (t5) => !t5.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,
      pendingRetryErrorItem,
      pendingRetryCountdownItem,
      pendingToolCallGroupDisplay
    ].filter((i3) => i3 !== void 0 && i3 !== null),
    [
      pendingHistoryItem,
      pendingRetryErrorItem,
      pendingRetryCountdownItem,
      pendingToolCallGroupDisplay
    ]
  );
  (0, import_react115.useEffect)(() => {
    const saveRestorableToolCalls = /* @__PURE__ */ __name(async () => {
      if (!config2.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 fs101.mkdir(checkpointDir, { recursive: true });
        } catch (error2) {
          if (!isNodeError(error2) || error2.code !== "EEXIST") {
            onDebugMessage(
              `Failed to create checkpoint directory: ${getErrorMessage(error2)}`
            );
            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 (error2) {
              onDebugMessage(
                `Failed to create new snapshot: ${getErrorMessage(error2)}. 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 = path111.basename(filePath);
            const toolCallWithSnapshotFileName = `${timestamp}-${fileName}-${toolName}.json`;
            const clientHistory = await geminiClient?.getHistory();
            const toolCallWithSnapshotFilePath = path111.join(
              checkpointDir,
              toolCallWithSnapshotFileName
            );
            await fs101.writeFile(
              toolCallWithSnapshotFilePath,
              JSON.stringify(
                {
                  history,
                  clientHistory,
                  toolCall: {
                    name: toolCall.request.name,
                    args: toolCall.request.args
                  },
                  commitHash,
                  filePath
                },
                null,
                2
              )
            );
          } catch (error2) {
            onDebugMessage(
              `Failed to create checkpoint for ${filePath}: ${getErrorMessage(
                error2
              )}. This may indicate a problem with Git or file system permissions.`
            );
          }
        }
      }
    }, "saveRestorableToolCalls");
    saveRestorableToolCalls();
  }, [
    toolCalls,
    config2,
    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 debugLogger114 = createDebugLogger("VIM_MODE");
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.meta) && 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 (error2) {
        debugLogger114.warn("Malformed key input in vim mode:", key, error2);
        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/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"];
var PHRASE_CHANGE_INTERVAL_MS = 15e3;
var usePhraseCycler = /* @__PURE__ */ __name((isActive, isWaiting, customPhrases) => {
  const loadingPhrases = (0, import_react119.useMemo)(() => {
    if (customPhrases && customPhrases.length > 0) {
      return customPhrases;
    }
    const translatedPhrases = ta("WITTY_LOADING_PHRASES");
    return translatedPhrases.length > 0 ? translatedPhrases : WITTY_LOADING_PHRASES;
  }, [customPhrases]);
  const [currentLoadingPhrase, setCurrentLoadingPhrase] = (0, import_react119.useState)(
    loadingPhrases[0]
  );
  const phraseIntervalRef = (0, import_react119.useRef)(null);
  (0, import_react119.useEffect)(() => {
    if (isWaiting) {
      setCurrentLoadingPhrase(t4("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/hooks/useCommandMigration.ts
init_esbuild_shims();
var import_react122 = __toESM(require_react(), 1);

// packages/cli/src/services/command-migration-tool.ts
init_esbuild_shims();
init_esm11();
import { promises as fs102 } from "node:fs";
import path112 from "node:path";
async function detectTomlCommands(commandDir) {
  try {
    await fs102.access(commandDir);
  } catch {
    return [];
  }
  const tomlFiles = await glob("**/*.toml", {
    cwd: commandDir,
    nodir: true,
    dot: false
  });
  return tomlFiles;
}
__name(detectTomlCommands, "detectTomlCommands");
async function migrateTomlCommands(options2) {
  const { commandDir, createBackup = true, deleteOriginal = false } = options2;
  const result = {
    success: true,
    convertedFiles: [],
    failedFiles: []
  };
  const tomlFiles = await detectTomlCommands(commandDir);
  if (tomlFiles.length === 0) {
    return result;
  }
  for (const relativeFile of tomlFiles) {
    const tomlPath = path112.join(commandDir, relativeFile);
    try {
      const tomlContent = await fs102.readFile(tomlPath, "utf-8");
      const markdownContent = convertTomlToMarkdown(tomlContent);
      const markdownPath = tomlPath.replace(/\.toml$/, ".md");
      try {
        await fs102.access(markdownPath);
        throw new Error(
          t4("Markdown file already exists: {{filename}}", {
            filename: path112.basename(markdownPath)
          })
        );
      } catch (error2) {
        if (error2.code !== "ENOENT") {
          throw error2;
        }
      }
      await fs102.writeFile(markdownPath, markdownContent, "utf-8");
      if (createBackup) {
        const backupPath = `${tomlPath}.backup`;
        await fs102.rename(tomlPath, backupPath);
      } else if (deleteOriginal) {
        await fs102.unlink(tomlPath);
      }
      result.convertedFiles.push(relativeFile);
    } catch (error2) {
      result.success = false;
      result.failedFiles.push({
        file: relativeFile,
        error: error2 instanceof Error ? error2.message : String(error2)
      });
    }
  }
  return result;
}
__name(migrateTomlCommands, "migrateTomlCommands");

// packages/cli/src/ui/hooks/useCommandMigration.ts
function useCommandMigration(settings, storage) {
  const [showMigrationNudge, setShowMigrationNudge] = (0, import_react122.useState)(false);
  const [tomlFiles, setTomlFiles] = (0, import_react122.useState)([]);
  (0, import_react122.useEffect)(() => {
    const checkTomlCommands = /* @__PURE__ */ __name(async () => {
      const allFiles = [];
      const workspaceCommandsDir = storage.getProjectCommandsDir();
      const workspaceFiles = await detectTomlCommands(workspaceCommandsDir);
      allFiles.push(...workspaceFiles.map((f5) => `workspace: ${f5}`));
      const userCommandsDir = Storage.getUserCommandsDir();
      const userFiles = await detectTomlCommands(userCommandsDir);
      allFiles.push(...userFiles.map((f5) => `user: ${f5}`));
      if (allFiles.length > 0) {
        setTomlFiles(allFiles);
        setShowMigrationNudge(true);
      }
    }, "checkTomlCommands");
    checkTomlCommands();
  }, [storage]);
  return {
    showMigrationNudge,
    tomlFiles,
    setShowMigrationNudge
  };
}
__name(useCommandMigration, "useCommandMigration");

// 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 spawn9 } from "node:child_process";
import { fileURLToPath as fileURLToPath15 } from "node:url";
import path120 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 path116 from "node:path";
import os39 from "node:os";

// node_modules/xdg-basedir/index.js
init_esbuild_shims();
import os37 from "os";
import path113 from "path";
var homeDirectory = os37.homedir();
var { env: env5 } = process;
var xdgData = env5.XDG_DATA_HOME || (homeDirectory ? path113.join(homeDirectory, ".local", "share") : void 0);
var xdgConfig = env5.XDG_CONFIG_HOME || (homeDirectory ? path113.join(homeDirectory, ".config") : void 0);
var xdgState = env5.XDG_STATE_HOME || (homeDirectory ? path113.join(homeDirectory, ".local", "state") : void 0);
var xdgCache = env5.XDG_CACHE_HOME || (homeDirectory ? path113.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 path115 from "node:path";

// node_modules/stubborn-fs/dist/index.js
init_esbuild_shims();
import fs103 from "node:fs";
import { promisify as promisify11 } 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 (error2) {
      return onError2(error2);
    }
  }, "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((error2) => {
    if (!Handlers.isNodeError(error2))
      return false;
    const { code: code2 } = error2;
    if (code2 === "ENOSYS")
      return true;
    if (!IS_USER_ROOT && (code2 === "EINVAL" || code2 === "EPERM"))
      return true;
    return false;
  }, "isChangeErrorOk"),
  isNodeError: /* @__PURE__ */ __name((error2) => {
    return error2 instanceof Error;
  }, "isNodeError"),
  isRetriableError: /* @__PURE__ */ __name((error2) => {
    if (!Handlers.isNodeError(error2))
      return false;
    const { code: code2 } = error2;
    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((error2) => {
    if (!Handlers.isNodeError(error2))
      throw error2;
    if (Handlers.isChangeErrorOk(error2))
      return;
    throw error2;
  }, "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((resolve30) => {
        const cleanup = /* @__PURE__ */ __name(() => this.remove(resolver), "cleanup");
        const resolver = /* @__PURE__ */ __name(() => resolve30(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((error2) => {
          cleanup();
          if (Date.now() >= timestamp)
            throw error2;
          if (isRetriableError(error2)) {
            const delay4 = Math.round(100 * Math.random());
            const delayPromise = new Promise((resolve30) => setTimeout(resolve30, delay4));
            return delayPromise.then(() => attempt.apply(void 0, args));
          }
          throw error2;
        }, "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 (error2) {
        if (Date.now() > timestamp)
          throw error2;
        if (isRetriableError(error2))
          return attempt.apply(void 0, args);
        throw error2;
      }
    }, "attempt");
  }, "retrified");
}, "retryifySync");

// node_modules/stubborn-fs/dist/index.js
var FS = {
  attempt: {
    /* ASYNC */
    chmod: attemptifyAsync(promisify11(fs103.chmod), handlers_default.onChangeError),
    chown: attemptifyAsync(promisify11(fs103.chown), handlers_default.onChangeError),
    close: attemptifyAsync(promisify11(fs103.close), NOOP2),
    fsync: attemptifyAsync(promisify11(fs103.fsync), NOOP2),
    mkdir: attemptifyAsync(promisify11(fs103.mkdir), NOOP2),
    realpath: attemptifyAsync(promisify11(fs103.realpath), NOOP2),
    stat: attemptifyAsync(promisify11(fs103.stat), NOOP2),
    unlink: attemptifyAsync(promisify11(fs103.unlink), NOOP2),
    /* SYNC */
    chmodSync: attemptifySync(fs103.chmodSync, handlers_default.onChangeError),
    chownSync: attemptifySync(fs103.chownSync, handlers_default.onChangeError),
    closeSync: attemptifySync(fs103.closeSync, NOOP2),
    existsSync: attemptifySync(fs103.existsSync, NOOP2),
    fsyncSync: attemptifySync(fs103.fsync, NOOP2),
    mkdirSync: attemptifySync(fs103.mkdirSync, NOOP2),
    realpathSync: attemptifySync(fs103.realpathSync, NOOP2),
    statSync: attemptifySync(fs103.statSync, NOOP2),
    unlinkSync: attemptifySync(fs103.unlinkSync, NOOP2)
  },
  retry: {
    /* ASYNC */
    close: retryifyAsync(promisify11(fs103.close), handlers_default.isRetriableError),
    fsync: retryifyAsync(promisify11(fs103.fsync), handlers_default.isRetriableError),
    open: retryifyAsync(promisify11(fs103.open), handlers_default.isRetriableError),
    readFile: retryifyAsync(promisify11(fs103.readFile), handlers_default.isRetriableError),
    rename: retryifyAsync(promisify11(fs103.rename), handlers_default.isRetriableError),
    stat: retryifyAsync(promisify11(fs103.stat), handlers_default.isRetriableError),
    write: retryifyAsync(promisify11(fs103.write), handlers_default.isRetriableError),
    writeFile: retryifyAsync(promisify11(fs103.writeFile), handlers_default.isRetriableError),
    /* SYNC */
    closeSync: retryifySync(fs103.closeSync, handlers_default.isRetriableError),
    fsyncSync: retryifySync(fs103.fsyncSync, handlers_default.isRetriableError),
    openSync: retryifySync(fs103.openSync, handlers_default.isRetriableError),
    readFileSync: retryifySync(fs103.readFileSync, handlers_default.isRetriableError),
    renameSync: retryifySync(fs103.renameSync, handlers_default.isRetriableError),
    statSync: retryifySync(fs103.statSync, handlers_default.isRetriableError),
    writeSync: retryifySync(fs103.writeSync, handlers_default.isRetriableError),
    writeFileSync: retryifySync(fs103.writeFileSync, handlers_default.isRetriableError)
  }
};
var dist_default7 = FS;

// node_modules/atomically/dist/constants.js
init_esbuild_shims();
import os38 from "node:os";
import process40 from "node:process";
var DEFAULT_ENCODING = "utf8";
var DEFAULT_FILE_MODE = 438;
var DEFAULT_FOLDER_MODE = 511;
var DEFAULT_WRITE_OPTIONS = {};
var DEFAULT_USER_UID = os38.userInfo().uid;
var DEFAULT_USER_GID = os38.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 path114 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_default7.attempt.unlink(filePath);
  }, "purge"),
  purgeSync: /* @__PURE__ */ __name((filePath) => {
    if (!Temp.store[filePath])
      return;
    delete Temp.store[filePath];
    dist_default7.attempt.unlinkSync(filePath);
  }, "purgeSync"),
  purgeSyncAll: /* @__PURE__ */ __name(() => {
    for (const filePath in Temp.store) {
      Temp.purgeSync(filePath);
    }
  }, "purgeSyncAll"),
  truncate: /* @__PURE__ */ __name((filePath) => {
    const basename26 = path114.basename(filePath);
    if (basename26.length <= LIMIT_BASENAME_LENGTH)
      return filePath;
    const truncable = /^(\.?)(.*?)((?:\.[^.]+)?(?:\.tmp-\d{10}[a-f0-9]{6})?)$/.exec(basename26);
    if (!truncable)
      return filePath;
    const truncationLength = basename26.length - LIMIT_BASENAME_LENGTH;
    return `${filePath.slice(0, -basename26.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 writeFileSync11(filePath, data, options2 = DEFAULT_WRITE_OPTIONS) {
  if (isString(options2))
    return writeFileSync11(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_default7.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_default7.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 = path115.dirname(filePath);
      dist_default7.attempt.mkdirSync(parentPath, {
        mode: DEFAULT_FOLDER_MODE,
        recursive: true
      });
    }
    fd = dist_default7.retry.openSync(timeout2)(tempPath, "w", options2.mode || DEFAULT_FILE_MODE);
    if (options2.tmpCreated) {
      options2.tmpCreated(tempPath);
    }
    if (isString(data)) {
      dist_default7.retry.writeSync(timeout2)(fd, data, 0, options2.encoding || DEFAULT_ENCODING);
    } else if (!isUndefined(data)) {
      dist_default7.retry.writeSync(timeout2)(fd, data, 0, data.length, 0);
    }
    if (options2.fsync !== false) {
      if (options2.fsyncWait !== false) {
        dist_default7.retry.fsyncSync(timeout2)(fd);
      } else {
        dist_default7.attempt.fsync(fd);
      }
    }
    dist_default7.retry.closeSync(timeout2)(fd);
    fd = null;
    if (options2.chown && (options2.chown.uid !== DEFAULT_USER_UID || options2.chown.gid !== DEFAULT_USER_GID)) {
      dist_default7.attempt.chownSync(tempPath, options2.chown.uid, options2.chown.gid);
    }
    if (options2.mode && options2.mode !== DEFAULT_FILE_MODE) {
      dist_default7.attempt.chmodSync(tempPath, options2.mode);
    }
    try {
      dist_default7.retry.renameSync(timeout2)(tempPath, filePath);
    } catch (error2) {
      if (!isException(error2))
        throw error2;
      if (error2.code !== "ENAMETOOLONG")
        throw error2;
      dist_default7.retry.renameSync(timeout2)(tempPath, temp_default.truncate(filePath));
    }
    tempDisposer();
    tempPath = null;
  } finally {
    if (fd)
      dist_default7.attempt.closeSync(fd);
    if (tempPath)
      temp_default.purge(tempPath);
  }
}
__name(writeFileSync11, "writeFileSync");

// node_modules/dot-prop/index.js
init_esbuild_shims();
var isObject2 = /* @__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(path125) {
  const parts = [];
  let currentSegment = "";
  let currentPart = "start";
  let isIgnoring = false;
  for (const character of path125) {
    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(object3, key) {
  if (typeof key !== "number" && Array.isArray(object3)) {
    const index = Number.parseInt(key, 10);
    return Number.isInteger(index) && object3[index] === object3[key];
  }
  return false;
}
__name(isStringIndex, "isStringIndex");
function assertNotStringIndex(object3, key) {
  if (isStringIndex(object3, key)) {
    throw new Error("Cannot use string index");
  }
}
__name(assertNotStringIndex, "assertNotStringIndex");
function getProperty(object3, path125, value) {
  if (!isObject2(object3) || typeof path125 !== "string") {
    return value === void 0 ? object3 : value;
  }
  const pathArray = getPathSegments(path125);
  if (pathArray.length === 0) {
    return value;
  }
  for (let index = 0; index < pathArray.length; index++) {
    const key = pathArray[index];
    if (isStringIndex(object3, key)) {
      object3 = index === pathArray.length - 1 ? void 0 : null;
    } else {
      object3 = object3[key];
    }
    if (object3 === void 0 || object3 === null) {
      if (index !== pathArray.length - 1) {
        return value;
      }
      break;
    }
  }
  return object3 === void 0 ? value : object3;
}
__name(getProperty, "getProperty");
function setProperty(object3, path125, value) {
  if (!isObject2(object3) || typeof path125 !== "string") {
    return object3;
  }
  const root = object3;
  const pathArray = getPathSegments(path125);
  for (let index = 0; index < pathArray.length; index++) {
    const key = pathArray[index];
    assertNotStringIndex(object3, key);
    if (index === pathArray.length - 1) {
      object3[key] = value;
    } else if (!isObject2(object3[key])) {
      object3[key] = typeof pathArray[index + 1] === "number" ? [] : {};
    }
    object3 = object3[key];
  }
  return root;
}
__name(setProperty, "setProperty");
function deleteProperty(object3, path125) {
  if (!isObject2(object3) || typeof path125 !== "string") {
    return false;
  }
  const pathArray = getPathSegments(path125);
  for (let index = 0; index < pathArray.length; index++) {
    const key = pathArray[index];
    assertNotStringIndex(object3, key);
    if (index === pathArray.length - 1) {
      delete object3[key];
      return true;
    }
    object3 = object3[key];
    if (!isObject2(object3)) {
      return false;
    }
  }
}
__name(deleteProperty, "deleteProperty");
function hasProperty(object3, path125) {
  if (!isObject2(object3) || typeof path125 !== "string") {
    return false;
  }
  const pathArray = getPathSegments(path125);
  if (pathArray.length === 0) {
    return false;
  }
  for (const key of pathArray) {
    if (!isObject2(object3) || !(key in object3) || isStringIndex(object3, key)) {
      return false;
    }
    object3 = object3[key];
  }
  return true;
}
__name(hasProperty, "hasProperty");

// node_modules/configstore/index.js
function getConfigDirectory(id, globalConfigPath) {
  const pathPrefix = globalConfigPath ? path116.join(id, "config.json") : path116.join("configstore", `${id}.json`);
  const configDirectory = xdgConfig ?? import_graceful_fs.default.mkdtempSync(import_graceful_fs.default.realpathSync(os39.tmpdir()) + path116.sep);
  return path116.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 (error2) {
      if (error2.code === "ENOENT") {
        return {};
      }
      if (error2.code === "EACCES") {
        error2.message = `${error2.message}
${permissionError}
`;
      }
      if (error2.name === "SyntaxError") {
        writeFileSync11(this._path, "", writeFileOptions);
        return {};
      }
      throw error2;
    }
  }
  set all(value) {
    try {
      import_graceful_fs.default.mkdirSync(path116.dirname(this._path), mkdirOptions);
      writeFileSync11(this._path, JSON.stringify(value, void 0, "	"), writeFileOptions);
    } catch (error2) {
      if (error2.code === "EACCES") {
        error2.message = `${error2.message}
${permissionError}
`;
      }
      throw error2;
    }
  }
  get size() {
    return Object.keys(this.all || {}).length;
  }
  get(key) {
    return getProperty(this.all, key);
  }
  set(key, value) {
    const config2 = this.all;
    if (arguments.length === 1) {
      for (const k2 of Object.keys(key)) {
        setProperty(config2, k2, key[k2]);
      }
    } else {
      setProperty(config2, key, value);
    }
    this.all = config2;
  }
  has(key) {
    return hasProperty(this.all, key);
  }
  delete(key) {
    const config2 = this.all;
    deleteProperty(config2, key);
    this.all = config2;
  }
  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 integer2 = Number.parseInt(colorString, 16);
        return [
          /* eslint-disable no-bitwise */
          integer2 >> 16 & 255,
          integer2 >> 8 & 255,
          integer2 & 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 os40 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 = os40.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(string4, substring, replacer) {
  let index = string4.indexOf(substring);
  if (index === -1) {
    return string4;
  }
  const substringLength = substring.length;
  let endIndex = 0;
  let returnValue = "";
  do {
    returnValue += string4.slice(endIndex, index) + substring + replacer;
    endIndex = index + substringLength;
    index = string4.indexOf(substring, endIndex);
  } while (index !== -1);
  returnValue += string4.slice(endIndex);
  return returnValue;
}
__name(stringReplaceAll2, "stringReplaceAll");
function stringEncaseCRLFWithFirstIndex2(string4, prefix, postfix, index) {
  let endIndex = 0;
  let returnValue = "";
  do {
    const gotCR = string4[index - 1] === "\r";
    returnValue += string4.slice(endIndex, gotCR ? index - 1 : index) + prefix + (gotCR ? "\r\n" : "\n") + postfix;
    endIndex = index + 1;
    index = string4.indexOf("\n", endIndex);
  } while (index !== -1);
  returnValue += string4.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((object3, 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;
  object3.level = options2.level === void 0 ? colorLevel : options2.level;
}, "applyOptions");
var chalkFactory2 = /* @__PURE__ */ __name((options2) => {
  const chalk9 = /* @__PURE__ */ __name((...strings) => strings.join(" "), "chalk");
  applyOptions2(chalk9, options2);
  Object.setPrototypeOf(chalk9, createChalk2.prototype);
  return chalk9;
}, "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((open4, close, parent) => {
  let openAll;
  let closeAll;
  if (parent === void 0) {
    openAll = open4;
    closeAll = close;
  } else {
    openAll = parent.openAll + open4;
    closeAll = close + parent.closeAll;
  }
  return {
    open: open4,
    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, string4) => {
  if (self2.level <= 0 || !string4) {
    return self2[IS_EMPTY2] ? "" : string4;
  }
  let styler = self2[STYLER2];
  if (styler === void 0) {
    return string4;
  }
  const { openAll, closeAll } = styler;
  if (string4.includes("\x1B")) {
    while (styler !== void 0) {
      string4 = stringReplaceAll2(string4, styler.close, styler.open);
      styler = styler.parent;
    }
  }
  const lfIndex = string4.indexOf("\n");
  if (lfIndex !== -1) {
    string4 = stringEncaseCRLFWithFirstIndex2(string4, closeAll, openAll, lfIndex);
  }
  return openAll + string4 + closeAll;
}, "applyStyle");
Object.defineProperties(createChalk2.prototype, styles9);
var chalk8 = createChalk2();
var chalkStderr2 = createChalk2({ level: stderrColor2 ? stderrColor2.level : 0 });
var source_default2 = chalk8;

// 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 (error2) {
      if (error2 instanceof Error && error2.message === "unsupported BodyInit type") {
        return false;
      }
      throw error2;
    }
  }
  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 validate2 = /* @__PURE__ */ __name(() => void 0, "validate");
validate2();
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 read3() {
        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 read3();
      }
      __name(read3, "read");
      await read3();
    }
  }), {
    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 read3() {
          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 read3();
        }
        __name(read3, "read");
        await read3();
      }
    })
  });
}, "streamRequest");

// node_modules/ky/distribution/utils/merge.js
init_esbuild_shims();

// node_modules/ky/distribution/utils/is.js
init_esbuild_shims();
var isObject3 = /* @__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 ((!isObject3(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 (isObject3(source2)) {
      for (let [key, value] of Object.entries(source2)) {
        if (isObject3(value) && key in returnValue) {
          value = deepMerge(returnValue[key], value);
        }
        returnValue = { ...returnValue, [key]: value };
      }
      if (isObject3(source2.hooks)) {
        hooks = mergeHooks(hooks, source2.hooks);
        returnValue.hooks = hooks;
      }
      if (isObject3(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((resolve30, reject) => {
    const timeoutId = setTimeout(() => {
      if (abortController) {
        abortController.abort();
      }
      reject(new TimeoutError(request4));
    }, options2.timeout);
    void options2.fetch(request4, init).then(resolve30).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((resolve30, 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);
      resolve30();
    }, 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 error2 = new HTTPError(response, ky2.request, ky2._options);
        for (const hook of ky2._options.hooks.beforeError) {
          error2 = await hook(error2);
        }
        throw error2;
      }
      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(error2) {
    this._retryCount++;
    if (this._retryCount > this._options.retry.limit || error2 instanceof TimeoutError) {
      throw error2;
    }
    if (error2 instanceof HTTPError) {
      if (!this._options.retry.statusCodes.includes(error2.response.status)) {
        throw error2;
      }
      const retryAfter = error2.response.headers.get("Retry-After") ?? error2.response.headers.get("RateLimit-Reset") ?? error2.response.headers.get("X-RateLimit-Reset") ?? error2.response.headers.get("X-Rate-Limit-Reset");
      if (retryAfter && this._options.retry.afterStatusCodes.includes(error2.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 (error2.response.status === 413) {
        throw error2;
      }
    }
    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 (error2) {
      const ms = Math.min(this._calculateRetryDelay(error2), maxSafeTimeout);
      if (this._retryCount < 1) {
        throw error2;
      }
      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: error2,
          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 (error2) {
    if (error2?.response?.status === 404) {
      throw new PackageNotFoundError(packageName);
    }
    throw error2;
  }
  if (options2.allVersions) {
    return data;
  }
  const versionError = new VersionNotFoundError(packageName, version2);
  if (data["dist-tags"][version2]) {
    const { time: time3 } = data;
    data = data.versions[data["dist-tags"][version2]];
    data.time = time3;
  } 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: time3 } = data;
    data = data.versions[version2];
    data.time = time3;
    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 fs106 from "node:fs";
import path119 from "node:path";
import { fileURLToPath as fileURLToPath14 } 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 path117 from "node:path";
import os41 from "node:os";
import fs105 from "node:fs";
var isWindows8 = process45.platform === "win32";
var readRc = /* @__PURE__ */ __name((filePath) => {
  try {
    return import_ini2.default.parse(fs105.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 (isWindows8 && process45.env.APPDATA) {
    return path117.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 path117.join(homebrewPrefix, "/lib/node_modules/npm/npmrc");
  }
  if (process45.execPath.endsWith("/bin/node")) {
    const installDir = path117.dirname(path117.dirname(process45.execPath));
    return path117.join(installDir, "/etc/npmrc");
  }
}, "getGlobalNpmrc");
var getDefaultNpmPrefix = /* @__PURE__ */ __name(() => {
  if (isWindows8) {
    const { APPDATA } = process45.env;
    return APPDATA ? path117.join(APPDATA, "npm") : path117.dirname(process45.execPath);
  }
  return path117.dirname(path117.dirname(process45.execPath));
}, "getDefaultNpmPrefix");
var getNpmPrefix = /* @__PURE__ */ __name(() => {
  const envPrefix = getEnvNpmPrefix();
  if (envPrefix) {
    return envPrefix;
  }
  const homePrefix = readRc(path117.join(os41.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 = path117.resolve(getNpmPrefix());
var getYarnWindowsDirectory = /* @__PURE__ */ __name(() => {
  if (isWindows8 && process45.env.LOCALAPPDATA) {
    const dir = path117.join(process45.env.LOCALAPPDATA, "Yarn");
    if (fs105.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 = path117.join(os41.homedir(), ".config/yarn");
  if (fs105.existsSync(configPrefix)) {
    return configPrefix;
  }
  const homePrefix = path117.join(os41.homedir(), ".yarn-config");
  if (fs105.existsSync(homePrefix)) {
    return homePrefix;
  }
  return npmPrefix;
}, "getYarnPrefix");
var globalDirectory = {};
globalDirectory.npm = {};
globalDirectory.npm.prefix = npmPrefix;
globalDirectory.npm.packages = path117.join(npmPrefix, isWindows8 ? "node_modules" : "lib/node_modules");
globalDirectory.npm.binaries = isWindows8 ? npmPrefix : path117.join(npmPrefix, "bin");
var yarnPrefix = path117.resolve(getYarnPrefix());
globalDirectory.yarn = {};
globalDirectory.yarn.prefix = yarnPrefix;
globalDirectory.yarn.packages = path117.join(yarnPrefix, getYarnWindowsDirectory() ? "Data/global/node_modules" : "global/node_modules");
globalDirectory.yarn.binaries = path117.join(globalDirectory.yarn.packages, ".bin");
var global_directory_default = globalDirectory;

// node_modules/is-path-inside/index.js
init_esbuild_shims();
import path118 from "node:path";
function isPathInside(childPath, parentPath) {
  const relation = path118.relative(parentPath, childPath);
  return Boolean(
    relation && relation !== ".." && !relation.startsWith(`..${path118.sep}`) && relation !== path118.resolve(childPath)
  );
}
__name(isPathInside, "isPathInside");

// node_modules/is-installed-globally/index.js
var __dirname7 = path119.dirname(fileURLToPath14(import.meta.url));
var isInstalledGlobally = (() => {
  try {
    return isPathInside(__dirname7, global_directory_default.yarn.packages) || isPathInside(__dirname7, fs106.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(string4, options2 = {}) {
  if (typeof string4 !== "string" || string4.length === 0) {
    return 0;
  }
  const {
    ambiguousIsNarrow = true,
    countAnsiEscapeCodes = false
  } = options2;
  if (!countAnsiEscapeCodes) {
    string4 = stripAnsi(string4);
  }
  if (string4.length === 0) {
    return 0;
  }
  let width = 0;
  const eastAsianWidthOptions = { ambiguousAsWide: !ambiguousIsNarrow };
  for (const { segment: character } of segmenter5.segment(string4)) {
    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(string4) {
  let lineWidth = 0;
  for (const line of string4.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((string4, toLowerCase, toUpperCase, preserveConsecutiveUppercase2) => {
  let isLastCharLower = false;
  let isLastCharUpper = false;
  let isLastLastCharUpper = false;
  let isLastLastCharPreserved = false;
  for (let index = 0; index < string4.length; index++) {
    const character = string4[index];
    isLastLastCharPreserved = index > 2 ? string4[index - 3] === "-" : true;
    if (isLastCharLower && UPPERCASE.test(character)) {
      string4 = string4.slice(0, index) + "-" + string4.slice(index);
      isLastCharLower = false;
      isLastLastCharUpper = isLastCharUpper;
      isLastCharUpper = true;
      index++;
    } else if (isLastCharUpper && isLastLastCharUpper && LOWERCASE.test(character) && (!isLastLastCharPreserved || preserveConsecutiveUppercase2)) {
      string4 = string4.slice(0, index - 1) + "-" + string4.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 string4;
}, "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, (_2, 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((x3) => x3.trim()).filter((x3) => x3.length).join("-");
  } else {
    input = input.trim();
  }
  if (input.length === 0) {
    return "";
  }
  const toLowerCase = options2.locale === false ? (string4) => string4.toLowerCase() : (string4) => string4.toLocaleLowerCase(options2.locale);
  const toUpperCase = options2.locale === false ? (string4) => string4.toUpperCase() : (string4) => string4.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((s5) => stringWidth5(s5)));
      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((string4) => string4.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: transform2 = /* @__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 = transform2({ 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 = path120.dirname(fileURLToPath15(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;
    }
    spawn9(process47.execPath, [path120.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 installCommand3 = 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: installCommand3
      }),
      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);
var debugLogger115 = createDebugLogger("UPDATE_CHECK");
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 (e4) {
    debugLogger115.warn("Failed to check for updates: " + e4);
    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 fs107 from "node:fs";
import * as path121 from "node:path";
import * as childProcess2 from "node:child_process";
var debugLogger116 = createDebugLogger("INSTALLATION_INFO");
function getInstallationInfo(projectRoot, isAutoUpdateEnabled) {
  const cliPath = process.argv[1];
  if (!cliPath) {
    return { packageManager: "unknown" /* UNKNOWN */, isGlobal: false };
  }
  try {
    const realPath = fs107.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: isAutoUpdateEnabled ? "Installed with pnpm. Attempting to automatically update now..." : `Please run ${updateCommand3} to update`
      };
    }
    if (realPath.includes("/.yarn/global")) {
      const updateCommand3 = "yarn global add @qwen-code/qwen-code@latest";
      return {
        packageManager: "yarn" /* YARN */,
        isGlobal: true,
        updateCommand: updateCommand3,
        updateMessage: isAutoUpdateEnabled ? "Installed with yarn. Attempting to automatically update now..." : `Please run ${updateCommand3} to update`
      };
    }
    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: isAutoUpdateEnabled ? "Installed with bun. Attempting to automatically update now..." : `Please run ${updateCommand3} to update`
      };
    }
    if (normalizedProjectRoot && realPath.startsWith(`${normalizedProjectRoot}/node_modules`)) {
      let pm = "npm" /* NPM */;
      if (fs107.existsSync(path121.join(projectRoot, "yarn.lock"))) {
        pm = "yarn" /* YARN */;
      } else if (fs107.existsSync(path121.join(projectRoot, "pnpm-lock.yaml"))) {
        pm = "pnpm" /* PNPM */;
      } else if (fs107.existsSync(path121.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: isAutoUpdateEnabled ? "Installed with npm. Attempting to automatically update now..." : `Please run ${updateCommand2} to update`
    };
  } catch (error2) {
    debugLogger116.error("Failed to detect installation info:", error2);
    return { packageManager: "unknown" /* UNKNOWN */, isGlobal: false };
  }
}
__name(getInstallationInfo, "getInstallationInfo");

// packages/cli/src/utils/updateEventEmitter.ts
init_esbuild_shims();
import { EventEmitter as EventEmitter10 } from "node:events";
var updateEventEmitter = new EventEmitter10();

// packages/cli/src/utils/spawnWrapper.ts
init_esbuild_shims();
import { spawn as spawn10 } from "node:child_process";
var spawnWrapper = spawn10;

// packages/cli/src/utils/handleAutoUpdate.ts
import os42 from "node:os";
function handleAutoUpdate(info, settings, projectRoot, spawnFn = spawnWrapper) {
  if (!info) {
    return;
  }
  const isAutoUpdateEnabled = settings.merged.general?.enableAutoUpdate !== false;
  const installationInfo = getInstallationInfo(
    projectRoot,
    isAutoUpdateEnabled
  );
  let combinedMessage = info.message;
  if (installationInfo.updateMessage) {
    combinedMessage += `
${installationInfo.updateMessage}`;
  }
  updateEventEmitter.emit("update-received", {
    message: combinedMessage
  });
  if (!installationInfo.updateCommand || !isAutoUpdateEnabled) {
    return;
  }
  const isNightly = info.update.latest.includes("nightly");
  const updateCommand2 = installationInfo.updateCommand.replace(
    "@latest",
    isNightly ? "@nightly" : `@${info.update.latest}`
  );
  const isWindows9 = os42.platform() === "win32";
  const shell2 = isWindows9 ? "cmd.exe" : "bash";
  const shellArgs = isWindows9 ? ["/c", updateCommand2] : ["-c", updateCommand2];
  const updateProcess = spawnFn(shell2, shellArgs, { stdio: "pipe" });
  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/hooks/useMessageQueue.ts
init_esbuild_shims();
var import_react123 = __toESM(require_react(), 1);
function useMessageQueue({
  isConfigInitialized,
  streamingState,
  submitQuery
}) {
  const [messageQueue, setMessageQueue] = (0, import_react123.useState)([]);
  const addMessage = (0, import_react123.useCallback)((message) => {
    const trimmedMessage = message.trim();
    if (trimmedMessage.length > 0) {
      setMessageQueue((prev) => [...prev, trimmedMessage]);
    }
  }, []);
  const clearQueue = (0, import_react123.useCallback)(() => {
    setMessageQueue([]);
  }, []);
  const getQueuedMessagesText = (0, import_react123.useCallback)(() => {
    if (messageQueue.length === 0) return "";
    return messageQueue.join("\n\n");
  }, [messageQueue]);
  (0, import_react123.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_react124 = __toESM(require_react(), 1);
function useAutoAcceptIndicator({
  config: config2,
  addItem,
  onApprovalModeChange,
  shouldBlockTab
}) {
  const currentConfigValue = config2.getApprovalMode();
  const [showAutoAcceptIndicator, setShowAutoAcceptIndicator] = (0, import_react124.useState)(currentConfigValue);
  (0, import_react124.useEffect)(() => {
    setShowAutoAcceptIndicator(currentConfigValue);
  }, [currentConfigValue]);
  useKeypress(
    (key) => {
      const isShiftTab = key.shift && key.name === "tab";
      const isWindowsTab = process.platform === "win32" && key.name === "tab" && !key.ctrl && !key.meta;
      if (isShiftTab || isWindowsTab) {
        if (isWindowsTab && shouldBlockTab?.()) {
          return;
        }
        const currentMode = config2.getApprovalMode();
        const currentIndex = APPROVAL_MODES.indexOf(currentMode);
        const nextIndex = currentIndex === -1 ? 0 : (currentIndex + 1) % APPROVAL_MODES.length;
        const nextApprovalMode = APPROVAL_MODES[nextIndex];
        try {
          config2.setApprovalMode(nextApprovalMode);
          setShowAutoAcceptIndicator(nextApprovalMode);
          onApprovalModeChange?.(nextApprovalMode);
        } catch (e4) {
          addItem?.(
            {
              type: "info" /* INFO */,
              text: e4.message
            },
            Date.now()
          );
        }
      }
    },
    { isActive: true }
  );
  return showAutoAcceptIndicator;
}
__name(useAutoAcceptIndicator, "useAutoAcceptIndicator");

// packages/cli/src/ui/hooks/useGitBranchName.ts
init_esbuild_shims();
var import_react125 = __toESM(require_react(), 1);
import fs108 from "node:fs";
import fsPromises6 from "node:fs/promises";
import path122 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 = path122.join(cwd7, ".git", "logs", "HEAD");
    let watcher;
    const setupWatcher = /* @__PURE__ */ __name(async () => {
      try {
        await fsPromises6.access(gitLogsHeadPath, fs108.constants.F_OK);
        watcher = fs108.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((r5) => r5 !== action.request);
    default:
      checkExhaustive(action);
      return state;
  }
}
__name(confirmationRequestsReducer, "confirmationRequestsReducer");
var useConfirmUpdateRequests = /* @__PURE__ */ __name(() => {
  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]
  );
  return {
    addConfirmUpdateExtensionRequest,
    confirmUpdateExtensionRequests,
    dispatchConfirmUpdateExtensionRequests
  };
}, "useConfirmUpdateRequests");
function settingInputRequestsReducer(state, action) {
  switch (action.type) {
    case "add":
      return [...state, action.request];
    case "remove":
      return state.filter((r5) => r5 !== action.request);
    default:
      checkExhaustive(action);
      return state;
  }
}
__name(settingInputRequestsReducer, "settingInputRequestsReducer");
var useSettingInputRequests = /* @__PURE__ */ __name(() => {
  const [settingInputRequests, dispatchSettingInputRequests] = (0, import_react126.useReducer)(
    settingInputRequestsReducer,
    []
  );
  const addSettingInputRequest = (0, import_react126.useCallback)(
    (original) => {
      const wrappedRequest = {
        settingName: original.settingName,
        settingDescription: original.settingDescription,
        sensitive: original.sensitive,
        onSubmit: /* @__PURE__ */ __name((value) => {
          dispatchSettingInputRequests({
            type: "remove",
            request: wrappedRequest
          });
          original.onSubmit(value);
        }, "onSubmit"),
        onCancel: /* @__PURE__ */ __name(() => {
          dispatchSettingInputRequests({
            type: "remove",
            request: wrappedRequest
          });
          original.onCancel();
        }, "onCancel")
      };
      dispatchSettingInputRequests({
        type: "add",
        request: wrappedRequest
      });
    },
    [dispatchSettingInputRequests]
  );
  return {
    addSettingInputRequest,
    settingInputRequests,
    dispatchSettingInputRequests
  };
}, "useSettingInputRequests");
function pluginChoiceRequestsReducer(state, action) {
  switch (action.type) {
    case "add":
      return [...state, action.request];
    case "remove":
      return state.filter((r5) => r5 !== action.request);
    default:
      checkExhaustive(action);
      return state;
  }
}
__name(pluginChoiceRequestsReducer, "pluginChoiceRequestsReducer");
var usePluginChoiceRequests = /* @__PURE__ */ __name(() => {
  const [pluginChoiceRequests, dispatchPluginChoiceRequests] = (0, import_react126.useReducer)(
    pluginChoiceRequestsReducer,
    []
  );
  const addPluginChoiceRequest = (0, import_react126.useCallback)(
    (original) => {
      const wrappedRequest = {
        marketplaceName: original.marketplaceName,
        plugins: original.plugins,
        onSelect: /* @__PURE__ */ __name((pluginName) => {
          dispatchPluginChoiceRequests({
            type: "remove",
            request: wrappedRequest
          });
          original.onSelect(pluginName);
        }, "onSelect"),
        onCancel: /* @__PURE__ */ __name(() => {
          dispatchPluginChoiceRequests({
            type: "remove",
            request: wrappedRequest
          });
          original.onCancel();
        }, "onCancel")
      };
      dispatchPluginChoiceRequests({
        type: "add",
        request: wrappedRequest
      });
    },
    [dispatchPluginChoiceRequests]
  );
  return {
    addPluginChoiceRequest,
    pluginChoiceRequests,
    dispatchPluginChoiceRequests
  };
}, "usePluginChoiceRequests");
var useExtensionUpdates = /* @__PURE__ */ __name((extensionManager, addItem, cwd7) => {
  const [extensionsUpdateState, dispatchExtensionStateUpdate] = (0, import_react126.useReducer)(
    extensionUpdatesReducer,
    initialExtensionUpdatesState
  );
  const extensions = extensionManager.getLoadedExtensions();
  (0, import_react126.useEffect)(() => {
    (async () => {
      const extensionsToCheck = extensions.filter((extension) => {
        const currentStatus = extensionsUpdateState.extensionStatuses.get(
          extension.name
        );
        if (!currentStatus) return true;
        const currentState = currentStatus.status;
        return !currentState || currentState === "unknown" /* UNKNOWN */;
      });
      if (extensionsToCheck.length === 0) return;
      dispatchExtensionStateUpdate({ type: "BATCH_CHECK_START" });
      await extensionManager.checkForAllExtensionUpdates(
        (extensionName, state) => {
          dispatchExtensionStateUpdate({
            type: "SET_STATE",
            payload: { name: extensionName, state }
          });
        }
      );
      dispatchExtensionStateUpdate({ type: "BATCH_CHECK_END" });
    })();
  }, [
    extensions,
    extensionManager,
    extensionsUpdateState.extensionStatuses,
    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) {
        extensionManager.updateExtension(
          extension,
          currentState.status,
          (extensionName, state) => {
            dispatchExtensionStateUpdate({
              type: "SET_STATE",
              payload: { name: extensionName, state }
            });
          }
        ).then((result) => {
          if (!result) return;
          addItem(
            {
              type: "info" /* INFO */,
              text: `Extension "${extension.name}" successfully updated: ${result.originalVersion} \u2192 ${result.updatedVersion}.`
            },
            Date.now()
          );
        }).catch((error2) => {
          addItem(
            {
              type: "error" /* ERROR */,
              text: getErrorMessage3(error2)
            },
            Date.now()
          );
        });
      } else {
        extensionsWithUpdatesCount++;
      }
    }
    if (extensionsWithUpdatesCount > 0) {
      const s5 = extensionsWithUpdatesCount > 1 ? "s" : "";
      addItem(
        {
          type: "info" /* INFO */,
          text: `You have ${extensionsWithUpdatesCount} extension${s5} with an update available, run "/extensions list" for more information.`
        },
        Date.now()
      );
    }
  }, [extensions, extensionManager, extensionsUpdateState, 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
  };
}, "useExtensionUpdates");

// packages/cli/src/ui/hooks/useWelcomeBack.ts
init_esbuild_shims();
var import_react127 = __toESM(require_react(), 1);
function useWelcomeBack(config2, submitQuery, buffer, settings) {
  const [welcomeBackInfo, setWelcomeBackInfo] = (0, import_react127.useState)(null);
  const [showWelcomeBackDialog, setShowWelcomeBackDialog] = (0, import_react127.useState)(false);
  const [welcomeBackChoice, setWelcomeBackChoice] = (0, import_react127.useState)(null);
  const [shouldFillInput, setShouldFillInput] = (0, import_react127.useState)(false);
  const [inputFillText, setInputFillText] = (0, import_react127.useState)(null);
  const checkWelcomeBack = (0, import_react127.useCallback)(async () => {
    if (settings.ui?.enableWelcomeBack === false) {
      return;
    }
    try {
      const info = await getProjectSummaryInfo();
      if (info.hasHistory) {
        setWelcomeBackInfo(info);
        setShowWelcomeBackDialog(true);
      }
    } catch (error2) {
      config2.getDebugLogger().debug("Welcome back check failed:", error2);
    }
  }, [config2, settings.ui?.enableWelcomeBack]);
  const handleWelcomeBackSelection = (0, import_react127.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_react127.useCallback)(() => {
    setWelcomeBackChoice("restart");
    setShowWelcomeBackDialog(false);
  }, []);
  const clearInputFill = (0, import_react127.useCallback)(() => {
    setShouldFillInput(false);
    setInputFillText(null);
  }, []);
  (0, import_react127.useEffect)(() => {
    if (shouldFillInput && inputFillText) {
      buffer.setText(inputFillText);
      clearInputFill();
    }
  }, [shouldFillInput, inputFillText, buffer, clearInputFill]);
  (0, import_react127.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_react128 = __toESM(require_react(), 1);
function useDialogClose(options2) {
  const closeAnyOpenDialog = (0, import_react128.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_react129 = __toESM(require_react(), 1);
var useInitializationAuthError = /* @__PURE__ */ __name((authError, onAuthError) => {
  const hasHandled = (0, import_react129.useRef)(false);
  const authErrorRef = (0, import_react129.useRef)(authError);
  const onAuthErrorRef = (0, import_react129.useRef)(onAuthError);
  authErrorRef.current = authError;
  onAuthErrorRef.current = onAuthError;
  (0, import_react129.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_react130 = __toESM(require_react(), 1);
function useSubagentCreateDialog() {
  const [isSubagentCreateDialogOpen, setIsSubagentCreateDialogOpen] = (0, import_react130.useState)(false);
  const openSubagentCreateDialog = (0, import_react130.useCallback)(() => {
    setIsSubagentCreateDialogOpen(true);
  }, []);
  const closeSubagentCreateDialog = (0, import_react130.useCallback)(() => {
    setIsSubagentCreateDialogOpen(false);
  }, []);
  return {
    isSubagentCreateDialogOpen,
    openSubagentCreateDialog,
    closeSubagentCreateDialog
  };
}
__name(useSubagentCreateDialog, "useSubagentCreateDialog");

// packages/cli/src/ui/hooks/useAgentsManagerDialog.ts
init_esbuild_shims();
var import_react131 = __toESM(require_react(), 1);
var useAgentsManagerDialog = /* @__PURE__ */ __name(() => {
  const [isAgentsManagerDialogOpen, setIsAgentsManagerDialogOpen] = (0, import_react131.useState)(false);
  const openAgentsManagerDialog = (0, import_react131.useCallback)(() => {
    setIsAgentsManagerDialogOpen(true);
  }, []);
  const closeAgentsManagerDialog = (0, import_react131.useCallback)(() => {
    setIsAgentsManagerDialogOpen(false);
  }, []);
  return {
    isAgentsManagerDialogOpen,
    openAgentsManagerDialog,
    closeAgentsManagerDialog
  };
}, "useAgentsManagerDialog");

// packages/cli/src/ui/hooks/useAttentionNotifications.ts
init_esbuild_shims();
var import_react132 = __toESM(require_react(), 1);

// packages/cli/src/utils/attentionNotification.ts
init_esbuild_shims();
import process48 from "node:process";
var TERMINAL_BELL = "\x07";
var debugLogger117 = createDebugLogger("ATTENTION_NOTIFICATION");
function notifyTerminalAttention(_reason, options2 = {}) {
  if (options2.enabled === false) {
    return false;
  }
  const stream2 = options2.stream ?? process48.stdout;
  if (!stream2?.write || stream2.isTTY === false) {
    return false;
  }
  try {
    stream2.write(TERMINAL_BELL);
    return true;
  } catch (error2) {
    debugLogger117.warn("Failed to send terminal bell:", error2);
    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,
  settings
}) => {
  const terminalBellEnabled = settings?.merged?.general?.terminalBell ?? true;
  const awaitingNotificationSentRef = (0, import_react132.useRef)(false);
  const respondingElapsedRef = (0, import_react132.useRef)(0);
  (0, import_react132.useEffect)(() => {
    if (streamingState === "waiting_for_confirmation" /* WaitingForConfirmation */ && !isFocused && !awaitingNotificationSentRef.current) {
      notifyTerminalAttention("tool_approval" /* ToolApproval */, {
        enabled: terminalBellEnabled
      });
      awaitingNotificationSentRef.current = true;
    }
    if (streamingState !== "waiting_for_confirmation" /* WaitingForConfirmation */ || isFocused) {
      awaitingNotificationSentRef.current = false;
    }
  }, [isFocused, streamingState, terminalBellEnabled]);
  (0, import_react132.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 */, {
          enabled: terminalBellEnabled
        });
      }
      respondingElapsedRef.current = 0;
      return;
    }
  }, [streamingState, elapsedTime, isFocused, terminalBellEnabled]);
}, "useAttentionNotifications");

// packages/cli/src/ui/AppContainer.tsx
var import_jsx_runtime109 = __toESM(require_jsx_runtime(), 1);
var CTRL_EXIT_PROMPT_DURATION_MS = 1e3;
var debugLogger118 = createDebugLogger("APP_CONTAINER");
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: config2, initializationResult } = props;
  const historyManager = useHistory();
  useMemoryMonitor(historyManager);
  const [debugMessage, setDebugMessage] = (0, import_react133.useState)("");
  const [quittingMessages, setQuittingMessages] = (0, import_react133.useState)(null);
  const [themeError, setThemeError] = (0, import_react133.useState)(
    initializationResult.themeError
  );
  const [isProcessing, setIsProcessing] = (0, import_react133.useState)(false);
  const [embeddedShellFocused, setEmbeddedShellFocused] = (0, import_react133.useState)(false);
  const [geminiMdFileCount, setGeminiMdFileCount] = (0, import_react133.useState)(
    initializationResult.geminiMdFileCount
  );
  const [shellModeActive, setShellModeActive] = (0, import_react133.useState)(false);
  const [modelSwitchedFromQuotaError, setModelSwitchedFromQuotaError] = (0, import_react133.useState)(false);
  const [historyRemountKey, setHistoryRemountKey] = (0, import_react133.useState)(0);
  const [updateInfo, setUpdateInfo] = (0, import_react133.useState)(null);
  const [isTrustedFolder, setIsTrustedFolder] = (0, import_react133.useState)(
    config2.isTrustedFolder()
  );
  const extensionManager = config2.getExtensionManager();
  const { addConfirmUpdateExtensionRequest, confirmUpdateExtensionRequests } = useConfirmUpdateRequests();
  const { addSettingInputRequest, settingInputRequests } = useSettingInputRequests();
  const { addPluginChoiceRequest, pluginChoiceRequests } = usePluginChoiceRequests();
  extensionManager.setRequestConsent(
    requestConsentOrFail.bind(
      null,
      (description) => requestConsentInteractive(description, addConfirmUpdateExtensionRequest)
    )
  );
  extensionManager.setRequestChoicePlugin(
    (marketplace) => new Promise((resolve30, reject) => {
      addPluginChoiceRequest({
        marketplaceName: marketplace.name,
        plugins: marketplace.plugins.map((p2) => ({
          name: p2.name,
          description: p2.description
        })),
        onSelect: /* @__PURE__ */ __name((pluginName) => {
          resolve30(pluginName);
        }, "onSelect"),
        onCancel: /* @__PURE__ */ __name(() => {
          reject(new Error("Plugin selection cancelled"));
        }, "onCancel")
      });
    })
  );
  extensionManager.setRequestSetting(
    (setting) => new Promise((resolve30, reject) => {
      addSettingInputRequest({
        settingName: setting.name,
        settingDescription: setting.description,
        sensitive: setting.sensitive ?? false,
        onSubmit: /* @__PURE__ */ __name((value) => {
          resolve30(value);
        }, "onSubmit"),
        onCancel: /* @__PURE__ */ __name(() => {
          reject(new Error("Setting input cancelled"));
        }, "onCancel")
      });
    })
  );
  const {
    extensionsUpdateState,
    extensionsUpdateStateInternal,
    dispatchExtensionStateUpdate
  } = useExtensionUpdates(
    extensionManager,
    historyManager.addItem,
    config2.getWorkingDir()
  );
  const { codingPlanUpdateRequest, dismissCodingPlanUpdate } = useCodingPlanUpdates(settings, config2, historyManager.addItem);
  const [isPermissionsDialogOpen, setPermissionsDialogOpen] = (0, import_react133.useState)(false);
  const openPermissionsDialog = (0, import_react133.useCallback)(
    () => setPermissionsDialogOpen(true),
    []
  );
  const closePermissionsDialog = (0, import_react133.useCallback)(
    () => setPermissionsDialogOpen(false),
    []
  );
  const getCurrentModel = (0, import_react133.useCallback)(() => config2.getModel(), [config2]);
  const [currentModel, setCurrentModel] = (0, import_react133.useState)(getCurrentModel());
  const [isConfigInitialized, setConfigInitialized] = (0, import_react133.useState)(false);
  const [userMessages, setUserMessages] = (0, import_react133.useState)([]);
  const { columns: terminalWidth, rows: terminalHeight } = useTerminalSize();
  const { stdin, setRawMode } = use_stdin_default();
  const { stdout } = use_stdout_default();
  const { stats: sessionStats, startNewSession } = useSessionStats();
  const logger6 = useLogger(config2.storage, sessionStats.sessionId);
  const branchName = useGitBranchName(config2.getTargetDir());
  const mainControlsRef = (0, import_react133.useRef)(null);
  const originalTitleRef = (0, import_react133.useRef)(
    computeWindowTitle(basename24(config2.getTargetDir()))
  );
  const lastTitleRef = (0, import_react133.useRef)(null);
  const staticExtraHeight = 3;
  (0, import_react133.useEffect)(() => {
    (async () => {
      await config2.initialize();
      setConfigInitialized(true);
      const resumedSessionData = config2.getResumedSessionData();
      if (resumedSessionData) {
        const historyItems = buildResumedHistoryItems(
          resumedSessionData,
          config2
        );
        historyManager.loadHistory(historyItems);
      }
    })();
    registerCleanup(async () => {
      const ideClient = await IdeClient.getInstance();
      await ideClient.disconnect();
    });
  }, [config2]);
  (0, import_react133.useEffect)(
    () => setUpdateHandler(historyManager.addItem, setUpdateInfo),
    [historyManager.addItem]
  );
  (0, import_react133.useEffect)(() => {
    const checkModelChange = /* @__PURE__ */ __name(() => {
      const model = getCurrentModel();
      if (model !== currentModel) {
        setCurrentModel(model);
      }
    }, "checkModelChange");
    checkModelChange();
    const interval = setInterval(checkModelChange, 1e3);
    return () => clearInterval(interval);
  }, [config2, currentModel, getCurrentModel]);
  const { inputWidth, suggestionsWidth } = (0, import_react133.useMemo)(() => {
    const { inputWidth: inputWidth2, suggestionsWidth: suggestionsWidth2 } = calculatePromptWidths(terminalWidth);
    return { inputWidth: inputWidth2, suggestionsWidth: suggestionsWidth2 };
  }, [terminalWidth]);
  const mainAreaWidth = Math.min(terminalWidth - 4, 100);
  const staticAreaMaxItemHeight = Math.max(terminalHeight * 4, 100);
  const isValidPath = (0, import_react133.useCallback)((filePath) => {
    try {
      return fs109.existsSync(filePath) && fs109.statSync(filePath).isFile();
    } catch (_e2) {
      return false;
    }
  }, []);
  const buffer = useTextBuffer({
    initialText: "",
    viewport: { height: 10, width: inputWidth },
    stdin,
    setRawMode,
    isValidPath,
    shellModeActive
  });
  (0, import_react133.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 i3 = 1; i3 < combinedMessages.length; i3++) {
          if (combinedMessages[i3] !== combinedMessages[i3 - 1]) {
            deduplicatedMessages.push(combinedMessages[i3]);
          }
        }
      }
      setUserMessages(deduplicatedMessages.reverse());
    }, "fetchUserMessages");
    fetchUserMessages();
  }, [historyManager.history, logger6]);
  const refreshStatic = (0, import_react133.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, config2);
  const {
    setAuthState,
    authError,
    onAuthError,
    isAuthDialogOpen,
    isAuthenticating,
    pendingAuthType,
    qwenAuthState,
    handleAuthSelect,
    handleCodingPlanSubmit,
    openAuthDialog,
    cancelAuthentication
  } = useAuthCommand(settings, config2, historyManager.addItem, refreshStatic);
  useInitializationAuthError(initializationResult.authError, onAuthError);
  (0, import_react133.useEffect)(() => {
    const currentAuthType = config2.getModelsConfig().getCurrentAuthType();
    if (settings.merged.security?.auth?.enforcedType && currentAuthType && settings.merged.security?.auth.enforcedType !== currentAuthType) {
      onAuthError(
        t4(
          "Authentication is enforced to be {{enforcedType}}, but you are currently using {{currentType}}.",
          {
            enforcedType: String(settings.merged.security?.auth.enforcedType),
            currentType: String(currentAuthType)
          }
        )
      );
    } else if (!settings.merged.security?.auth?.useExternal) {
      if (currentAuthType) {
        const error2 = validateAuthMethod(currentAuthType, config2);
        if (error2) {
          onAuthError(error2);
        }
      }
    }
  }, [
    settings.merged.security?.auth?.enforcedType,
    settings.merged.security?.auth?.useExternal,
    config2,
    onAuthError
  ]);
  const [editorError, setEditorError] = (0, import_react133.useState)(null);
  const {
    isEditorDialogOpen,
    openEditorDialog,
    handleEditorSelect,
    exitEditorDialog
  } = useEditorSettings(settings, setEditorError, historyManager.addItem);
  const { isSettingsDialogOpen, openSettingsDialog, closeSettingsDialog } = useSettingsCommand();
  const { isModelDialogOpen, openModelDialog, closeModelDialog } = useModelCommand();
  const {
    isResumeDialogOpen,
    openResumeDialog,
    closeResumeDialog,
    handleResume
  } = useResumeCommand({
    config: config2,
    historyManager,
    startNewSession,
    remount: refreshStatic
  });
  const { toggleVimEnabled } = useVimMode();
  const {
    isSubagentCreateDialogOpen,
    openSubagentCreateDialog,
    closeSubagentCreateDialog
  } = useSubagentCreateDialog();
  const {
    isAgentsManagerDialogOpen,
    openAgentsManagerDialog,
    closeAgentsManagerDialog
  } = useAgentsManagerDialog();
  const slashCommandActions = (0, import_react133.useMemo)(
    () => ({
      openAuthDialog,
      openThemeDialog,
      openEditorDialog,
      openSettingsDialog,
      openModelDialog,
      openPermissionsDialog,
      openApprovalModeDialog,
      quit: /* @__PURE__ */ __name((messages) => {
        setQuittingMessages(messages);
        setTimeout(async () => {
          await runExitCleanup();
          process49.exit(0);
        }, 100);
      }, "quit"),
      setDebugMessage,
      dispatchExtensionStateUpdate,
      addConfirmUpdateExtensionRequest,
      openSubagentCreateDialog,
      openAgentsManagerDialog,
      openResumeDialog
    }),
    [
      openAuthDialog,
      openThemeDialog,
      openEditorDialog,
      openSettingsDialog,
      openModelDialog,
      setDebugMessage,
      dispatchExtensionStateUpdate,
      openPermissionsDialog,
      openApprovalModeDialog,
      addConfirmUpdateExtensionRequest,
      openSubagentCreateDialog,
      openAgentsManagerDialog,
      openResumeDialog
    ]
  );
  const {
    handleSlashCommand: handleSlashCommand2,
    slashCommands,
    pendingHistoryItems: pendingSlashCommandHistoryItems,
    commandContext,
    shellConfirmationRequest,
    confirmationRequest
  } = useSlashCommandProcessor(
    config2,
    settings,
    historyManager.addItem,
    historyManager.clearItems,
    historyManager.loadHistory,
    refreshStatic,
    toggleVimEnabled,
    isProcessing,
    setIsProcessing,
    setGeminiMdFileCount,
    slashCommandActions,
    extensionsUpdateStateInternal,
    isConfigInitialized,
    logger6
  );
  const onDebugMessage = (0, import_react133.useCallback)(
    (message) => {
      config2.getDebugLogger().debug(message);
    },
    [config2]
  );
  const performMemoryRefresh = (0, import_react133.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(
        process49.cwd(),
        settings.merged.context?.loadFromIncludeDirectories ? config2.getWorkspaceContext().getDirectories() : [],
        config2.getFileService(),
        config2.getExtensionContextFilePaths(),
        config2.isTrustedFolder(),
        settings.merged.context?.importFormat || "tree"
        // Use setting or default to 'tree'
      );
      config2.setUserMemory(memoryContent);
      config2.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()
      );
      debugLogger118.debug(
        `[DEBUG] Refreshed memory content in config: ${memoryContent.substring(
          0,
          200
        )}...`
      );
    } catch (error2) {
      const errorMessage = getErrorMessage(error2);
      historyManager.addItem(
        {
          type: "error" /* ERROR */,
          text: `Error refreshing memory: ${errorMessage}`
        },
        Date.now()
      );
      debugLogger118.error("Error refreshing memory:", error2);
    }
  }, [config2, historyManager, settings.merged]);
  const cancelHandlerRef = (0, import_react133.useRef)(() => {
  });
  const {
    streamingState,
    submitQuery,
    initError,
    pendingHistoryItems: pendingGeminiHistoryItems,
    thought,
    cancelOngoingRequest,
    handleApprovalModeChange,
    activePtyId,
    loopDetectionConfirmationRequest
  } = useGeminiStream(
    config2.getGeminiClient(),
    historyManager.history,
    historyManager.addItem,
    config2,
    settings,
    onDebugMessage,
    handleSlashCommand2,
    shellModeActive,
    () => settings.merged.general?.preferredEditor,
    onAuthError,
    performMemoryRefresh,
    modelSwitchedFromQuotaError,
    setModelSwitchedFromQuotaError,
    refreshStatic,
    () => cancelHandlerRef.current(),
    setEmbeddedShellFocused,
    terminalWidth,
    terminalHeight
  );
  const [hasSuggestionsVisible, setHasSuggestionsVisible] = (0, import_react133.useState)(false);
  const showAutoAcceptIndicator = useAutoAcceptIndicator({
    config: config2,
    addItem: historyManager.addItem,
    onApprovalModeChange: handleApprovalModeChange,
    shouldBlockTab: /* @__PURE__ */ __name(() => hasSuggestionsVisible, "shouldBlockTab")
  });
  const { messageQueue, addMessage, clearQueue, getQueuedMessagesText } = useMessageQueue({
    isConfigInitialized,
    streamingState,
    submitQuery
  });
  const handleFinalSubmit = (0, import_react133.useCallback)(
    (submittedValue) => {
      addMessage(submittedValue);
    },
    [addMessage]
  );
  const {
    welcomeBackInfo,
    showWelcomeBackDialog,
    welcomeBackChoice,
    handleWelcomeBackSelection,
    handleWelcomeBackClose
  } = useWelcomeBack(config2, handleFinalSubmit, buffer, settings.merged);
  cancelHandlerRef.current = (0, import_react133.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_react133.useCallback)(() => {
    historyManager.clearItems();
    clearScreen2();
    refreshStatic();
  }, [historyManager, refreshStatic]);
  const { handleInput: vimHandleInput } = useVim(buffer, handleFinalSubmit);
  const isInputActive = !initError && !isProcessing && (streamingState === "idle" /* Idle */ || streamingState === "responding" /* Responding */);
  const [controlsHeight, setControlsHeight] = (0, import_react133.useState)(0);
  (0, import_react133.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
  );
  config2.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_react133.useMemo)(() => {
    const fromSettings = settings.merged.context?.fileName;
    return fromSettings ? Array.isArray(fromSettings) ? fromSettings : [fromSettings] : getAllGeminiMdFilenames();
  }, [settings.merged.context?.fileName]);
  const initialPrompt = (0, import_react133.useMemo)(() => config2.getQuestion(), [config2]);
  const initialPromptSubmitted = (0, import_react133.useRef)(false);
  const geminiClient = config2.getGeminiClient();
  (0, import_react133.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_react133.useEffect)(() => {
    if (initialPrompt && isConfigInitialized && !initialPromptSubmitted.current && !isAuthenticating && !isAuthDialogOpen && !isThemeDialogOpen && !isEditorDialogOpen && !showWelcomeBackDialog && welcomeBackChoice !== "restart" && geminiClient?.isInitialized?.()) {
      handleFinalSubmit(initialPrompt);
      initialPromptSubmitted.current = true;
    }
  }, [
    initialPrompt,
    isConfigInitialized,
    handleFinalSubmit,
    isAuthenticating,
    isAuthDialogOpen,
    isThemeDialogOpen,
    isEditorDialogOpen,
    showWelcomeBackDialog,
    welcomeBackChoice,
    geminiClient
  ]);
  const [idePromptAnswered, setIdePromptAnswered] = (0, import_react133.useState)(false);
  const [currentIDE, setCurrentIDE] = (0, import_react133.useState)(null);
  (0, import_react133.useEffect)(() => {
    const getIde = /* @__PURE__ */ __name(async () => {
      const ideClient = await IdeClient.getInstance();
      const currentIde = ideClient.getCurrentIde();
      setCurrentIDE(currentIde || null);
    }, "getIde");
    getIde();
  }, []);
  const shouldShowIdePrompt = Boolean(
    currentIDE && !config2.getIdeMode() && !settings.merged.ide?.hasSeenNudge && !idePromptAnswered
  );
  const {
    showMigrationNudge: shouldShowCommandMigrationNudge,
    tomlFiles: commandMigrationTomlFiles,
    setShowMigrationNudge: setShowCommandMigrationNudge
  } = useCommandMigration(settings, config2.storage);
  const [showToolDescriptions, setShowToolDescriptions] = (0, import_react133.useState)(false);
  const [ctrlCPressedOnce, setCtrlCPressedOnce] = (0, import_react133.useState)(false);
  const ctrlCTimerRef = (0, import_react133.useRef)(null);
  const [ctrlDPressedOnce, setCtrlDPressedOnce] = (0, import_react133.useState)(false);
  const ctrlDTimerRef = (0, import_react133.useRef)(null);
  const [escapePressedOnce, setEscapePressedOnce] = (0, import_react133.useState)(false);
  const escapeTimerRef = (0, import_react133.useRef)(null);
  const [constrainHeight, setConstrainHeight] = (0, import_react133.useState)(true);
  const [ideContextState, setIdeContextState] = (0, import_react133.useState)();
  const [showEscapePrompt, setShowEscapePrompt] = (0, import_react133.useState)(false);
  const [showIdeRestartPrompt, setShowIdeRestartPrompt] = (0, import_react133.useState)(false);
  const { isFolderTrustDialogOpen, handleFolderTrustSelect, isRestarting } = useFolderTrust(settings, setIsTrustedFolder);
  const {
    needsRestart: ideNeedsRestart,
    restartReason: ideTrustRestartReason
  } = useIdeTrustListener();
  const isInitialMount = (0, import_react133.useRef)(true);
  (0, import_react133.useEffect)(() => {
    if (ideNeedsRestart) {
      setShowIdeRestartPrompt(true);
    }
  }, [ideNeedsRestart]);
  (0, import_react133.useEffect)(() => {
    if (isInitialMount.current) {
      isInitialMount.current = false;
      return;
    }
    const handler = setTimeout(() => {
      refreshStatic();
    }, 300);
    return () => {
      clearTimeout(handler);
    };
  }, [terminalWidth, refreshStatic]);
  (0, import_react133.useEffect)(() => {
    const unsubscribe = ideContextStore.subscribe(setIdeContextState);
    setIdeContextState(ideContextStore.get());
    return unsubscribe;
  }, []);
  const handleEscapePromptChange = (0, import_react133.useCallback)((showPrompt) => {
    setShowEscapePrompt(showPrompt);
  }, []);
  const handleIdePromptComplete = (0, import_react133.useCallback)(
    (result) => {
      if (result.userSelection === "yes") {
        if (result.isExtensionPreInstalled) {
          handleSlashCommand2("/ide enable");
        } else {
          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 handleCommandMigrationComplete = (0, import_react133.useCallback)(
    async (result) => {
      setShowCommandMigrationNudge(false);
      if (result.userSelection === "yes") {
        try {
          const results = [];
          const workspaceCommandsDir = config2.storage.getProjectCommandsDir();
          const workspaceResult = await migrateTomlCommands({
            commandDir: workspaceCommandsDir,
            createBackup: true,
            deleteOriginal: false
          });
          if (workspaceResult.convertedFiles.length > 0 || workspaceResult.failedFiles.length > 0) {
            results.push({ level: "workspace", result: workspaceResult });
          }
          const userCommandsDir = Storage.getUserCommandsDir();
          const userResult = await migrateTomlCommands({
            commandDir: userCommandsDir,
            createBackup: true,
            deleteOriginal: false
          });
          if (userResult.convertedFiles.length > 0 || userResult.failedFiles.length > 0) {
            results.push({ level: "user", result: userResult });
          }
          for (const { level, result: migrationResult } of results) {
            if (migrationResult.success && migrationResult.convertedFiles.length > 0) {
              historyManager.addItem(
                {
                  type: "info" /* INFO */,
                  text: `[${level}] Successfully migrated ${migrationResult.convertedFiles.length} command file${migrationResult.convertedFiles.length > 1 ? "s" : ""} to Markdown format. Original files backed up as .toml.backup`
                },
                Date.now()
              );
            }
            if (migrationResult.failedFiles.length > 0) {
              historyManager.addItem(
                {
                  type: "error" /* ERROR */,
                  text: `[${level}] Failed to migrate ${migrationResult.failedFiles.length} file${migrationResult.failedFiles.length > 1 ? "s" : ""}:
${migrationResult.failedFiles.map((f5) => `  \u2022 ${f5.file}: ${f5.error}`).join("\n")}`
                },
                Date.now()
              );
            }
          }
          if (results.length === 0) {
            historyManager.addItem(
              {
                type: "info" /* INFO */,
                text: "No TOML files found to migrate."
              },
              Date.now()
            );
          }
        } catch (error2) {
          historyManager.addItem(
            {
              type: "error" /* ERROR */,
              text: `\u274C Migration failed: ${getErrorMessage(error2)}`
            },
            Date.now()
          );
        }
      }
    },
    [historyManager, setShowCommandMigrationNudge, config2.storage]
  );
  const { elapsedTime, currentLoadingPhrase } = useLoadingIndicator(
    streamingState,
    settings.merged.ui?.customWittyPhrases
  );
  useAttentionNotifications({
    isFocused,
    streamingState,
    elapsedTime,
    settings
  });
  const { closeAnyOpenDialog } = useDialogClose({
    isThemeDialogOpen,
    handleThemeSelect,
    isApprovalModeDialogOpen,
    handleApprovalModeSelect,
    isAuthDialogOpen,
    handleAuthSelect,
    pendingAuthType,
    isEditorDialogOpen,
    exitEditorDialog,
    isSettingsDialogOpen,
    closeSettingsDialog,
    isFolderTrustDialogOpen,
    showWelcomeBackDialog,
    handleWelcomeBackClose
  });
  const handleExit = (0, import_react133.useCallback)(
    (pressedOnce, setPressedOnce, timerRef) => {
      if (pressedOnce) {
        if (timerRef.current) {
          clearTimeout(timerRef.current);
        }
        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;
      }
      setPressedOnce(true);
      timerRef.current = setTimeout(() => {
        setPressedOnce(false);
      }, CTRL_EXIT_PROMPT_DURATION_MS);
    },
    [
      isAuthDialogOpen,
      handleSlashCommand2,
      closeAnyOpenDialog,
      streamingState,
      cancelOngoingRequest,
      buffer
    ]
  );
  const handleGlobalKeypress = (0, import_react133.useCallback)(
    (key) => {
      if (settings.merged.general?.debugKeystrokeLogging) {
        debugLogger118.debug("[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;
      } else if (keyMatchers["escape" /* ESCAPE */](key)) {
        if (embeddedShellFocused) {
          return;
        }
        if (buffer.text.length > 0) {
          if (escapePressedOnce) {
            buffer.setText("");
            return;
          }
          setEscapePressedOnce(true);
          escapeTimerRef.current = setTimeout(() => {
            setEscapePressedOnce(false);
            escapeTimerRef.current = null;
          }, CTRL_EXIT_PROMPT_DURATION_MS);
          return;
        }
        if (streamingState === "responding" /* Responding */) {
          if (escapeTimerRef.current) {
            clearTimeout(escapeTimerRef.current);
            escapeTimerRef.current = null;
          }
          cancelOngoingRequest?.();
          setEscapePressedOnce(false);
          return;
        }
        if (escapeTimerRef.current) {
          clearTimeout(escapeTimerRef.current);
          escapeTimerRef.current = null;
        }
        setEscapePressedOnce(false);
        return;
      }
      let enteringConstrainHeightMode = false;
      if (!constrainHeight) {
        enteringConstrainHeightMode = true;
        setConstrainHeight(true);
      }
      if (keyMatchers["toggleToolDescriptions" /* TOGGLE_TOOL_DESCRIPTIONS */](key)) {
        const newValue = !showToolDescriptions;
        setShowToolDescriptions(newValue);
        const mcpServers = config2.getMcpServers();
        if (Object.keys(mcpServers || {}).length > 0) {
          handleSlashCommand2(newValue ? "/mcp desc" : "/mcp nodesc");
        }
      } else if (keyMatchers["toggleIDEContextDetail" /* TOGGLE_IDE_CONTEXT_DETAIL */](key) && config2.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,
      showToolDescriptions,
      setShowToolDescriptions,
      config2,
      ideContextState,
      handleExit,
      ctrlCPressedOnce,
      setCtrlCPressedOnce,
      ctrlCTimerRef,
      ctrlDPressedOnce,
      setCtrlDPressedOnce,
      ctrlDTimerRef,
      escapePressedOnce,
      setEscapePressedOnce,
      escapeTimerRef,
      streamingState,
      cancelOngoingRequest,
      buffer,
      handleSlashCommand2,
      activePtyId,
      embeddedShellFocused,
      settings.merged.general?.debugKeystrokeLogging,
      isAuthenticating
    ]
  );
  useKeypress(handleGlobalKeypress, { isActive: true });
  (0, import_react133.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 nightly = props.version.includes("nightly");
  const dialogsVisible = showWelcomeBackDialog || shouldShowIdePrompt || shouldShowCommandMigrationNudge || isFolderTrustDialogOpen || !!shellConfirmationRequest || !!confirmationRequest || confirmUpdateExtensionRequests.length > 0 || !!codingPlanUpdateRequest || settingInputRequests.length > 0 || pluginChoiceRequests.length > 0 || !!loopDetectionConfirmationRequest || isThemeDialogOpen || isSettingsDialogOpen || isModelDialogOpen || isPermissionsDialogOpen || isAuthDialogOpen || isAuthenticating || isEditorDialogOpen || showIdeRestartPrompt || isSubagentCreateDialogOpen || isAgentsManagerDialogOpen || isApprovalModeDialogOpen || isResumeDialogOpen;
  const {
    isFeedbackDialogOpen,
    openFeedbackDialog,
    closeFeedbackDialog,
    temporaryCloseFeedbackDialog,
    submitFeedback
  } = useFeedbackDialog({
    config: config2,
    settings,
    streamingState,
    history: historyManager.history,
    sessionStats
  });
  const pendingHistoryItems = (0, import_react133.useMemo)(
    () => [...pendingSlashCommandHistoryItems, ...pendingGeminiHistoryItems],
    [pendingSlashCommandHistoryItems, pendingGeminiHistoryItems]
  );
  const uiState = (0, import_react133.useMemo)(
    () => ({
      history: historyManager.history,
      historyManager,
      isThemeDialogOpen,
      themeError,
      isAuthenticating,
      isConfigInitialized,
      authError,
      isAuthDialogOpen,
      pendingAuthType,
      // Qwen OAuth state
      qwenAuthState,
      editorError,
      isEditorDialogOpen,
      debugMessage,
      quittingMessages,
      isSettingsDialogOpen,
      isModelDialogOpen,
      isPermissionsDialogOpen,
      isApprovalModeDialogOpen,
      isResumeDialogOpen,
      slashCommands,
      pendingSlashCommandHistoryItems,
      commandContext,
      shellConfirmationRequest,
      confirmationRequest,
      confirmUpdateExtensionRequests,
      codingPlanUpdateRequest,
      settingInputRequests,
      pluginChoiceRequests,
      loopDetectionConfirmationRequest,
      geminiMdFileCount,
      streamingState,
      initError,
      pendingGeminiHistoryItems,
      thought,
      shellModeActive,
      userMessages,
      buffer,
      inputWidth,
      suggestionsWidth,
      isInputActive,
      shouldShowIdePrompt,
      shouldShowCommandMigrationNudge,
      commandMigrationTomlFiles,
      isFolderTrustDialogOpen: isFolderTrustDialogOpen ?? false,
      isTrustedFolder,
      constrainHeight,
      ideContextState,
      showToolDescriptions,
      ctrlCPressedOnce,
      ctrlDPressedOnce,
      showEscapePrompt,
      isFocused,
      elapsedTime,
      currentLoadingPhrase,
      historyRemountKey,
      messageQueue,
      showAutoAcceptIndicator,
      currentModel,
      contextFileNames,
      availableTerminalHeight,
      mainAreaWidth,
      staticAreaMaxItemHeight,
      staticExtraHeight,
      dialogsVisible,
      pendingHistoryItems,
      nightly,
      branchName,
      sessionStats,
      terminalWidth,
      terminalHeight,
      mainControlsRef,
      currentIDE,
      updateInfo,
      showIdeRestartPrompt,
      ideTrustRestartReason,
      isRestarting,
      extensionsUpdateState,
      activePtyId,
      embeddedShellFocused,
      // Welcome back dialog
      showWelcomeBackDialog,
      welcomeBackInfo,
      welcomeBackChoice,
      // Subagent dialogs
      isSubagentCreateDialogOpen,
      isAgentsManagerDialogOpen,
      // Feedback dialog
      isFeedbackDialogOpen
    }),
    [
      isThemeDialogOpen,
      themeError,
      isAuthenticating,
      isConfigInitialized,
      authError,
      isAuthDialogOpen,
      pendingAuthType,
      // Qwen OAuth state
      qwenAuthState,
      editorError,
      isEditorDialogOpen,
      debugMessage,
      quittingMessages,
      isSettingsDialogOpen,
      isModelDialogOpen,
      isPermissionsDialogOpen,
      isApprovalModeDialogOpen,
      isResumeDialogOpen,
      slashCommands,
      pendingSlashCommandHistoryItems,
      commandContext,
      shellConfirmationRequest,
      confirmationRequest,
      confirmUpdateExtensionRequests,
      codingPlanUpdateRequest,
      settingInputRequests,
      pluginChoiceRequests,
      loopDetectionConfirmationRequest,
      geminiMdFileCount,
      streamingState,
      initError,
      pendingGeminiHistoryItems,
      thought,
      shellModeActive,
      userMessages,
      buffer,
      inputWidth,
      suggestionsWidth,
      isInputActive,
      shouldShowIdePrompt,
      shouldShowCommandMigrationNudge,
      commandMigrationTomlFiles,
      isFolderTrustDialogOpen,
      isTrustedFolder,
      constrainHeight,
      ideContextState,
      showToolDescriptions,
      ctrlCPressedOnce,
      ctrlDPressedOnce,
      showEscapePrompt,
      isFocused,
      elapsedTime,
      currentLoadingPhrase,
      historyRemountKey,
      messageQueue,
      showAutoAcceptIndicator,
      contextFileNames,
      availableTerminalHeight,
      mainAreaWidth,
      staticAreaMaxItemHeight,
      staticExtraHeight,
      dialogsVisible,
      pendingHistoryItems,
      nightly,
      branchName,
      sessionStats,
      terminalWidth,
      terminalHeight,
      mainControlsRef,
      currentIDE,
      updateInfo,
      showIdeRestartPrompt,
      ideTrustRestartReason,
      isRestarting,
      currentModel,
      extensionsUpdateState,
      activePtyId,
      historyManager,
      embeddedShellFocused,
      // Welcome back dialog
      showWelcomeBackDialog,
      welcomeBackInfo,
      welcomeBackChoice,
      // Subagent dialogs
      isSubagentCreateDialogOpen,
      isAgentsManagerDialogOpen,
      // Feedback dialog
      isFeedbackDialogOpen
    ]
  );
  const uiActions = (0, import_react133.useMemo)(
    () => ({
      openThemeDialog,
      openEditorDialog,
      handleThemeSelect,
      handleThemeHighlight,
      handleApprovalModeSelect,
      handleAuthSelect,
      setAuthState,
      onAuthError,
      cancelAuthentication,
      handleCodingPlanSubmit,
      handleEditorSelect,
      exitEditorDialog,
      closeSettingsDialog,
      closeModelDialog,
      dismissCodingPlanUpdate,
      closePermissionsDialog,
      setShellModeActive,
      vimHandleInput,
      handleIdePromptComplete,
      handleCommandMigrationComplete,
      handleFolderTrustSelect,
      setConstrainHeight,
      onEscapePromptChange: handleEscapePromptChange,
      onSuggestionsVisibilityChange: setHasSuggestionsVisible,
      refreshStatic,
      handleFinalSubmit,
      handleClearScreen,
      // Welcome back dialog
      handleWelcomeBackSelection,
      handleWelcomeBackClose,
      // Subagent dialogs
      closeSubagentCreateDialog,
      closeAgentsManagerDialog,
      // Resume session dialog
      openResumeDialog,
      closeResumeDialog,
      handleResume,
      // Feedback dialog
      openFeedbackDialog,
      closeFeedbackDialog,
      temporaryCloseFeedbackDialog,
      submitFeedback
    }),
    [
      openThemeDialog,
      openEditorDialog,
      handleThemeSelect,
      handleThemeHighlight,
      handleApprovalModeSelect,
      handleAuthSelect,
      setAuthState,
      onAuthError,
      cancelAuthentication,
      handleCodingPlanSubmit,
      handleEditorSelect,
      exitEditorDialog,
      closeSettingsDialog,
      closeModelDialog,
      dismissCodingPlanUpdate,
      closePermissionsDialog,
      setShellModeActive,
      vimHandleInput,
      handleIdePromptComplete,
      handleCommandMigrationComplete,
      handleFolderTrustSelect,
      setConstrainHeight,
      handleEscapePromptChange,
      refreshStatic,
      handleFinalSubmit,
      handleClearScreen,
      handleWelcomeBackSelection,
      handleWelcomeBackClose,
      // Subagent dialogs
      closeSubagentCreateDialog,
      closeAgentsManagerDialog,
      // Resume session dialog
      openResumeDialog,
      closeResumeDialog,
      handleResume,
      // Feedback dialog
      openFeedbackDialog,
      closeFeedbackDialog,
      temporaryCloseFeedbackDialog,
      submitFeedback
    ]
  );
  return /* @__PURE__ */ (0, import_jsx_runtime109.jsx)(UIStateContext.Provider, { value: uiState, children: /* @__PURE__ */ (0, import_jsx_runtime109.jsx)(UIActionsContext.Provider, { value: uiActions, children: /* @__PURE__ */ (0, import_jsx_runtime109.jsx)(ConfigContext.Provider, { value: config2, children: /* @__PURE__ */ (0, import_jsx_runtime109.jsx)(
    AppContext2.Provider,
    {
      value: {
        version: props.version,
        startupWarnings: props.startupWarnings || []
      },
      children: /* @__PURE__ */ (0, import_jsx_runtime109.jsx)(ShellFocusContext.Provider, { value: isFocused, children: /* @__PURE__ */ (0, import_jsx_runtime109.jsx)(App2, {}) })
    }
  ) }) }) });
}, "AppContainer");

// packages/cli/src/ui/hooks/useKittyKeyboardProtocol.ts
init_esbuild_shims();
var import_react134 = __toESM(require_react(), 1);
function useKittyKeyboardProtocol() {
  const [status] = (0, import_react134.useState)({
    supported: isKittyProtocolSupported(),
    enabled: isKittyProtocolEnabled(),
    checking: false
  });
  return status;
}
__name(useKittyKeyboardProtocol, "useKittyKeyboardProtocol");

// packages/cli/src/utils/readStdin.ts
init_esbuild_shims();
async function readStdin() {
  const MAX_STDIN_SIZE = 8 * 1024 * 1024;
  return new Promise((resolve30, 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);
          writeStderrLine(
            `Warning: stdin input truncated to ${MAX_STDIN_SIZE} bytes.`
          );
          process.stdin.destroy();
          break;
        }
        data += chunk;
        totalSize += chunk.length;
      }
    }, "onReadable");
    const onEnd = /* @__PURE__ */ __name(() => {
      cleanup();
      resolve30(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/utils/relaunch.ts
init_esbuild_shims();
import { spawn as spawn11 } from "node:child_process";
async function relaunchOnExitCode(runner) {
  while (true) {
    try {
      const exitCode = await runner();
      if (exitCode !== RELAUNCH_EXIT_CODE) {
        process.exit(exitCode);
      }
    } catch (error2) {
      process.stdin.resume();
      writeStderrLine("Fatal error: Failed to relaunch the CLI process.");
      writeStderrLine(error2 instanceof Error ? error2.message : String(error2));
      process.exit(1);
    }
  }
}
__name(relaunchOnExitCode, "relaunchOnExitCode");
async function relaunchAppInChildProcess(additionalNodeArgs, additionalScriptArgs) {
  if (process.env["QWEN_CODE_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, QWEN_CODE_NO_RELAUNCH: "true" };
    process.stdin.pause();
    const child = spawn11(process.execPath, nodeArgs, {
      stdio: "inherit",
      env: newEnv
    });
    return new Promise((resolve30, reject) => {
      child.on("error", reject);
      child.on("close", (code2) => {
        process.stdin.resume();
        resolve30(code2 ?? 1);
      });
    });
  }, "runner");
  await relaunchOnExitCode(runner);
}
__name(relaunchAppInChildProcess, "relaunchAppInChildProcess");

// packages/cli/src/utils/sandbox.ts
init_esbuild_shims();
var import_shell_quote5 = __toESM(require_shell_quote(), 1);
import { exec as exec4, execSync as execSync8, spawn as spawn12 } from "node:child_process";
import os43 from "node:os";
import path123 from "node:path";
import fs110 from "node:fs";
import { fileURLToPath as fileURLToPath16 } from "node:url";
import { promisify as promisify12 } from "node:util";
import { randomBytes as randomBytes5 } from "node:crypto";
var execAsync3 = promisify12(exec4);
function getContainerPath(hostPath) {
  if (os43.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 (os43.platform() === "linux") {
    const debugEnv = [process.env["DEBUG"], process.env["DEBUG_MODE"]].some(
      (v2) => v2 === "true" || v2 === "1"
    );
    if (debugEnv) {
      writeStderrLine(
        "INFO: Using current user UID/GID in Linux sandbox. Set SANDBOX_SET_UID_GID=false to disable."
      );
    }
    return true;
  }
  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((p2) => p2.trim()).map((p2) => p2.trim());
}
__name(ports, "ports");
function entrypoint(workdir, cliArgs) {
  const isWindows9 = os43.platform() === "win32";
  const containerWorkdir = getContainerPath(workdir);
  const shellCmds = [];
  const pathSeparator = isWindows9 ? ";" : ":";
  let pathSuffix = "";
  if (process.env["PATH"]) {
    const paths = process.env["PATH"].split(pathSeparator);
    for (const p2 of paths) {
      const containerPath = getContainerPath(p2);
      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 p2 of paths) {
      const containerPath = getContainerPath(p2);
      if (containerPath.toLowerCase().startsWith(containerWorkdir.toLowerCase())) {
        pythonPathSuffix += `:${containerPath}`;
      }
    }
  }
  if (pythonPathSuffix) {
    shellCmds.push(`export PYTHONPATH="$PYTHONPATH${pythonPathSuffix}";`);
  }
  const projectSandboxBashrc = path123.join(
    SETTINGS_DIRECTORY_NAME2,
    "sandbox.bashrc"
  );
  if (fs110.existsSync(projectSandboxBashrc)) {
    shellCmds.push(`source ${getContainerPath(projectSandboxBashrc)};`);
  }
  ports().forEach(
    (p2) => shellCmds.push(
      `socat TCP4-LISTEN:${p2},bind=$(hostname -i),fork,reuseaddr TCP4:127.0.0.1:${p2} 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(config2, nodeArgs = [], cliConfig, cliArgs = []) {
  if (config2.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 = fileURLToPath16(
      new URL(`sandbox-macos-${profile}.sb`, import.meta.url)
    );
    if (!BUILTIN_SEATBELT_PROFILES.includes(profile)) {
      profileFile = path123.join(
        SETTINGS_DIRECTORY_NAME2,
        `sandbox-macos-${profile}.sb`
      );
    }
    if (!fs110.existsSync(profileFile)) {
      throw new FatalSandboxError(
        `Missing macos seatbelt profile file '${profileFile}'`
      );
    }
    writeStderrLine(`using macos seatbelt (profile: ${profile}) ...`);
    const nodeOptions = [
      ...process.env["DEBUG"] ? ["--inspect-brk"] : [],
      ...nodeArgs
    ].join(" ");
    const args2 = [
      "-D",
      `TARGET_DIR=${fs110.realpathSync(process.cwd())}`,
      "-D",
      `TMP_DIR=${fs110.realpathSync(os43.tmpdir())}`,
      "-D",
      `HOME_DIR=${fs110.realpathSync(os43.homedir())}`,
      "-D",
      `CACHE_DIR=${fs110.realpathSync(execSync8(`getconf DARWIN_USER_CACHE_DIR`).toString().trim())}`
    ];
    const MAX_INCLUDE_DIRS = 5;
    const targetDir = fs110.realpathSync(cliConfig?.getTargetDir() || "");
    const includedDirs = [];
    if (cliConfig) {
      const workspaceContext = cliConfig.getWorkspaceContext();
      const directories = workspaceContext.getDirectories();
      for (const dir of directories) {
        const realDir = fs110.realpathSync(dir);
        if (realDir !== targetDir) {
          includedDirs.push(realDir);
        }
      }
    }
    for (let i3 = 0; i3 < MAX_INCLUDE_DIRS; i3++) {
      let dirPath = "/dev/null";
      if (i3 < includedDirs.length) {
        dirPath = includedDirs[i3];
      }
      args2.push("-D", `INCLUDE_DIR_${i3}=${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 = spawn12("bash", ["-c", proxyCommand2], {
        stdio: ["ignore", "pipe", "pipe"],
        detached: true
      });
      const stopProxy = /* @__PURE__ */ __name(() => {
        writeStderrLine("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) => {
        writeStderrLine(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}`
        );
      });
      writeStderrLine("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 = spawn12(config2.command, args2, {
      stdio: "inherit"
    });
    return new Promise((resolve30, reject) => {
      sandboxProcess2?.on("error", reject);
      sandboxProcess2?.on("close", (code2) => {
        process.stdin.resume();
        resolve30(code2 ?? 1);
      });
    });
  }
  writeStderrLine(`hopping into sandbox (command: ${config2.command}) ...`);
  const gcPath = fs110.realpathSync(process.argv[1]);
  const projectSandboxDockerfile = path123.join(
    SETTINGS_DIRECTORY_NAME2,
    "sandbox.Dockerfile"
  );
  const isCustomProjectSandbox = fs110.existsSync(projectSandboxDockerfile);
  const image2 = config2.image;
  const workdir = path123.resolve(process.cwd());
  const containerWorkdir = getContainerPath(workdir);
  if (process.env["BUILD_SANDBOX"]) {
    if (!gcPath.includes("qwen-code/packages/")) {
      throw new FatalSandboxError(
        "Cannot build sandbox using installed Qwen Code binary; run `npm link ./packages/cli` under QwenCode-cli repo to switch to linked binary."
      );
    } else {
      writeStderrLine("building sandbox ...");
      const gcRoot = gcPath.split("/packages/")[0];
      let buildArgs = "";
      const projectSandboxDockerfile2 = path123.join(
        SETTINGS_DIRECTORY_NAME2,
        "sandbox.Dockerfile"
      );
      if (isCustomProjectSandbox) {
        writeStderrLine(`using ${projectSandboxDockerfile2} for sandbox`);
        buildArgs += `-f ${path123.resolve(projectSandboxDockerfile2)} -i ${image2}`;
      }
      execSync8(
        `cd ${gcRoot} && node scripts/build_sandbox.js -s ${buildArgs}`,
        {
          stdio: "inherit",
          env: {
            ...process.env,
            GEMINI_SANDBOX: config2.command
            // in case sandbox is enabled via flags (see config.ts under cli package)
          }
        }
      );
    }
  }
  if (!await ensureSandboxImageIsPresent(config2.command, image2)) {
    const remedy = image2 === LOCAL_DEV_SANDBOX_IMAGE_NAME ? "Try running `npm run build:all` or `npm run build:sandbox` under the qwen-code repo to build it locally, or check the image name and your network connection." : "Please check the image name, your network connection, or notify qwen-code-dev@service.alibaba.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(
      (f5) => typeof f5 === "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 (!fs110.existsSync(userSettingsDirOnHost)) {
    fs110.mkdirSync(userSettingsDirOnHost);
  }
  args.push("--volume", `${userSettingsDirOnHost}:${userSettingsDirInSandbox}`);
  if (userSettingsDirInSandbox !== userSettingsDirOnHost) {
    args.push(
      "--volume",
      `${userSettingsDirOnHost}:${getContainerPath(userSettingsDirOnHost)}`
    );
  }
  args.push("--volume", `${os43.tmpdir()}:${getContainerPath(os43.tmpdir())}`);
  const gcloudConfigDir = path123.join(os43.homedir(), ".config", "gcloud");
  if (fs110.existsSync(gcloudConfigDir)) {
    args.push(
      "--volume",
      `${gcloudConfigDir}:${getContainerPath(gcloudConfigDir)}:ro`
    );
  }
  if (process.env["GOOGLE_APPLICATION_CREDENTIALS"]) {
    const adcFile = process.env["GOOGLE_APPLICATION_CREDENTIALS"];
    if (fs110.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 (!path123.isAbsolute(from)) {
          throw new FatalSandboxError(
            `Path '${from}' listed in SANDBOX_MOUNTS must be absolute`
          );
        }
        if (!fs110.existsSync(from)) {
          throw new FatalSandboxError(
            `Missing mount path '${from}' listed in SANDBOX_MOUNTS`
          );
        }
        writeStderrLine(`SANDBOX_MOUNTS: ${from} -> ${to} (${opts})`);
        args.push("--volume", mount);
      }
    }
  }
  ports().forEach((p2) => args.push("--publish", `${p2}:${p2}`));
  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) {
      execSync8(
        `${config2.command} network inspect ${SANDBOX_NETWORK_NAME} || ${config2.command} network create --internal ${SANDBOX_NETWORK_NAME}`
      );
      args.push("--network", SANDBOX_NETWORK_NAME);
      if (proxyCommand) {
        execSync8(
          `${config2.command} network inspect ${SANDBOX_PROXY_NAME} || ${config2.command} network create ${SANDBOX_PROXY_NAME}`
        );
      }
    }
  }
  const imageName = parseImageName(image2);
  const isIntegrationTest = process.env["QWEN_CODE_INTEGRATION_TEST"] === "true";
  let containerName;
  if (isIntegrationTest) {
    containerName = `qwen-code-integration-test-${randomBytes5(4).toString(
      "hex"
    )}`;
    writeStderrLine(`ContainerName: ${containerName}`);
  } else {
    let index = 0;
    const containerNameCheck = execSync8(
      `${config2.command} ps -a --format "{{.Names}}"`
    ).toString().trim();
    while (containerNameCheck.includes(`${imageName}-${index}`)) {
      index++;
    }
    containerName = `${imageName}-${index}`;
    writeStderrLine(`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 = path123.resolve(
      SETTINGS_DIRECTORY_NAME2,
      "sandbox.venv"
    );
    if (!fs110.existsSync(sandboxVenvPath)) {
      fs110.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("=")) {
          writeStderrLine(`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 (config2.command === "podman") {
    const emptyAuthFilePath = path123.join(os43.tmpdir(), "empty_auth.json");
    fs110.writeFileSync(emptyAuthFilePath, "{}", "utf-8");
    args.push("--authfile", emptyAuthFilePath);
  }
  let userFlag = "";
  const finalEntrypoint = entrypoint(workdir, cliArgs);
  const useCurrentUser = await shouldUseCurrentUserInSandbox();
  if (useCurrentUser) {
    args.push("--user", "root");
    const uid = execSync8("id -u").toString().trim();
    const gid = execSync8("id -g").toString().trim();
    const username = "qwen";
    const homeDir = getContainerPath(os43.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=${os43.homedir()}`);
  } else if (isIntegrationTest) {
    args.push("--user", "root");
    userFlag = "--user root";
  }
  args.push(image2);
  args.push(...finalEntrypoint);
  let proxyProcess = void 0;
  let sandboxProcess = void 0;
  if (proxyCommand) {
    const proxyContainerCommand = `${config2.command} run --rm --init ${userFlag} --name ${SANDBOX_PROXY_NAME} --network ${SANDBOX_PROXY_NAME} -p 8877:8877 -v ${process.cwd()}:${workdir} --workdir ${workdir} ${image2} ${proxyCommand}`;
    const isWindows9 = os43.platform() === "win32";
    const proxyShell = isWindows9 ? "cmd.exe" : "bash";
    const proxyShellArgs = isWindows9 ? ["/c", proxyContainerCommand] : ["-c", proxyContainerCommand];
    proxyProcess = spawn12(proxyShell, proxyShellArgs, {
      stdio: ["ignore", "pipe", "pipe"],
      detached: true
    });
    const stopProxy = /* @__PURE__ */ __name(() => {
      writeStderrLine("stopping proxy container ...");
      execSync8(`${config2.command} rm -f ${SANDBOX_PROXY_NAME}`);
    }, "stopProxy");
    process.on("exit", stopProxy);
    process.on("SIGINT", stopProxy);
    process.on("SIGTERM", stopProxy);
    proxyProcess.stderr?.on("data", (data) => {
      writeStderrLine(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}`
      );
    });
    writeStderrLine("waiting for proxy to start ...");
    await execAsync3(
      `until timeout 0.25 curl -s http://localhost:8877; do sleep 0.25; done`
    );
    await execAsync3(
      `${config2.command} network connect ${SANDBOX_NETWORK_NAME} ${SANDBOX_PROXY_NAME}`
    );
  }
  process.stdin.pause();
  sandboxProcess = spawn12(config2.command, args, {
    stdio: "inherit"
  });
  return new Promise((resolve30, reject) => {
    sandboxProcess.on("error", (err) => {
      writeStderrLine(`Sandbox process error: ${err}`);
      reject(err);
    });
    sandboxProcess?.on("close", (code2, signal) => {
      process.stdin.resume();
      if (code2 !== 0 && code2 !== null) {
        writeStderrLine(
          `Sandbox process exited with code: ${code2}, signal: ${signal}`
        );
      }
      resolve30(code2 ?? 1);
    });
  });
}
__name(start_sandbox, "start_sandbox");
async function imageExists(sandbox, image2) {
  return new Promise((resolve30) => {
    const args = ["images", "-q", image2];
    const checkProcess = spawn12(sandbox, args);
    let stdoutData = "";
    if (checkProcess.stdout) {
      checkProcess.stdout.on("data", (data) => {
        stdoutData += data.toString();
      });
    }
    checkProcess.on("error", (err) => {
      writeStderrLine(
        `Failed to start '${sandbox}' command for image check: ${err.message}`
      );
      resolve30(false);
    });
    checkProcess.on("close", (code2) => {
      if (code2 !== 0) {
      }
      resolve30(stdoutData.trim() !== "");
    });
  });
}
__name(imageExists, "imageExists");
async function pullImage(sandbox, image2) {
  writeStderrLine(`Attempting to pull image ${image2} using ${sandbox}...`);
  return new Promise((resolve30) => {
    const args = ["pull", image2];
    const pullProcess = spawn12(sandbox, args, { stdio: "pipe" });
    let stderrData = "";
    const onStdoutData = /* @__PURE__ */ __name((data) => {
      writeStderrLine(data.toString().trim());
    }, "onStdoutData");
    const onStderrData = /* @__PURE__ */ __name((data) => {
      stderrData += data.toString();
      writeStderrLine(data.toString().trim());
    }, "onStderrData");
    const onError2 = /* @__PURE__ */ __name((err) => {
      writeStderrLine(
        `Failed to start '${sandbox} pull ${image2}' command: ${err.message}`
      );
      cleanup();
      resolve30(false);
    }, "onError");
    const onClose = /* @__PURE__ */ __name((code2) => {
      if (code2 === 0) {
        writeStderrLine(`Successfully pulled image ${image2}.`);
        cleanup();
        resolve30(true);
      } else {
        writeStderrLine(
          `Failed to pull image ${image2}. '${sandbox} pull ${image2}' exited with code ${code2}.`
        );
        if (stderrData.trim()) {
        }
        cleanup();
        resolve30(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) {
  writeStderrLine(`Checking for sandbox image: ${image2}`);
  if (await imageExists(sandbox, image2)) {
    writeStderrLine(`Sandbox image ${image2} found locally.`);
    return true;
  }
  writeStderrLine(`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)) {
      writeStderrLine(`Sandbox image ${image2} is now available after pulling.`);
      return true;
    } else {
      writeStderrLine(
        `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;
    }
  }
  writeStderrLine(
    `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 fs111 from "node:fs/promises";
import os44 from "node:os";
import { join as pathJoin } from "node:path";
var warningsFilePath = pathJoin(os44.tmpdir(), "qwen-code-warnings.txt");
async function getStartupWarnings() {
  try {
    await fs111.access(warningsFilePath);
    const warningsContent = await fs111.readFile(warningsFilePath, "utf-8");
    const warnings = warningsContent.split("\n").filter((line) => line.trim() !== "");
    try {
      await fs111.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 fs112 from "node:fs/promises";
import * as os45 from "node:os";
import path124 from "node:path";
var homeDirectoryCheck = {
  id: "home-directory",
  check: /* @__PURE__ */ __name(async (options2) => {
    try {
      const [workspaceRealPath, homeRealPath] = await Promise.all([
        fs112.realpath(options2.workspaceRoot),
        fs112.realpath(os45.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 fs112.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 (path124.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 (error2) {
      return `Ripgrep not available: ${error2 instanceof Error ? error2.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((check2) => check2.check(options2))
  );
  return results.filter((msg) => msg !== null);
}
__name(getUserStartupWarnings, "getUserStartupWarnings");

// packages/cli/src/validateNonInterActiveAuth.ts
init_esbuild_shims();
async function validateNonInteractiveAuth(useExternalAuth, nonInteractiveConfig, settings) {
  try {
    const authType = nonInteractiveConfig.getModelsConfig().getCurrentAuthType();
    if (!authType) {
      throw new Error(
        "No auth type is selected. Please configure an auth type (e.g. via settings or `--auth-type`) before running in non-interactive mode."
      );
    }
    const resolvedAuthType = authType;
    const enforcedType = settings.merged.security?.auth?.enforcedType;
    if (enforcedType && enforcedType !== resolvedAuthType) {
      const message = `The configured auth type is ${enforcedType}, but the current auth type is ${resolvedAuthType}. Please re-authenticate with the correct type.`;
      throw new Error(message);
    }
    if (!useExternalAuth) {
      const err = validateAuthMethod(resolvedAuthType, nonInteractiveConfig);
      if (err != null) {
        throw new Error(err);
      }
    }
    await nonInteractiveConfig.refreshAuth(resolvedAuthType);
    return nonInteractiveConfig;
  } catch (error2) {
    const outputFormat = nonInteractiveConfig.getOutputFormat();
    if (outputFormat === OutputFormat.JSON || outputFormat === OutputFormat.STREAM_JSON) {
      let adapter;
      if (outputFormat === OutputFormat.JSON) {
        adapter = new JsonOutputAdapter(nonInteractiveConfig);
      } else {
        adapter = new StreamJsonOutputAdapter(
          nonInteractiveConfig,
          nonInteractiveConfig.getIncludePartialMessages()
        );
      }
      const errorMessage = error2 instanceof Error ? error2.message : String(error2);
      adapter.emitResult({
        isError: true,
        errorMessage,
        durationMs: 0,
        apiDurationMs: 0,
        numTurns: 0,
        usage: void 0
      });
      await runExitCleanup();
      process.exit(1);
    }
    writeStderrLine(error2 instanceof Error ? error2.message : String(error2));
    process.exit(1);
  }
}
__name(validateNonInteractiveAuth, "validateNonInteractiveAuth");

// packages/cli/src/ui/components/StandaloneSessionPicker.tsx
init_esbuild_shims();
var import_react135 = __toESM(require_react(), 1);
var import_jsx_runtime110 = __toESM(require_jsx_runtime(), 1);
function StandalonePickerScreen({
  sessionService,
  onSelect,
  onCancel,
  currentBranch
}) {
  const { exit } = use_app_default();
  const [isExiting, setIsExiting] = (0, import_react135.useState)(false);
  const handleExit = /* @__PURE__ */ __name(() => {
    setIsExiting(true);
    exit();
  }, "handleExit");
  if (isExiting) {
    return /* @__PURE__ */ (0, import_jsx_runtime110.jsx)(Box_default, {});
  }
  return /* @__PURE__ */ (0, import_jsx_runtime110.jsx)(
    SessionPicker,
    {
      sessionService,
      onSelect: (id) => {
        onSelect(id);
        handleExit();
      },
      onCancel: () => {
        onCancel();
        handleExit();
      },
      currentBranch,
      centerSelection: true
    }
  );
}
__name(StandalonePickerScreen, "StandalonePickerScreen");
function clearScreen3() {
  process.stdout.write("\x1B[2J\x1B[H");
}
__name(clearScreen3, "clearScreen");
async function showResumeSessionPicker(cwd7 = process.cwd()) {
  const sessionService = new SessionService(cwd7);
  const hasSession = await sessionService.loadLastSession();
  if (!hasSession) {
    writeStdoutLine("No sessions found. Start a new session with `qwen`.");
    return void 0;
  }
  clearScreen3();
  const wasRaw = process.stdin.isRaw;
  if (process.stdin.isTTY && !wasRaw) {
    process.stdin.setRawMode(true);
  }
  return new Promise((resolve30) => {
    let selectedId;
    const { unmount, waitUntilExit } = render_default(
      /* @__PURE__ */ (0, import_jsx_runtime110.jsx)(
        KeypressProvider,
        {
          kittyProtocolEnabled: false,
          pasteWorkaround: process.platform === "win32" || parseInt(process.versions.node.split(".")[0], 10) < 20,
          children: /* @__PURE__ */ (0, import_jsx_runtime110.jsx)(
            StandalonePickerScreen,
            {
              sessionService,
              onSelect: (id) => {
                selectedId = id;
              },
              onCancel: () => {
                selectedId = void 0;
              },
              currentBranch: getGitBranch(cwd7)
            }
          )
        }
      ),
      {
        exitOnCtrlC: false
      }
    );
    waitUntilExit().then(() => {
      unmount();
      clearScreen3();
      if (process.stdin.isTTY && !wasRaw && !selectedId) {
        process.stdin.setRawMode(false);
      }
      resolve30(selectedId);
    });
  });
}
__name(showResumeSessionPicker, "showResumeSessionPicker");

// packages/cli/src/acp-integration/acpAgent.ts
init_esbuild_shims();

// packages/cli/src/acp-integration/acp.ts
init_esbuild_shims();
init_zod();

// packages/cli/src/acp-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",
  session_list: "session/list",
  session_set_mode: "session/set_mode",
  session_set_model: "session/set_model"
};
var CLIENT_METHODS = {
  fs_read_text_file: "fs/read_text_file",
  fs_write_text_file: "fs/write_text_file",
  authenticate_update: "authenticate/update",
  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("switch_mode"),
  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 approvalModeValueSchema = external_exports.union([
  external_exports.literal("plan"),
  external_exports.literal("default"),
  external_exports.literal("auto-edit"),
  external_exports.literal("yolo")
]);
var setModeRequestSchema = external_exports.object({
  sessionId: external_exports.string(),
  modeId: approvalModeValueSchema
});
var setModeResponseSchema = external_exports.object({
  modeId: approvalModeValueSchema
});
var authenticateRequestSchema = external_exports.object({
  methodId: external_exports.string()
});
var authenticateUpdateSchema = external_exports.object({
  _meta: external_exports.object({
    authUri: external_exports.string()
  })
});
var acpMetaSchema = external_exports.record(external_exports.unknown()).nullable().optional();
var modelIdSchema = external_exports.string();
var modelInfoSchema = external_exports.object({
  _meta: acpMetaSchema,
  description: external_exports.string().nullable().optional(),
  modelId: modelIdSchema,
  name: external_exports.string()
});
var setModelRequestSchema = external_exports.object({
  sessionId: external_exports.string(),
  modelId: external_exports.string()
});
var setModelResponseSchema = external_exports.object({
  modelId: external_exports.string()
});
var sessionModelStateSchema = external_exports.object({
  _meta: acpMetaSchema,
  availableModels: external_exports.array(modelInfoSchema),
  currentModelId: modelIdSchema
});
var newSessionResponseSchema = external_exports.object({
  sessionId: external_exports.string(),
  models: sessionModelStateSchema
});
var loadSessionResponseSchema = external_exports.null();
var sessionListItemSchema = external_exports.object({
  cwd: external_exports.string(),
  filePath: external_exports.string(),
  gitBranch: external_exports.string().optional(),
  messageCount: external_exports.number(),
  mtime: external_exports.number(),
  prompt: external_exports.string(),
  sessionId: external_exports.string(),
  startTime: external_exports.string()
});
var listSessionsResponseSchema = external_exports.object({
  hasMore: external_exports.boolean(),
  items: external_exports.array(sessionListItemSchema),
  nextCursor: external_exports.number().optional()
});
var listSessionsRequestSchema = external_exports.object({
  cursor: external_exports.number().optional(),
  cwd: external_exports.string(),
  size: external_exports.number().optional()
});
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 usageSchema = external_exports.object({
  promptTokens: external_exports.number().optional().nullable(),
  completionTokens: external_exports.number().optional().nullable(),
  thoughtsTokens: external_exports.number().optional().nullable(),
  totalTokens: external_exports.number().optional().nullable(),
  cachedTokens: external_exports.number().optional().nullable()
});
var sessionUpdateMetaSchema = external_exports.object({
  usage: usageSchema.optional().nullable(),
  durationMs: external_exports.number().optional().nullable(),
  toolName: external_exports.string().optional().nullable(),
  parentToolCallId: external_exports.string().optional().nullable(),
  subagentType: external_exports.string().optional().nullable(),
  /** Server-side timestamp (ms since epoch) for correct message ordering */
  timestamp: 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({
  args: external_exports.array(external_exports.string()).optional(),
  description: external_exports.string().nullable(),
  env: external_exports.record(external_exports.string()).optional(),
  id: external_exports.string(),
  name: external_exports.string(),
  type: external_exports.string().optional()
});
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 modeInfoSchema = external_exports.object({
  id: approvalModeValueSchema,
  name: external_exports.string(),
  description: external_exports.string()
});
var modesDataSchema = external_exports.object({
  currentModeId: approvalModeValueSchema,
  availableModes: external_exports.array(modeInfoSchema)
});
var agentInfoSchema = external_exports.object({
  name: external_exports.string(),
  title: external_exports.string(),
  version: external_exports.string()
});
var initializeResponseSchema = external_exports.object({
  agentCapabilities: agentCapabilitiesSchema,
  agentInfo: agentInfoSchema,
  authMethods: external_exports.array(authMethodSchema),
  modes: modesDataSchema,
  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 currentModeUpdateSchema = external_exports.object({
  sessionUpdate: external_exports.literal("current_mode_update"),
  modeId: approvalModeValueSchema
});
var currentModelUpdateSchema = external_exports.object({
  sessionUpdate: external_exports.literal("current_model_update"),
  model: modelInfoSchema
});
var sessionUpdateSchema = external_exports.union([
  external_exports.object({
    content: contentBlockSchema,
    sessionUpdate: external_exports.literal("user_message_chunk"),
    _meta: sessionUpdateMetaSchema.optional().nullable()
  }),
  external_exports.object({
    content: contentBlockSchema,
    sessionUpdate: external_exports.literal("agent_message_chunk"),
    _meta: sessionUpdateMetaSchema.optional().nullable()
  }),
  external_exports.object({
    content: contentBlockSchema,
    sessionUpdate: external_exports.literal("agent_thought_chunk"),
    _meta: sessionUpdateMetaSchema.optional().nullable()
  }),
  external_exports.object({
    content: external_exports.array(toolCallContentSchema).optional(),
    kind: toolKindSchema,
    locations: external_exports.array(toolCallLocationSchema).optional(),
    rawInput: external_exports.unknown().optional(),
    _meta: sessionUpdateMetaSchema.optional().nullable(),
    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(),
    rawOutput: external_exports.unknown().optional(),
    _meta: sessionUpdateMetaSchema.optional().nullable(),
    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")
  }),
  currentModeUpdateSchema,
  currentModelUpdateSchema,
  availableCommandsUpdateSchema
]);
var agentResponseSchema = external_exports.union([
  initializeResponseSchema,
  newSessionResponseSchema,
  loadSessionResponseSchema,
  promptResponseSchema,
  listSessionsResponseSchema,
  setModeResponseSchema,
  setModelResponseSchema
]);
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,
  listSessionsRequestSchema,
  setModeRequestSchema,
  setModelRequestSchema
]);

// packages/cli/src/acp-integration/errorCodes.ts
init_esbuild_shims();
var ACP_ERROR_CODES = {
  // Parse error: invalid JSON received by server.
  PARSE_ERROR: -32700,
  // Invalid request: JSON is not a valid Request object.
  INVALID_REQUEST: -32600,
  // Method not found: method does not exist or is unavailable.
  METHOD_NOT_FOUND: -32601,
  // Invalid params: invalid method parameter(s).
  INVALID_PARAMS: -32602,
  // Internal error: implementation-defined server error.
  INTERNAL_ERROR: -32603,
  // Authentication required: must authenticate before operation.
  AUTH_REQUIRED: -32e3,
  // Resource not found: e.g. missing file.
  RESOURCE_NOT_FOUND: -32002
};

// packages/cli/src/acp-integration/authMethods.ts
init_esbuild_shims();
function buildAuthMethods() {
  return [
    {
      id: AuthType2.USE_OPENAI,
      name: "Use OpenAI API key",
      description: "Requires setting the `OPENAI_API_KEY` environment variable",
      type: "terminal",
      args: ["--auth-type=openai"]
    },
    {
      id: AuthType2.QWEN_OAUTH,
      name: "Qwen OAuth",
      description: "OAuth authentication for Qwen models with free daily requests",
      type: "terminal",
      args: ["--auth-type=qwen-oauth"]
    }
  ];
}
__name(buildAuthMethods, "buildAuthMethods");
function filterAuthMethodsById(authMethods, authMethodId) {
  return authMethods.filter((method) => method.id === authMethodId);
}
__name(filterAuthMethodsById, "filterAuthMethodsById");
function pickAuthMethodsForDetails(details) {
  const authMethods = buildAuthMethods();
  if (!details) {
    return authMethods;
  }
  if (details.includes("qwen-oauth") || details.includes("Qwen OAuth")) {
    const narrowed = filterAuthMethodsById(authMethods, AuthType2.QWEN_OAUTH);
    return narrowed.length ? narrowed : authMethods;
  }
  return authMethods;
}
__name(pickAuthMethodsForDetails, "pickAuthMethodsForDetails");

// packages/cli/src/acp-integration/acp.ts
var debugLogger119 = createDebugLogger("ACP_PROTOCOL");
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.session_list: {
          if (!agent.listSessions) {
            throw RequestError.methodNotFound();
          }
          const validatedParams = listSessionsRequestSchema.parse(params);
          return agent.listSessions(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);
        }
        case AGENT_METHODS.session_set_mode: {
          if (!agent.setMode) {
            throw RequestError.methodNotFound();
          }
          const validatedParams = setModeRequestSchema.parse(params);
          return agent.setMode(validatedParams);
        }
        case AGENT_METHODS.session_set_model: {
          if (!agent.setModel) {
            throw RequestError.methodNotFound();
          }
          const validatedParams = setModelRequestSchema.parse(params);
          return agent.setModel(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
    );
  }
  /**
   * Streams authentication updates (e.g. Qwen OAuth authUri) to the client.
   */
  async authenticateUpdate(params) {
    return await this.#connection.sendNotification(
      CLIENT_METHODS.authenticate_update,
      params
    );
  }
  /**
   * Sends a custom notification to the client.
   * Used for extension-specific notifications that are not part of the core ACP protocol.
   */
  async sendCustomNotification(method, params) {
    return await this.#connection.sendNotification(method, 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) {
          try {
            const message = JSON.parse(trimmedLine);
            this.#processMessage(message);
          } catch (error2) {
            debugLogger119.error("ACP parse error for inbound message.", {
              code: ACP_ERROR_CODES.PARSE_ERROR,
              line: trimmedLine,
              error: error2
            });
          }
        }
      }
    }
  }
  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 (error2) {
      if (error2 instanceof RequestError) {
        debugLogger119.debug("ACP handler returned request error.", {
          method,
          code: error2.code,
          message: error2.message,
          details: error2.data?.details
        });
        return error2.toResult();
      }
      if (error2 instanceof external_exports.ZodError) {
        const formattedDetails = JSON.stringify(error2.format(), void 0, 2);
        debugLogger119.debug("ACP handler validation error.", {
          method,
          code: ACP_ERROR_CODES.INVALID_PARAMS,
          details: formattedDetails
        });
        return RequestError.invalidParams(formattedDetails).toResult();
      }
      let errorName;
      let details;
      if (error2 instanceof Error) {
        errorName = error2.name;
        details = error2.message;
      } else if (typeof error2 === "object" && error2 != null && "message" in error2 && typeof error2.message === "string") {
        details = error2.message;
      }
      if (errorName === "TokenManagerError" || details?.includes("/auth")) {
        return RequestError.authRequired(
          details,
          pickAuthMethodsForDetails(details)
        ).toResult();
      }
      debugLogger119.error(
        "ACP handler failed with internal error.",
        { method, errorName, details },
        error2
      );
      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) {
        const { error: error2 } = response;
        debugLogger119.warn("ACP response error received.", {
          id: response.id,
          code: error2.code,
          message: error2.message,
          data: error2.data
        });
        pendingResponse.reject(error2);
      }
      this.#pendingResponses.delete(response.id);
    }
  }
  async sendRequest(method, params) {
    const id = this.#nextRequestId++;
    const responsePromise = new Promise((resolve30, reject) => {
      this.#pendingResponses.set(id, { resolve: resolve30, 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((error2) => {
      debugLogger119.error("ACP write error:", error2);
    });
    return this.#writeQueue;
  }
};
var RequestError = class _RequestError extends Error {
  constructor(code2, message, details, authMethods) {
    super(message);
    this.code = code2;
    this.name = "RequestError";
    if (details || authMethods) {
      this.data = {};
      if (details) {
        this.data.details = details;
      }
      if (authMethods) {
        this.data.authMethods = authMethods;
      }
    }
  }
  static {
    __name(this, "RequestError");
  }
  data;
  static parseError(details) {
    return new _RequestError(
      ACP_ERROR_CODES.PARSE_ERROR,
      "Parse error",
      details
    );
  }
  static invalidRequest(details) {
    return new _RequestError(
      ACP_ERROR_CODES.INVALID_REQUEST,
      "Invalid request",
      details
    );
  }
  static methodNotFound(details) {
    return new _RequestError(
      ACP_ERROR_CODES.METHOD_NOT_FOUND,
      "Method not found",
      details
    );
  }
  static invalidParams(details) {
    return new _RequestError(
      ACP_ERROR_CODES.INVALID_PARAMS,
      "Invalid params",
      details
    );
  }
  static internalError(details) {
    return new _RequestError(
      ACP_ERROR_CODES.INTERNAL_ERROR,
      "Internal error",
      details
    );
  }
  static authRequired(details, authMethods) {
    return new _RequestError(
      ACP_ERROR_CODES.AUTH_REQUIRED,
      "Authentication required",
      details,
      authMethods
    );
  }
  toResult() {
    return {
      error: {
        code: this.code,
        message: this.message,
        data: this.data
      }
    };
  }
};

// packages/cli/src/acp-integration/service/filesystem.ts
init_esbuild_shims();
var AcpFileSystemService = class {
  constructor(client, sessionId, capabilities, fallback) {
    this.client = client;
    this.sessionId = sessionId;
    this.capabilities = capabilities;
    this.fallback = fallback;
  }
  static {
    __name(this, "AcpFileSystemService");
  }
  async readTextFile(filePath) {
    if (!this.capabilities.readTextFile) {
      return this.fallback.readTextFile(filePath);
    }
    let response;
    try {
      response = await this.client.readTextFile({
        path: filePath,
        sessionId: this.sessionId,
        line: null,
        limit: null
      });
    } catch (error2) {
      const errorCode = typeof error2 === "object" && error2 !== null && "code" in error2 ? error2.code : void 0;
      if (errorCode === ACP_ERROR_CODES.RESOURCE_NOT_FOUND) {
        const err = new Error(
          `File not found: ${filePath}`
        );
        err.code = "ENOENT";
        err.errno = -2;
        err.path = filePath;
        throw err;
      }
      throw error2;
    }
    return response.content;
  }
  async writeTextFile(filePath, content, options2) {
    if (!this.capabilities.writeTextFile) {
      return this.fallback.writeTextFile(filePath, content, options2);
    }
    const finalContent = options2?.bom ? "\uFEFF" + content : content;
    await this.client.writeTextFile({
      path: filePath,
      content: finalContent,
      sessionId: this.sessionId
    });
  }
  async detectFileBOM(filePath) {
    if (this.capabilities.readTextFile) {
      try {
        const response = await this.client.readTextFile({
          path: filePath,
          sessionId: this.sessionId,
          line: null,
          limit: 1
        });
        return response.content.length > 0 && response.content.codePointAt(0) === 65279;
      } catch {
      }
    }
    return this.fallback.detectFileBOM(filePath);
  }
  findFiles(fileName, searchPaths) {
    return this.fallback.findFiles(fileName, searchPaths);
  }
};

// packages/cli/src/acp-integration/acpAgent.ts
import { Readable as Readable5, Writable as Writable2 } from "node:stream";
init_zod();

// packages/cli/src/acp-integration/session/Session.ts
init_esbuild_shims();
init_zod();

// packages/cli/src/utils/acpModelUtils.ts
init_esbuild_shims();
init_zod();
function formatAcpModelId(modelId, authType) {
  return `${modelId}(${authType})`;
}
__name(formatAcpModelId, "formatAcpModelId");
function parseAcpModelOption(input) {
  const trimmed2 = input.trim();
  const closeIdx = trimmed2.lastIndexOf(")");
  const openIdx = trimmed2.lastIndexOf("(");
  if (openIdx >= 0 && closeIdx === trimmed2.length - 1 && openIdx < closeIdx) {
    const maybeModelId = trimmed2.slice(0, openIdx);
    const maybeAuthType = trimmed2.slice(openIdx + 1, closeIdx);
    const parsedAuthType = external_exports.nativeEnum(AuthType2).safeParse(maybeAuthType);
    if (parsedAuthType.success) {
      return { modelId: maybeModelId, authType: parsedAuthType.data };
    }
  }
  return { modelId: trimmed2 };
}
__name(parseAcpModelOption, "parseAcpModelOption");

// packages/cli/src/acp-integration/session/SubAgentTracker.ts
init_esbuild_shims();
init_zod();
var debugLogger120 = createDebugLogger("ACP_SUBAGENT_TRACKER");
var basicPermissionOptions = [
  {
    optionId: ToolConfirmationOutcome.ProceedOnce,
    name: "Allow",
    kind: "allow_once"
  },
  {
    optionId: ToolConfirmationOutcome.Cancel,
    name: "Reject",
    kind: "reject_once"
  }
];
var SubAgentTracker = class {
  constructor(ctx, client, parentToolCallId, subagentType) {
    this.ctx = ctx;
    this.client = client;
    this.parentToolCallId = parentToolCallId;
    this.subagentType = subagentType;
    this.toolCallEmitter = new ToolCallEmitter(ctx);
    this.messageEmitter = new MessageEmitter(ctx);
  }
  static {
    __name(this, "SubAgentTracker");
  }
  toolCallEmitter;
  messageEmitter;
  toolStates = /* @__PURE__ */ new Map();
  /**
   * Gets the subagent metadata to attach to all events.
   */
  getSubagentMeta() {
    return {
      parentToolCallId: this.parentToolCallId,
      subagentType: this.subagentType
    };
  }
  /**
   * Sets up event listeners for a sub-agent's tool events.
   *
   * @param eventEmitter - The SubAgentEventEmitter from TaskTool
   * @param abortSignal - Signal to abort tracking if parent is cancelled
   * @returns Array of cleanup functions to remove listeners
   */
  setup(eventEmitter, abortSignal) {
    const onToolCall = this.createToolCallHandler(abortSignal);
    const onToolResult = this.createToolResultHandler(abortSignal);
    const onApproval = this.createApprovalHandler(abortSignal);
    const onUsageMetadata = this.createUsageMetadataHandler(abortSignal);
    const onStreamText = this.createStreamTextHandler(abortSignal);
    eventEmitter.on(SubAgentEventType.TOOL_CALL, onToolCall);
    eventEmitter.on(SubAgentEventType.TOOL_RESULT, onToolResult);
    eventEmitter.on(SubAgentEventType.TOOL_WAITING_APPROVAL, onApproval);
    eventEmitter.on(SubAgentEventType.USAGE_METADATA, onUsageMetadata);
    eventEmitter.on(SubAgentEventType.STREAM_TEXT, onStreamText);
    return [
      () => {
        eventEmitter.off(SubAgentEventType.TOOL_CALL, onToolCall);
        eventEmitter.off(SubAgentEventType.TOOL_RESULT, onToolResult);
        eventEmitter.off(SubAgentEventType.TOOL_WAITING_APPROVAL, onApproval);
        eventEmitter.off(SubAgentEventType.USAGE_METADATA, onUsageMetadata);
        eventEmitter.off(SubAgentEventType.STREAM_TEXT, onStreamText);
        this.toolStates.clear();
      }
    ];
  }
  /**
   * Creates a handler for tool call start events.
   */
  createToolCallHandler(abortSignal) {
    return (...args) => {
      const event = args[0];
      if (abortSignal.aborted) return;
      const toolRegistry = this.ctx.config.getToolRegistry();
      const tool = toolRegistry.getTool(event.name);
      let invocation;
      if (tool) {
        try {
          invocation = tool.build(event.args);
        } catch (e4) {
          debugLogger120.warn(`Failed to build subagent tool ${event.name}:`, e4);
        }
      }
      this.toolStates.set(event.callId, {
        tool,
        invocation,
        args: event.args
      });
      void this.toolCallEmitter.emitStart({
        toolName: event.name,
        callId: event.callId,
        args: event.args,
        subagentMeta: this.getSubagentMeta()
      });
    };
  }
  /**
   * Creates a handler for tool result events.
   */
  createToolResultHandler(abortSignal) {
    return (...args) => {
      const event = args[0];
      if (abortSignal.aborted) return;
      const state = this.toolStates.get(event.callId);
      void this.toolCallEmitter.emitResult({
        toolName: event.name,
        callId: event.callId,
        success: event.success,
        message: event.responseParts ?? [],
        resultDisplay: event.resultDisplay,
        args: state?.args,
        subagentMeta: this.getSubagentMeta()
      });
      this.toolStates.delete(event.callId);
    };
  }
  /**
   * Creates a handler for tool approval request events.
   */
  createApprovalHandler(abortSignal) {
    return async (...args) => {
      const event = args[0];
      if (abortSignal.aborted) return;
      const state = this.toolStates.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 { title, locations, kind: kind2 } = this.toolCallEmitter.resolveToolMetadata(event.name, state?.args);
      const params = {
        sessionId: this.ctx.sessionId,
        options: this.toPermissionOptions(fullConfirmationDetails),
        toolCall: {
          toolCallId: event.callId,
          status: "pending",
          title,
          content,
          locations,
          kind: kind2,
          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 (error2) {
        debugLogger120.error(
          `Permission request failed for subagent tool ${event.name}:`,
          error2
        );
        await event.respond(ToolConfirmationOutcome.Cancel);
      }
    };
  }
  /**
   * Creates a handler for usage metadata events.
   */
  createUsageMetadataHandler(abortSignal) {
    return (...args) => {
      const event = args[0];
      if (abortSignal.aborted) return;
      this.messageEmitter.emitUsageMetadata(
        event.usage,
        "",
        event.durationMs,
        this.getSubagentMeta()
      );
    };
  }
  /**
   * Creates a handler for stream text events.
   * Emits agent message or thought chunks for text content from subagent model responses.
   */
  createStreamTextHandler(abortSignal) {
    return (...args) => {
      const event = args[0];
      if (abortSignal.aborted) return;
      void this.messageEmitter.emitMessage(
        event.text,
        "assistant",
        event.thought ?? false
      );
    };
  }
  /**
   * Converts confirmation details to permission options for the client.
   */
  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 ?? "command"}`,
            kind: "allow_always"
          },
          ...basicPermissionOptions
        ];
      case "mcp":
        return [
          {
            optionId: ToolConfirmationOutcome.ProceedAlwaysServer,
            name: `Always Allow ${confirmation.serverName ?? "server"}`,
            kind: "allow_always"
          },
          {
            optionId: ToolConfirmationOutcome.ProceedAlwaysTool,
            name: `Always Allow ${confirmation.toolName ?? "tool"}`,
            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: {
        return [...basicPermissionOptions];
      }
    }
  }
};

// packages/cli/src/acp-integration/session/Session.ts
var debugLogger121 = createDebugLogger("SESSION");
var Session3 = class {
  constructor(id, chat, config2, client, settings) {
    this.chat = chat;
    this.config = config2;
    this.client = client;
    this.settings = settings;
    this.sessionId = id;
    this.toolCallEmitter = new ToolCallEmitter(this);
    this.planEmitter = new PlanEmitter(this);
    this.historyReplayer = new HistoryReplayer(this);
    this.messageEmitter = new MessageEmitter(this);
  }
  static {
    __name(this, "Session");
  }
  pendingPrompt = null;
  turn = 0;
  // Modular components
  historyReplayer;
  toolCallEmitter;
  planEmitter;
  messageEmitter;
  // Implement SessionContext interface
  sessionId;
  getId() {
    return this.sessionId;
  }
  getConfig() {
    return this.config;
  }
  /**
   * Replays conversation history to the client using modular components.
   * Delegates to HistoryReplayer for consistent event emission.
   */
  async replayHistory(records) {
    await this.historyReplayer.replay(records);
  }
  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
      )
    );
    this.config.getChatRecordingService()?.recordUserMessage(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
      );
      parts = await this.#processSlashCommandResult(
        slashCommandResult,
        params.prompt
      );
      if (parts === null) {
        return { stopReason: "end_turn" };
      }
    } 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 = [];
      let usageMetadata = null;
      const streamStartTime = Date.now();
      try {
        const responseStream = await chat.sendMessageStream(
          this.config.getModel(),
          {
            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;
              }
              this.messageEmitter.emitMessage(
                part.text,
                "assistant",
                part.thought
              );
            }
          }
          if (resp.type === StreamEventType.CHUNK && resp.value.usageMetadata) {
            usageMetadata = resp.value.usageMetadata;
          }
          if (resp.type === StreamEventType.CHUNK && resp.value.functionCalls) {
            functionCalls.push(...resp.value.functionCalls);
          }
        }
      } catch (error2) {
        if (getErrorStatus(error2) === 429) {
          throw new RequestError(
            429,
            "Rate limit exceeded. Try again later."
          );
        }
        throw error2;
      }
      if (usageMetadata) {
        const durationMs = Date.now() - streamStartTime;
        await this.messageEmitter.emitUsageMetadata(
          usageMetadata,
          "",
          durationMs
        );
      }
      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.sessionId,
      update: update2
    };
    await this.client.sessionUpdate(params);
  }
  async sendAvailableCommandsUpdate() {
    const abortController = new AbortController();
    try {
      const slashCommands = await getAvailableCommands(
        this.config,
        abortController.signal
      );
      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 (error2) {
      debugLogger121.error("Error sending available commands update:", error2);
    }
  }
  /**
   * Requests permission from the client for a tool call.
   * Used by SubAgentTracker for sub-agent approval requests.
   */
  async requestPermission(params) {
    return this.client.requestPermission(params);
  }
  /**
   * Sets the approval mode for the current session.
   * Maps ACP approval mode values to core ApprovalMode enum.
   */
  async setMode(params) {
    const modeMap = {
      plan: ApprovalMode.PLAN,
      default: ApprovalMode.DEFAULT,
      "auto-edit": ApprovalMode.AUTO_EDIT,
      yolo: ApprovalMode.YOLO
    };
    const approvalMode = modeMap[params.modeId];
    this.config.setApprovalMode(approvalMode);
    return { modeId: params.modeId };
  }
  /**
   * Sets the model for the current session.
   * Validates the model ID and switches the model via Config.
   */
  async setModel(params) {
    const rawModelId = params.modelId.trim();
    if (!rawModelId) {
      throw RequestError.invalidParams("modelId cannot be empty");
    }
    const parsed = parseAcpModelOption(rawModelId);
    const previousAuthType = this.config.getAuthType?.();
    const selectedAuthType = parsed.authType ?? previousAuthType;
    if (!selectedAuthType) {
      throw RequestError.invalidParams(
        `authType cannot be determined for modelId "${parsed.modelId}"`
      );
    }
    await this.config.switchModel(
      selectedAuthType,
      parsed.modelId,
      selectedAuthType !== previousAuthType && selectedAuthType === AuthType2.QWEN_OAUTH ? { requireCachedCredentials: true } : void 0
    );
    const currentModel = this.config.getModel();
    const currentAuthType = this.config.getAuthType?.() ?? selectedAuthType;
    return {
      modelId: formatAcpModelId(currentModel, currentAuthType)
    };
  }
  /**
   * Sends a current_mode_update notification to the client.
   * Called after the agent switches modes (e.g., from exit_plan_mode tool).
   */
  async sendCurrentModeUpdateNotification(outcome) {
    let newModeId;
    switch (outcome) {
      case ToolConfirmationOutcome.ProceedAlways:
        newModeId = "auto-edit";
        break;
      case ToolConfirmationOutcome.ProceedOnce:
      default:
        newModeId = "default";
        break;
    }
    const update2 = {
      sessionUpdate: "current_mode_update",
      modeId: newModeId
    };
    await this.sendUpdate(update2);
  }
  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((error2) => {
      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: error2.message,
        tool_type: typeof tool !== "undefined" && tool instanceof DiscoveredMCPTool ? "mcp" : "native"
      });
      return [
        {
          functionResponse: {
            id: callId,
            name: fc.name ?? "",
            response: { error: error2.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 = tool.name === TodoWriteTool.Name;
    const isTaskTool = tool.name === TaskTool.Name;
    const isExitPlanModeTool = tool.name === ExitPlanModeTool.Name;
    let subAgentCleanupFunctions = [];
    try {
      const invocation = tool.build(args);
      if (isTaskTool && "eventEmitter" in invocation) {
        const taskEventEmitter = invocation.eventEmitter;
        const parentToolCallId = callId;
        const subagentType = args["subagent_type"] ?? "";
        const subAgentTracker = new SubAgentTracker(
          this,
          this.client,
          parentToolCallId,
          subagentType
        );
        subAgentCleanupFunctions = subAgentTracker.setup(
          taskEventEmitter,
          abortSignal
        );
      }
      const confirmationDetails = this.config.getApprovalMode() !== ApprovalMode.YOLO ? await invocation.shouldConfirmExecute(abortSignal) : false;
      const isPlanMode = this.config.getApprovalMode() === ApprovalMode.PLAN;
      if (isPlanMode && !isExitPlanModeTool && confirmationDetails) {
        return errorResponse(
          new Error(
            `Plan mode is active. The tool "${fc.name}" cannot be executed because it modifies the system. Please use the exit_plan_mode tool to present your plan and exit plan mode before making changes.`
          )
        );
      }
      if (confirmationDetails) {
        const content = [];
        if (confirmationDetails.type === "edit") {
          content.push({
            type: "diff",
            path: confirmationDetails.fileName,
            oldText: confirmationDetails.originalContent,
            newText: confirmationDetails.newContent
          });
        }
        if (confirmationDetails.type === "plan") {
          content.push({
            type: "content",
            content: {
              type: "text",
              text: confirmationDetails.plan
            }
          });
        }
        const mappedKind = this.toolCallEmitter.mapToolKind(tool.kind, fc.name);
        const params = {
          sessionId: this.sessionId,
          options: toPermissionOptions(confirmationDetails),
          toolCall: {
            toolCallId: callId,
            status: "pending",
            title: invocation.getDescription(),
            content,
            locations: invocation.toolLocations(),
            kind: mappedKind
          }
        };
        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);
        if (isExitPlanModeTool && outcome !== ToolConfirmationOutcome.Cancel) {
          await this.sendCurrentModeUpdateNotification(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) {
        const startParams = {
          callId,
          toolName: fc.name,
          args,
          status: "in_progress"
        };
        await this.toolCallEmitter.emitStart(startParams);
      }
      const toolResult = await invocation.execute(abortSignal);
      subAgentCleanupFunctions.forEach((cleanup) => cleanup());
      const responseParts = convertToFunctionResponse(
        fc.name,
        callId,
        toolResult.llmContent
      );
      if (isTodoWriteTool) {
        const todos = this.planEmitter.extractTodos(
          toolResult.returnDisplay,
          args
        );
        if (todos && todos.length > 0 || Array.isArray(args["todos"])) {
          await this.planEmitter.emitPlan(todos ?? []);
        }
      } else {
        const error2 = toolResult.error ? new Error(toolResult.error.message) : void 0;
        await this.toolCallEmitter.emitResult({
          callId,
          toolName: fc.name,
          args,
          message: responseParts,
          resultDisplay: toolResult.returnDisplay,
          error: error2,
          success: !toolResult.error
        });
      }
      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"
      });
      this.config.getChatRecordingService()?.recordToolResult(responseParts, {
        callId,
        status: "success",
        resultDisplay: toolResult.returnDisplay,
        error: void 0,
        errorType: void 0
      });
      return responseParts;
    } catch (e4) {
      subAgentCleanupFunctions.forEach((cleanup) => cleanup());
      const error2 = e4 instanceof Error ? e4 : new Error(String(e4));
      await this.toolCallEmitter.emitError(
        callId,
        fc.name ?? "unknown_tool",
        error2
      );
      const errorParts = [
        {
          functionResponse: {
            id: callId,
            name: fc.name ?? "",
            response: { error: error2.message }
          }
        }
      ];
      this.config.getChatRecordingService()?.recordToolResult(errorParts, {
        callId,
        status: "error",
        resultDisplay: void 0,
        error: error2,
        errorType: void 0
      });
      return errorResponse(error2);
    }
  }
  /**
   * Processes the result of a slash command execution.
   *
   * Supported result types in ACP mode:
   * - submit_prompt: Submits content to the model
   * - stream_messages: Streams multiple messages to the client (ACP-specific)
   * - unsupported: Command cannot be executed in ACP mode
   * - no_command: No command was found, use original prompt
   *
   * Note: 'message' type is not supported in ACP mode - commands should use
   * 'stream_messages' instead for consistent async handling.
   *
   * @param result The result from handleSlashCommand
   * @param originalPrompt The original prompt blocks
   * @returns Parts to use for the prompt, or null if command was handled without needing model interaction
   */
  async #processSlashCommandResult(result, originalPrompt) {
    switch (result.type) {
      case "submit_prompt":
        return normalizePartList(result.content);
      case "message": {
        await this.client.sendCustomNotification("_qwencode/slash_command", {
          sessionId: this.sessionId,
          command: originalPrompt.filter((block2) => block2.type === "text").map((block2) => block2.type === "text" ? block2.text : "").join(" "),
          messageType: result.messageType,
          message: result.content || ""
        });
        if (result.messageType === "error") {
          throw new Error(result.content || "Slash command failed.");
        }
        return null;
      }
      case "stream_messages": {
        const command2 = originalPrompt.filter((block2) => block2.type === "text").map((block2) => block2.type === "text" ? block2.text : "").join(" ");
        for await (const msg of result.messages) {
          await this.client.sendCustomNotification("_qwencode/slash_command", {
            sessionId: this.sessionId,
            command: command2,
            messageType: msg.messageType,
            message: msg.content
          });
          if (msg.messageType === "error") {
            throw new Error(msg.content || "Slash command failed.");
          }
        }
        return null;
      }
      case "unsupported": {
        const unsupportedError = `Slash command not supported in ACP integration: ${result.reason}`;
        throw new Error(unsupportedError);
      }
      case "no_command":
        return originalPrompt.map((block2) => {
          if (block2.type === "text") {
            return { text: block2.text };
          }
          throw new Error(`Unsupported block type: ${block2.type}`);
        });
      default: {
        const _exhaustive = result;
        const unknownError = `Unknown slash command result type: ${_exhaustive.type}`;
        throw new Error(unknownError);
      }
    }
  }
  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 pathSpecsToRead = atPathCommandParts.map(
      (part) => part.fileData.fileUri
    );
    let initialQueryText = "";
    for (let i3 = 0; i3 < parts.length; i3++) {
      const chunk = parts[i3];
      if ("text" in chunk) {
        initialQueryText += chunk.text;
      } else if ("fileData" in chunk) {
        const pathName = chunk.fileData.fileUri;
        if (i3 > 0 && initialQueryText.length > 0 && !initialQueryText.endsWith(" ")) {
          initialQueryText += " ";
        }
        initialQueryText += `@${pathName}`;
      }
    }
    const processedQueryParts = [];
    if (pathSpecsToRead.length > 0) {
      const readResult = await readManyFiles(this.config, {
        paths: pathSpecsToRead,
        signal: abortSignal
      });
      const contentParts = Array.isArray(readResult.contentParts) ? readResult.contentParts : [readResult.contentParts];
      processedQueryParts.push({ text: initialQueryText });
      for (const part of contentParts) {
        if (typeof part === "string") {
          processedQueryParts.push({ text: part });
        } else {
          processedQueryParts.push(part);
        }
      }
    } else if (embeddedContext.length > 0) {
      processedQueryParts.push({ text: initialQueryText.trim() });
    } else {
      processedQueryParts.push({ text: initialQueryText.trim() });
    }
    for (const contextPart of embeddedContext) {
      if ("text" in contextPart && contextPart.text) {
        processedQueryParts.push({
          text: `File: ${contextPart.uri}
${contextPart.text}`
        });
      }
      if ("blob" in contextPart && contextPart.blob) {
        processedQueryParts.push({
          inlineData: {
            mimeType: contextPart.mimeType ?? "application/octet-stream",
            data: contextPart.blob
          }
        });
      }
    }
    return processedQueryParts;
  }
  debug(msg) {
    if (this.config.getDebugMode()) {
      debugLogger121.warn(msg);
    }
  }
};
var basicPermissionOptions2 = [
  {
    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"
        },
        ...basicPermissionOptions2
      ];
    case "exec":
      return [
        {
          optionId: ToolConfirmationOutcome.ProceedAlways,
          name: `Always Allow ${confirmation.rootCommand}`,
          kind: "allow_always"
        },
        ...basicPermissionOptions2
      ];
    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"
        },
        ...basicPermissionOptions2
      ];
    case "info":
      return [
        {
          optionId: ToolConfirmationOutcome.ProceedAlways,
          name: `Always Allow`,
          kind: "allow_always"
        },
        ...basicPermissionOptions2
      ];
    case "plan":
      return [
        {
          optionId: ToolConfirmationOutcome.ProceedAlways,
          name: `Yes, and auto-accept edits`,
          kind: "allow_always"
        },
        {
          optionId: ToolConfirmationOutcome.ProceedOnce,
          name: `Yes, and manually approve edits`,
          kind: "allow_once"
        },
        {
          optionId: ToolConfirmationOutcome.Cancel,
          name: `No, keep planning (esc)`,
          kind: "reject_once"
        }
      ];
    default: {
      const unreachable = confirmation;
      throw new Error(`Unexpected: ${unreachable}`);
    }
  }
}
__name(toPermissionOptions, "toPermissionOptions");

// packages/cli/src/acp-integration/acpAgent.ts
var debugLogger122 = createDebugLogger("ACP_AGENT");
async function runAcpAgent(config2, settings, argv) {
  const stdout = Writable2.toWeb(process.stdout);
  const stdin = Readable5.toWeb(process.stdin);
  console.log = console.error;
  console.info = console.error;
  console.debug = console.error;
  new AgentSideConnection(
    (client) => new GeminiAgent(config2, settings, argv, client),
    stdout,
    stdin
  );
}
__name(runAcpAgent, "runAcpAgent");
var GeminiAgent = class {
  constructor(config2, settings, argv, client) {
    this.config = config2;
    this.settings = settings;
    this.argv = argv;
    this.client = client;
  }
  static {
    __name(this, "GeminiAgent");
  }
  sessions = /* @__PURE__ */ new Map();
  clientCapabilities;
  async initialize(args) {
    this.clientCapabilities = args.clientCapabilities;
    const authMethods = buildAuthMethods();
    const currentApprovalMode = this.config.getApprovalMode();
    const availableModes = APPROVAL_MODES.map((mode) => ({
      id: mode,
      name: APPROVAL_MODE_INFO[mode].name,
      description: APPROVAL_MODE_INFO[mode].description
    }));
    const version2 = "0.11.0";
    return {
      protocolVersion: PROTOCOL_VERSION,
      agentInfo: {
        name: "qwen-code",
        title: "Qwen Code",
        version: version2
      },
      authMethods,
      modes: {
        currentModeId: currentApprovalMode,
        availableModes
      },
      agentCapabilities: {
        loadSession: true,
        promptCapabilities: {
          image: true,
          audio: true,
          embeddedContext: true
        }
      }
    };
  }
  async authenticate({ methodId }) {
    const method = external_exports.nativeEnum(AuthType2).parse(methodId);
    let authUri;
    const authUriHandler = /* @__PURE__ */ __name((deviceAuth) => {
      authUri = deviceAuth.verification_uri_complete;
      void this.client.authenticateUpdate({ _meta: { authUri } });
    }, "authUriHandler");
    if (method === AuthType2.QWEN_OAUTH) {
      qwenOAuth2Events.once(QwenOAuth2Event.AuthUri, authUriHandler);
    }
    await clearCachedCredentialFile();
    try {
      await this.config.refreshAuth(method);
      this.settings.setValue(
        "User" /* User */,
        "security.auth.selectedType",
        method
      );
    } finally {
      if (method === AuthType2.QWEN_OAUTH) {
        qwenOAuth2Events.off(QwenOAuth2Event.AuthUri, authUriHandler);
      }
    }
    return;
  }
  async newSession({
    cwd: cwd7,
    mcpServers
  }) {
    const config2 = await this.newSessionConfig(cwd7, mcpServers);
    await this.ensureAuthenticated(config2);
    this.setupFileSystem(config2);
    const session = await this.createAndStoreSession(config2);
    const availableModels = this.buildAvailableModels(config2);
    return {
      sessionId: session.getId(),
      models: availableModels
    };
  }
  async newSessionConfig(cwd7, mcpServers, sessionId) {
    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 argvForSession = {
      ...this.argv,
      resume: sessionId,
      continue: false
    };
    const config2 = await loadCliConfig(settings, argvForSession, cwd7);
    await config2.initialize();
    return config2;
  }
  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);
  }
  async loadSession(params) {
    const sessionService = new SessionService(params.cwd);
    const exists2 = await sessionService.sessionExists(params.sessionId);
    if (!exists2) {
      throw RequestError.invalidParams(
        `Session not found for id: ${params.sessionId}`
      );
    }
    const config2 = await this.newSessionConfig(
      params.cwd,
      params.mcpServers,
      params.sessionId
    );
    await this.ensureAuthenticated(config2);
    this.setupFileSystem(config2);
    const sessionData = config2.getResumedSessionData();
    if (!sessionData) {
      throw RequestError.internalError(
        `Failed to load session data for id: ${params.sessionId}`
      );
    }
    await this.createAndStoreSession(config2, sessionData.conversation);
    return null;
  }
  async listSessions(params) {
    const sessionService = new SessionService(params.cwd);
    const result = await sessionService.listSessions({
      cursor: params.cursor,
      size: params.size
    });
    return {
      items: result.items.map((item) => ({
        sessionId: item.sessionId,
        cwd: item.cwd,
        startTime: item.startTime,
        mtime: item.mtime,
        prompt: item.prompt,
        gitBranch: item.gitBranch,
        filePath: item.filePath,
        messageCount: item.messageCount
      })),
      nextCursor: result.nextCursor,
      hasMore: result.hasMore
    };
  }
  async setMode(params) {
    const session = this.sessions.get(params.sessionId);
    if (!session) {
      throw RequestError.invalidParams(
        `Session not found for id: ${params.sessionId}`
      );
    }
    return session.setMode(params);
  }
  async setModel(params) {
    const session = this.sessions.get(params.sessionId);
    if (!session) {
      throw RequestError.invalidParams(
        `Session not found for id: ${params.sessionId}`
      );
    }
    return await session.setModel(params);
  }
  async ensureAuthenticated(config2) {
    const selectedType = config2.getModelsConfig().getCurrentAuthType();
    if (!selectedType) {
      throw RequestError.authRequired(
        "Use Qwen Code CLI to authenticate first.",
        this.pickAuthMethodsForAuthRequired()
      );
    }
    try {
      await config2.refreshAuth(selectedType, true);
    } catch (e4) {
      debugLogger122.error(`Authentication failed: ${e4}`);
      throw RequestError.authRequired(
        "Authentication failed: " + e4.message,
        this.pickAuthMethodsForAuthRequired(selectedType, e4)
      );
    }
  }
  pickAuthMethodsForAuthRequired(selectedType, error2) {
    const authMethods = buildAuthMethods();
    const errorMessage = this.extractErrorMessage(error2);
    if (errorMessage?.includes("qwen-oauth") || errorMessage?.includes("Qwen OAuth")) {
      const qwenOAuthMethods = authMethods.filter(
        (method) => method.id === AuthType2.QWEN_OAUTH
      );
      return qwenOAuthMethods.length ? qwenOAuthMethods : authMethods;
    }
    if (selectedType) {
      const matchedMethods = authMethods.filter(
        (method) => method.id === selectedType
      );
      return matchedMethods.length ? matchedMethods : authMethods;
    }
    return authMethods;
  }
  extractErrorMessage(error2) {
    if (error2 instanceof Error) {
      return error2.message;
    }
    if (typeof error2 === "object" && error2 != null && "message" in error2 && typeof error2.message === "string") {
      return error2.message;
    }
    if (typeof error2 === "string") {
      return error2;
    }
    return void 0;
  }
  setupFileSystem(config2) {
    if (!this.clientCapabilities?.fs) {
      return;
    }
    const acpFileSystemService = new AcpFileSystemService(
      this.client,
      config2.getSessionId(),
      this.clientCapabilities.fs,
      config2.getFileSystemService()
    );
    config2.setFileSystemService(acpFileSystemService);
  }
  async createAndStoreSession(config2, conversation) {
    const sessionId = config2.getSessionId();
    const geminiClient = config2.getGeminiClient();
    if (!geminiClient.isInitialized()) {
      await geminiClient.initialize();
    }
    const chat = geminiClient.getChat();
    const session = new Session3(
      sessionId,
      chat,
      config2,
      this.client,
      this.settings
    );
    this.sessions.set(sessionId, session);
    setTimeout(async () => {
      await session.sendAvailableCommandsUpdate();
    }, 0);
    if (conversation && conversation.messages) {
      await session.replayHistory(conversation.messages);
    }
    return session;
  }
  buildAvailableModels(config2) {
    const rawCurrentModelId = (config2.getModel() || this.config.getModel() || "").trim();
    const currentAuthType = config2.getAuthType();
    const allConfiguredModels = config2.getAllConfiguredModels();
    const activeRuntimeSnapshot = config2.getActiveRuntimeModelSnapshot?.();
    const currentModelId = activeRuntimeSnapshot ? formatAcpModelId(
      activeRuntimeSnapshot.id,
      activeRuntimeSnapshot.authType
    ) : this.formatCurrentModelId(rawCurrentModelId, currentAuthType);
    const availableModels = allConfiguredModels;
    const mappedAvailableModels = availableModels.map((model) => {
      const effectiveModelId = model.isRuntimeModel && model.runtimeSnapshotId ? model.runtimeSnapshotId : model.id;
      return {
        modelId: formatAcpModelId(effectiveModelId, model.authType),
        name: model.label,
        description: model.description ?? null,
        _meta: {
          contextLimit: model.contextWindowSize ?? tokenLimit(model.id)
        }
      };
    });
    return {
      currentModelId,
      availableModels: mappedAvailableModels
    };
  }
  formatCurrentModelId(baseModelId, authType) {
    if (!baseModelId) {
      return baseModelId;
    }
    return authType ? formatAcpModelId(baseModelId, authType) : baseModelId;
  }
};

// packages/cli/src/gemini.tsx
var import_jsx_runtime111 = __toESM(require_jsx_runtime(), 1);
var debugLogger123 = createDebugLogger("STARTUP");
function validateDnsResolutionOrder(order) {
  const defaultValue = "ipv4first";
  if (order === void 0) {
    return defaultValue;
  }
  if (order === "ipv4first" || order === "verbatim") {
    return order;
  }
  writeStderrLine(
    `Invalid value for dnsResolutionOrder in settings: "${order}". Using default "${defaultValue}".`
  );
  return defaultValue;
}
__name(validateDnsResolutionOrder, "validateDnsResolutionOrder");
function getNodeMemoryArgs(isDebugMode2) {
  const totalMemoryMB = os46.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) {
    writeStderrLine(
      `Current heap size ${currentMaxOldSpaceSizeMb.toFixed(2)} MB`
    );
  }
  if (process.env["QWEN_CODE_NO_RELAUNCH"]) {
    return [];
  }
  if (targetMaxOldSpaceSizeInMB > currentMaxOldSpaceSizeMb) {
    if (isDebugMode2) {
      writeStderrLine(
        `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(config2, settings, startupWarnings, workspaceRoot = process.cwd(), initializationResult) {
  const version2 = await getCliVersion();
  setWindowTitle(basename25(workspaceRoot), settings);
  const AppWrapper = /* @__PURE__ */ __name(() => {
    const kittyProtocolStatus = useKittyKeyboardProtocol();
    const nodeMajorVersion = parseInt(process.versions.node.split(".")[0], 10);
    return /* @__PURE__ */ (0, import_jsx_runtime111.jsx)(SettingsContext.Provider, { value: settings, children: /* @__PURE__ */ (0, import_jsx_runtime111.jsx)(
      KeypressProvider,
      {
        kittyProtocolEnabled: kittyProtocolStatus.enabled,
        config: config2,
        debugKeystrokeLogging: settings.merged.general?.debugKeystrokeLogging,
        pasteWorkaround: process.platform === "win32" || nodeMajorVersion < 20,
        children: /* @__PURE__ */ (0, import_jsx_runtime111.jsx)(SessionStatsProvider, { sessionId: config2.getSessionId(), children: /* @__PURE__ */ (0, import_jsx_runtime111.jsx)(VimModeProvider, { settings, children: /* @__PURE__ */ (0, import_jsx_runtime111.jsx)(
          AppContainer,
          {
            config: config2,
            settings,
            startupWarnings,
            version: version2,
            initializationResult
          }
        ) }) })
      }
    ) });
  }, "AppWrapper");
  const instance = render_default(
    process.env["DEBUG"] ? /* @__PURE__ */ (0, import_jsx_runtime111.jsx)(import_react136.default.StrictMode, { children: /* @__PURE__ */ (0, import_jsx_runtime111.jsx)(AppWrapper, {}) }) : /* @__PURE__ */ (0, import_jsx_runtime111.jsx)(AppWrapper, {}),
    {
      exitOnCtrlC: false,
      isScreenReaderEnabled: config2.getScreenReader()
    }
  );
  if (settings.merged.general?.enableAutoUpdate !== false) {
    checkForUpdates().then((info) => {
      handleAutoUpdate(info, settings, config2.getProjectRoot());
    }).catch((err) => {
      debugLogger123.warn(`Update check failed: ${err}`);
    });
  }
  registerCleanup(() => instance.unmount());
}
__name(startInteractiveUI, "startInteractiveUI");
async function main() {
  setupUnhandledRejectionHandler();
  const settings = loadSettings();
  await cleanupCheckpoints();
  let argv = await parseArguments();
  if (argv.promptInteractive && !process.stdin.isTTY) {
    writeStderrLine(
      "Error: The --prompt-interactive flag cannot be used when input is piped from stdin."
    );
    process.exit(1);
  }
  const isDebugMode2 = isDebugMode(argv);
  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)) {
      writeStderrLine(
        `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,
        argv,
        void 0,
        []
      );
      if (!settings.merged.security?.auth?.useExternal) {
        try {
          const authType = partialConfig.getModelsConfig().getCurrentAuthType();
          if (authType) {
            const err = validateAuthMethod(authType, partialConfig);
            if (err) {
              throw new Error(err);
            }
            await partialConfig.refreshAuth(authType);
          }
        } catch (err) {
          writeStderrLine(`Error authenticating: ${err}`);
          process.exit(1);
        }
      }
      const inputFormat = argv.inputFormat;
      let stdinData = "";
      if (!process.stdin.isTTY && inputFormat !== "stream-json") {
        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, []);
    }
  }
  if (argv.resume === "") {
    const selectedSessionId = await showResumeSessionPicker();
    if (!selectedSessionId) {
      process.exit(0);
    }
    argv = { ...argv, resume: selectedSessionId };
  }
  initializeLlmOutputLanguage(settings.merged.general?.outputLanguage);
  {
    const config2 = await loadCliConfig(
      settings.merged,
      argv,
      process.cwd(),
      argv.extensions
    );
    registerCleanup(() => config2.shutdown());
    const wasRaw = process.stdin.isRaw;
    let kittyProtocolDetectionComplete;
    if (config2.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 inputFormat = typeof config2.getInputFormat === "function" ? config2.getInputFormat() : InputFormat.TEXT;
    let initializationResult;
    if (inputFormat !== InputFormat.STREAM_JSON) {
      initializationResult = await initializeApp(config2, settings);
    }
    if (config2.getExperimentalZedIntegration()) {
      return runAcpAgent(config2, settings, argv);
    }
    let input = config2.getQuestion();
    const startupWarnings = [
      .../* @__PURE__ */ new Set([
        ...await getStartupWarnings(),
        ...await getUserStartupWarnings({
          workspaceRoot: process.cwd(),
          useRipgrep: settings.merged.tools?.useRipgrep ?? true,
          useBuiltinRipgrep: settings.merged.tools?.useBuiltinRipgrep ?? true
        }),
        ...getSettingsWarnings(settings),
        ...config2.getWarnings()
      ])
    ];
    if (config2.isInteractive()) {
      await kittyProtocolDetectionComplete;
      await startInteractiveUI(
        config2,
        settings,
        startupWarnings,
        process.cwd(),
        initializationResult
      );
      return;
    }
    if (config2.getDebugMode()) {
      writeStderrLine("Debug mode enabled");
      writeStderrLine(
        `Logging to: ${Storage.getDebugLogPath(config2.getSessionId())}`
      );
      if (isDebugLoggingDegraded()) {
        writeStderrLine(
          "Warning: Debug logging is degraded (write failures occurred)"
        );
      }
    }
    if (inputFormat !== InputFormat.STREAM_JSON) {
      await config2.initialize();
    }
    if (inputFormat !== InputFormat.STREAM_JSON && !process.stdin.isTTY) {
      const stdinData = await readStdin();
      if (stdinData) {
        input = `${stdinData}

${input}`;
      }
    }
    const nonInteractiveConfig = await validateNonInteractiveAuth(
      settings.merged.security?.auth?.useExternal,
      config2,
      settings
    );
    const prompt_id = Math.random().toString(16).slice(2);
    if (inputFormat === InputFormat.STREAM_JSON) {
      const trimmedInput = (input ?? "").trim();
      await runNonInteractiveStreamJson(
        nonInteractiveConfig,
        trimmedInput.length > 0 ? trimmedInput : ""
      );
      await runExitCleanup();
      process.exit(0);
    }
    if (!input) {
      writeStderrLine(
        `No input provided via stdin. Input can be provided by piping data into gemini or using the --prompt option.`
      );
      process.exit(1);
    }
    logUserPrompt(config2, {
      "event.name": "user_prompt",
      "event.timestamp": (/* @__PURE__ */ new Date()).toISOString(),
      prompt: input,
      prompt_id,
      auth_type: config2.getContentGeneratorConfig()?.authType,
      prompt_length: input.length
    });
    debugLogger123.debug(`Session ID: ${config2.getSessionId()}`);
    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((error2) => {
  if (error2 instanceof FatalError) {
    let errorMessage = error2.message;
    if (!process.env["NO_COLOR"]) {
      errorMessage = `\x1B[31m${errorMessage}\x1B[0m`;
    }
    console.error(errorMessage);
    process.exit(error2.exitCode);
  }
  console.error("An unexpected critical error occurred:");
  if (error2 instanceof Error) {
    console.error(error2.stack);
  } else {
    console.error(String(error2));
  }
  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
 */
/**
 * @license
 * Copyright 2025 Qwen Code
 * SPDX-License-Identifier: Apache-2.0
 */
/**
 * @license
 * Copyright 2025 Qwen team
 * SPDX-License-Identifier: Apache-2.0
 */
/**
 * @license
 * Copyright 2026 Google LLC
 * SPDX-License-Identifier: Apache-2.0
 */
/**
 * @license
 * Copyright 2025 Qwen Team
 * SPDX-License-Identifier: Apache-2.0
 *
 * This file is code-generated; do not edit manually.
 */
/**
 * @license
 * Copyright 2025 Qwen Team
 * SPDX-License-Identifier: Apache-2.0
 *
 * This HTML template is code-generated; do not edit manually.
 */
/*! Bundled license information:

undici/lib/web/fetch/body.js:
formdata-polyfill/esm.min.js:
undici/lib/web/fetch/body.js:
  (*! formdata-polyfill. MIT License. Jimmy Wärting <https://jimmy.warting.se/opensource> *)

undici/lib/web/websocket/frame.js:
undici/lib/web/websocket/frame.js:
  (*! ws. MIT License. Einar Otto Stangvik <einaros@gmail.com> *)

web-streams-polyfill/dist/ponyfill.es2018.js:
  (**
   * @license
   * web-streams-polyfill v3.3.3
   * Copyright 2024 Mattias Buelens, Diwank Singh Tomer and other contributors.
   * This code is released under the MIT license.
   * SPDX-License-Identifier: MIT
   *)

fetch-blob/index.js:
  (*! fetch-blob. MIT License. Jimmy Wärting <https://jimmy.warting.se/opensource> *)

node-domexception/index.js:
  (*! node-domexception. MIT License. Jimmy Wärting <https://jimmy.warting.se/opensource> *)

safe-buffer/index.js:
  (*! safe-buffer. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> *)

gtoken/build/cjs/src/index.cjs:
gtoken/build/cjs/src/index.cjs:
  (*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/babel/babel/blob/main/packages/babel-helpers/LICENSE *)

@google/genai/dist/node/index.mjs:
@google/genai/dist/node/index.mjs:
@google/genai/dist/node/index.mjs:
@google/genai/dist/node/index.mjs:
@google/genai/dist/node/index.mjs:
@google/genai/dist/node/index.mjs:
@google/genai/dist/node/index.mjs:
@google/genai/dist/node/index.mjs:
@google/genai/dist/node/index.mjs:
@google/genai/dist/node/index.mjs:
@google/genai/dist/node/index.mjs:
@google/genai/dist/node/index.mjs:
@google/genai/dist/node/index.mjs:
@google/genai/dist/node/index.mjs:
@google/genai/dist/node/index.mjs:
@google/genai/dist/node/index.mjs:
@google/genai/dist/node/index.mjs:
@google/genai/dist/node/index.mjs:
@google/genai/dist/node/index.mjs:
@google/genai/dist/node/index.mjs:
@google/genai/dist/node/index.mjs:
@google/genai/dist/node/index.mjs:
@google/genai/dist/node/index.mjs:
@google/genai/dist/node/index.mjs:
@google/genai/dist/node/index.mjs:
@google/genai/dist/node/index.mjs:
@google/genai/dist/node/index.mjs:
@google/genai/dist/node/index.mjs:
@google/genai/dist/node/index.mjs:
@google/genai/dist/node/index.mjs:
@google/genai/dist/node/index.mjs:
@google/genai/dist/node/index.mjs:
@google/genai/dist/node/index.mjs:
@google/genai/dist/node/index.mjs:
@google/genai/dist/node/index.mjs:
@google/genai/dist/node/index.mjs:
@google/genai/dist/node/index.mjs:
@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
   *)

web-streams-polyfill/dist/ponyfill.mjs:
  (**
   * @license
   * web-streams-polyfill v4.0.0-beta.3
   * Copyright 2021 Mattias Buelens, Diwank Singh Tomer and other contributors.
   * This code is released under the MIT license.
   * SPDX-License-Identifier: MIT
   *)

formdata-node/lib/esm/blobHelpers.js:
formdata-node/lib/esm/Blob.js:
  (*! Based on fetch-blob. MIT License. Jimmy Wärting <https://jimmy.warting.se/opensource> & David Frank *)

humanize-ms/index.js:
  (*!
   * humanize-ms - index.js
   * Copyright(c) 2014 dead_horse <dead_horse@qq.com>
   * MIT Licensed
   *)

chokidar/esm/index.js:
  (*! chokidar - MIT License (c) 2012 Paul Miller (paulmillr.com) *)

fzf/dist/fzf.es.js:
  (** @license
   * fzf v0.5.2
   * Copyright (c) 2021 Ajit
   * Licensed under BSD 3-Clause
   *)

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.
   *)

repeat-string/index.js:
  (*!
   * repeat-string <https://github.com/jonschlinkert/repeat-string>
   *
   * Copyright (c) 2014-2015, Jon Schlinkert.
   * Licensed under the MIT License.
   *)

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
  *)

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 *)
*/
